mermaid-cli 0.18.0

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
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
use crate::constants::{DEFAULT_OLLAMA_PORT, DEFAULT_TEMPERATURE, LEGACY_DEFAULT_MAX_TOKENS};
use crate::models::ReasoningLevel;
use crate::runtime::{PolicyOverride, SafetyMode};
use anyhow::{Context, Result};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Main configuration structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    /// Last used model (persisted between sessions)
    #[serde(default)]
    pub last_used_model: Option<String>,

    /// Default model configuration
    #[serde(default)]
    pub default_model: ModelSettings,

    /// Ollama configuration
    #[serde(default)]
    pub ollama: OllamaConfig,

    /// Web tool (`web_search` / `web_fetch`) backend selection.
    #[serde(default)]
    pub web: WebConfig,

    /// TUI appearance preferences (`[ui]` table).
    #[serde(default)]
    pub ui: UiConfig,

    /// Non-interactive mode configuration
    #[serde(default)]
    pub non_interactive: NonInteractiveConfig,

    /// MCP server configurations
    #[serde(default)]
    pub mcp_servers: HashMap<String, McpServerConfig>,

    /// When unset or true, MCP tools are DEFERRED: instead of advertising
    /// every server's tools on every request, the model gets one
    /// `tool_search` tool that returns matching schemas and promotes them
    /// to direct advertisement. Bounds the always-on tool surface.
    /// `Option` so the derived `Config::default()` and the serde default
    /// agree (both `None` = on) and saved configs don't freeze the value.
    /// Per-server override: `defer = false` on the server entry. Read via
    /// [`Config::mcp_deferral_enabled`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mcp_defer_tools: Option<bool>,

    /// User overrides + custom OpenAI-compatible providers. Keys are
    /// provider names; matching a built-in registry entry overrides its
    /// defaults, anything else defines a fully custom provider.
    /// Example:
    /// ```toml
    /// [providers.groq]
    /// api_key_env = "MY_GROQ_KEY"  # override default GROQ_API_KEY
    ///
    /// [providers.my-vllm]
    /// base_url = "http://192.168.1.42:8000/v1"
    /// api_key_env = "VLLM_KEY"
    /// compat = "openai-effort"
    /// ```
    #[serde(default)]
    pub providers: HashMap<String, UserProviderConfig>,

    /// Per-model reasoning preferences keyed by full model ID
    /// (`provider/name`). Set when the user runs `/reasoning <level>` or
    /// Alt+T cycles while using a specific model — the new value sticks
    /// for that model until changed. Falls back to
    /// `default_model.reasoning` when no entry exists.
    /// Example:
    /// ```toml
    /// [reasoning_per_model]
    /// "<provider>/<model>" = "high"
    /// "ollama/qwen3-coder:30b" = "low"
    /// ```
    #[serde(default)]
    pub reasoning_per_model: HashMap<String, ReasoningLevel>,

    /// Per-model Ollama `num_ctx` override set via `/context <n>`/`max`. Beats
    /// auto-fit; cleared by `/context auto`. Keyed by model id.
    ///
    /// Example:
    /// ```toml
    /// [ollama_num_ctx_per_model]
    /// "ollama/ornith:9b" = 131072
    /// ```
    #[serde(default)]
    pub ollama_num_ctx_per_model: HashMap<String, u32>,

    /// Named model-id aliases that agents/plugins can request without
    /// hardcoding a concrete provider model. Values are full model IDs.
    /// (Distinct from `[profiles.<name>]`, which are whole-config overlays
    /// selected with `--profile`.) Example:
    /// ```toml
    /// [model_aliases]
    /// fast = "ollama/qwen3-coder:14b"
    /// large-context = "openai/<model>"
    /// tool-strong = "anthropic/<model>"
    /// vision = "gemini/gemini-2.5-pro"
    /// cheap = "groq/llama-3.3-70b-versatile"
    /// ```
    #[serde(default)]
    pub model_aliases: HashMap<String, String>,

    /// Runtime safety policy. Defaults to `Ask` so mutations / shell /
    /// network actions require approval out of the box; users opt into
    /// `Auto` (LLM-vetted) or `FullAccess` deliberately.
    #[serde(default)]
    pub safety: SafetyConfig,

    /// Durable semantic memory settings.
    #[serde(default)]
    pub memory: MemoryConfig,

    /// `mermaidd` background-daemon settings (task scheduler).
    #[serde(default)]
    pub daemon: DaemonConfig,

    /// Context-compaction settings.
    #[serde(default)]
    pub compaction: CompactionConfig,

    /// Computer-use (desktop control) preferences.
    #[serde(default)]
    pub computer_use: ComputerUseConfig,

    /// Foreground `execute_command` behavior.
    #[serde(default)]
    pub exec: ExecConfig,

    /// Plan-mode behavior (`/plan`, Alt+P).
    #[serde(default)]
    pub plan: PlanConfig,

    /// Subagent (`agent` tool) settings: drive timeout and user-defined
    /// agent types.
    #[serde(default)]
    pub agents: AgentsConfig,

    /// Runtime-only prompt customizations supplied by CLI flags. These are
    /// deliberately skipped when saving config so one-off agent personas do
    /// not pollute the user's persistent Mermaid settings.
    #[serde(skip)]
    pub prompt: PromptConfig,

    /// The `--profile <name>` overlay active this session, for `doctor` and
    /// startup notices. Runtime-only (`skip`): never persisted, and
    /// `[profiles.*]` itself is excised before deserialization ever sees it.
    #[serde(skip)]
    pub active_profile: Option<String>,
}

impl Config {
    /// Effective value of [`Config::mcp_defer_tools`]: unset means ON.
    pub fn mcp_deferral_enabled(&self) -> bool {
        self.mcp_defer_tools.unwrap_or(true)
    }
}

/// Foreground `execute_command` behavior (`[exec]` table).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ExecConfig {
    /// Run foreground commands on a pseudo-terminal (openpty on Unix,
    /// ConPTY on Windows). On a PTY, `tty`/`isatty` report a terminal,
    /// spinner-heavy tools emit sane progress, and on Unix `/dev/tty`
    /// resolves to the CAPTURED pty instead of scribbling over the TUI.
    /// `Option` so the
    /// derived default and the serde default agree (both `None` = on) and
    /// saved configs don't freeze the value. `pty = false` restores pipes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pty: Option<bool>,
}

impl ExecConfig {
    /// Effective value of [`ExecConfig::pty`]: unset means ON.
    pub fn pty_enabled(&self) -> bool {
        self.pty.unwrap_or(true)
    }
}

/// TUI appearance preferences.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UiConfig {
    /// Color theme the TUI renders with. Switched live via `/theme`.
    #[serde(default)]
    pub theme: ThemeChoice,
}

/// Which built-in color theme the TUI renders with. A typed enum (not a
/// free string) so a typo in config.toml is a clear deserialize error and
/// the reducer's match stays exhaustive when a theme is added.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeChoice {
    #[default]
    Dark,
    Light,
}

impl ThemeChoice {
    /// The lowercase config-file spelling (`/theme` echo + persistence).
    pub fn as_str(self) -> &'static str {
        match self {
            ThemeChoice::Dark => "dark",
            ThemeChoice::Light => "light",
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct PromptConfig {
    pub system_prompt: Option<String>,
    pub append_system_prompt: Vec<String>,
}

impl PromptConfig {
    pub fn render_system_prompt(&self, default_prompt: &str) -> String {
        let mut rendered = self
            .system_prompt
            .as_deref()
            .unwrap_or(default_prompt)
            .trim_end()
            .to_string();

        for extra in &self.append_system_prompt {
            let extra = extra.trim();
            if extra.is_empty() {
                continue;
            }
            if !rendered.is_empty() {
                rendered.push_str("\n\n");
            }
            rendered.push_str(extra);
        }

        rendered
    }

    pub fn is_customized(&self) -> bool {
        self.system_prompt.is_some() || !self.append_system_prompt.is_empty()
    }
}

/// Whether model-driven shell commands may reach the network. `Deny` engages
/// the Linux seccomp network kill-switch (`--no-network`); a no-op on other
/// platforms. Default `Allow` preserves today's behavior.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetworkPolicy {
    #[default]
    Allow,
    Deny,
}

/// Where model-driven shell commands may write. `Project` engages Linux
/// Landlock write-confinement (`--confine-fs`): writes are allowed only beneath
/// the project directory, the system temp directory, and `/dev`; reads and
/// execution stay unrestricted. Best-effort (no-op on kernels without Landlock
/// and on other platforms). Default `Unrestricted` preserves today's behavior.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FilesystemPolicy {
    #[default]
    Unrestricted,
    Project,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SafetyConfig {
    pub mode: SafetyMode,
    pub checkpoint_on_mutation: bool,
    /// Network access policy for shell commands. `Deny` installs the OS
    /// network kill-switch on Linux. See [`NetworkPolicy`].
    #[serde(default)]
    pub network: NetworkPolicy,
    /// Filesystem write policy for shell commands. `Project` confines writes
    /// to the project/temp/`/dev` directories on Linux. See
    /// [`FilesystemPolicy`].
    #[serde(default)]
    pub filesystem: FilesystemPolicy,
    #[serde(default)]
    pub overrides: Vec<PolicyOverride>,
    /// Enforcement floor for write-shaped MCP tools (no server-advertised
    /// `readOnlyHint`): `allow` | `auto` | `ask` | `deny`. Safety mode alone
    /// never authorizes an external side effect — with the default `auto`,
    /// even full_access routes MCP writes through the intent classifier
    /// (aligned runs silently, off-task escalates). `allow` restores the old
    /// unconditional-allow behavior.
    #[serde(default)]
    pub external_writes: crate::runtime::FloorLevel,
    /// Enforcement floor for machine-scoped package operations (`npm -g`,
    /// `cargo install`, `pip install`, `brew`/`apt`/`winget` installs) —
    /// same levels and default as `external_writes`. They mutate the
    /// MACHINE, not the project (outside checkpoint reach), so even
    /// full_access vets them. Project-local installs (`npm install`,
    /// `cargo add`) are untouched.
    #[serde(default)]
    pub system_installs: crate::runtime::FloorLevel,
    /// Model id the `Auto`-mode safety classifier uses to vet borderline
    /// actions. `None` ⇒ vet with the session's active model. Set this to
    /// point the vet at a cheaper/faster model than the one driving the work.
    #[serde(default)]
    pub auto_classifier_model: Option<String>,
    /// Headless escape hatch: when true, non-replayable tools (web/mcp/
    /// subagent/computer_use) are allowed to PROCEED on an `Ask` decision in a
    /// headless run (no approval UI) instead of being blocked. Default `false`
    /// — `mermaid run` in `ask` mode otherwise refuses these. Set via
    /// `--allow-untrusted-tools` or config for CI that needs them.
    #[serde(default)]
    pub allow_untrusted_headless_tools: bool,
}

impl Default for SafetyConfig {
    fn default() -> Self {
        Self {
            // Safe-by-default: the first run prompts for approval on
            // mutations / shell / network rather than silently auto-allowing
            // everything. FullAccess remains available via config.
            mode: SafetyMode::Ask,
            checkpoint_on_mutation: true,
            network: NetworkPolicy::default(),
            filesystem: FilesystemPolicy::default(),
            overrides: Vec::new(),
            external_writes: crate::runtime::FloorLevel::default(),
            system_installs: crate::runtime::FloorLevel::default(),
            auto_classifier_model: None,
            allow_untrusted_headless_tools: false,
        }
    }
}

/// `mermaidd` background-daemon settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DaemonConfig {
    /// How many daemon-queued tasks may execute concurrently. Each task is a
    /// full agent run holding a model context, so the default is strictly
    /// serial — honest for a single local GPU. Raise it when the daemon's
    /// tasks target cloud providers (or a box with VRAM to spare).
    pub max_concurrent_tasks: usize,
    /// Wall-clock budget per daemon task, in minutes. `None` keeps the
    /// headless runner's built-in 20-minute deadline; set it to give queued
    /// batch work a shorter (or longer) leash. A task over budget is failed
    /// with a timeout report.
    pub task_timeout_minutes: Option<u64>,
    /// Days to retain finished runtime rows (terminal tasks, stale sessions,
    /// finished tool runs, old compactions, …) before the startup GC prunes
    /// them. Active data is never pruned regardless of this value.
    pub retention_days: i64,
    /// Days to retain `outcomes` reward rows — the self-improving-loop training
    /// corpus. Deliberately longer than `retention_days` so a large training
    /// history survives the shorter task/session window; each outcome's
    /// denormalized context keeps it usable after its task row is pruned.
    pub outcomes_retention_days: i64,
    /// Days to retain unlocked per-session scratch directories before the
    /// daemon's startup sweep reaps them. Sessions whose owning process is
    /// still alive are never reaped regardless of age. Interactive sessions
    /// sweep with the built-in default; this knob only tunes mermaidd.
    pub scratchpad_retention_days: i64,
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            max_concurrent_tasks: 1,
            task_timeout_minutes: None,
            retention_days: 30,
            outcomes_retention_days: 180,
            scratchpad_retention_days: crate::session::scratchpad::RETENTION_DAYS as i64,
        }
    }
}

/// What approval does once granted, when the user has pinned it in config.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanPostApprove {
    /// Approval immediately auto-submits "Implement the plan."
    Start,
    /// Approval finalizes the plan and returns to the idle prompt.
    Wait,
}

/// Permission level for one plan-mode category. Mirrors the safety-mode
/// ladder so the picker reads familiarly: `allow` runs, `auto` is vetted by
/// the Auto classifier, `ask` raises the approval modal, `deny` blocks with
/// the plan-flavored teaching denial.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanPermLevel {
    Allow,
    Auto,
    Ask,
    Deny,
}

impl PlanPermLevel {
    pub fn as_str(self) -> &'static str {
        match self {
            PlanPermLevel::Allow => "allow",
            PlanPermLevel::Auto => "auto",
            PlanPermLevel::Ask => "ask",
            PlanPermLevel::Deny => "deny",
        }
    }
}

/// Per-category permission profile applied while a plan is being drafted.
/// The read-only floor stays the base; these levels decide how far each
/// carve-out opens. The plan file itself is not a category — being able to
/// author the plan IS plan mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PlanPermissions {
    /// Known-safe build/test commands (`is_plan_safe_build_command`).
    pub builds: PlanPermLevel,
    /// `web_search` / `web_fetch` (GET-shaped reads).
    pub web: PlanPermLevel,
    /// Durable memory writes.
    pub memory: PlanPermLevel,
    /// The checklist writers (`task_create` / `task_update`). Only `allow`
    /// unblocks them — `auto`/`ask` collapse to `deny` (they are ungated
    /// tools with no approval path, and the checklist is seeded from the
    /// approved plan anyway).
    pub tasks: PlanPermLevel,
}

impl Default for PlanPermissions {
    fn default() -> Self {
        Self {
            builds: PlanPermLevel::Allow,
            web: PlanPermLevel::Allow,
            memory: PlanPermLevel::Allow,
            tasks: PlanPermLevel::Deny,
        }
    }
}

impl PlanPermissions {
    /// The top-level picker presets; `None` when the current values match
    /// none of them (the picker shows "custom").
    pub fn preset_name(&self) -> Option<&'static str> {
        if *self == Self::default() {
            Some("default")
        } else if *self == Self::strict() {
            Some("strict")
        } else if *self == Self::open() {
            Some("open")
        } else {
            None
        }
    }

    /// Everything denied: pure read-only exploration plus the plan file.
    pub fn strict() -> Self {
        Self {
            builds: PlanPermLevel::Deny,
            web: PlanPermLevel::Deny,
            memory: PlanPermLevel::Deny,
            tasks: PlanPermLevel::Deny,
        }
    }

    /// Everything allowed (the working tree stays read-only regardless).
    pub fn open() -> Self {
        Self {
            builds: PlanPermLevel::Allow,
            web: PlanPermLevel::Allow,
            memory: PlanPermLevel::Allow,
            tasks: PlanPermLevel::Allow,
        }
    }
}

/// Plan-mode settings (`[plan]`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PlanConfig {
    /// When true, `exit_plan_mode` skips the approval dialog entirely: the
    /// plan is approved the moment the model presents it. Default false —
    /// the dialog is the point of plan mode.
    pub auto_approve: bool,
    /// Pin what approval does. Unset (default) the dialog offers both
    /// "Approve and start" and "Approve and wait" every time; set, it
    /// collapses to a single Approve option with this behavior. Option +
    /// skip_serializing keeps "unset" meaningful in saved configs (the
    /// freeze-defaults rule).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_approve: Option<PlanPostApprove>,
    /// Per-category permission profile while planning. Edited live in the
    /// `/plan config` picker; the reducer threads the LIVE values onto each
    /// tool dispatch (the startup `Config` snapshot in `ExecContext` would
    /// go stale).
    pub permissions: PlanPermissions,
    /// Plan-phase model override: entering plan mode swaps the session to
    /// this model and leaving restores the previous one — plan on a frontier
    /// model, execute locally (or invert for privacy). Unset = plan with
    /// whatever is running.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Plan-phase reasoning override, same swap/restore contract as `model`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<crate::models::ReasoningLevel>,
}

/// Durable semantic memory settings (v0.10.0).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MemoryConfig {
    /// Master switch for agent memory (the tool, the always-loaded index, and
    /// the slash commands). On by default.
    pub enabled: bool,
    /// Byte cap on the always-loaded memory index before it's truncated.
    pub index_cap_bytes: usize,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            index_cap_bytes: crate::constants::MAX_MEMORY_INDEX_BYTES,
        }
    }
}

/// Context-compaction settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CompactionConfig {
    /// Cap on consecutive auto-compact-and-continue recoveries after a
    /// context-window truncation, before the run stops and shows the manual
    /// levers (`/context max`, `/context offload on`). The counter resets
    /// whenever the run makes progress, so this bounds only no-progress
    /// thrashing on a too-small window. `0` means uncapped.
    ///
    /// Example:
    /// ```toml
    /// [compaction]
    /// max_truncation_recoveries = 0  # never give up on its own
    /// ```
    pub max_truncation_recoveries: u8,
}

impl Default for CompactionConfig {
    fn default() -> Self {
        Self {
            max_truncation_recoveries: crate::constants::COMPACTION_MAX_TRUNCATION_RECOVERIES,
        }
    }
}

/// Computer-use (desktop control) preferences.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ComputerUseConfig {
    /// After a successful click / type_text / press_key, auto-capture the
    /// focused window and attach it inline so the model can verify the result.
    /// On by default (non-breaking); set false to cut the per-action capture
    /// cost + image tokens when visual feedback isn't needed. The model can
    /// still call `screenshot` explicitly.
    pub auto_screenshot: bool,
}

impl Default for ComputerUseConfig {
    fn default() -> Self {
        Self {
            auto_screenshot: true,
        }
    }
}

/// Subagent (`agent` tool) settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentsConfig {
    /// Hard ceiling on one subagent drive's wall-clock runtime, in seconds.
    /// `0` falls back to the built-in default (1200 = 20 minutes).
    pub timeout_secs: u64,
    /// User-defined agent types for the `agent` tool's `type` arg, keyed by
    /// type name. A custom name shadows a built-in (`general`, `explore`),
    /// so `[agents.types.explore]` retunes the built-in Explore.
    /// ```toml
    /// [agents.types.scout]
    /// tools = ["read_file", "execute_command"]  # omit for the full child set
    /// safety = "read_only"    # ceiling — the child never runs looser
    /// preamble = "You are a scout: find and report, fast."
    /// model = "ollama/qwen3:8b"  # default model; per-call `model` arg wins
    /// ```
    pub types: HashMap<String, AgentTypeConfig>,
}

impl Default for AgentsConfig {
    fn default() -> Self {
        Self {
            timeout_secs: 1200,
            types: HashMap::new(),
        }
    }
}

/// One user-defined agent type (see [`AgentsConfig::types`]). Every field is
/// optional; an empty table behaves like the built-in `general` type.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentTypeConfig {
    /// Tool names the child registry is filtered to. Valid names:
    /// `read_file`, `write_file`, `apply_patch`, `delete_file`,
    /// `create_directory`, `execute_command`, `web_search`, `web_fetch`,
    /// `mcp`. Omit for the full child set.
    pub tools: Option<Vec<String>>,
    /// Safety ceiling (canonical mode name: `read_only`/`ask`/`auto`/
    /// `full_access`). The child runs at the LESS permissive of the parent's
    /// live mode and this ceiling.
    pub safety: Option<String>,
    /// Extra system-prompt block appended after the child's subagent
    /// contract.
    pub preamble: Option<String>,
    /// Default model id for this type (e.g. `"ollama/qwen3:8b"`); a per-call
    /// `model` arg wins over it.
    pub model: Option<String>,
}

/// User-supplied remote provider configuration. All fields are optional for a
/// built-in provider; fully custom OpenAI-compatible providers require a base
/// URL and API-key environment variable.
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct UserProviderConfig {
    /// Override the provider API base URL (None = built-in default; required
    /// for fully custom providers).
    #[serde(default)]
    pub base_url: Option<String>,
    /// Env var name to read the API key from (None = use the built-in
    /// registry default like `GROQ_API_KEY`; required for fully custom
    /// providers).
    #[serde(default)]
    pub api_key_env: Option<String>,
    /// Extra HTTP headers sent on every request to this provider.
    #[serde(default)]
    pub extra_headers: HashMap<String, String>,
    /// Extra HTTP headers whose VALUES come from environment variables
    /// (map is header name -> env var name), resolved at request-build time so
    /// a secret header (e.g. a gateway token) never has to live in config.toml.
    /// A missing env var is skipped.
    #[serde(default)]
    pub env_headers: HashMap<String, String>,
    /// For fully custom providers (no built-in registry entry), declares
    /// which OpenAI-compatible shape the endpoint speaks. Ignored when
    /// the provider name matches a built-in registry entry. Values:
    /// `"openai"` (no reasoning), `"openai-effort"` (`reasoning_effort`
    /// field), `"openrouter"` (nested `reasoning: {effort}` object).
    #[serde(default)]
    pub compat: Option<String>,
    /// Optional preferred model — surfaced by `mermaid status` and used
    /// as the default when the user picks this provider with no model
    /// suffix.
    #[serde(default)]
    pub default_model: Option<String>,
}

/// MCP server configuration
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Command to execute (e.g., "npx", "node", "python"). Empty = unset;
    /// exactly one of `command` / `url` must be set (see [`Self::transport_kind`]).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub command: String,
    /// Command-line arguments
    #[serde(default)]
    pub args: Vec<String>,
    /// Environment variables for the server process
    #[serde(default)]
    pub env: HashMap<String, String>,
    /// Streamable HTTP endpoint URL for a remote MCP server. Presence selects
    /// the HTTP transport; mutually exclusive with `command`. Must never
    /// serialize as a bare `None` — toml errors on unsupported None values.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Literal HTTP headers sent on every request to `url` (e.g. an
    /// `Authorization` token). Values are secrets: redacted in `Debug`.
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// HTTP headers whose VALUES come from environment variables (map is
    /// header name -> env var name), resolved at request-build time so a
    /// secret header never has to live in config.toml. A missing env var is
    /// skipped. Same semantics as `UserProviderConfig::env_headers`.
    #[serde(default)]
    pub env_headers: HashMap<String, String>,
    /// Allow `url` to resolve to private/link-local addresses. Off by default:
    /// plugin bundles ship MCP configs, and a malicious bundle must not be
    /// able to point a server entry at 169.254.169.254 or the LAN.
    #[serde(default)]
    pub allow_private_network: bool,
    /// If non-empty, only these tool names are exposed to the model.
    #[serde(default)]
    pub enabled_tools: Vec<String>,
    /// Tool names hidden from the model. Takes precedence over `enabled_tools`.
    #[serde(default)]
    pub disabled_tools: Vec<String>,
    /// Per-server deferral override: `Some(false)` always advertises this
    /// server's tools directly (skips `tool_search`); `Some(true)` defers
    /// even when the global `mcp_defer_tools` is off; `None` follows the
    /// global setting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub defer: Option<bool>,
}

/// Which transport an [`McpServerConfig`] selects: a spawned child process
/// (stdio) or a remote Streamable HTTP endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransportKind {
    Stdio,
    Http,
}

impl McpServerConfig {
    /// Resolve which transport this config selects, enforcing the invariants:
    /// exactly one of `command` / `url` set, and an HTTP url must be `https`
    /// anywhere or `http` to a loopback host only (plaintext to a routable
    /// host would leak `Authorization` headers in cleartext).
    pub fn transport_kind(&self) -> Result<TransportKind> {
        match (&self.url, self.command.is_empty()) {
            (Some(_), false) => Err(anyhow::anyhow!(
                "MCP server config sets both `command` and `url`; they are mutually exclusive"
            )),
            (None, true) => Err(anyhow::anyhow!(
                "MCP server config sets neither `command` nor `url`"
            )),
            (None, false) => Ok(TransportKind::Stdio),
            (Some(url), true) => {
                let parsed = reqwest::Url::parse(url)
                    .map_err(|e| anyhow::anyhow!("invalid MCP server url '{url}': {e}"))?;
                let host = parsed.host_str().unwrap_or("");
                match parsed.scheme() {
                    "https" => Ok(TransportKind::Http),
                    "http" if crate::utils::classify_host(host).is_loopback() => {
                        Ok(TransportKind::Http)
                    },
                    "http" => Err(anyhow::anyhow!(
                        "MCP server url '{url}' uses plaintext http to a non-loopback host; \
                         use https (auth headers would travel in cleartext)"
                    )),
                    other => Err(anyhow::anyhow!(
                        "MCP server url '{url}' has unsupported scheme '{other}' \
                         (expected https, or http to loopback)"
                    )),
                }
            },
        }
    }

    /// Whether `tool_name` should be exposed to the model: hidden when listed in
    /// `disabled_tools` (which wins), else allowed when `enabled_tools` is empty
    /// (allow-all) or names it.
    pub fn tool_allowed(&self, tool_name: &str) -> bool {
        if self.disabled_tools.iter().any(|t| t == tool_name) {
            return false;
        }
        self.enabled_tools.is_empty() || self.enabled_tools.iter().any(|t| t == tool_name)
    }
}

/// Mask a header/env map for `Debug`: keys are kept (so you can still see which
/// vars are set) but values are never rendered — they hold secrets like API keys
/// and `Authorization` tokens (#F12). A `BTreeMap` keeps the output deterministic.
fn debug_masked_map(
    map: &HashMap<String, String>,
) -> std::collections::BTreeMap<&str, &'static str> {
    map.keys().map(|k| (k.as_str(), "[REDACTED]")).collect()
}

// Manual `Debug` for the secret-bearing config structs so a `{:?}` (into
// tracing, a panic, or an error) cannot dump provider keys / Authorization
// headers / MCP env secrets. `Config` keeps its derived `Debug`, which now
// recurses through these redacting impls (#F12).
impl std::fmt::Debug for McpServerConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpServerConfig")
            .field("command", &self.command)
            // args may carry an inline secret (e.g. `--api-key=sk-...`).
            .field(
                "args",
                &self
                    .args
                    .iter()
                    .map(|a| crate::utils::redact_secrets(a))
                    .collect::<Vec<_>>(),
            )
            .field("env", &debug_masked_map(&self.env))
            .field("url", &self.url)
            // Literal header values are secrets (Authorization tokens).
            .field("headers", &debug_masked_map(&self.headers))
            // Values are env var NAMES (not secrets), so render them.
            .field("env_headers", &self.env_headers)
            .field("allow_private_network", &self.allow_private_network)
            // Tool allow/deny lists are plain tool names, not secrets.
            .field("enabled_tools", &self.enabled_tools)
            .field("disabled_tools", &self.disabled_tools)
            .finish()
    }
}

impl std::fmt::Debug for UserProviderConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UserProviderConfig")
            .field("base_url", &self.base_url)
            .field("api_key_env", &self.api_key_env)
            .field("extra_headers", &debug_masked_map(&self.extra_headers))
            // Values are env var NAMES (not secrets), so render them.
            .field("env_headers", &self.env_headers)
            .field("compat", &self.compat)
            .field("default_model", &self.default_model)
            .finish()
    }
}

/// Default model settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ModelSettings {
    /// Model provider (ollama, openai, anthropic)
    pub provider: String,
    /// Model name
    pub name: String,
    /// Temperature for generation
    pub temperature: f32,
    /// Maximum tokens to generate
    pub max_tokens: usize,
    /// Default reasoning depth used for new sessions when no `--reasoning`
    /// flag is given. Each adapter snaps this onto the closest level the
    /// model actually supports via `nearest_effort()`.
    pub reasoning: ReasoningLevel,
}

impl Default for ModelSettings {
    fn default() -> Self {
        Self {
            provider: String::new(),
            name: String::new(),
            temperature: DEFAULT_TEMPERATURE,
            // 0 = AUTO: the model-scaled output budget (adapters omit the cap so
            // the provider decides, or size it to the context window). A positive
            // value set by the user is an explicit hard cap.
            max_tokens: 0,
            reasoning: ReasoningLevel::default(),
        }
    }
}

/// Ollama configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct OllamaConfig {
    /// Ollama server host
    pub host: String,
    /// Ollama server port
    pub port: u16,
    /// Number of GPU layers to offload (None = auto, 0 = CPU only, positive = specific count)
    /// Lower values free up VRAM for larger models at the cost of speed
    pub num_gpu: Option<i32>,
    /// Number of CPU threads for processing offloaded layers
    /// Higher values improve CPU inference speed for large models
    pub num_thread: Option<i32>,
    /// Context window size (number of tokens)
    /// Larger values allow longer conversations but use more memory
    pub num_ctx: Option<i32>,
    /// Enable NUMA optimization for multi-CPU systems
    pub numa: Option<bool>,
    /// Allow Ollama to offload the model/KV cache to system RAM when it doesn't
    /// fit VRAM. **Disabled by default**: RAM offload is 5–20× slower, so by
    /// default Mermaid auto-fits `num_ctx` to VRAM (keeping the model on the
    /// GPU). Enable to trade speed for a larger context window. Toggle in-app
    /// with `/context offload on|off`.
    pub allow_ram_offload: bool,
    /// Optional hard cap on the auto-fitted context window (in tokens). `None`
    /// lets auto-fit use the full memory budget up to the model's max; set this
    /// to bound it (e.g. to leave VRAM headroom for other apps).
    pub max_auto_num_ctx: Option<usize>,
    /// Start `ollama serve` automatically when the configured server is local
    /// (loopback) and not running — the user should never have to leave
    /// mermaid to start Ollama. Disable if you manage the server yourself
    /// (e.g. systemd with custom flags). Never applies to remote hosts.
    pub auto_start: bool,
}

impl Default for OllamaConfig {
    fn default() -> Self {
        Self {
            host: String::from("localhost"),
            port: DEFAULT_OLLAMA_PORT,
            num_gpu: None,            // Let Ollama auto-detect
            num_thread: None,         // Let Ollama auto-detect
            num_ctx: None,            // Use model default (overrides auto-fit)
            numa: None,               // Auto-detect
            allow_ram_offload: false, // VRAM-only by default (RAM is slow)
            max_auto_num_ctx: None,   // No cap; auto-fit to the memory budget
            auto_start: true,         // A dead local server is mermaid's problem
        }
    }
}

/// Backend for the `web_fetch` tool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FetchBackend {
    /// Fetch the URL directly from this machine and convert it to markdown.
    /// No API key, no third party — works for any user with network access.
    #[default]
    Native,
    /// Route through Ollama Cloud's `/api/web_fetch` (needs `OLLAMA_API_KEY`).
    Ollama,
}

/// Backend for the `web_search` tool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SearchBackend {
    /// Zero-config default: Ollama Cloud when `OLLAMA_API_KEY` is set, otherwise
    /// an auto-managed local SearXNG container (mermaid starts it on the first
    /// search and tears it down on exit). The user configures nothing.
    #[default]
    Auto,
    /// Ollama Cloud's `/api/web_search` (needs `OLLAMA_API_KEY`).
    Ollama,
    /// A self-hosted SearXNG instance queried at `searxng_url` — keyless.
    Searxng,
}

/// Web tool backend configuration.
///
/// ```toml
/// [web]
/// fetch_backend = "native"   # or "ollama"
/// search_backend = "auto"    # or "ollama" / "searxng"
/// searxng_url = "http://localhost:8080"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WebConfig {
    /// Backend for `web_fetch`. `native` (default) fetches the URL from this
    /// machine and needs no key; `ollama` uses Ollama Cloud.
    pub fetch_backend: FetchBackend,
    /// Backend for `web_search`. `auto` (default) uses Ollama Cloud when
    /// `OLLAMA_API_KEY` is set and otherwise auto-manages a local SearXNG
    /// container. `ollama` forces Ollama Cloud; `searxng` forces a self-hosted
    /// instance at `searxng_url`.
    pub search_backend: SearchBackend,
    /// SearXNG base URL, used when `search_backend = "searxng"` (your own
    /// instance). The instance must have the JSON output format enabled
    /// (`search.formats` includes `json`). The `auto` managed instance ignores
    /// this and picks its own port.
    pub searxng_url: String,
}

impl Default for WebConfig {
    fn default() -> Self {
        Self {
            fetch_backend: FetchBackend::Native,
            search_backend: SearchBackend::Auto,
            searxng_url: String::from("http://localhost:8080"),
        }
    }
}

/// Non-interactive mode configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct NonInteractiveConfig {
    /// Output format (text, json, markdown)
    pub output_format: String,
    /// Maximum tokens to generate
    pub max_tokens: usize,
    /// Don't execute agent actions (dry run)
    pub no_execute: bool,
}

impl Default for NonInteractiveConfig {
    fn default() -> Self {
        Self {
            output_format: String::from("text"),
            // 0 = AUTO (see `ModelSettings::max_tokens`).
            max_tokens: 0,
            no_execute: false,
        }
    }
}

/// One source of configuration in the layered merge. Declaration order IS
/// precedence: every later layer's table is deep-merged over the earlier ones,
/// so `Defaults < User < Profile < Project < Session`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConfigLayer {
    /// Built-in defaults (`Config::default()`); the implicit base — an empty
    /// table deserializes to it, so no explicit table is ever built for it.
    Defaults = 0,
    /// The user's `~/.config/mermaid/config.toml` — the only layer persists
    /// write to.
    User = 1,
    /// A named overlay from the user file's `[profiles.<name>]`, selected
    /// with `--profile <name>`. Sits BELOW Project so a repo's tighten-only
    /// safety clamp still wins over a profile's choices.
    Profile = 2,
    /// A repo's `<git-root>/.mermaid/config.toml` (sanitized + tighten-only;
    /// populated by the project-config loader).
    Project = 3,
    /// This invocation's CLI flags: `-c KEY=VALUE` plus the dedicated flags
    /// (`--no-network`, `--confine-fs`, `--sandbox`, `run --max-tokens`,
    /// `run --allow-untrusted-tools`).
    Session = 4,
}

impl ConfigLayer {
    /// Human name used in unknown-key warnings ("in user config (…)").
    fn name(self) -> &'static str {
        match self {
            ConfigLayer::Defaults => "defaults",
            ConfigLayer::User => "user config",
            ConfigLayer::Profile => "config profile",
            ConfigLayer::Project => "project config",
            ConfigLayer::Session => "session flags",
        }
    }
}

/// One layer's raw table plus where it came from (for warning attribution).
#[derive(Debug, Clone)]
pub(crate) struct LayerSource {
    /// Which precedence slot this table occupies.
    pub layer: ConfigLayer,
    /// Human-readable origin (file path or "command line") for warnings.
    pub origin: String,
    /// The layer's raw parsed TOML, merged verbatim (already sanitized for
    /// the project layer).
    pub table: toml::Table,
}

/// The per-invocation config overrides carried by CLI flags — the `Session`
/// layer's inputs. Built from the parsed CLI by `Cli::session_flags()`.
#[derive(Debug, Clone, Default)]
pub struct SessionFlags {
    /// Repeatable `-c KEY=VALUE` overrides, applied first (dedicated flags
    /// deep-set on top, so a flag beats a contradictory `-c`).
    pub overrides: Vec<String>,
    /// `--no-network` or `--sandbox` → `safety.network = "deny"`.
    pub deny_network: bool,
    /// `--confine-fs` or `--sandbox` → `safety.filesystem = "project"`.
    pub confine_fs: bool,
    /// `run --max-tokens <n>` → `default_model.max_tokens`.
    pub max_tokens: Option<usize>,
    /// `run --allow-untrusted-tools` → `safety.allow_untrusted_headless_tools`.
    pub allow_untrusted_tools: bool,
    /// `--profile <name>`: select a `[profiles.<name>]` overlay from the user
    /// config file. NOT rendered into `to_table` — profiles are their own
    /// layer, resolved by `load_layered_config`.
    pub profile: Option<String>,
}

impl SessionFlags {
    /// Render the flags as the `Session` layer's raw table. `-c` overrides go
    /// in first; the dedicated flags deep-set on top of them, preserving the
    /// historical ordering where `--no-network` beats `-c safety.network=allow`.
    pub(crate) fn to_table(&self) -> Result<toml::Table> {
        let mut table = toml::Table::new();
        apply_cli_overrides(&mut table, &self.overrides)?;
        if self.deny_network {
            deep_set_segments(
                &mut table,
                &["safety", "network"],
                toml::Value::String("deny".into()),
            )?;
        }
        if self.confine_fs {
            deep_set_segments(
                &mut table,
                &["safety", "filesystem"],
                toml::Value::String("project".into()),
            )?;
        }
        if let Some(n) = self.max_tokens {
            deep_set_segments(
                &mut table,
                &["default_model", "max_tokens"],
                toml::Value::Integer(n as i64),
            )?;
        }
        if self.allow_untrusted_tools {
            deep_set_segments(
                &mut table,
                &["safety", "allow_untrusted_headless_tools"],
                toml::Value::Boolean(true),
            )?;
        }
        Ok(table)
    }
}

/// Remove the `profiles` table from a raw user-config table and return it
/// (empty when absent). `[profiles.<name>]` overlays must NEVER reach
/// `Config` deserialization — they are a container of layer tables, not
/// config keys — so every user-file read excises them before
/// `finalize_config` (which would otherwise warn about unknown keys) and
/// before any safety baseline is computed.
fn take_profiles(table: &mut toml::Table) -> toml::Table {
    match table.remove("profiles") {
        Some(toml::Value::Table(profiles)) => profiles,
        // A non-table `profiles` key is malformed; drop it (the profile
        // lookup errors clearly when one was requested).
        _ => toml::Table::new(),
    }
}

/// Resolve `--profile <name>` against the user file's excised `[profiles.*]`
/// table: the named overlay as a `Profile` layer, or a hard error naming the
/// available profiles (sorted).
fn resolve_profile_layer(
    profiles: &toml::Table,
    name: &str,
    config_path: &std::path::Path,
) -> Result<LayerSource> {
    match profiles.get(name) {
        Some(toml::Value::Table(overlay)) => Ok(LayerSource {
            layer: ConfigLayer::Profile,
            origin: format!("profile:{} ({})", name, config_path.display()),
            table: overlay.clone(),
        }),
        Some(_) => anyhow::bail!(
            "config profile '{}' is not a table; define it as [profiles.{}] in {}",
            name,
            name,
            config_path.display()
        ),
        None => {
            let mut available: Vec<&str> = profiles.keys().map(String::as_str).collect();
            available.sort_unstable();
            if available.is_empty() {
                anyhow::bail!(
                    "no config profiles defined; add [profiles.{}] to {}",
                    name,
                    config_path.display()
                );
            }
            anyhow::bail!(
                "unknown config profile '{}'; available: {}",
                name,
                available.join(", ")
            )
        },
    }
}

/// Load the user-scope configuration (defaults + the user file, no project or
/// session layers). This is the view persistence baselines, the daemon, and
/// runtime re-reads use — anything that must not observe another repo's
/// project config or a one-off CLI flag.
pub fn load_config() -> Result<Config> {
    let config_path = get_config_path()?;
    let mut table = read_config_table(&config_path)?;
    migrate_legacy_max_tokens(&mut table);
    migrate_legacy_model_profiles(&mut table);
    let _ = take_profiles(&mut table);
    Ok(finalize_config(table)?.0)
}

/// A completed layered load: the merged config plus the messages the startup
/// path surfaces.
pub struct LayeredLoad {
    /// The merged, typed configuration.
    pub config: Config,
    /// Layer-attributed unknown-key and project-sanitizer warnings.
    pub warnings: Vec<String>,
    /// Informational lines (e.g. "using project config …").
    pub notices: Vec<String>,
}

/// Load the full layered configuration:
/// defaults < user file < project file < session flags.
/// `cwd` locates the project layer (`<git-root>/.mermaid/config.toml`,
/// sanitized + safety-clamped); pass `None` to skip it (daemon, tests).
pub fn load_layered_config(
    cwd: Option<&std::path::Path>,
    flags: &SessionFlags,
) -> Result<LayeredLoad> {
    let config_path = get_config_path()?;
    let mut user_table = read_config_table(&config_path)?;
    migrate_legacy_max_tokens(&mut user_table);
    migrate_legacy_model_profiles(&mut user_table);
    // Excise [profiles.*] BEFORE anything deserializes the user table (the
    // safety baseline below and finalize_config's unknown-key scan).
    let profiles = take_profiles(&mut user_table);
    let mut layers = vec![LayerSource {
        layer: ConfigLayer::User,
        origin: config_path.display().to_string(),
        table: user_table.clone(),
    }];
    let mut sanitizer_warnings = Vec::new();
    let mut notices = Vec::new();
    if let Some(name) = flags.profile.as_deref() {
        let layer = resolve_profile_layer(&profiles, name, &config_path)?;
        notices.push(format!(
            "using config profile '{}' (from {})",
            name,
            config_path.display()
        ));
        layers.push(layer);
    }
    if let Some(cwd) = cwd {
        // The tighten-only safety clamp compares against the user-scope
        // (defaults + user file) values.
        let base_safety = finalize_config(user_table)?.0.safety;
        let (layer, warnings, notice) =
            super::project_config::load_project_layer(cwd, &base_safety);
        sanitizer_warnings.extend(warnings);
        notices.extend(notice);
        if let Some(layer) = layer {
            layers.push(layer);
        }
    }
    layers.push(LayerSource {
        layer: ConfigLayer::Session,
        origin: "command line".to_string(),
        table: flags.to_table()?,
    });
    let (mut config, unknown_key_warnings) = merge_layers(layers)?;
    config.active_profile = flags.profile.clone();
    // Sanitizer warnings first: they explain keys that will also be absent
    // from the merged result.
    sanitizer_warnings.extend(unknown_key_warnings);
    Ok(LayeredLoad {
        config,
        warnings: sanitizer_warnings,
        notices,
    })
}

/// The project-scoped view (defaults + user + project, NO session flags) for
/// runtime re-reads keyed to a workdir — e.g. the memory settings consulted
/// per operation. Never fails and never prints; warnings/notices were already
/// surfaced by the startup load.
pub fn load_project_scoped_config(cwd: &std::path::Path) -> Config {
    fn load(cwd: &std::path::Path) -> Result<Config> {
        let config_path = get_config_path()?;
        let mut user_table = read_config_table(&config_path)?;
        migrate_legacy_max_tokens(&mut user_table);
        migrate_legacy_model_profiles(&mut user_table);
        let _ = take_profiles(&mut user_table);
        let base_safety = finalize_config(user_table.clone())?.0.safety;
        let mut layers = vec![LayerSource {
            layer: ConfigLayer::User,
            origin: config_path.display().to_string(),
            table: user_table,
        }];
        let (layer, _warnings, _notice) =
            super::project_config::load_project_layer(cwd, &base_safety);
        if let Some(layer) = layer {
            layers.push(layer);
        }
        Ok(merge_layers(layers)?.0)
    }
    load(cwd).unwrap_or_default()
}

/// Like [`load_config`] (user scope, no session flags) but never fails: on a
/// malformed config, warn on stderr (secret-redacted, #F13) and fall back to
/// defaults (#111). For standalone subcommands that only read user settings.
pub fn load_config_or_warn() -> Config {
    load_config().unwrap_or_else(|e| {
        eprintln!(
            "mermaid: {}",
            crate::utils::redact_secrets(&format!("{e:#}"))
        );
        Config::default()
    })
}

/// Read and parse one layer's TOML file; a missing file is an empty table.
pub(crate) fn read_config_table(path: &std::path::Path) -> Result<toml::Table> {
    if !path.exists() {
        return Ok(toml::Table::new());
    }
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read {}", path.display()))?;
    toml::from_str::<toml::Table>(&raw).with_context(|| {
        format!(
            "Failed to parse {}. Run 'mermaid init' to regenerate.",
            path.display()
        )
    })
}

/// Deep-merge the layers in order (later wins) and deserialize the result
/// once. Unknown-key warnings are collected per layer so each names the file
/// (or flag set) that actually contains the typo.
pub(crate) fn merge_layers(layers: Vec<LayerSource>) -> Result<(Config, Vec<String>)> {
    let mut warnings = Vec::new();
    let mut merged = toml::Table::new();
    for layer in layers {
        collect_layer_warnings(&layer, &mut warnings);
        deep_merge(&mut merged, layer.table);
    }
    let (config, _) = finalize_config(merged)?;
    Ok((config, warnings))
}

/// Run one layer's table through `serde_ignored` purely for warning
/// attribution. A layer that fails to deserialize on its own contributes no
/// warnings — the authoritative merged deserialize in `merge_layers` surfaces
/// any real error (and a later layer may legitimately fix an earlier one's
/// value).
fn collect_layer_warnings(layer: &LayerSource, warnings: &mut Vec<String>) {
    let mut ignored = Vec::new();
    let result: Result<Config, _> =
        serde_ignored::deserialize(toml::Value::Table(layer.table.clone()), |path| {
            ignored.push(path.to_string())
        });
    if result.is_ok() {
        for path in ignored {
            warnings.push(format!(
                "unknown config key '{path}' in {} ({}) — check for a typo",
                layer.layer.name(),
                layer.origin
            ));
        }
    }
}

/// Recursively merge `overlay` into `base`: tables merge key-by-key, while
/// scalars and arrays replace wholesale (arrays are atomic values here — an
/// element-wise merge could never express removing an entry). A kind conflict
/// (table over scalar or vice versa) resolves to the overlay's value.
fn deep_merge(base: &mut toml::Table, overlay: toml::Table) {
    for (key, value) in overlay {
        match (base.get_mut(&key), value) {
            (Some(toml::Value::Table(base_table)), toml::Value::Table(overlay_table)) => {
                deep_merge(base_table, overlay_table);
            },
            (_, value) => {
                base.insert(key, value);
            },
        }
    }
}

/// One-time migration for the AUTO output-budget change. Existing config files
/// froze the old `default_model.max_tokens = 4096` default to disk (`save_config`
/// serializes every field), which would otherwise pin the stale cap forever.
/// Coerce that legacy value to `0` (AUTO) so upgraded users get the model-scaled
/// budget. Applied to the on-disk table *before* CLI overrides, so an explicit
/// `-c default_model.max_tokens=4096` still wins. The only unpreserved case is a
/// user who hand-wrote exactly `4096` in config.toml — an unusual deliberate
/// value, and AUTO is the better default regardless.
fn migrate_legacy_max_tokens(table: &mut toml::Table) {
    if let Some(dm) = table
        .get_mut("default_model")
        .and_then(|v| v.as_table_mut())
        && dm.get("max_tokens").and_then(|v| v.as_integer())
            == Some(LEGACY_DEFAULT_MAX_TOKENS as i64)
    {
        dm.insert("max_tokens".to_string(), toml::Value::Integer(0));
    }
}

/// Migrate the pre-profiles `[model_profiles]` table to its new name,
/// `[model_aliases]` (the `profile` name now belongs to `--profile` config
/// overlays). Runs wherever `migrate_legacy_max_tokens` runs: config loads
/// stop warning immediately, and the next persist converges the file on
/// disk. A file that somehow has BOTH tables keeps `model_aliases`.
fn migrate_legacy_model_profiles(table: &mut toml::Table) {
    if table.contains_key("model_aliases") {
        table.remove("model_profiles");
        return;
    }
    if let Some(profiles) = table.remove("model_profiles") {
        table.insert("model_aliases".to_string(), profiles);
    }
}

/// Deserialize a (possibly merged) config `Table` into `Config`, collecting the
/// dotted paths of any keys `Config` doesn't recognize so the caller can warn.
/// An empty table yields `Config::default()` (every field is `#[serde(default)]`).
fn finalize_config(table: toml::Table) -> Result<(Config, Vec<String>)> {
    let mut ignored = Vec::new();
    let config: Config = serde_ignored::deserialize(toml::Value::Table(table), |path| {
        ignored.push(path.to_string());
    })
    .context("Failed to interpret configuration. Run 'mermaid init' to regenerate.")?;
    Ok((config, ignored))
}

/// Apply repeatable `-c KEY=VALUE` overrides onto a config table. `KEY` is a
/// dotted path (`default_model.model`); `VALUE` is parsed as a TOML scalar so
/// `true`/`3`/`"x"` keep their types, with a bare word treated as a string.
fn apply_cli_overrides(table: &mut toml::Table, overrides: &[String]) -> Result<()> {
    for raw in overrides {
        let (key, val) = raw
            .split_once('=')
            .with_context(|| format!("invalid -c override '{raw}' (expected KEY=VALUE)"))?;
        let key = key.trim();
        if key.is_empty() {
            anyhow::bail!("invalid -c override '{raw}' (empty key)");
        }
        deep_set(table, key, parse_override_value(val.trim()))?;
    }
    Ok(())
}

/// Parse an override value as a standalone TOML value, falling back to a plain
/// string when it isn't valid TOML on its own (e.g. `ollama/qwen`).
fn parse_override_value(s: &str) -> toml::Value {
    toml::from_str::<toml::Table>(&format!("x = {s}"))
        .ok()
        .and_then(|t| t.get("x").cloned())
        .unwrap_or_else(|| toml::Value::String(s.to_string()))
}

/// Set a dotted `key` path in `table` to `value`, creating intermediate
/// tables. Dotted-path parsing means a `-c` override cannot address a map key
/// that itself contains a dot (e.g. a `reasoning_per_model` model id) — a
/// documented syntax limitation; internal persists use
/// [`deep_set_segments`] directly and are immune.
fn deep_set(table: &mut toml::Table, key: &str, value: toml::Value) -> Result<()> {
    let parts: Vec<&str> = key.split('.').collect();
    deep_set_segments(table, &parts, value).with_context(|| format!("cannot set '{key}'"))
}

/// Set a pre-split `path` in `table` to `value`, creating intermediate tables.
/// Segments are literal keys — a segment containing a dot addresses exactly
/// that key (which dotted parsing cannot express).
fn deep_set_segments(table: &mut toml::Table, path: &[&str], value: toml::Value) -> Result<()> {
    let Some((leaf, parents)) = path.split_last() else {
        anyhow::bail!("empty config key path");
    };
    let mut cur = table;
    for part in parents {
        let next = cur
            .entry((*part).to_string())
            .or_insert_with(|| toml::Value::Table(toml::Table::new()));
        cur = next
            .as_table_mut()
            .with_context(|| format!("'{part}' is not a table"))?;
    }
    cur.insert((*leaf).to_string(), value);
    Ok(())
}

/// Remove a pre-split `path` from `table`. Returns whether a value was
/// actually removed. Never creates intermediate tables; a missing parent
/// simply means there was nothing to remove.
pub(crate) fn deep_remove_segments(table: &mut toml::Table, path: &[&str]) -> bool {
    let Some((leaf, parents)) = path.split_last() else {
        return false;
    };
    let mut cur = table;
    for part in parents {
        match cur.get_mut(*part).and_then(|v| v.as_table_mut()) {
            Some(next) => cur = next,
            None => return false,
        }
    }
    cur.remove(*leaf).is_some()
}

/// Like [`load_layered_config`] but never fails — the startup entry point.
/// On success, prints notices and layer-attributed warnings to stderr. On a
/// malformed layer, warns (secret-redacted, #F13) and degrades: the session
/// flags are re-applied over bare defaults so `--no-network`/`-c` survive a
/// corrupt user file rather than being silently dropped with it.
pub fn load_layered_config_or_warn(cwd: Option<&std::path::Path>, flags: &SessionFlags) -> Config {
    match load_layered_config(cwd, flags) {
        Ok(load) => {
            for notice in &load.notices {
                eprintln!("mermaid: {notice}");
            }
            for warning in &load.warnings {
                eprintln!("mermaid: warning: {warning}");
            }
            load.config
        },
        Err(e) => {
            // A TOML parse error renders the offending source line, which can be
            // a secret-bearing one (`extra_headers`/`env`/`api_key_env`); scrub
            // credential-shaped content before it reaches stderr (#F13).
            eprintln!(
                "mermaid: {}",
                crate::utils::redact_secrets(&format!("{e:#}"))
            );
            flags
                .to_table()
                .ok()
                .and_then(|table| finalize_config(table).ok())
                .map(|(config, _)| config)
                .unwrap_or_default()
        },
    }
}

/// Get the path to the single config file
pub fn get_config_path() -> Result<PathBuf> {
    Ok(get_config_dir()?.join("config.toml"))
}

/// Get the configuration directory
pub fn get_config_dir() -> Result<PathBuf> {
    if let Some(proj_dirs) = ProjectDirs::from("", "", "mermaid") {
        let config_dir = proj_dirs.config_dir();
        std::fs::create_dir_all(config_dir)?;
        Ok(config_dir.to_path_buf())
    } else {
        // Fallback to home directory
        let home = std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .context("Could not determine home directory")?;
        let config_dir = PathBuf::from(home).join(".config").join("mermaid");
        std::fs::create_dir_all(&config_dir)?;
        Ok(config_dir)
    }
}

/// Save a full configuration to file. Private on purpose: serializing the
/// whole typed `Config` freezes every default (and would freeze merged
/// project/session values) into the file, so the only legitimate callers are
/// `init_config` (writing pristine defaults to an absent file) and tests.
/// Runtime persistence goes through [`update_user_config_key`] /
/// [`remove_user_config_key`], which rewrite only their own keys.
fn save_config(config: &Config, path: Option<PathBuf>) -> Result<()> {
    let path = if let Some(p) = path {
        p
    } else {
        get_config_dir()?.join("config.toml")
    };
    write_config_bytes(&path, toml::to_string_pretty(config)?.as_bytes())
}

/// Write raw config bytes atomically and owner-only.
///
/// The config can carry literal secrets — `mcp_servers[].env`,
/// `mcp_servers[].args`, `mcp_servers[].headers`, and
/// `providers[].extra_headers` all accept inline credential values — so it
/// must not be left world-readable, and a crash
/// mid-write must not truncate it. Write atomically (temp → fsync → rename),
/// creating the temp 0600 on Unix so the renamed file is never even briefly
/// world-readable (this also tightens a pre-existing config, since the new
/// file replaces the old one). Windows relies on the per-user profile ACL.
fn write_config_bytes(path: &std::path::Path, bytes: &[u8]) -> Result<()> {
    #[cfg(unix)]
    crate::runtime::write_atomic_with_mode(path, bytes, 0o600)
        .with_context(|| format!("Failed to write config to {}", path.display()))?;
    #[cfg(not(unix))]
    crate::runtime::write_atomic(path, bytes)
        .with_context(|| format!("Failed to write config to {}", path.display()))?;
    Ok(())
}

/// Create a default configuration file if it doesn't exist
pub fn init_config() -> Result<()> {
    let config_file = get_config_path()?;

    if config_file.exists() {
        println!("Configuration already exists at: {}", config_file.display());
    } else {
        let default_config = Config::default();
        save_config(&default_config, Some(config_file.clone()))?;
        println!("Created configuration at: {}", config_file.display());
    }

    Ok(())
}

/// Serializes the read-modify-write persistence path. The `persist_*` helpers
/// run as concurrent detached tasks (dispatched by the effect runner) that all
/// load → mutate → save the same file; without a lock two quick toggles
/// (`/model` then Alt+T) can interleave their loads and lose one write. Held
/// only across the synchronous fs work — never across an `.await`.
static PERSIST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Read the raw USER config table, apply `mutate`, and write it back — under
/// `PERSIST_LOCK` so concurrent persists can't clobber each other. Operating
/// on the raw table (never the merged typed `Config`) means a persist rewrites
/// only its own keys: unknown keys survive, defaults are not frozen in, and
/// project-layer or session-flag values can never leak into the user file.
/// A malformed file propagates the parse error rather than being overwritten
/// with defaults (#111).
fn update_user_config_table(mutate: impl FnOnce(&mut toml::Table) -> Result<()>) -> Result<()> {
    update_user_config_table_at(&get_config_path()?, mutate)
}

/// [`update_user_config_table`] against an explicit path (test seam).
fn update_user_config_table_at(
    path: &std::path::Path,
    mutate: impl FnOnce(&mut toml::Table) -> Result<()>,
) -> Result<()> {
    let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let mut table = read_config_table(path)?;
    // Converge the on-disk legacy output cap while we're rewriting anyway.
    migrate_legacy_max_tokens(&mut table);
    migrate_legacy_model_profiles(&mut table);
    mutate(&mut table)?;
    write_config_bytes(path, toml::to_string_pretty(&table)?.as_bytes())
}

/// Set one key (pre-split path segments, so map keys containing dots — e.g.
/// `reasoning_per_model."ollama/qwen3:8b"` — address correctly) in the USER
/// config file, leaving every other key untouched.
pub fn update_user_config_key(path: &[&str], value: toml::Value) -> Result<()> {
    update_user_config_table(|table| deep_set_segments(table, path, value))
}

/// Persist the whole `[plan]` table (the `/plan config` picker). Values the
/// user set through the picker are explicit choices, so writing them —
/// including ones that currently match defaults — is correct; unset Options
/// stay absent via `skip_serializing_if`.
pub fn persist_plan_config(plan: &PlanConfig) -> Result<()> {
    update_user_config_key(&["plan"], toml::Value::try_from(plan)?)
}

/// Remove one key (pre-split path segments) from the USER config file.
/// Returns whether the key existed.
pub fn remove_user_config_key(path: &[&str]) -> Result<bool> {
    let mut removed = false;
    update_user_config_table(|table| {
        removed = deep_remove_segments(table, path);
        Ok(())
    })?;
    Ok(removed)
}

/// Persist the last used model to the user config file.
pub fn persist_last_model(model: &str) -> Result<()> {
    update_user_config_key(&["last_used_model"], toml::Value::String(model.to_string()))
}

/// Persist the TUI theme choice (`/theme dark|light`).
pub fn persist_ui_theme(theme: ThemeChoice) -> Result<()> {
    update_user_config_key(
        &["ui", "theme"],
        toml::Value::String(theme.as_str().to_string()),
    )
}

/// Persist the user's default reasoning level. Used by the `/reasoning` slash
/// command and the Alt+T cycle handler so the choice survives across sessions.
pub fn persist_default_reasoning(level: ReasoningLevel) -> Result<()> {
    update_user_config_key(
        &["default_model", "reasoning"],
        toml::Value::try_from(level)?,
    )
}

/// Persist a reasoning level for a specific model ID
/// (e.g. `<provider>/<model>`). The TUI calls this from Alt+T,
/// `/reasoning <level>`, and the does-not-support-thinking auto-snap so
/// the choice sticks per-model rather than bleeding into other models on
/// next session start.
pub fn persist_reasoning_for_model(model_id: &str, level: ReasoningLevel) -> Result<()> {
    update_user_config_key(
        &["reasoning_per_model", model_id],
        toml::Value::try_from(level)?,
    )
}

/// Persist (or clear) a per-model Ollama `num_ctx` override. `Some(n)` sets it,
/// `None` removes the entry (returning that model to auto-fit).
pub fn persist_ollama_num_ctx_for_model(model_id: &str, num_ctx: Option<u32>) -> Result<()> {
    match num_ctx {
        Some(n) => update_user_config_key(
            &["ollama_num_ctx_per_model", model_id],
            toml::Value::Integer(i64::from(n)),
        ),
        None => remove_user_config_key(&["ollama_num_ctx_per_model", model_id]).map(|_| ()),
    }
}

/// Persist the Ollama RAM-offload toggle (`/context offload on|off`).
pub fn persist_ollama_allow_ram_offload(enabled: bool) -> Result<()> {
    update_user_config_key(
        &["ollama", "allow_ram_offload"],
        toml::Value::Boolean(enabled),
    )
}

/// Resolve which model to use: CLI arg > last_used > default_model > any available
pub async fn resolve_model_id(cli_model: Option<&str>, config: &Config) -> anyhow::Result<String> {
    if let Some(model) = cli_model {
        if let Some(resolved) = resolve_model_alias(model, config)? {
            return Ok(resolved);
        }
        return Ok(model.to_string());
    }
    if let Some(last_model) = &config.last_used_model {
        if let Some(resolved) = resolve_model_alias(last_model, config)? {
            return Ok(resolved);
        }
        return Ok(last_model.clone());
    }
    if !config.default_model.provider.is_empty() && !config.default_model.name.is_empty() {
        return Ok(format!(
            "{}/{}",
            config.default_model.provider, config.default_model.name
        ));
    }
    let available = crate::ollama::require_any_model(config).await?;
    // `require_any_model` already errors on empty, so this `.first()` is
    // never `None` in practice. Use `.first()` over `[0]` so the precondition
    // is enforced by the type system instead of by a comment.
    let first = available
        .first()
        .ok_or_else(|| anyhow::anyhow!("require_any_model returned empty list"))?;
    Ok(format!("ollama/{}", first))
}

fn resolve_model_alias(requested: &str, config: &Config) -> anyhow::Result<Option<String>> {
    let alias = requested.strip_prefix("alias:").unwrap_or(requested);
    if let Some(model) = config.model_aliases.get(alias) {
        anyhow::ensure!(
            !model.trim().is_empty(),
            "model alias `{}` is configured with an empty model id",
            alias
        );
        return Ok(Some(model.clone()));
    }
    if requested.starts_with("alias:") {
        anyhow::bail!(
            "model alias `{}` is not configured; add it under [model_aliases]",
            alias
        );
    }
    Ok(None)
}

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

    #[test]
    fn legacy_default_max_tokens_migrates_to_auto() {
        // The frozen pre-AUTO default (4096) on disk is coerced to 0 = AUTO…
        let mut table: toml::Table =
            toml::from_str("[default_model]\nmax_tokens = 4096\n").unwrap();
        migrate_legacy_max_tokens(&mut table);
        migrate_legacy_model_profiles(&mut table);
        let (config, _) = finalize_config(table).unwrap();
        assert_eq!(config.default_model.max_tokens, 0);

        // …while any other explicit cap is preserved.
        let mut table: toml::Table =
            toml::from_str("[default_model]\nmax_tokens = 8192\n").unwrap();
        migrate_legacy_max_tokens(&mut table);
        migrate_legacy_model_profiles(&mut table);
        let (config, _) = finalize_config(table).unwrap();
        assert_eq!(config.default_model.max_tokens, 8192);

        // A config without the key is untouched (stays the 0 default).
        let mut table = toml::Table::new();
        migrate_legacy_max_tokens(&mut table);
        migrate_legacy_model_profiles(&mut table);
        let (config, _) = finalize_config(table).unwrap();
        assert_eq!(config.default_model.max_tokens, 0);
    }

    #[test]
    fn legacy_model_profiles_table_migrates_to_model_aliases() {
        // Loads stop warning immediately...
        let mut table: toml::Table =
            toml::from_str("[model_profiles]\nfast = \"ollama/qwen3:8b\"\n").unwrap();
        migrate_legacy_model_profiles(&mut table);
        let (config, ignored) = finalize_config(table).unwrap();
        assert_eq!(config.model_aliases["fast"], "ollama/qwen3:8b");
        assert!(ignored.is_empty(), "no unknown-key warning: {ignored:?}");
        // ...and a file with BOTH keeps the new table.
        let mut table: toml::Table =
            toml::from_str("[model_profiles]\nfast = \"old\"\n[model_aliases]\nfast = \"new\"\n")
                .unwrap();
        migrate_legacy_model_profiles(&mut table);
        let (config, ignored) = finalize_config(table).unwrap();
        assert_eq!(config.model_aliases["fast"], "new");
        assert!(ignored.is_empty());
        // ...and the persist path rewrites the key on disk.
        let dir = std::env::temp_dir().join("mermaid_test_model_profiles_migrate");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        std::fs::write(&path, "[model_profiles]\nfast = \"ollama/x\"\n").unwrap();
        update_user_config_table_at(&path, |_| Ok(())).unwrap();
        let blob = std::fs::read_to_string(&path).unwrap();
        assert!(blob.contains("[model_aliases]"), "{blob}");
        assert!(!blob.contains("model_profiles"), "{blob}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn ui_theme_deserializes_defaults_and_rejects_typos() {
        let config: Config = toml::from_str("[ui]\ntheme = \"light\"\n").unwrap();
        assert_eq!(config.ui.theme, ThemeChoice::Light);
        // Absent → dark, both from an empty file and from Config::default().
        let config: Config = toml::from_str("").unwrap();
        assert_eq!(config.ui.theme, ThemeChoice::Dark);
        assert_eq!(Config::default().ui.theme, ThemeChoice::Dark);
        // Typos are a clear deserialize error, not a silent fallback.
        assert!(toml::from_str::<Config>("[ui]\ntheme = \"solarized\"\n").is_err());
    }

    #[test]
    fn finalize_config_flags_unknown_keys() {
        let table: toml::Table =
            toml::from_str("unknown_top = 1\n[default_model]\nmax_tokens = 512\nbogus = true\n")
                .unwrap();
        let (config, ignored) = finalize_config(table).expect("finalizes despite unknown keys");
        assert_eq!(config.default_model.max_tokens, 512);
        assert!(
            ignored.iter().any(|p| p == "unknown_top"),
            "got {ignored:?}"
        );
        assert!(
            ignored.iter().any(|p| p.contains("bogus")),
            "got {ignored:?}"
        );
    }

    #[test]
    fn cli_overrides_beat_file_and_create_nested_tables() {
        // Override beats the file value...
        let mut table: toml::Table = toml::from_str("[default_model]\nmax_tokens = 100\n").unwrap();
        apply_cli_overrides(&mut table, &["default_model.max_tokens=8192".to_string()]).unwrap();
        let (config, ignored) = finalize_config(table).unwrap();
        assert_eq!(config.default_model.max_tokens, 8192);
        assert!(ignored.is_empty());
        // ...and creates a section absent from the file.
        let mut empty = toml::Table::new();
        apply_cli_overrides(&mut empty, &["default_model.max_tokens=256".to_string()]).unwrap();
        assert_eq!(
            finalize_config(empty).unwrap().0.default_model.max_tokens,
            256
        );
    }

    #[test]
    fn parse_override_value_keeps_toml_types_with_string_fallback() {
        assert_eq!(parse_override_value("true"), toml::Value::Boolean(true));
        assert_eq!(parse_override_value("42"), toml::Value::Integer(42));
        assert_eq!(
            parse_override_value("ollama/qwen"),
            toml::Value::String("ollama/qwen".to_string())
        );
    }

    #[test]
    fn cli_override_invalid_format_errors() {
        let mut table = toml::Table::new();
        assert!(apply_cli_overrides(&mut table, &["noequalssign".to_string()]).is_err());
        assert!(apply_cli_overrides(&mut table, &["=novalue".to_string()]).is_err());
    }

    #[test]
    fn deep_merge_recurses_tables_and_replaces_scalars_and_arrays() {
        let mut base: toml::Table = toml::from_str(
            "top = 1\n[ollama]\nhost = \"localhost\"\nport = 11434\n[safety]\noverrides = [\"a\", \"b\"]\n",
        )
        .unwrap();
        let overlay: toml::Table =
            toml::from_str("[ollama]\nhost = \"gpu-box\"\n[safety]\noverrides = [\"c\"]\n")
                .unwrap();
        deep_merge(&mut base, overlay);
        // Sibling keys inside a merged table survive...
        assert_eq!(base["ollama"]["port"].as_integer(), Some(11434));
        // ...the overlaid scalar wins...
        assert_eq!(base["ollama"]["host"].as_str(), Some("gpu-box"));
        // ...arrays replace wholesale (no concat)...
        assert_eq!(base["safety"]["overrides"].as_array().unwrap().len(), 1);
        // ...and untouched top-level keys survive.
        assert_eq!(base["top"].as_integer(), Some(1));
    }

    #[test]
    fn deep_merge_overlay_wins_on_kind_conflict() {
        // Scalar over table and table over scalar both resolve to the overlay.
        let mut base: toml::Table = toml::from_str("[a]\nx = 1\nb = 2\n").unwrap();
        let overlay: toml::Table = toml::from_str("a = 5\n[b]\ny = 3\n").unwrap();
        deep_merge(&mut base, overlay);
        assert_eq!(base["a"].as_integer(), Some(5));
        assert_eq!(base["b"]["y"].as_integer(), Some(3));
    }

    #[test]
    fn merge_layers_precedence_and_layer_attributed_warnings() {
        let user: toml::Table = toml::from_str(
            "last_used_model = \"ollama/a\"\nuser_typo = 1\n[default_model]\nmax_tokens = 100\n",
        )
        .unwrap();
        let session: toml::Table =
            toml::from_str("last_used_model = \"ollama/b\"\nsession_typo = 2\n").unwrap();
        let (config, warnings) = merge_layers(vec![
            LayerSource {
                layer: ConfigLayer::User,
                origin: "/tmp/user.toml".to_string(),
                table: user,
            },
            LayerSource {
                layer: ConfigLayer::Session,
                origin: "command line".to_string(),
                table: session,
            },
        ])
        .expect("merges");
        // Later layer wins; earlier layer's untouched keys survive.
        assert_eq!(config.last_used_model.as_deref(), Some("ollama/b"));
        assert_eq!(config.default_model.max_tokens, 100);
        // Each unknown key names its own layer + origin.
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("user_typo") && w.contains("user config (/tmp/user.toml)")),
            "got {warnings:?}"
        );
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("session_typo") && w.contains("session flags")),
            "got {warnings:?}"
        );
    }

    #[test]
    fn take_profiles_excises_and_tolerates_absence() {
        let mut table: toml::Table =
            toml::from_str("[profiles.fast.default_model]\ntemperature = 0.1\n").unwrap();
        let profiles = take_profiles(&mut table);
        assert!(table.is_empty(), "profiles must be excised: {table:?}");
        assert!(profiles.contains_key("fast"));
        // Absent -> empty, table untouched.
        let mut table: toml::Table = toml::from_str("last_used_model = \"x\"\n").unwrap();
        assert!(take_profiles(&mut table).is_empty());
        assert_eq!(table.len(), 1);
        // Malformed (non-table) -> dropped, empty result.
        let mut table: toml::Table = toml::from_str("profiles = 3\n").unwrap();
        assert!(take_profiles(&mut table).is_empty());
        assert!(table.is_empty());
    }

    #[test]
    fn resolve_profile_layer_errors_name_available_profiles() {
        let profiles: toml::Table = toml::from_str("[work]\n[fast]\n").unwrap();
        let path = std::path::Path::new("/tmp/config.toml");
        let err = resolve_profile_layer(&profiles, "nope", path).unwrap_err();
        assert!(err.to_string().contains("available: fast, work"), "{err}");
        // No profiles at all -> a distinct, actionable error.
        let err = resolve_profile_layer(&toml::Table::new(), "work", path).unwrap_err();
        assert!(
            err.to_string().contains("no config profiles defined"),
            "{err}"
        );
        // Non-table profile value -> hard error.
        let profiles: toml::Table = toml::from_str("work = 1\n").unwrap();
        let err = resolve_profile_layer(&profiles, "work", path).unwrap_err();
        assert!(err.to_string().contains("not a table"), "{err}");
        // Hit -> Profile layer with attributing origin.
        let profiles: toml::Table =
            toml::from_str("[work.default_model]\ntemperature = 0.2\n").unwrap();
        let layer = resolve_profile_layer(&profiles, "work", path).unwrap();
        assert_eq!(layer.layer, ConfigLayer::Profile);
        assert!(layer.origin.contains("profile:work"));
    }

    #[test]
    fn profile_layer_beats_user_loses_to_project_and_session() {
        let user: toml::Table = toml::from_str(
            "last_used_model = \"ollama/user\"\n[default_model]\ntemperature = 0.9\nmax_tokens = 100\n",
        )
        .unwrap();
        let profile: toml::Table = toml::from_str(
            "last_used_model = \"ollama/profile\"\n[default_model]\ntemperature = 0.1\nprofile_typo = 1\n",
        )
        .unwrap();
        let project: toml::Table = toml::from_str("[default_model]\ntemperature = 0.5\n").unwrap();
        let session: toml::Table =
            toml::from_str("last_used_model = \"ollama/session\"\n").unwrap();
        let (config, warnings) = merge_layers(vec![
            LayerSource {
                layer: ConfigLayer::User,
                origin: "/tmp/user.toml".to_string(),
                table: user,
            },
            LayerSource {
                layer: ConfigLayer::Profile,
                origin: "profile:work (/tmp/user.toml)".to_string(),
                table: profile,
            },
            LayerSource {
                layer: ConfigLayer::Project,
                origin: "/repo/.mermaid/config.toml".to_string(),
                table: project,
            },
            LayerSource {
                layer: ConfigLayer::Session,
                origin: "command line".to_string(),
                table: session,
            },
        ])
        .expect("merges");
        // Project beats profile; session beats everything; profile beats user
        // where later layers are silent.
        assert_eq!(config.default_model.temperature, 0.5);
        assert_eq!(config.last_used_model.as_deref(), Some("ollama/session"));
        assert_eq!(config.default_model.max_tokens, 100);
        // Unknown keys inside the profile attribute to it.
        assert!(
            warnings.iter().any(|w| w.contains("profile_typo")
                && w.contains("config profile (profile:work (/tmp/user.toml))")),
            "got {warnings:?}"
        );
    }

    #[test]
    fn persists_never_touch_profile_tables() {
        let dir = std::env::temp_dir().join("mermaid_test_profiles_persist");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");
        std::fs::write(
            &path,
            "[profiles.fast.default_model]\ntemperature = 0.1\n\n[safety]\nmode = \"ask\"\n",
        )
        .expect("seed");

        update_user_config_table_at(&path, |table| {
            deep_set_segments(
                table,
                &["safety", "mode"],
                toml::Value::String("auto".to_string()),
            )
        })
        .expect("persist");

        let table: toml::Table =
            toml::from_str(&std::fs::read_to_string(&path).expect("read back")).expect("parse");
        assert_eq!(table["safety"]["mode"].as_str(), Some("auto"));
        // The overlay table survives persists byte-for-byte semantically.
        assert_eq!(
            table["profiles"]["fast"]["default_model"]["temperature"].as_float(),
            Some(0.1)
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn session_flags_table_maps_each_flag() {
        let flags = SessionFlags {
            overrides: vec!["web.searxng_url=\"http://x:1\"".to_string()],
            deny_network: true,
            confine_fs: true,
            max_tokens: Some(512),
            allow_untrusted_tools: true,
            profile: None,
        };
        let (config, _) = finalize_config(flags.to_table().unwrap()).unwrap();
        assert_eq!(config.safety.network, NetworkPolicy::Deny);
        assert_eq!(config.safety.filesystem, FilesystemPolicy::Project);
        assert_eq!(config.default_model.max_tokens, 512);
        assert!(config.safety.allow_untrusted_headless_tools);
        assert_eq!(config.web.searxng_url, "http://x:1");
    }

    #[test]
    fn session_dedicated_flags_beat_dash_c() {
        // `--no-network` wins over a contradictory `-c safety.network=allow`
        // (the dedicated flags deep-set after the -c overrides).
        let flags = SessionFlags {
            overrides: vec!["safety.network=allow".to_string()],
            deny_network: true,
            ..Default::default()
        };
        let (config, _) = finalize_config(flags.to_table().unwrap()).unwrap();
        assert_eq!(config.safety.network, NetworkPolicy::Deny);
    }

    #[test]
    fn corrupt_layer_yields_no_warnings_but_merged_error_surfaces() {
        // A layer that doesn't deserialize on its own contributes no warnings…
        let bad: toml::Table = toml::from_str("[safety]\nmode = 42\n").unwrap();
        let mut warnings = Vec::new();
        collect_layer_warnings(
            &LayerSource {
                layer: ConfigLayer::User,
                origin: "x".to_string(),
                table: bad.clone(),
            },
            &mut warnings,
        );
        assert!(warnings.is_empty());
        // …and the merged deserialize is what errors…
        assert!(
            merge_layers(vec![LayerSource {
                layer: ConfigLayer::User,
                origin: "x".to_string(),
                table: bad.clone(),
            }])
            .is_err()
        );
        // …unless a later layer fixes the value (session repairing a bad file).
        let fix: toml::Table = toml::from_str("[safety]\nmode = \"ask\"\n").unwrap();
        let (config, _) = merge_layers(vec![
            LayerSource {
                layer: ConfigLayer::User,
                origin: "x".to_string(),
                table: bad,
            },
            LayerSource {
                layer: ConfigLayer::Session,
                origin: "command line".to_string(),
                table: fix,
            },
        ])
        .expect("later layer repairs the earlier one");
        assert_eq!(config.safety.mode, SafetyMode::Ask);
    }

    #[test]
    fn project_layer_beats_user_and_loses_to_session() {
        let user: toml::Table = toml::from_str("last_used_model = \"ollama/user\"\n").unwrap();
        let project: toml::Table = toml::from_str(
            "last_used_model = \"ollama/project\"\n[default_model]\nreasoning = \"low\"\n",
        )
        .unwrap();
        let session: toml::Table =
            toml::from_str("last_used_model = \"ollama/session\"\n").unwrap();
        let (config, _) = merge_layers(vec![
            LayerSource {
                layer: ConfigLayer::User,
                origin: "user".to_string(),
                table: user,
            },
            LayerSource {
                layer: ConfigLayer::Project,
                origin: "project".to_string(),
                table: project,
            },
            LayerSource {
                layer: ConfigLayer::Session,
                origin: "command line".to_string(),
                table: session,
            },
        ])
        .expect("merges");
        // Session beats project beats user for the contested key…
        assert_eq!(config.last_used_model.as_deref(), Some("ollama/session"));
        // …while the project's uncontested key lands.
        assert_eq!(config.default_model.reasoning, ReasoningLevel::Low);
    }

    #[test]
    fn session_flags_survive_corrupt_user_layer_fallback() {
        // The or_warn fallback re-applies the session flags over bare defaults;
        // pin the exact expression it uses.
        let flags = SessionFlags {
            deny_network: true,
            ..Default::default()
        };
        let config = flags
            .to_table()
            .ok()
            .and_then(|table| finalize_config(table).ok())
            .map(|(config, _)| config)
            .unwrap_or_default();
        assert_eq!(config.safety.network, NetworkPolicy::Deny);
    }

    #[test]
    fn deep_set_segments_addresses_keys_containing_dots() {
        // A model id with dots must be ONE key, which dotted parsing cannot
        // express — the latent bug the segment API fixes.
        let mut table = toml::Table::new();
        deep_set_segments(
            &mut table,
            &["reasoning_per_model", "gemini/gemini-2.5-pro"],
            toml::Value::String("high".to_string()),
        )
        .unwrap();
        let (config, ignored) = finalize_config(table).unwrap();
        assert!(ignored.is_empty(), "got {ignored:?}");
        assert_eq!(
            config.reasoning_per_model.get("gemini/gemini-2.5-pro"),
            Some(&ReasoningLevel::High)
        );
    }

    #[test]
    fn deep_remove_segments_removes_leaf_only() {
        let mut table: toml::Table =
            toml::from_str("[ollama_num_ctx_per_model]\n\"ollama/a\" = 1\n\"ollama/b\" = 2\n")
                .unwrap();
        assert!(deep_remove_segments(
            &mut table,
            &["ollama_num_ctx_per_model", "ollama/a"]
        ));
        // Sibling survives; parent table survives; missing keys report false.
        assert_eq!(
            table["ollama_num_ctx_per_model"]["ollama/b"].as_integer(),
            Some(2)
        );
        assert!(!deep_remove_segments(
            &mut table,
            &["ollama_num_ctx_per_model", "ollama/a"]
        ));
        assert!(!deep_remove_segments(&mut table, &["nope", "x"]));
    }

    #[test]
    fn update_user_config_table_preserves_unknown_keys() {
        let dir = std::env::temp_dir().join("mermaid_test_config_targeted_persist");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");
        // A file with an unknown key (maybe from a newer mermaid) and one known
        // setting the persist must not disturb.
        std::fs::write(
            &path,
            "future_key = \"kept\"\nlast_used_model = \"ollama/old\"\n\n[ollama]\nport = 12345\n",
        )
        .expect("seed");

        update_user_config_table_at(&path, |table| {
            deep_set_segments(
                table,
                &["last_used_model"],
                toml::Value::String("ollama/new".to_string()),
            )
        })
        .expect("persist");

        let blob = std::fs::read_to_string(&path).expect("read back");
        let table: toml::Table = toml::from_str(&blob).expect("parse back");
        // The targeted key changed…
        assert_eq!(table["last_used_model"].as_str(), Some("ollama/new"));
        // …the unknown key survived (typed round-trips would have dropped it)…
        assert_eq!(table["future_key"].as_str(), Some("kept"));
        // …and no defaults were frozen in (only the keys that were there).
        assert!(!blob.contains("safety"), "defaults must not be frozen in");
        assert_eq!(table["ollama"]["port"].as_integer(), Some(12345));

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

    #[test]
    fn mcp_tool_allowed_honors_enabled_and_disabled() {
        // Default (both empty) allows everything.
        let cfg = McpServerConfig::default();
        assert!(cfg.tool_allowed("anything"));
        // enabled_tools acts as an allowlist.
        let cfg = McpServerConfig {
            enabled_tools: vec!["read".into(), "search".into()],
            ..Default::default()
        };
        assert!(cfg.tool_allowed("read"));
        assert!(!cfg.tool_allowed("write"));
        // disabled_tools wins over enabled_tools.
        let cfg = McpServerConfig {
            enabled_tools: vec!["read".into(), "write".into()],
            disabled_tools: vec!["write".into()],
            ..Default::default()
        };
        assert!(cfg.tool_allowed("read"));
        assert!(!cfg.tool_allowed("write"));
    }

    #[test]
    fn mcp_transport_kind_requires_exactly_one_of_command_and_url() {
        // command-only → stdio.
        let cfg = McpServerConfig {
            command: "npx".to_string(),
            ..Default::default()
        };
        assert_eq!(cfg.transport_kind().unwrap(), TransportKind::Stdio);
        // url-only → http.
        let cfg = McpServerConfig {
            url: Some("https://example.com/mcp".to_string()),
            ..Default::default()
        };
        assert_eq!(cfg.transport_kind().unwrap(), TransportKind::Http);
        // Both set → error.
        let cfg = McpServerConfig {
            command: "npx".to_string(),
            url: Some("https://example.com/mcp".to_string()),
            ..Default::default()
        };
        assert!(
            cfg.transport_kind()
                .unwrap_err()
                .to_string()
                .contains("mutually exclusive")
        );
        // Neither set → error.
        let cfg = McpServerConfig::default();
        assert!(
            cfg.transport_kind()
                .unwrap_err()
                .to_string()
                .contains("neither")
        );
    }

    #[test]
    fn mcp_transport_kind_gates_url_scheme() {
        let with_url = |url: &str| McpServerConfig {
            url: Some(url.to_string()),
            ..Default::default()
        };
        // https anywhere is fine; http only to loopback (plaintext to a
        // routable host would leak auth headers).
        assert!(
            with_url("https://mcp.example.com/x")
                .transport_kind()
                .is_ok()
        );
        assert!(
            with_url("http://localhost:8080/mcp")
                .transport_kind()
                .is_ok()
        );
        assert!(
            with_url("http://127.0.0.1:8080/mcp")
                .transport_kind()
                .is_ok()
        );
        assert!(with_url("http://192.168.1.5/mcp").transport_kind().is_err());
        assert!(with_url("ftp://example.com/mcp").transport_kind().is_err());
        assert!(with_url("not a url").transport_kind().is_err());
    }

    #[test]
    fn mcp_server_config_debug_masks_header_values() {
        let mut headers = HashMap::new();
        headers.insert("Authorization".to_string(), "Bearer sk-secret".to_string());
        let mut env_headers = HashMap::new();
        env_headers.insert("X-Api-Key".to_string(), "MY_TOKEN_VAR".to_string());
        let cfg = McpServerConfig {
            url: Some("https://example.com/mcp".to_string()),
            headers,
            env_headers,
            ..Default::default()
        };
        let rendered = format!("{cfg:?}");
        assert!(!rendered.contains("sk-secret"), "{rendered}");
        assert!(rendered.contains("Authorization"), "{rendered}");
        // env_headers values are env var NAMES, safe to render.
        assert!(rendered.contains("MY_TOKEN_VAR"), "{rendered}");
    }

    #[test]
    fn mcp_url_config_round_trips_through_toml_without_command() {
        // `mermaid add --url` persists via toml::Value::try_from; a bare None
        // url or a forced empty `command` key would break that round-trip.
        let cfg = McpServerConfig {
            url: Some("https://example.com/mcp".to_string()),
            ..Default::default()
        };
        let blob = toml::to_string(&toml::Value::try_from(&cfg).unwrap()).unwrap();
        assert!(
            !blob.contains("command"),
            "empty command must be omitted: {blob}"
        );
        let back: McpServerConfig = toml::from_str(&blob).unwrap();
        assert_eq!(back.url.as_deref(), Some("https://example.com/mcp"));
        assert!(back.command.is_empty());
        // And a stdio config must not serialize a `url` key at all.
        let cfg = McpServerConfig {
            command: "npx".to_string(),
            ..Default::default()
        };
        let blob = toml::to_string(&toml::Value::try_from(&cfg).unwrap()).unwrap();
        assert!(!blob.contains("url"), "{blob}");
    }

    /// Configs persisted before Step 4 don't have a `reasoning` field on
    /// `[default_model]`. Loading them must succeed and yield the
    /// `Medium` default — otherwise existing user configs break on
    /// upgrade.
    #[test]
    fn model_settings_deserializes_without_reasoning_field() {
        let toml_blob = r#"
            provider = "ollama"
            name = "qwen3-coder:30b"
            temperature = 0.7
            max_tokens = 4096
        "#;
        let settings: ModelSettings = toml::from_str(toml_blob).expect("backward compat");
        assert_eq!(settings.reasoning, ReasoningLevel::Medium);
        assert_eq!(settings.provider, "ollama");
    }

    #[test]
    fn model_settings_round_trips_reasoning_high() {
        let original = ModelSettings {
            provider: "anthropic".to_string(),
            name: "claude-sonnet-4-6".to_string(),
            temperature: 0.5,
            max_tokens: 8192,
            reasoning: ReasoningLevel::High,
        };
        let toml_blob = toml::to_string(&original).expect("serialize");
        let back: ModelSettings = toml::from_str(&toml_blob).expect("deserialize");
        assert_eq!(back.reasoning, ReasoningLevel::High);
        assert_eq!(back.name, "claude-sonnet-4-6");
    }

    #[test]
    fn agents_config_defaults_and_parses_custom_types() {
        // Absent section → defaults (20-minute timeout, no custom types).
        let config: Config = toml::from_str("").expect("empty config parses");
        assert_eq!(config.agents.timeout_secs, 1200);
        assert!(config.agents.types.is_empty());

        let config: Config = toml::from_str(
            r#"
[agents]
timeout_secs = 300

[agents.types.scout]
tools = ["read_file", "execute_command"]
safety = "read_only"
preamble = "You are a scout."
model = "ollama/qwen3:8b"
"#,
        )
        .expect("agents section parses");
        assert_eq!(config.agents.timeout_secs, 300);
        let scout = &config.agents.types["scout"];
        assert_eq!(
            scout.tools.as_deref(),
            Some(&["read_file".to_string(), "execute_command".to_string()][..])
        );
        assert_eq!(scout.safety.as_deref(), Some("read_only"));
        assert_eq!(scout.model.as_deref(), Some("ollama/qwen3:8b"));
    }

    #[test]
    fn configured_model_alias_resolves_explicit_prefix() {
        let mut config = Config::default();
        config
            .model_aliases
            .insert("fast".to_string(), "ollama/qwen3-coder:14b".to_string());
        assert_eq!(
            resolve_model_alias("fast", &config).unwrap(),
            Some("ollama/qwen3-coder:14b".to_string())
        );
        assert_eq!(
            resolve_model_alias("alias:fast", &config).unwrap(),
            Some("ollama/qwen3-coder:14b".to_string())
        );
    }

    #[test]
    fn alias_prefix_requires_configuration() {
        let config = Config::default();
        assert!(resolve_model_alias("alias:vision", &config).is_err());
        assert_eq!(resolve_model_alias("vision", &config).unwrap(), None);
    }

    /// `persist_default_reasoning` writes to the real config path, so
    /// this test goes through `save_config(_, Some(path))` directly to
    /// avoid clobbering the user's actual `~/.config/mermaid/config.toml`.
    /// Uses `std::env::temp_dir` (matching the pattern in
    /// `session::conversation` and `utils::logger`) — no external
    /// `tempfile` crate dependency.
    #[test]
    fn save_and_reload_preserves_reasoning_field() {
        let dir = std::env::temp_dir().join("mermaid_test_config_reasoning");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");

        let mut cfg = Config::default();
        cfg.default_model.provider = "ollama".to_string();
        cfg.default_model.name = "qwen3-coder:30b".to_string();
        cfg.default_model.reasoning = ReasoningLevel::Low;

        save_config(&cfg, Some(path.clone())).expect("save");

        let blob = std::fs::read_to_string(&path).expect("read");
        let loaded: Config = toml::from_str(&blob).expect("parse back");
        assert_eq!(loaded.default_model.reasoning, ReasoningLevel::Low);

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

    /// Per-model entries serialize as a TOML table with quoted keys (the
    /// model IDs contain `/`). This test verifies the round-trip works
    /// through both serialization and deserialization, matching what
    /// `persist_reasoning_for_model` would produce in real use.
    #[test]
    fn save_and_reload_preserves_reasoning_per_model_table() {
        let dir = std::env::temp_dir().join("mermaid_test_config_per_model_reasoning");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");

        let mut cfg = Config::default();
        cfg.reasoning_per_model.insert(
            "anthropic/claude-sonnet-4-6".to_string(),
            ReasoningLevel::High,
        );
        cfg.reasoning_per_model
            .insert("ollama/qwen3-coder:30b".to_string(), ReasoningLevel::Low);

        save_config(&cfg, Some(path.clone())).expect("save");

        let blob = std::fs::read_to_string(&path).expect("read");
        let loaded: Config = toml::from_str(&blob).expect("parse back");
        assert_eq!(
            loaded
                .reasoning_per_model
                .get("anthropic/claude-sonnet-4-6"),
            Some(&ReasoningLevel::High)
        );
        assert_eq!(
            loaded.reasoning_per_model.get("ollama/qwen3-coder:30b"),
            Some(&ReasoningLevel::Low)
        );

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

    /// `/context <n>` overrides round-trip through the per-model TOML table, and
    /// the offload toggle persists on `[ollama]`.
    #[test]
    fn save_and_reload_preserves_ollama_context_overrides() {
        let dir = std::env::temp_dir().join("mermaid_test_config_ollama_ctx");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");

        let mut cfg = Config::default();
        cfg.ollama_num_ctx_per_model
            .insert("ollama/ornith:9b".to_string(), 131_072);
        cfg.ollama.allow_ram_offload = true;
        cfg.ollama.max_auto_num_ctx = Some(65_536);

        save_config(&cfg, Some(path.clone())).expect("save");
        let blob = std::fs::read_to_string(&path).expect("read");
        let loaded: Config = toml::from_str(&blob).expect("parse back");

        assert_eq!(
            loaded.ollama_num_ctx_per_model.get("ollama/ornith:9b"),
            Some(&131_072)
        );
        assert!(loaded.ollama.allow_ram_offload);
        assert_eq!(loaded.ollama.max_auto_num_ctx, Some(65_536));

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

    /// Older configs have neither the per-model num_ctx table nor the new
    /// `[ollama]` keys; loading must default cleanly (empty map, offload off).
    #[test]
    fn config_deserializes_without_ollama_context_keys() {
        let toml_blob = r#"
[ollama]
host = "localhost"
port = 11434
"#;
        let cfg: Config = toml::from_str(toml_blob).expect("parse");
        assert!(cfg.ollama_num_ctx_per_model.is_empty());
        assert!(!cfg.ollama.allow_ram_offload);
        assert_eq!(cfg.ollama.max_auto_num_ctx, None);
        // Configs from before the auto-start knob default it ON — reviving a
        // dead local server is the out-of-the-box behavior.
        assert!(cfg.ollama.auto_start);
    }

    /// Configs from before Step 5b don't have a `reasoning_per_model`
    /// section. Loading them must succeed with an empty map — otherwise
    /// upgrade breaks every existing user.
    #[test]
    fn config_deserializes_without_reasoning_per_model() {
        let toml_blob = r#"
            last_used_model = "ollama/qwen3-coder:30b"

            [default_model]
            provider = "ollama"
            name = "qwen3-coder:30b"
            temperature = 0.7
            max_tokens = 4096
        "#;
        let cfg: Config = toml::from_str(toml_blob).expect("backward compat");
        assert!(cfg.reasoning_per_model.is_empty());
        assert!(!cfg.prompt.is_customized());
    }

    /// Config holds inline-secret-capable fields (`mcp_servers[].env`, `args`,
    /// `headers`, `providers[].extra_headers`), so it must be written
    /// owner-only rather than inheriting a world-readable umask.
    #[cfg(unix)]
    #[test]
    fn save_config_writes_owner_only_perms() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join("mermaid_test_config_perms");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");
        // Pre-create a world-readable file to prove we also tighten existing.
        std::fs::write(&path, "stale").expect("seed");
        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644));

        save_config(&Config::default(), Some(path.clone())).expect("save");
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "config must be written owner-only");

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

    #[test]
    fn config_defaults_computer_use_auto_screenshot_on() {
        // An empty/legacy config must keep the auto-screenshot behavior (#98).
        let cfg: Config = toml::from_str("").expect("empty config");
        assert!(cfg.computer_use.auto_screenshot);
    }

    #[test]
    fn prompt_config_replaces_and_appends_without_persisting() {
        let mut cfg = Config::default();
        cfg.prompt.system_prompt = Some("base".to_string());
        cfg.prompt
            .append_system_prompt
            .push("extra instructions".to_string());

        assert_eq!(
            cfg.prompt.render_system_prompt("default"),
            "base\n\nextra instructions"
        );

        let blob = toml::to_string(&cfg).expect("serialize");
        assert!(!blob.contains("extra instructions"));
        let loaded: Config = toml::from_str(&blob).expect("deserialize");
        assert!(!loaded.prompt.is_customized());
    }

    #[test]
    fn plan_config_defaults_parse_and_do_not_freeze() {
        // Absent section: dialog on, nothing pinned.
        let c: Config = toml::from_str("").expect("empty config parses");
        assert!(!c.plan.auto_approve);
        assert!(c.plan.post_approve.is_none());
        // Explicit values parse.
        let c: Config = toml::from_str("[plan]\nauto_approve = true\npost_approve = \"start\"\n")
            .expect("plan section parses");
        assert!(c.plan.auto_approve);
        assert_eq!(c.plan.post_approve, Some(PlanPostApprove::Start));
        assert_eq!(
            toml::from_str::<Config>("[plan]\npost_approve = \"wait\"\n")
                .expect("wait parses")
                .plan
                .post_approve,
            Some(PlanPostApprove::Wait)
        );
        // The unset pin is never frozen into a saved config (Option +
        // skip_serializing_if), so a future default change still reaches
        // existing files.
        let blob = toml::to_string(&Config::default()).expect("serialize");
        assert!(!blob.contains("post_approve"));
    }
}