whycodes-config 0.6.29

Configuration load, merge, and validation for WhyCodes
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
//! Config schema types and serde defaults.
//!
//! Leaf types (`Message`, `Tool`, sandbox policy) live in `whycodes-core`.
//! This module owns the user-facing `Config` tree.

use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;

use whycodes_core::network::{self, NetworkPolicy};
use whycodes_core::sandbox::SandboxSettings;
use whycodes_core::types::{
    AgentInfo, ApprovalMode, ModelConfig, PermissionAction, ProviderConfig,
};

/// First-run / CLI fallback provider when nothing is configured.
pub const DEFAULT_PROVIDER: &str = "openrouter";
/// OpenRouter model id used as the first-run default.
pub const DEFAULT_MODEL_ID: &str = "anthropic/claude-sonnet-4.5";

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CommandConfig {
    /// Override the model for this command
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<ModelConfig>,

    /// Override the agent for this command
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent: Option<String>,

    /// Override the max turns for this command
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_turns: Option<usize>,
}

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// API provider configurations
    #[serde(default)]
    pub providers: HashMap<String, ProviderConfig>,

    /// Model configurations
    #[serde(default)]
    pub models: HashMap<String, ModelConfig>,
    /// USD per million tokens, keyed `"provider/model"`. Overrides prices
    /// learned from the provider's `/v1/models` catalog.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub pricing: HashMap<String, PriceConfig>,

    /// Agent definitions
    #[serde(default)]
    pub agents: Vec<AgentInfo>,

    /// Default agent name
    #[serde(default = "default_agent")]
    pub default_agent: String,

    /// Default model
    #[serde(default)]
    pub default_model: Option<ModelConfig>,

    /// Per-command configuration overrides
    #[serde(default)]
    pub command_configs: HashMap<String, CommandConfig>,

    /// Tools configuration
    #[serde(default)]
    pub tools: ToolsConfig,

    /// Session configuration
    #[serde(default)]
    pub session: SessionConfig,

    /// TUI configuration
    #[serde(default)]
    pub tui: TuiConfig,

    /// General settings
    #[serde(default)]
    pub general: GeneralConfig,

    /// On-disk schema version. Missing / `0` is migrated to
    /// [`CONFIG_SCHEMA_VERSION`] on load.
    #[serde(default)]
    pub schema_version: u32,

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

    /// Language-server overlay. Empty `servers` keeps built-in auto-detect.
    #[serde(default)]
    pub lsp: LspConfig,

    /// Global tool permissions (allow/ask/deny).
    /// Merged into each agent; agent-level `permission.rules` wins on conflict.
    #[serde(default)]
    pub permission: HashMap<String, PermissionAction>,

    /// Custom slash commands keyed by name (from config.toml + markdown files)
    #[serde(default)]
    pub commands: HashMap<String, CustomCommandConfig>,

    /// Shell command risk gating.
    #[serde(default)]
    pub security: SecurityConfig,

    /// Pre/post tool hooks (shell commands). Empty by default.
    #[serde(default)]
    pub hooks: Vec<HookConfig>,

    /// Cross-session semantic / auto memory.
    #[serde(default)]
    pub memory: MemoryConfig,

    /// Parallel multi-agent swarm + file conflict notify.
    #[serde(default)]
    pub swarm: SwarmConfig,

    /// Background jobs and lightweight scheduling (FEATURES §11).
    #[serde(default)]
    pub automation: AutomationConfig,

    /// Discord / Telegram session notifications (off by default).
    #[serde(default)]
    pub notify: NotifyConfig,

    /// Code-slop tripwires (`whycodes slop` / `/slop`). Not a training objective.
    #[serde(default)]
    pub slop: SlopConfig,

    /// `websearch` engine choice, fallback order, and the custom endpoint.
    #[serde(default)]
    pub websearch: WebSearchConfig,

    /// Extra system-prompt text loaded from `prompts/*.md` (not stored in TOML).
    #[serde(default, skip)]
    pub system_prompt_overlays: SystemPromptOverlays,
}

/// Verbosity / erosion / ΔLOC tripwires. Default `verdict` is `review`, not block.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SlopConfig {
    /// Review when verbosity ≥ this (default 0.25).
    #[serde(default = "default_slop_verbosity")]
    pub verbosity: f64,
    /// Review when erosion ≥ this (default 0.50).
    #[serde(default = "default_slop_erosion")]
    pub erosion: f64,
    /// Review when |ΔLOC| of the diff ≥ this (default 800).
    #[serde(default = "default_slop_delta_loc")]
    pub delta_loc: i64,
    /// Block when verbosity ≥ this (default 0.40).
    #[serde(default = "default_slop_block_verbosity")]
    pub block_verbosity: f64,
    /// Block when erosion ≥ this (default 0.75).
    #[serde(default = "default_slop_block_erosion")]
    pub block_erosion: f64,
    /// Block when ΔLOC ≥ this (default 5000).
    #[serde(default = "default_slop_block_delta_loc")]
    pub block_delta_loc: i64,
    /// How many hotspot functions to list (default 8).
    #[serde(default = "default_slop_hotspots")]
    pub hotspots: usize,
}

pub(crate) fn default_slop_verbosity() -> f64 {
    0.25
}
pub(crate) fn default_slop_erosion() -> f64 {
    0.50
}
pub(crate) fn default_slop_delta_loc() -> i64 {
    800
}
pub(crate) fn default_slop_block_verbosity() -> f64 {
    0.40
}
pub(crate) fn default_slop_block_erosion() -> f64 {
    0.75
}
pub(crate) fn default_slop_block_delta_loc() -> i64 {
    5_000
}
pub(crate) fn default_slop_hotspots() -> usize {
    8
}

impl Default for SlopConfig {
    fn default() -> Self {
        Self {
            verbosity: default_slop_verbosity(),
            erosion: default_slop_erosion(),
            delta_loc: default_slop_delta_loc(),
            block_verbosity: default_slop_block_verbosity(),
            block_erosion: default_slop_block_erosion(),
            block_delta_loc: default_slop_block_delta_loc(),
            hotspots: default_slop_hotspots(),
        }
    }
}

impl SlopConfig {
    /// Overlay non-default fields from `other` (higher-priority layer).
    pub fn merge_with(&self, other: &Self) -> Self {
        let d = Self::default();
        Self {
            verbosity: if (other.verbosity - d.verbosity).abs() > f64::EPSILON {
                other.verbosity
            } else {
                self.verbosity
            },
            erosion: if (other.erosion - d.erosion).abs() > f64::EPSILON {
                other.erosion
            } else {
                self.erosion
            },
            delta_loc: if other.delta_loc != d.delta_loc {
                other.delta_loc
            } else {
                self.delta_loc
            },
            block_verbosity: if (other.block_verbosity - d.block_verbosity).abs() > f64::EPSILON {
                other.block_verbosity
            } else {
                self.block_verbosity
            },
            block_erosion: if (other.block_erosion - d.block_erosion).abs() > f64::EPSILON {
                other.block_erosion
            } else {
                self.block_erosion
            },
            block_delta_loc: if other.block_delta_loc != d.block_delta_loc {
                other.block_delta_loc
            } else {
                self.block_delta_loc
            },
            hotspots: if other.hotspots != d.hotspots {
                other.hotspots
            } else {
                self.hotspots
            },
        }
    }
}

/// Process-local background shell jobs and schedule/loop knobs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutomationConfig {
    /// Max concurrent background shell jobs. Default 8.
    #[serde(default = "default_max_background_jobs")]
    pub max_background_jobs: usize,
}

pub(crate) fn default_max_background_jobs() -> usize {
    8
}

impl Default for AutomationConfig {
    fn default() -> Self {
        Self {
            max_background_jobs: default_max_background_jobs(),
        }
    }
}

/// Concurrent multi-agent work (`swarm` tool).
///
/// When `worktrees` is on (default) and the project is a git repo, each worker
/// runs in a detached git worktree under `.whycodes/swarm/`. Changes merge back
/// into the main checkout with three-way conflict detection. File claims still
/// gate same-checkout mode and pre-declared path ownership.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwarmConfig {
    /// Advertise and run the `swarm` tool. Default on.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Max concurrent workers (hard-capped at 8 in the agent). Default 4.
    #[serde(default = "default_swarm_max_agents")]
    pub max_agents: usize,
    /// Isolate writers in git worktrees (default on). Falls back to same-checkout
    /// + file claims when the project is not a git repo.
    #[serde(default = "default_true")]
    pub worktrees: bool,
    /// `worktree` or `checkout`. When set, overrides `worktrees`.
    #[serde(default)]
    pub isolation: Option<String>,
}

impl SwarmConfig {
    /// Whether to try git worktrees for this run.
    pub fn use_worktrees(&self) -> bool {
        match self.isolation.as_deref() {
            Some(s) if s.eq_ignore_ascii_case("checkout") => false,
            Some(s) if s.eq_ignore_ascii_case("worktree") => true,
            _ => self.worktrees,
        }
    }
}

pub(crate) fn default_swarm_max_agents() -> usize {
    4
}

impl Default for SwarmConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_agents: default_swarm_max_agents(),
            worktrees: true,
            isolation: None,
        }
    }
}

/// When a hook runs relative to a tool call.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HookEvent {
    /// Before the tool executes. Non-zero exit can block when `block_on_failure`.
    #[default]
    PreTool,
    /// Before every gate: a successful hook whose stdout is a JSON object
    /// replaces the tool input. Failures keep the input (fail open).
    PreToolTransform,
    /// After the tool finishes. Failures are logged only.
    PostTool,
    /// Once per session in this process (new or resumed), before its first turn.
    SessionStart,
    /// Before each user turn. Non-zero exit can block the turn when `block_on_failure`.
    UserPromptSubmit,
    /// After a user turn finishes with a reply.
    Stop,
    /// Before the transcript is compacted (auto, overflow, or `/compact`).
    PreCompact,
    /// After a `task` / `swarm` subagent finishes. `match` filters the agent type.
    SubagentStop,
}

impl HookEvent {
    /// Config spelling (`pre_tool`, `session_start`, …).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::PreTool => "pre_tool",
            Self::PreToolTransform => "pre_tool_transform",
            Self::PostTool => "post_tool",
            Self::SessionStart => "session_start",
            Self::UserPromptSubmit => "user_prompt_submit",
            Self::Stop => "stop",
            Self::PreCompact => "pre_compact",
            Self::SubagentStop => "subagent_stop",
        }
    }

    /// Whether `block_on_failure` can refuse the action (tool call / turn).
    pub fn can_block(self) -> bool {
        matches!(self, Self::PreTool | Self::UserPromptSubmit)
    }
}

/// A single shell hook attached to tool execution.
///
/// ```toml
/// [[hooks]]
/// event = "pre_tool"
/// match = "bash"           # tool name; `*` or `prefix*` / `*suffix`
/// command = "echo check"
/// block_on_failure = true  # pre_tool / user_prompt_submit: non-zero exit refuses
/// feedback = false         # stdout of a successful hook goes to the model
/// timeout_secs = 30
/// ```
///
/// Environment for the command: `WHYCODES_HOOK_EVENT`, `WHYCODES_TOOL_NAME`,
/// `WHYCODES_TOOL_INPUT` (JSON), `WHYCODES_TOOL_ID`, `WHYCODES_SESSION_ID`,
/// `WHYCODES_WORKING_DIR`. Post-tool also sets `WHYCODES_TOOL_IS_ERROR` and
/// `WHYCODES_TOOL_OUTPUT` (truncated). Lifecycle events add their own
/// variables (`WHYCODES_PROMPT`, `WHYCODES_RESPONSE`, `WHYCODES_SUBAGENT_*`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookConfig {
    /// `pre_tool`, `pre_tool_transform`, `post_tool`, `session_start`,
    /// `user_prompt_submit`, `stop`, `pre_compact`, or `subagent_stop`.
    #[serde(default)]
    pub event: HookEvent,

    /// Tool name pattern. Default `*` (all tools).
    #[serde(default = "default_hook_match", rename = "match")]
    pub tool_match: String,

    /// Shell command (run via `sh -c` / `cmd /C`).
    pub command: String,

    /// When true on `pre_tool` / `user_prompt_submit`, a non-zero exit refuses
    /// the tool call / the turn.
    #[serde(default)]
    pub block_on_failure: bool,

    /// When true, a successful hook's stdout is shown to the model: appended
    /// to the tool result (`post_tool`) or to the user turn (`session_start`,
    /// `user_prompt_submit`). Ignored for other events.
    #[serde(default)]
    pub feedback: bool,

    /// Kill the hook after this many seconds. Default 30.
    #[serde(default = "default_hook_timeout")]
    pub timeout_secs: u64,
}

pub(crate) fn default_hook_match() -> String {
    "*".to_string()
}

pub(crate) fn default_hook_timeout() -> u64 {
    30
}

impl Default for HookConfig {
    fn default() -> Self {
        Self {
            event: HookEvent::PreTool,
            tool_match: default_hook_match(),
            command: String::new(),
            block_on_failure: false,
            feedback: false,
            timeout_secs: default_hook_timeout(),
        }
    }
}

/// Settings for shell safety: risk classification, OS sandbox, and network
/// domain policy for HTTP tools.
///
/// The risk classifier inspects the command *string* a model asked to run.
/// The sandbox (when enabled) confines the process that runs it. They stack;
/// neither replaces the other. See the README security section.
///
/// `network_allowlist` / `network_denylist` gate `webfetch`, `websearch`, and
/// GitHub API tools by host pattern. Shell network stays binary
/// (`sandbox_network`); domain filtering does not apply inside the shell.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// Lowest risk level that requires confirmation: `caution`, `destructive`
    /// or `off`. Commands classified `catastrophic` are always refused and
    /// this setting cannot override that.
    #[serde(default = "default_risk_threshold")]
    pub bash_risk_threshold: String,

    /// OS sandbox for `bash` / `shell`: `off` | `workspace` (default).
    #[serde(default = "default_sandbox_mode")]
    pub sandbox: String,

    /// When `sandbox = "workspace"`, whether the sandboxed shell may use the
    /// network. Default `true` so `cargo` / `npm` / `git` keep working.
    #[serde(default = "default_true_bool")]
    pub sandbox_network: bool,

    /// When the requested sandbox cannot be applied (no `bwrap`, non-Linux):
    /// `allow` (default — warn and run on host) or `deny` (fail the tool call).
    #[serde(default = "default_sandbox_fallback")]
    pub sandbox_fallback: String,

    /// Host patterns allowed for outbound HTTP tools. Empty (default) means
    /// unrestricted. See [`NetworkPolicy`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub network_allowlist: Vec<String>,

    /// Host patterns always blocked for outbound HTTP tools (wins over
    /// allowlist).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub network_denylist: Vec<String>,

    /// Replace credential-looking values (environment variables named like
    /// secrets, known token shapes, URL passwords) with placeholders in every
    /// request sent to a provider, and restore them inside the model's tool
    /// arguments before execution. Default `true`.
    #[serde(default = "default_true_bool")]
    pub redact_secrets: bool,
}

pub(crate) fn default_risk_threshold() -> String {
    "destructive".to_string()
}

pub(crate) fn default_sandbox_mode() -> String {
    "workspace".to_string()
}

pub(crate) fn default_sandbox_fallback() -> String {
    "allow".to_string()
}

pub(crate) fn default_true_bool() -> bool {
    true
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            bash_risk_threshold: default_risk_threshold(),
            sandbox: default_sandbox_mode(),
            sandbox_network: true,
            sandbox_fallback: default_sandbox_fallback(),
            network_allowlist: Vec::new(),
            network_denylist: Vec::new(),
            redact_secrets: true,
        }
    }
}

impl SecurityConfig {
    /// Build the HTTP-tool network policy from config lists.
    pub fn network_policy(&self) -> NetworkPolicy {
        NetworkPolicy {
            allowlist: self.network_allowlist.clone(),
            denylist: self.network_denylist.clone(),
        }
    }

    /// Resolved OS sandbox policy for shell tools.
    pub fn sandbox_settings(&self) -> SandboxSettings {
        SandboxSettings::from_raw(&self.sandbox, self.sandbox_network, &self.sandbox_fallback)
    }
}

/// Custom slash command definition (`/commands`)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomCommandConfig {
    /// Prompt template (`$ARGUMENTS`, `$1`, `$2`, …)
    pub template: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Force subagent invocation
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subtask: Option<bool>,
}

/// How to reach an MCP server.
///
/// - `stdio` — spawn a local process (default when `command` is set)
/// - `http` — Streamable HTTP (spec 2025-03-26+); preferred remote transport
/// - `sse` — legacy HTTP+SSE (spec 2024-11-05)
/// - `auto` — for URL endpoints: try Streamable HTTP, fall back to legacy SSE
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum McpTransportKind {
    #[default]
    Stdio,
    /// Streamable HTTP (single MCP endpoint, POST/GET + optional SSE)
    Http,
    /// Legacy dual-endpoint HTTP+SSE transport
    Sse,
    /// Probe Streamable HTTP first, then fall back to legacy SSE
    Auto,
}

/// Language-server overlay stored in `config.toml` under `[lsp]`.
///
/// Empty `servers` keeps built-in auto-detect. Named entries overlay matching
/// built-ins (or register a new server). Nested objects replace.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct LspConfig {
    #[serde(
        default,
        alias = "idleTimeoutMs",
        skip_serializing_if = "Option::is_none"
    )]
    pub idle_timeout_ms: Option<u64>,
    /// Wait (ms) for language-server diagnostics after `edit` / `write`;
    /// `0` turns it off. Unset uses the runtime default.
    #[serde(
        default,
        alias = "editDiagnosticsMs",
        skip_serializing_if = "Option::is_none"
    )]
    pub edit_diagnostics_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub servers: HashMap<String, LspServerConfig>,
}

/// `[pricing."provider/model"]`: USD per million tokens.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
pub struct PriceConfig {
    pub input: f64,
    pub output: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_read: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_write: Option<f64>,
}

/// One language-server overlay entry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct LspServerConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    #[serde(default, alias = "fileTypes", skip_serializing_if = "Vec::is_empty")]
    pub file_types: Vec<String>,
    #[serde(default, alias = "languageId", skip_serializing_if = "Option::is_none")]
    pub language_id: Option<String>,
    #[serde(default, alias = "rootMarkers", skip_serializing_if = "Vec::is_empty")]
    pub root_markers: Vec<String>,
    #[serde(
        default,
        alias = "initOptions",
        skip_serializing_if = "Option::is_none"
    )]
    pub init_options: Option<toml::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub settings: Option<toml::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    #[serde(default, alias = "isLinter", skip_serializing_if = "Option::is_none")]
    pub is_linter: Option<bool>,
}

impl LspConfig {
    /// Convert this TOML overlay into JSON-valued runtime settings.
    ///
    /// The `lsp` crate owns detection and built-in servers; this is the user
    /// overlay only (empty `servers` still auto-detects).
    pub fn to_runtime_settings(&self) -> (Option<u64>, Vec<(String, RuntimeLspServer)>) {
        let servers = self
            .servers
            .iter()
            .map(|(name, spec)| (name.clone(), spec.to_runtime()))
            .collect();
        (self.idle_timeout_ms, servers)
    }
}

/// JSON-valued overlay sent to `whycodes-lsp` (avoids a config → lsp edge).
#[derive(Debug, Clone)]
pub struct RuntimeLspServer {
    pub command: Option<String>,
    pub args: Vec<String>,
    pub file_types: Vec<String>,
    pub language_id: Option<String>,
    pub root_markers: Vec<String>,
    pub init_options: Option<serde_json::Value>,
    pub settings: Option<serde_json::Value>,
    pub disabled: Option<bool>,
    pub is_linter: Option<bool>,
}

impl LspServerConfig {
    fn to_runtime(&self) -> RuntimeLspServer {
        RuntimeLspServer {
            command: self.command.clone(),
            args: self.args.clone(),
            file_types: self.file_types.clone(),
            language_id: self.language_id.clone(),
            root_markers: self.root_markers.clone(),
            init_options: self.init_options.as_ref().and_then(toml_to_json),
            settings: self.settings.as_ref().and_then(toml_to_json),
            disabled: self.disabled,
            is_linter: self.is_linter,
        }
    }
}

fn toml_to_json(value: &toml::Value) -> Option<serde_json::Value> {
    serde_json::to_value(value).ok()
}

/// MCP server definition stored in config.
///
/// Stdio: `command` + `args`. Remote: `url` (+ optional `type` / `headers`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Explicit transport (`stdio` | `http` | `sse` | `auto`).
    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
    pub transport: Option<McpTransportKind>,
    /// Command to spawn (stdio transport)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub env: Option<HashMap<String, String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// Remote MCP endpoint URL (Streamable HTTP or legacy SSE)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
}

impl McpServerConfig {
    pub fn resolved_transport(&self) -> std::result::Result<McpTransportKind, String> {
        if let Some(kind) = self.transport {
            return match kind {
                McpTransportKind::Stdio if self.command.is_none() => {
                    Err("MCP transport 'stdio' requires `command`".into())
                }
                McpTransportKind::Http | McpTransportKind::Sse | McpTransportKind::Auto
                    if self.url.is_none() =>
                {
                    Err(format!("MCP transport '{kind:?}' requires `url`"))
                }
                other => Ok(other),
            };
        }
        match (&self.url, &self.command) {
            (Some(_), _) => Ok(McpTransportKind::Auto),
            (None, Some(_)) => Ok(McpTransportKind::Stdio),
            (None, None) => {
                Err("MCP server config needs either `command` (stdio) or `url` (http/sse)".into())
            }
        }
    }

    /// Why this stdio entry cannot work, before anything is spawned: an
    /// empty `command`, or a package runner (`npx`, `uvx`, …) given no
    /// package in `args`, which waits for input until the connect times out.
    pub fn stdio_problem(&self) -> Option<String> {
        let command = self.command.as_deref()?.trim();
        if command.is_empty() {
            return Some("MCP server `command` is empty".into());
        }
        // Both separators on every OS: a Windows path in a shared config.
        let file = command.rsplit(['/', '\\']).next().unwrap_or(command);
        let stem = file.split('.').next().unwrap_or(file).to_ascii_lowercase();
        let runner = matches!(stem.as_str(), "npx" | "pnpx" | "bunx" | "uvx");
        (runner && self.args.iter().all(|a| a.trim().is_empty())).then(|| {
            format!(
                "`{command}` needs the package to run in `args` \
                 (e.g. args = [\"-y\", \"<package>\"])"
            )
        })
    }

    pub fn is_remote(&self) -> bool {
        matches!(
            self.resolved_transport().ok(),
            Some(McpTransportKind::Http | McpTransportKind::Sse | McpTransportKind::Auto)
        )
    }
}

impl Default for Config {
    fn default() -> Self {
        use whycodes_core::types::{AgentInfo, AgentMode, PermissionSet};

        let build_agent = AgentInfo {
            name: "build".to_string(),
            description:
                "Primary coding agent with full tool access — write, edit, shell, and network."
                    .to_string(),
            mode: AgentMode::Primary,
            permission: PermissionSet {
                allowed_tools: None,
                denied_tools: None,
                allow_file_writes: true,
                allow_network: true,
                allow_shell: true,
                allowed_paths: None,
                rules: Default::default(),
            },
            model: None,
            system_prompt: None, // Loaded from prompts/build.txt at runtime
            temperature: None,
            top_p: None,
        };

        // Plan: primary (Ctrl+T), file edits denied
        let plan_agent = AgentInfo {
            name: "plan".to_string(),
            description: "Read-only planning agent — analyzes code and proposes changes but does not modify files.".to_string(),
            mode: AgentMode::Primary,
            permission: PermissionSet {
                allowed_tools: Some(vec![
                    "read".to_string(),
                    "grep".to_string(),
                    "glob".to_string(),
                    "list".to_string(),
                    "repomap".to_string(),
                    "webfetch".to_string(),
                    "websearch".to_string(),
                    "lsp".to_string(),
                ]),
                denied_tools: Some(vec![
                    "write".to_string(),
                    "edit".to_string(),
                    "bash".to_string(),
                    "shell".to_string(),
                    "apply_patch".to_string(),
                    "todowrite".to_string(),
                    "todo".to_string(),
                    "git_commit".to_string(),
                    "task".to_string(),
                    "swarm".to_string(),
                ]),
                allow_file_writes: false,
                allow_network: true,
                allow_shell: false,
                allowed_paths: None,
                rules: Default::default(),
            },
            model: None,
            system_prompt: None, // prompts/plan.txt
            temperature: None,
            top_p: None,
        };

        // Ask: primary read-only Q&A (no implementation)
        let ask_agent = AgentInfo {
            name: "ask".to_string(),
            description:
                "Read-only Q&A agent — explains code and answers questions without modifying files."
                    .to_string(),
            mode: AgentMode::Primary,
            permission: PermissionSet {
                allowed_tools: Some(vec![
                    "read".to_string(),
                    "grep".to_string(),
                    "glob".to_string(),
                    "list".to_string(),
                    "repomap".to_string(),
                    "webfetch".to_string(),
                    "websearch".to_string(),
                    "lsp".to_string(),
                    "question".to_string(),
                ]),
                denied_tools: Some(vec![
                    "write".to_string(),
                    "edit".to_string(),
                    "bash".to_string(),
                    "shell".to_string(),
                    "apply_patch".to_string(),
                    "todowrite".to_string(),
                    "todo".to_string(),
                    "git_commit".to_string(),
                    "task".to_string(),
                    "swarm".to_string(),
                    "plan".to_string(),
                ]),
                allow_file_writes: false,
                allow_network: true,
                allow_shell: false,
                allowed_paths: None,
                rules: Default::default(),
            },
            model: None,
            system_prompt: None, // prompts/ask.txt
            temperature: None,
            top_p: None,
        };

        // WhyCodes: primary operator agent for WhyCodes itself. Path rules
        // deny every write except the project `.whycodes/` overlay (the
        // agent adds the resolved global `config.toml` at runtime); shell
        // rules allow only `whycodes config …` / `whycodes debug …`.
        let whycodes_agent = AgentInfo {
            name: "whycodes".to_string(),
            description: "WhyCodes operator — explains WhyCodes and repairs its config; never writes project source.".to_string(),
            mode: AgentMode::Primary,
            permission: PermissionSet {
                allowed_tools: Some(vec![
                    "read".to_string(),
                    "grep".to_string(),
                    "glob".to_string(),
                    "list".to_string(),
                    "write".to_string(),
                    "edit".to_string(),
                    "bash".to_string(),
                    "skill".to_string(),
                    "question".to_string(),
                ]),
                denied_tools: Some(vec![
                    "apply_patch".to_string(),
                    "ast_edit".to_string(),
                    "todowrite".to_string(),
                    "todo".to_string(),
                    "git_commit".to_string(),
                    "task".to_string(),
                    "swarm".to_string(),
                ]),
                allow_file_writes: true,
                allow_network: false,
                allow_shell: true,
                allowed_paths: None,
                rules: HashMap::from([
                    ("write(**)".to_string(), PermissionAction::Deny),
                    ("write(.whycodes/**)".to_string(), PermissionAction::Allow),
                    ("bash(*)".to_string(), PermissionAction::Deny),
                    (
                        "bash(whycodes config *)".to_string(),
                        PermissionAction::Allow,
                    ),
                    (
                        "bash(whycodes debug *)".to_string(),
                        PermissionAction::Allow,
                    ),
                ]),
            },
            model: None,
            system_prompt: None, // prompts/whycodes.txt
            temperature: None,
            top_p: None,
        };

        // Explore: subagent — fast read-only codebase search
        let explore_agent = AgentInfo {
            name: "explore".to_string(),
            description: "Fast read-only subagent for exploring codebases (find files, search keywords, answer questions).".to_string(),
            mode: AgentMode::Subagent,
            permission: PermissionSet {
                allowed_tools: Some(vec![
                    "read".to_string(),
                    "grep".to_string(),
                    "glob".to_string(),
                    "list".to_string(),
                    "repomap".to_string(),
                    "webfetch".to_string(),
                    "websearch".to_string(),
                    "lsp".to_string(),
                ]),
                denied_tools: Some(vec![
                    "write".to_string(),
                    "edit".to_string(),
                    "bash".to_string(),
                    "shell".to_string(),
                    "apply_patch".to_string(),
                    "todowrite".to_string(),
                    "todo".to_string(),
                    "question".to_string(),
                ]),
                allow_file_writes: false,
                allow_network: true,
                allow_shell: false,
                allowed_paths: None,
                rules: Default::default(),
            },
            model: None,
            system_prompt: Some("You are a read-only exploration subagent. Find files, search code, answer questions. No file modifications. Do not call `question` — report findings to the parent.".to_string()),
            temperature: None,
            top_p: None,
        };

        // General: subagent with full tool access except todo
        let general_agent = AgentInfo {
            name: "general".to_string(),
            description: "General-purpose subagent for complex multi-step tasks. Full tools except todo. Use for parallel units of work.".to_string(),
            mode: AgentMode::Subagent,
            permission: PermissionSet {
                allowed_tools: None,
                denied_tools: Some(vec![
                    "todowrite".to_string(),
                    "todo".to_string(),
                    "todoread".to_string(),
                ]),
                allow_file_writes: true,
                allow_network: true,
                allow_shell: true,
                allowed_paths: None,
                rules: Default::default(),
            },
            model: None,
            system_prompt: Some("You are a general-purpose subagent for complex searches and multi-step tasks. Complete the goal thoroughly.".to_string()),
            temperature: None,
            top_p: None,
        };

        // Scout: subagent for external docs / dependency research
        let scout_agent = AgentInfo {
            name: "scout".to_string(),
            description: "Read-only subagent for external docs and dependency research.".to_string(),
            mode: AgentMode::Subagent,
            permission: PermissionSet {
                allowed_tools: Some(vec![
                    "read".to_string(),
                    "grep".to_string(),
                    "glob".to_string(),
                    "list".to_string(),
                    "repomap".to_string(),
                    "webfetch".to_string(),
                    "websearch".to_string(),
                    "bash".to_string(), // limited: clone/inspect only ideally
                ]),
                denied_tools: Some(vec![
                    "write".to_string(),
                    "edit".to_string(),
                    "apply_patch".to_string(),
                    "todowrite".to_string(),
                    "todo".to_string(),
                    "question".to_string(),
                ]),
                allow_file_writes: false,
                allow_network: true,
                allow_shell: true,
                allowed_paths: None,
                rules: Default::default(),
            },
            model: None,
            system_prompt: Some("You are a scout subagent. Research external docs and dependencies. Prefer webfetch/websearch. Do not modify the workspace project files. Do not call `question` — report findings to the parent.".to_string()),
            temperature: None,
            top_p: None,
        };

        Config {
            providers: HashMap::new(),
            models: HashMap::new(),
            pricing: HashMap::new(),
            agents: vec![
                build_agent,
                plan_agent,
                ask_agent,
                whycodes_agent,
                explore_agent,
                general_agent,
                scout_agent,
            ],
            default_agent: "build".to_string(),
            default_model: None,
            command_configs: HashMap::new(),
            tools: ToolsConfig::default(),
            session: SessionConfig::default(),
            tui: TuiConfig::default(),
            general: GeneralConfig::default(),
            schema_version: CONFIG_SCHEMA_VERSION,
            mcp_servers: HashMap::new(),
            lsp: LspConfig::default(),
            permission: HashMap::new(),
            commands: HashMap::new(),
            security: SecurityConfig::default(),
            hooks: Vec::new(),
            memory: MemoryConfig::default(),
            swarm: SwarmConfig::default(),
            automation: AutomationConfig::default(),
            notify: NotifyConfig::default(),
            slop: SlopConfig::default(),
            websearch: WebSearchConfig::default(),
            system_prompt_overlays: SystemPromptOverlays::default(),
        }
    }
}

/// Provider / model system-prompt extras loaded from markdown files.
///
/// File layout (global `prompts/` next to `config.toml`, project
/// `.whycodes/prompts/` — project keys overwrite):
///
/// - `prompts/<provider>.md` — every model on that provider
/// - `prompts/<provider>/<model>.md` — that provider+model
/// - `prompts/models/<model>.md` — that model id on any provider
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SystemPromptOverlays {
    /// Keyed by lowercase provider id (`xai`).
    pub providers: HashMap<String, String>,
    /// Keyed by lowercase `provider/model` or bare `model`.
    pub models: HashMap<String, String>,
}

impl SystemPromptOverlays {
    pub fn is_empty(&self) -> bool {
        self.providers.is_empty() && self.models.is_empty()
    }

    /// Provider body (if any) then the most specific model body.
    ///
    /// Model match order: `provider/model`, then bare `model`.
    pub fn sections(&self, provider: &str, model: &str) -> Vec<(String, String)> {
        let p = overlay_key(provider);
        let m = overlay_key(model);
        let mut out = Vec::new();
        if !p.is_empty()
            && let Some(body) = self.providers.get(&p)
        {
            out.push((format!("Provider instructions ({p})"), body.clone()));
        }
        if !m.is_empty() {
            let body = if p.is_empty() {
                self.models.get(&m)
            } else {
                self.models
                    .get(&format!("{p}/{m}"))
                    .or_else(|| self.models.get(&m))
            };
            if let Some(body) = body {
                out.push((format!("Model instructions ({m})"), body.clone()));
            }
        }
        out
    }
}

pub(crate) fn overlay_key(raw: &str) -> String {
    raw.trim().to_ascii_lowercase()
}

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

    #[test]
    fn overlay_key_trims_and_lowercases() {
        assert_eq!(overlay_key("  XAI "), "xai");
        assert_eq!(overlay_key(""), "");
    }

    #[test]
    fn sections_provider_then_specific_model() {
        let mut o = SystemPromptOverlays::default();
        o.providers.insert("xai".into(), "prov".into());
        o.models.insert("xai/grok-4.6".into(), "specific".into());
        o.models.insert("grok-4.6".into(), "generic".into());
        let s = o.sections("XAI", "grok-4.6");
        assert_eq!(s.len(), 2);
        assert_eq!(s[0].0, "Provider instructions (xai)");
        assert_eq!(s[0].1, "prov");
        assert_eq!(s[1].0, "Model instructions (grok-4.6)");
        assert_eq!(s[1].1, "specific");
    }

    #[test]
    fn sections_bare_model_when_no_provider_or_specific() {
        let mut o = SystemPromptOverlays::default();
        o.models.insert("grok-4.6".into(), "generic".into());
        let s = o.sections("xai", "grok-4.6");
        assert_eq!(
            s,
            vec![("Model instructions (grok-4.6)".into(), "generic".into())]
        );
        let only_model = o.sections("", "grok-4.6");
        assert_eq!(only_model.len(), 1);
        assert!(o.sections("xai", "missing").is_empty());
        assert!(o.sections("", "").is_empty());
        assert!(SystemPromptOverlays::default().is_empty());
    }
}

/// Cross-session semantic / auto memory (Claude-style index + local recall).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryConfig {
    /// Master switch. Default on (cheap hashing embedder; no ONNX).
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Auto-inject top-k semantic hits for the current user message.
    #[serde(default = "default_true")]
    pub auto_inject: bool,
    /// Post-turn auto-retain (heuristic and/or LLM). Default on.
    #[serde(default = "default_true")]
    pub auto_retain: bool,
    /// Also call a small LLM to extract durable facts when heuristic finds none
    /// (or always when `retain_llm_always`). Default on.
    #[serde(default = "default_true")]
    pub retain_llm: bool,
    /// Run LLM retain even if heuristic already found facts.
    #[serde(default)]
    pub retain_llm_always: bool,
    /// Run retain every N user turns (1 = every turn).
    #[serde(default = "default_retain_every_n")]
    pub retain_every_n: usize,
    /// Max facts retained per turn.
    #[serde(default = "default_retain_max_facts")]
    pub retain_max_facts: usize,
    /// Max lines of MEMORY.md loaded into every session (Claude parity: 200).
    #[serde(default = "default_memory_index_lines")]
    pub max_index_lines: usize,
    /// Max bytes of MEMORY.md loaded into every session (Claude parity: 25 KiB).
    #[serde(default = "default_memory_index_bytes")]
    pub max_index_bytes: usize,
    /// Max recalled facts injected per turn.
    #[serde(default = "default_memory_top_k")]
    pub recall_top_k: usize,
    /// Minimum cosine similarity for a fact to be recalled.
    #[serde(default = "default_memory_min_score")]
    pub recall_min_score: f32,
    /// Token budget for recalled facts (chars ≈ tokens × 4).
    #[serde(default = "default_memory_token_budget")]
    pub recall_token_budget: usize,
    /// Hashing embedder dimension (stored BLOB width).
    #[serde(default = "default_memory_embed_dim")]
    pub embed_dim: usize,
    /// `user` (data_dir, default) or `project` (`.whycodes/memory`, git-shareable).
    #[serde(default = "default_memory_scope")]
    pub scope: String,
    /// `hash` (default) or `onnx` (MiniLM; needs `--features onnx`).
    #[serde(default = "default_memory_backend")]
    pub embed_backend: String,
    /// Inject code-index hits when available.
    #[serde(default = "default_true")]
    pub code_inject: bool,
    #[serde(default = "default_code_top_k")]
    pub code_top_k: usize,
    #[serde(default = "default_code_min_score")]
    pub code_min_score: f32,
    /// Give subagents their own memory bank (`project::agent_name`).
    #[serde(default = "default_true")]
    pub subagent_banks: bool,
    /// On session start, ensure a code index exists (skip if already indexed).
    #[serde(default = "default_true")]
    pub auto_index: bool,
    /// Max source files to walk when auto-indexing.
    #[serde(default = "default_auto_index_files")]
    pub auto_index_max_files: usize,
    /// Max chunks when auto-indexing.
    #[serde(default = "default_auto_index_chunks")]
    pub auto_index_max_chunks: usize,
    /// Inject related past-session turns.
    #[serde(default = "default_true")]
    pub session_inject: bool,
    #[serde(default = "default_session_top_k")]
    pub session_top_k: usize,
    #[serde(default = "default_session_min_score")]
    pub session_min_score: f32,
    /// Cap the fact bank after retain.
    #[serde(default = "default_true")]
    pub consolidate: bool,
    #[serde(default = "default_consolidate_max")]
    pub consolidate_max: usize,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            auto_inject: true,
            auto_retain: true,
            retain_llm: true,
            retain_llm_always: false,
            retain_every_n: default_retain_every_n(),
            retain_max_facts: default_retain_max_facts(),
            max_index_lines: default_memory_index_lines(),
            max_index_bytes: default_memory_index_bytes(),
            recall_top_k: default_memory_top_k(),
            recall_min_score: default_memory_min_score(),
            recall_token_budget: default_memory_token_budget(),
            embed_dim: default_memory_embed_dim(),
            scope: default_memory_scope(),
            embed_backend: default_memory_backend(),
            code_inject: true,
            code_top_k: default_code_top_k(),
            code_min_score: default_code_min_score(),
            subagent_banks: true,
            auto_index: true,
            auto_index_max_files: default_auto_index_files(),
            auto_index_max_chunks: default_auto_index_chunks(),
            session_inject: true,
            session_top_k: default_session_top_k(),
            session_min_score: default_session_min_score(),
            consolidate: true,
            consolidate_max: default_consolidate_max(),
        }
    }
}

pub(crate) fn default_memory_index_lines() -> usize {
    200
}
pub(crate) fn default_memory_index_bytes() -> usize {
    25_600
}
pub(crate) fn default_memory_top_k() -> usize {
    5
}
pub(crate) fn default_memory_min_score() -> f32 {
    0.28
}
pub(crate) fn default_memory_token_budget() -> usize {
    800
}
pub(crate) fn default_memory_embed_dim() -> usize {
    256
}
pub(crate) fn default_retain_every_n() -> usize {
    1
}
pub(crate) fn default_retain_max_facts() -> usize {
    3
}
pub(crate) fn default_memory_scope() -> String {
    "user".into()
}
pub(crate) fn default_memory_backend() -> String {
    "hash".into()
}
pub(crate) fn default_code_top_k() -> usize {
    4
}
pub(crate) fn default_code_min_score() -> f32 {
    0.22
}
pub(crate) fn default_auto_index_files() -> usize {
    1500
}
pub(crate) fn default_auto_index_chunks() -> usize {
    4000
}
pub(crate) fn default_session_top_k() -> usize {
    3
}
pub(crate) fn default_session_min_score() -> f32 {
    0.22
}
pub(crate) fn default_consolidate_max() -> usize {
    80
}

pub(crate) fn default_agent() -> String {
    "build".to_string()
}

/// Settings for the interactive `question` tool (questionnaire).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuestionToolConfig {
    /// When true, unanswered questionnaires fail after [`Self::timeout_secs`].
    #[serde(default = "default_question_timeout_enabled")]
    pub timeout_enabled: bool,
    /// Seconds to wait for answers when timeout is enabled (default 1800 = 30 min).
    #[serde(default = "default_question_timeout_secs")]
    pub timeout_secs: u64,
}

impl Default for QuestionToolConfig {
    fn default() -> Self {
        Self {
            timeout_enabled: default_question_timeout_enabled(),
            timeout_secs: default_question_timeout_secs(),
        }
    }
}

pub(crate) fn default_question_timeout_enabled() -> bool {
    true
}

pub(crate) fn default_question_timeout_secs() -> u64 {
    1800
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToolsConfig {
    #[serde(default = "default_true")]
    pub enable_read: bool,
    #[serde(default = "default_true")]
    pub enable_write: bool,
    #[serde(default = "default_true")]
    pub enable_edit: bool,
    #[serde(default = "default_true")]
    pub enable_glob: bool,
    #[serde(default = "default_true")]
    pub enable_grep: bool,
    #[serde(default = "default_true")]
    pub enable_shell: bool,
    #[serde(default = "default_true")]
    pub enable_webfetch: bool,
    #[serde(default = "default_true")]
    pub enable_websearch: bool,
    /// Interactive questionnaire (`question` tool).
    #[serde(default)]
    pub question: QuestionToolConfig,
    #[serde(default)]
    pub disabled_tools: Vec<String>,
    #[serde(default)]
    pub custom_tools: HashMap<String, CustomToolConfig>,
    /// Long-running `bash` auto-detach (issue #140).
    #[serde(default)]
    pub bash: BashConfig,
    /// Project formatter after `edit` / `write`.
    #[serde(default)]
    pub format: FormatConfig,
}

/// `[tools.format]` — run the project's own formatter (rustfmt, prettier,
/// ruff, black, gofmt) on a file `edit` / `write` changed, when the project
/// shows it uses one.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FormatConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
}

impl Default for FormatConfig {
    fn default() -> Self {
        Self { enabled: true }
    }
}

/// `[tools.bash]` — auto-background a still-running shell after idle.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BashConfig {
    /// Detach a still-running command after [`Self::auto_background_after_secs`].
    #[serde(default = "default_true")]
    pub auto_background: bool,
    /// Seconds before a non-catastrophic foreground `bash` is detached (default 20).
    #[serde(default = "default_auto_background_after_secs")]
    pub auto_background_after_secs: u64,
}

pub(crate) fn default_auto_background_after_secs() -> u64 {
    20
}

impl Default for BashConfig {
    fn default() -> Self {
        Self {
            auto_background: true,
            auto_background_after_secs: default_auto_background_after_secs(),
        }
    }
}

pub(crate) fn default_goal_max_turns() -> u32 {
    30
}

pub(crate) fn default_true() -> bool {
    true
}

/// Current `config.toml` schema. Bump when a load-time rewrite is required.
pub const CONFIG_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionConfig {
    #[serde(default = "default_max_tokens")]
    pub max_context_tokens: usize,
    #[serde(default = "default_compaction_threshold")]
    pub compaction_threshold: usize,
    /// Share of the model's context window to keep free. Auto-compaction
    /// fires at the lower of `compaction_threshold` and
    /// `window × (100 − p) / 100`. Unset uses `compaction_threshold` alone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compaction_buffer_percent: Option<u8>,
    #[serde(default)]
    pub store_path: Option<PathBuf>,
    /// Auto-name sessions: project placeholder → first-message heuristic →
    /// small-model refine after the first turn. Default on.
    #[serde(default = "default_true")]
    pub auto_title: bool,
    /// Optional title model: `provider/model` or bare model id (same provider).
    /// Empty = pick a known small/fast sibling (haiku / mini / flash).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title_model: Option<String>,
    /// Tools advertised to the model: `core` (default, ~12 tools, faster TTFT)
    /// or `full` (every built-in including github/web/lsp).
    #[serde(default = "default_tool_profile")]
    pub tool_profile: String,
    /// Anthropic-style prompt cache policy: `auto` (default) or `none`.
    #[serde(default = "default_prompt_cache")]
    pub prompt_cache: String,
    /// Keep the prompt cache warm for this many idle minutes after a turn
    /// (TUI). Each keep-alive is a paid request that re-reads the cached
    /// prefix; `0` (default) turns it off.
    #[serde(default)]
    pub cache_warm_minutes: u64,
    /// Turns `/undo` can step back. The oldest entries drop first past the
    /// cap; `0` = unlimited (memory grows with every turn).
    #[serde(default = "default_undo_depth")]
    pub undo_depth: usize,
    /// Fast model for trivial chat (`provider/model` or bare model id).
    /// Empty = auto-pick small sibling of the session model (haiku/mini/flash).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_fast: Option<String>,
    /// Turns a `/goal` may take before it pauses (counted from when it was
    /// set or last resumed); `0` = no cap.
    #[serde(default = "default_goal_max_turns")]
    pub goal_max_turns: u32,
    /// Model that checks `/goal` (`provider/model` or bare id). Empty = the
    /// session model.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub goal_model: Option<String>,
    /// Cheap model for `task` / `swarm` fan-out (`provider/model` or bare id).
    /// Empty = auto-pick the small sibling of the session model.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_smol: Option<String>,
    /// Model used while the `plan` agent is active (`provider/model` or bare id).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_plan: Option<String>,
    /// Plan on the strong model, then hand the rest of the turn to the cheap
    /// one (`model_smol`, else the small sibling) after the first edit.
    /// Unset = off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prewalk: Option<bool>,
    /// First-token race partner: `off` (default), `auto` (small sibling), or
    /// `provider/model`. When set, a slow primary TTFT starts the partner.
    #[serde(default = "default_model_race")]
    pub model_race: String,
    /// How long to wait for the primary first token before opening `model_race`.
    #[serde(default = "default_race_after_ms")]
    pub race_after_ms: u64,
    /// `provider/model` refs tried in order when the active model fails to
    /// open a stream (rate limit after named credentials, 5xx, network,
    /// timeout). Each needs a key: same provider, config `api_key`, or
    /// `<PROVIDER>_API_KEY`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fallback_models: Vec<String>,
    /// Re-send a step whose stream drops mid-response (network, timeout,
    /// 5xx, truncated body) for up to this many seconds after the first
    /// drop. The partial draft is discarded. Default 60; `0` turns it off.
    #[serde(default = "default_stream_retry_secs")]
    pub stream_retry_secs: u64,
    /// Process-local text-only response cache: `auto` (default) or `off`.
    #[serde(default = "default_response_cache")]
    pub response_cache: String,
    /// Open the provider connection while the prompt is being typed, so the
    /// first request skips DNS/TCP/TLS setup. Sends no credentials or prompt.
    #[serde(default = "default_true")]
    pub preconnect: bool,
    /// Heuristic intent posture for build turns: `auto` (default), `off`, or `always`.
    ///
    /// When enabled, high-confidence question/plan signals inject an ephemeral
    /// `<whycodes_intent>` block into the LLM request (not session history) so
    /// the model answers or plans instead of over-eager edits. Hard modes
    /// (`ask` / `plan`) still enforce tool denylists regardless of this flag.
    #[serde(default = "default_intent_guidance")]
    pub intent_guidance: String,
    /// Full-replace compact (manual `/compact` and auto over threshold):
    /// `"auto"` (default) asks the session model for a structured summary;
    /// `"off"` is the local stub only.
    #[serde(default = "default_compaction_llm")]
    pub compaction_llm: String,
    /// Which compaction runs first: `"auto"` uses the provider's own
    /// compaction when the model has it (Anthropic on-demand compaction,
    /// beta) and falls back to full-replace; `"local"` (default) is
    /// full-replace only.
    #[serde(default = "default_compaction_method")]
    pub compaction_method: String,
    /// OpenAI-compat / xAI `reasoning_effort`: `low` | `medium` | `high` | `xhigh`.
    /// Empty = family default (`medium` when the model supports effort).
    /// `xhigh` (Max) is grok-4.6+ and GLM-5+ only; a missing level clamps to
    /// `high` (GLM-5+ has no `medium` and defaults to `high`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<String>,
    /// Standalone prose keywords (`ultrathink`, `orchestrate`) that inject a
    /// hidden per-turn instruction. Default on.
    #[serde(default)]
    pub magic_keywords: MagicKeywordsConfig,
    /// Regexes matched against streamed assistant text. A hit aborts the
    /// current LLM request and injects `hint` before the next step.
    #[serde(default)]
    pub stream_rules: Vec<StreamRuleConfig>,
    /// How `--format json` / `stream-json` treat permission `ask`.
    ///
    /// Unset = deny (fail-closed). `allow` restores the old auto-approve
    /// behaviour; `--approve-tools` on the CLI also forces allow. TUI and
    /// `--plain` ignore this — they still prompt (or follow `WHYCODES_AUTO_*`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headless_ask: Option<HeadlessAskMode>,
}

/// Structured-run policy for permission `ask` (issue #122).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum HeadlessAskMode {
    /// Deny the tool, stamp `denied:headless`, do not execute.
    Deny,
    /// Auto-allow (legacy CI behaviour). Same as `--approve-tools`.
    Allow,
}

impl HeadlessAskMode {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "deny" | "ask-fail" | "fail" | "fail-closed" => Some(Self::Deny),
            "allow" | "auto" | "approve" => Some(Self::Allow),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Deny => "deny",
            Self::Allow => "allow",
        }
    }
}

/// One time-traveling stream rule (abort + inject).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct StreamRuleConfig {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub pattern: String,
    #[serde(default)]
    pub hint: String,
    /// What the pattern is matched against. Empty = `["text"]`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope: Vec<StreamRuleScope>,
    /// `tool_args` scope only: tool names the rule watches. Empty = every tool.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<String>,
    /// How often the rule may fire. Default `always` (every matching draft).
    #[serde(default, skip_serializing_if = "StreamRuleRepeat::is_always")]
    pub repeat: StreamRuleRepeat,
}

impl StreamRuleConfig {
    /// `scope`, or `["text"]` when unset.
    pub fn scopes(&self) -> Vec<StreamRuleScope> {
        if self.scope.is_empty() {
            vec![StreamRuleScope::Text]
        } else {
            self.scope.clone()
        }
    }
}

/// Streamed channel a stream rule watches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StreamRuleScope {
    /// Assistant reply text.
    Text,
    /// Accumulated thinking text of the step.
    Thinking,
    /// Each tool call's JSON arguments as they stream.
    ToolArgs,
}

impl StreamRuleScope {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().replace('-', "_").as_str() {
            "text" => Some(Self::Text),
            "thinking" => Some(Self::Thinking),
            "tool_args" => Some(Self::ToolArgs),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Thinking => "thinking",
            Self::ToolArgs => "tool_args",
        }
    }
}

/// `repeat = "once" | "always" | { after_turns = N }`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum StreamRuleRepeat {
    /// Fire at most once per session.
    Once,
    /// Fire on every match.
    #[default]
    Always,
    /// Fire again once N user turns have passed since the last hit.
    AfterTurns(u32),
}

impl StreamRuleRepeat {
    pub fn is_always(&self) -> bool {
        *self == Self::Always
    }

    /// `once`, `always`, `after_turns = N`, `{ after_turns: N }`, or a bare `N`.
    pub fn parse(s: &str) -> Option<Self> {
        let s = s
            .trim()
            .trim_start_matches('{')
            .trim_end_matches('}')
            .trim();
        match s.to_ascii_lowercase().as_str() {
            "once" => return Some(Self::Once),
            "always" => return Some(Self::Always),
            _ => {}
        }
        let n = match s.split_once([':', '=']) {
            Some((k, v)) if k.trim() == "after_turns" => v,
            Some(_) => return None,
            None => s,
        };
        n.trim().parse().ok().map(Self::AfterTurns)
    }

    /// Whether a rule last fired at `last` may fire on user turn `turn`.
    pub fn allows(self, last: Option<u64>, turn: u64) -> bool {
        match (self, last) {
            (_, None) | (Self::Always, _) => true,
            (Self::Once, Some(_)) => false,
            (Self::AfterTurns(n), Some(t)) => turn.saturating_sub(t) >= u64::from(n),
        }
    }

    pub fn label(self) -> String {
        match self {
            Self::Once => "once".into(),
            Self::Always => "always".into(),
            Self::AfterTurns(n) => format!("after_turns={n}"),
        }
    }
}

/// Per-turn hidden notices when the user writes a magic keyword in prose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MagicKeywordsConfig {
    /// Master switch. Default on.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// `ultrathink` — careful multi-step reasoning + highest thinking effort.
    #[serde(default = "default_true")]
    pub ultrathink: bool,
    /// `orchestrate` — parallel subagent contract until the request is done.
    #[serde(default = "default_true")]
    pub orchestrate: bool,
}

impl Default for MagicKeywordsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            ultrathink: true,
            orchestrate: true,
        }
    }
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            max_context_tokens: default_max_tokens(),
            compaction_threshold: default_compaction_threshold(),
            compaction_buffer_percent: None,
            store_path: None,
            auto_title: true,
            title_model: None,
            tool_profile: default_tool_profile(),
            prompt_cache: default_prompt_cache(),
            cache_warm_minutes: 0,
            undo_depth: default_undo_depth(),
            model_fast: None,
            goal_max_turns: default_goal_max_turns(),
            goal_model: None,
            model_smol: None,
            model_plan: None,
            prewalk: None,
            model_race: default_model_race(),
            race_after_ms: default_race_after_ms(),
            fallback_models: Vec::new(),
            stream_retry_secs: default_stream_retry_secs(),
            response_cache: default_response_cache(),
            preconnect: true,
            intent_guidance: default_intent_guidance(),
            compaction_llm: default_compaction_llm(),
            compaction_method: default_compaction_method(),
            reasoning_effort: None,
            magic_keywords: MagicKeywordsConfig::default(),
            stream_rules: Vec::new(),
            headless_ask: None,
        }
    }
}

pub(crate) fn default_compaction_llm() -> String {
    "auto".into()
}

pub(crate) fn default_compaction_method() -> String {
    "local".into()
}

pub(crate) fn default_tool_profile() -> String {
    "core".into()
}

pub(crate) fn default_prompt_cache() -> String {
    "auto".into()
}

pub(crate) fn default_model_race() -> String {
    "off".into()
}

pub(crate) fn default_race_after_ms() -> u64 {
    800
}

pub(crate) fn default_stream_retry_secs() -> u64 {
    60
}

pub(crate) fn default_undo_depth() -> usize {
    50
}

pub(crate) fn default_response_cache() -> String {
    "auto".into()
}

pub(crate) fn default_intent_guidance() -> String {
    "auto".into()
}

pub(crate) fn default_max_tokens() -> usize {
    200_000
}

pub(crate) fn default_compaction_threshold() -> usize {
    150_000
}

/// Session notifications over Discord Incoming Webhooks, Telegram bots, and/or
/// the terminal (desktop notification via OSC 9 / OSC 777).
///
/// Off until `on` is non-empty **and** at least one channel is configured.
/// Secrets should live in env (`WHYCODES_NOTIFY_*`) or `${VAR}` substitution,
/// not in a committed project config.
///
/// ```toml
/// [notify]
/// on = ["turn_done", "need_input"]
/// discord_webhook = "${DISCORD_WEBHOOK_URL}"
/// telegram_bot_token = "${TELEGRAM_BOT_TOKEN}"
/// telegram_chat_id = "${TELEGRAM_CHAT_ID}"
/// desktop = true   # TUI only, while the terminal window is not focused
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NotifyConfig {
    /// Events that fire a message. Empty = disabled.
    /// Known values: `turn_done`, `need_input`.
    #[serde(default)]
    pub on: Vec<String>,
    /// Discord Incoming Webhook URL. Empty / omitted = skip Discord.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discord_webhook: Option<String>,
    /// Telegram bot token from BotFather. Empty / omitted = skip Telegram.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub telegram_bot_token: Option<String>,
    /// Telegram chat / group / channel id (`sendMessage` `chat_id`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub telegram_chat_id: Option<String>,
    /// HTTP timeout per channel. Default 8s, clamped 1–60.
    #[serde(default = "default_notify_timeout_secs")]
    pub timeout_secs: u64,
    /// Desktop notification from the TUI through the terminal (OSC 9 / 777),
    /// sent only while the terminal window is not focused. Omitted = off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub desktop: Option<bool>,
}

pub(crate) fn default_notify_timeout_secs() -> u64 {
    8
}

impl Default for NotifyConfig {
    fn default() -> Self {
        Self {
            on: Vec::new(),
            discord_webhook: None,
            telegram_bot_token: None,
            telegram_chat_id: None,
            timeout_secs: default_notify_timeout_secs(),
            desktop: None,
        }
    }
}

impl NotifyConfig {
    /// True when this event is listed in `on` (case-insensitive).
    pub fn wants(&self, event: NotifyEvent) -> bool {
        self.on.iter().any(|e| NotifyEvent::parse(e) == Some(event))
    }

    /// Discord webhook after trim; `None` if unset/blank.
    pub fn discord_webhook_url(&self) -> Option<&str> {
        nonempty_str(self.discord_webhook.as_deref())
    }

    /// Telegram bot token after trim; `None` if unset/blank.
    pub fn telegram_token(&self) -> Option<&str> {
        nonempty_str(self.telegram_bot_token.as_deref())
    }

    /// Telegram chat id after trim; `None` if unset/blank.
    pub fn telegram_chat(&self) -> Option<&str> {
        nonempty_str(self.telegram_chat_id.as_deref())
    }

    /// True when Discord and/or a complete Telegram pair is configured.
    pub fn has_channel(&self) -> bool {
        self.discord_webhook_url().is_some()
            || (self.telegram_token().is_some() && self.telegram_chat().is_some())
    }

    /// True when this event should actually be sent.
    pub fn enabled_for(&self, event: NotifyEvent) -> bool {
        self.wants(event) && self.has_channel()
    }

    /// True when the TUI should raise a desktop notification for this event.
    pub fn desktop_for(&self, event: NotifyEvent) -> bool {
        self.desktop == Some(true) && self.wants(event)
    }

    pub(crate) fn merge_with(&self, other: &NotifyConfig) -> NotifyConfig {
        let mut merged = self.clone();
        if !other.on.is_empty() {
            merged.on = other.on.clone();
        }
        if other.discord_webhook.is_some() {
            merged.discord_webhook = other.discord_webhook.clone();
        }
        if other.telegram_bot_token.is_some() {
            merged.telegram_bot_token = other.telegram_bot_token.clone();
        }
        if other.telegram_chat_id.is_some() {
            merged.telegram_chat_id = other.telegram_chat_id.clone();
        }
        if other.timeout_secs != default_notify_timeout_secs() {
            merged.timeout_secs = other.timeout_secs;
        }
        if other.desktop.is_some() {
            merged.desktop = other.desktop;
        }
        merged
    }
}

/// `[websearch]` — which engine the `websearch` tool queries.
///
/// ```toml
/// [websearch]
/// engine = "custom"          # serpapi | duckduckgo | custom
/// fallback = ["duckduckgo"]  # tried in order when the primary fails
/// [websearch.custom]
/// endpoint = "https://search.example.com/api"
/// header_env = { "X-Api-Key" = "SEARCH_API_KEY" }
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebSearchConfig {
    /// `serpapi`, `duckduckgo` or `custom`. Omitted = SerpAPI when
    /// `SERPAPI_API_KEY` is set, else DuckDuckGo (the behaviour before this key).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub engine: Option<String>,
    /// Engines tried in order when the primary returns an error.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fallback: Vec<String>,
    /// The `custom` engine. A layer that sets this table replaces the whole table.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custom: Option<WebSearchCustomConfig>,
}

impl WebSearchConfig {
    /// Remove what a project layer may not set: the `custom` table (its
    /// endpoint, headers and `header_env` could send env secrets to a host the
    /// repository chose) and `custom` as `engine` or in `fallback`. Returns
    /// the dropped keys.
    pub(crate) fn strip_project_only_keys(&mut self) -> Vec<&'static str> {
        let mut dropped = Vec::new();
        if self.custom.take().is_some() {
            dropped.push("websearch.custom");
        }
        if self.engine.as_deref().is_some_and(is_custom_engine) {
            self.engine = None;
            dropped.push("websearch.engine = \"custom\"");
        }
        let before = self.fallback.len();
        self.fallback.retain(|e| !is_custom_engine(e));
        if self.fallback.len() != before {
            dropped.push("\"custom\" in websearch.fallback");
        }
        dropped
    }

    pub(crate) fn merge_with(&self, other: &WebSearchConfig) -> WebSearchConfig {
        let mut merged = self.clone();
        if other.engine.is_some() {
            merged.engine = other.engine.clone();
        }
        if !other.fallback.is_empty() {
            merged.fallback = other.fallback.clone();
        }
        if other.custom.is_some() {
            merged.custom = other.custom.clone();
        }
        merged
    }
}

fn is_custom_engine(name: &str) -> bool {
    name.trim().eq_ignore_ascii_case("custom")
}

/// `[websearch.custom]` — a JSON search API mapped with JSON Pointers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebSearchCustomConfig {
    /// Request URL. The network allowlist applies to its host.
    pub endpoint: String,
    /// `GET` (query string) or `POST` (JSON body). Default `GET`.
    #[serde(default = "default_websearch_method")]
    pub method: String,
    /// Parameter that carries the query. Default `q`.
    #[serde(default = "default_websearch_query_param")]
    pub query_param: String,
    /// Parameter that carries the result count. Omitted = not sent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub count_param: Option<String>,
    /// Extra static parameters sent with every request.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub params: BTreeMap<String, String>,
    /// Static request headers.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub headers: BTreeMap<String, String>,
    /// Header name → environment variable that holds its value (never stored).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub header_env: BTreeMap<String, String>,
    /// JSON Pointer to the result array. Default `/results`.
    #[serde(default = "default_websearch_results_pointer")]
    pub results_pointer: String,
    /// JSON Pointer (inside one result) to its title. Default `/title`.
    #[serde(default = "default_websearch_title_pointer")]
    pub title_pointer: String,
    /// JSON Pointer (inside one result) to its URL. Default `/url`.
    #[serde(default = "default_websearch_url_pointer")]
    pub url_pointer: String,
    /// JSON Pointer (inside one result) to its snippet. Default `/snippet`.
    #[serde(default = "default_websearch_snippet_pointer")]
    pub snippet_pointer: String,
}

pub(crate) fn default_websearch_method() -> String {
    "GET".to_string()
}
pub(crate) fn default_websearch_query_param() -> String {
    "q".to_string()
}
pub(crate) fn default_websearch_results_pointer() -> String {
    "/results".to_string()
}
pub(crate) fn default_websearch_title_pointer() -> String {
    "/title".to_string()
}
pub(crate) fn default_websearch_url_pointer() -> String {
    "/url".to_string()
}
pub(crate) fn default_websearch_snippet_pointer() -> String {
    "/snippet".to_string()
}

/// Lifecycle events that can fire a session notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotifyEvent {
    /// Parent agent turn finished (success or cancel). Subagents do not fire this.
    TurnDone,
    /// Interactive wait: permission dialog, `question` tool, or SDK/daemon ask.
    NeedInput,
}

impl NotifyEvent {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::TurnDone => "turn_done",
            Self::NeedInput => "need_input",
        }
    }

    pub fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "turn_done" | "turn-done" | "done" => Some(Self::TurnDone),
            "need_input" | "need-input" | "input" => Some(Self::NeedInput),
            _ => None,
        }
    }
}

pub(crate) fn parse_notify_on_csv(raw: &str) -> Vec<String> {
    raw.split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(|s| s.to_ascii_lowercase())
        .collect()
}

fn nonempty_str(s: Option<&str>) -> Option<&str> {
    s.map(str::trim).filter(|s| !s.is_empty())
}

pub(crate) fn nonempty_opt(s: String) -> Option<String> {
    let t = s.trim();
    if t.is_empty() {
        None
    } else {
        Some(t.to_string())
    }
}

/// Discord Incoming Webhook host allowlist (no arbitrary POST target).
pub fn is_discord_webhook_url(url: &str) -> bool {
    let url = url.trim();
    if !url.starts_with("https://") {
        return false;
    }
    let Ok(host) = network::host_from_url(url) else {
        return false;
    };
    let host = host.to_ascii_lowercase();
    if host != "discord.com" && host != "discordapp.com" {
        return false;
    }
    // Prefix already required above; `HTTPS://` is rejected by `starts_with`.
    let rest = url.strip_prefix("https://").unwrap_or(url);
    let path_start = rest.find('/').unwrap_or(rest.len());
    let path = rest[path_start..].split(['?', '#']).next().unwrap_or("");
    path.starts_with("/api/webhooks/") && path.len() > "/api/webhooks/".len()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TuiConfig {
    #[serde(default)]
    pub theme: Option<String>,
    #[serde(default)]
    pub key_bindings: Option<HashMap<String, String>>,
    /// Idle follow-up suggestions: `"off"` (default) or `"idle"`.
    #[serde(default = "default_prompt_suggestions")]
    pub prompt_suggestions: String,
    /// Show the sidebar when the TUI opens.
    #[serde(default)]
    pub show_sidebar: bool,
    /// Per-agent (and `model`) colors for prompt chrome.
    ///
    /// Values are `#rgb` / `#rrggbb`, a theme role (`accent`, `success`,
    /// `info`, `warning`, `error`, `primary`, `secondary`, `thinking`, `dim`),
    /// or an ANSI name (`red`, `green`, …).
    ///
    /// ```toml
    /// [tui.agent_colors]
    /// build = "#7aa2f7"
    /// plan = "accent"
    /// ask = "info"
    /// model = "secondary"
    /// ```
    #[serde(default)]
    pub agent_colors: HashMap<String, String>,
    /// First-launch TUI asked for an OpenRouter API key and the user skipped.
    /// Do not re-prompt on later launches (`/connect` and Ctrl+P stay available).
    #[serde(default)]
    pub skip_openrouter_key_prompt: bool,
}

impl Default for TuiConfig {
    fn default() -> Self {
        Self {
            theme: None,
            key_bindings: None,
            prompt_suggestions: default_prompt_suggestions(),
            show_sidebar: false,
            agent_colors: HashMap::new(),
            skip_openrouter_key_prompt: false,
        }
    }
}

pub(crate) fn default_prompt_suggestions() -> String {
    "off".into()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    pub project_path: Option<PathBuf>,
    pub log_level: Option<String>,
    pub default_gcp_project: Option<String>,
    /// Check GitHub for a newer release when an interactive TUI session starts
    /// (home-screen confirm; never a silent replace).
    #[serde(default = "default_true")]
    pub auto_update: bool,
    /// Session-level overlay for when to interrupt (`auto` | `important` | `manual`).
    /// Omitted = `auto`: auto-answer questions and auto-allow permission asks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approval_mode: Option<ApprovalMode>,
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            project_path: None,
            log_level: None,
            default_gcp_project: None,
            auto_update: true,
            approval_mode: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CustomToolConfig {
    pub command: String,
    pub description: String,
    pub parameters: Option<serde_json::Value>,
}

impl CustomCommandConfig {
    /// Expand `$ARGUMENTS`, `$1`… placeholders.
    pub fn render(&self, args: &str) -> String {
        let parts: Vec<&str> = args.split_whitespace().collect();
        let mut out = self.template.clone();
        out = out.replace("$ARGUMENTS", args);
        for (i, p) in parts.iter().enumerate() {
            out = out.replace(&format!("${}", i + 1), p);
        }
        // shell injection: !`cmd` — run and replace (best-effort, sync)
        while let Some(start) = out.find("!`") {
            if let Some(rel_end) = out[start + 2..].find('`') {
                let cmd = &out[start + 2..start + 2 + rel_end];
                let output = run_inline_shell(cmd);
                out.replace_range(start..start + 2 + rel_end + 1, &output);
            } else {
                break;
            }
        }
        out
    }
}

fn run_inline_shell(cmd: &str) -> String {
    #[cfg(windows)]
    let output = std::process::Command::new("cmd").args(["/C", cmd]).output();
    #[cfg(not(windows))]
    let output = std::process::Command::new("sh").args(["-c", cmd]).output();
    match output {
        Ok(o) => {
            let mut s = String::from_utf8_lossy(&o.stdout).to_string();
            let err = String::from_utf8_lossy(&o.stderr);
            if !err.is_empty() {
                s.push_str(&err);
            }
            s
        }
        Err(e) => format!("(command failed: {})", e),
    }
}

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

    fn mcp(
        command: Option<&str>,
        url: Option<&str>,
        transport: Option<McpTransportKind>,
    ) -> McpServerConfig {
        McpServerConfig {
            transport,
            command: command.map(str::to_string),
            args: vec![],
            env: None,
            cwd: None,
            url: url.map(str::to_string),
            headers: None,
        }
    }

    #[test]
    fn mcp_notify_hooks_and_discord() {
        assert_mcp_transport();
        assert_notify_channels();
        assert_notify_events_and_discord();
    }

    fn assert_mcp_transport() {
        assert_eq!(
            mcp(Some("npx"), None, None).resolved_transport().unwrap(),
            McpTransportKind::Stdio
        );
        assert_eq!(
            mcp(None, Some("https://mcp.example"), None)
                .resolved_transport()
                .unwrap(),
            McpTransportKind::Auto
        );
        assert!(mcp(None, None, None).resolved_transport().is_err());
        assert!(
            mcp(None, None, Some(McpTransportKind::Stdio))
                .resolved_transport()
                .is_err()
        );
        assert!(
            mcp(None, None, Some(McpTransportKind::Http))
                .resolved_transport()
                .is_err()
        );
        assert!(
            mcp(None, None, Some(McpTransportKind::Sse))
                .resolved_transport()
                .is_err()
        );
        assert!(
            mcp(None, None, Some(McpTransportKind::Auto))
                .resolved_transport()
                .is_err()
        );
        assert!(mcp(None, Some("https://x"), None).stdio_problem().is_none());
        let empty = mcp(Some("  "), None, None).stdio_problem().unwrap();
        assert!(empty.contains("empty"), "{empty}");
        let bare = mcp(Some(r"C:\nodejs\npx.cmd"), None, None);
        assert!(bare.stdio_problem().unwrap().contains("package"));
        let with_pkg = McpServerConfig {
            args: vec!["-y".into(), "@scope/server".into()],
            ..bare
        };
        assert!(with_pkg.stdio_problem().is_none());
        assert!(mcp(Some("node"), None, None).stdio_problem().is_none());
        let remote = mcp(None, Some("https://x"), Some(McpTransportKind::Http));
        assert!(remote.is_remote());
        assert!(!mcp(Some("npx"), None, Some(McpTransportKind::Stdio)).is_remote());
    }

    fn assert_notify_channels() {
        let mut notify = NotifyConfig::default();
        assert!(!notify.wants(NotifyEvent::TurnDone));
        assert!(!notify.has_channel());
        notify.on = vec!["turn_done".into(), "need-input".into()];
        notify.discord_webhook = Some(" https://discord.com/api/webhooks/1/t ".into());
        assert!(notify.wants(NotifyEvent::TurnDone));
        assert!(notify.wants(NotifyEvent::NeedInput));
        assert!(notify.has_channel());
        assert!(notify.enabled_for(NotifyEvent::TurnDone));
        assert_eq!(
            notify.discord_webhook_url(),
            Some("https://discord.com/api/webhooks/1/t")
        );
        notify.telegram_bot_token = Some(" tok ".into());
        notify.telegram_chat_id = Some(" chat ".into());
        assert_eq!(notify.telegram_token(), Some("tok"));
        assert_eq!(notify.telegram_chat(), Some("chat"));
        let overlay = NotifyConfig {
            on: vec!["turn_done".into()],
            discord_webhook: Some("https://other".into()),
            telegram_bot_token: Some("b".into()),
            telegram_chat_id: Some("c".into()),
            timeout_secs: 12,
            desktop: Some(true),
        };
        let merged = notify.merge_with(&overlay);
        assert_eq!(merged.timeout_secs, 12);
        assert!(merged.desktop_for(NotifyEvent::TurnDone));
        assert!(!merged.desktop_for(NotifyEvent::NeedInput), "not in `on`");
        assert_eq!(
            merged.merge_with(&NotifyConfig::default()).desktop,
            Some(true)
        );
        assert!(!NotifyConfig::default().desktop_for(NotifyEvent::TurnDone));
    }

    fn assert_notify_events_and_discord() {
        assert_eq!(NotifyEvent::TurnDone.as_str(), "turn_done");
        assert_eq!(NotifyEvent::NeedInput.as_str(), "need_input");
        assert_eq!(NotifyEvent::parse("done"), Some(NotifyEvent::TurnDone));
        assert_eq!(NotifyEvent::parse("input"), Some(NotifyEvent::NeedInput));
        assert_eq!(NotifyEvent::parse("nope"), None);
        assert_eq!(
            parse_notify_on_csv("turn_done, need_input"),
            vec!["turn_done", "need_input"]
        );

        assert_eq!(HookEvent::default(), HookEvent::PreTool);
        let hook_json = serde_json::to_string(&HookEvent::PostTool).unwrap();
        assert!(hook_json.contains("post_tool"));

        assert!(is_discord_webhook_url(
            "https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz"
        ));
        assert!(is_discord_webhook_url(
            "https://discordapp.com/api/webhooks/1/token"
        ));
        assert!(!is_discord_webhook_url(
            "https://example.com/api/webhooks/1/t"
        ));
        assert!(!is_discord_webhook_url("not-a-url"));
        assert!(!is_discord_webhook_url("https://discord.com/api/webhooks/"));
        assert_eq!(CONFIG_SCHEMA_VERSION, 1);
    }
}