cc-switch-tui 0.2.2

All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode, OpenClaw & Hermes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
//! Hermes Agent 配置文件读写模块
//!
//! 处理 `~/.hermes/config.yaml` 配置文件的读写操作(YAML 格式)。
//! Hermes 使用累加式供应商管理,所有供应商配置共存于同一配置文件中。
//!
//! ## 配置结构示例
//!
//! ```yaml
//! model:
//!   default: "anthropic/claude-opus-4-7"
//!   provider: "openrouter"
//!   base_url: "https://openrouter.ai/api/v1"
//!
//! agent:
//!   max_turns: 50
//!   reasoning_effort: "high"
//!
//! custom_providers:
//!   - name: openrouter
//!     base_url: https://openrouter.ai/api/v1
//!     api_key: sk-or-...
//!     model: anthropic/claude-opus-4-7
//!     models:
//!       anthropic/claude-opus-4-7:
//!         context_length: 200000
//!
//! mcp_servers:
//!   filesystem:
//!     command: npx
//!     args: ["-y", "@modelcontextprotocol/server-filesystem"]
//! ```

use crate::config::{atomic_write, get_app_config_dir};
use crate::error::AppError;
use crate::settings::{effective_backup_retain_count, get_hermes_override_dir};
use chrono::Local;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

// ============================================================================
// Path Functions
// ============================================================================

/// 获取 Hermes 配置目录
///
/// Priority: `HERMES_HOME` env var > cc-switch settings override > `$HOME/.hermes`
pub fn get_hermes_dir() -> PathBuf {
    if let Some(dir) = std::env::var_os("HERMES_HOME") {
        let dir = PathBuf::from(dir);
        if !dir.as_os_str().is_empty() && !dir.to_string_lossy().trim().is_empty() {
            return crate::config::expand_tilde(dir);
        }
    }

    if let Some(override_dir) = get_hermes_override_dir() {
        return override_dir;
    }

    crate::config::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".hermes")
}

/// 获取 Hermes 配置文件路径
///
/// 返回 `~/.hermes/config.yaml`
pub fn get_hermes_config_path() -> PathBuf {
    get_hermes_dir().join("config.yaml")
}

fn hermes_write_lock() -> &'static Mutex<()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

// ============================================================================
// Type Definitions
// ============================================================================

/// Hermes 写入结果
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct HermesWriteOutcome {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup_path: Option<String>,
}

/// Hermes model section config
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HermesModelConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_length: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u64>,
    /// Preserve unknown fields for forward compatibility
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

// ============================================================================
// Core YAML Read Functions
// ============================================================================

/// 读取 Hermes 配置文件为 serde_yaml::Value
///
/// 如果文件不存在,返回空 Mapping
pub fn read_hermes_config() -> Result<serde_yaml::Value, AppError> {
    let path = get_hermes_config_path();
    if !path.exists() {
        return Ok(serde_yaml::Value::Mapping(serde_yaml::Mapping::new()));
    }

    let content = fs::read_to_string(&path).map_err(|e| AppError::io(&path, e))?;
    if content.trim().is_empty() {
        return Ok(serde_yaml::Value::Mapping(serde_yaml::Mapping::new()));
    }

    serde_yaml::from_str(&content)
        .map_err(|e| AppError::Config(format!("Failed to parse Hermes config as YAML: {e}")))
}

// ============================================================================
// YAML Section-Level Replacement
// ============================================================================

/// Check if a line is a YAML top-level key (mapping key at column 0).
///
/// A top-level key line must:
/// - Start at column 0 (no leading whitespace)
/// - Not be empty or whitespace-only
/// - Not be a comment (starting with `#`)
/// - Not be a sequence item (starting with `-`)
/// - Contain `:` followed by space, tab, newline, or end-of-line
fn is_top_level_key_line(line: &str) -> bool {
    if line.is_empty() {
        return false;
    }
    let first_char = line.as_bytes()[0];
    if first_char == b' ' || first_char == b'\t' || first_char == b'#' || first_char == b'-' {
        return false;
    }
    if let Some(colon_pos) = line.find(':') {
        let after_colon = &line[colon_pos + 1..];
        after_colon.is_empty() || after_colon.starts_with(' ') || after_colon.starts_with('\t')
    } else {
        false
    }
}

/// Find the byte range of a top-level YAML section.
///
/// A YAML top-level key is a line that starts at column 0 (no leading
/// whitespace), is not a comment, and contains `:` after the key name.
///
/// Returns `(start_byte_inclusive, end_byte_exclusive)` or `None` if not found.
fn find_yaml_section_range(raw: &str, section_key: &str) -> Option<(usize, usize)> {
    let target = format!("{}:", section_key);
    let mut section_start = None;
    let mut offset = 0;

    for line in raw.split('\n') {
        if section_start.is_none() && is_top_level_key_line(line) && line.starts_with(&target) {
            // Verify exact match: after "key:" must be whitespace or EOL
            let after_target = &line[target.len()..];
            if after_target.is_empty()
                || after_target.starts_with(' ')
                || after_target.starts_with('\t')
                || after_target.starts_with('\r')
            {
                section_start = Some(offset);
            }
        } else if section_start.is_some() && is_top_level_key_line(line) {
            // Found the next top-level key — this is the end of our section
            return Some((section_start.unwrap(), offset));
        }
        offset += line.len() + 1; // +1 for the \n
    }

    // Section extends to end of file
    section_start.map(|start| (start, raw.len()))
}

/// Serialize a section key + value into a YAML fragment like:
///
/// ```yaml
/// model:
///   default: "anthropic/claude-opus-4-7"
///   provider: "openrouter"
/// ```
fn serialize_yaml_section(key: &str, value: &serde_yaml::Value) -> Result<String, AppError> {
    let mut section = serde_yaml::Mapping::new();
    section.insert(serde_yaml::Value::String(key.to_string()), value.clone());
    let yaml_str = serde_yaml::to_string(&serde_yaml::Value::Mapping(section))
        .map_err(|e| AppError::Config(format!("Failed to serialize YAML section '{key}': {e}")))?;
    Ok(yaml_str)
}

/// Replace a YAML section in raw text, or append it if not found.
fn replace_yaml_section(
    raw: &str,
    section_key: &str,
    value: &serde_yaml::Value,
) -> Result<String, AppError> {
    let serialized = serialize_yaml_section(section_key, value)?;

    if let Some((start, end)) = find_yaml_section_range(raw, section_key) {
        let mut result = String::with_capacity(raw.len());
        result.push_str(&raw[..start]);
        result.push_str(&serialized);
        // Ensure proper separation between sections
        let remainder = &raw[end..];
        if !serialized.ends_with('\n') && !remainder.is_empty() && !remainder.starts_with('\n') {
            result.push('\n');
        }
        result.push_str(remainder);
        Ok(result)
    } else {
        // Section not found — append at end
        let mut result = raw.to_string();
        if !result.is_empty() && !result.ends_with('\n') {
            result.push('\n');
        }
        result.push_str(&serialized);
        if !result.ends_with('\n') {
            result.push('\n');
        }
        Ok(result)
    }
}

// ============================================================================
// Backup & Cleanup
// ============================================================================

fn create_hermes_backup(source: &str) -> Result<PathBuf, AppError> {
    let backup_dir = get_app_config_dir().join("backups").join("hermes");
    fs::create_dir_all(&backup_dir).map_err(|e| AppError::io(&backup_dir, e))?;

    let base_id = format!("hermes_{}", Local::now().format("%Y%m%d_%H%M%S"));
    let mut filename = format!("{base_id}.yaml");
    let mut backup_path = backup_dir.join(&filename);
    let mut counter = 1;

    while backup_path.exists() {
        filename = format!("{base_id}_{counter}.yaml");
        backup_path = backup_dir.join(&filename);
        counter += 1;
    }

    atomic_write(&backup_path, source.as_bytes())?;
    cleanup_hermes_backups(&backup_dir)?;
    Ok(backup_path)
}

fn cleanup_hermes_backups(dir: &Path) -> Result<(), AppError> {
    let retain = effective_backup_retain_count();
    let mut entries = fs::read_dir(dir)
        .map_err(|e| AppError::io(dir, e))?
        .filter_map(|entry| entry.ok())
        .filter(|entry| {
            entry
                .path()
                .extension()
                .map(|ext| ext == "yaml" || ext == "yml")
                .unwrap_or(false)
        })
        .collect::<Vec<_>>();

    if entries.len() <= retain {
        return Ok(());
    }

    entries.sort_by_key(|entry| entry.metadata().and_then(|m| m.modified()).ok());
    let remove_count = entries.len().saturating_sub(retain);
    for entry in entries.into_iter().take(remove_count) {
        if let Err(err) = fs::remove_file(entry.path()) {
            log::warn!(
                "Failed to remove old Hermes config backup {}: {err}",
                entry.path().display()
            );
        }
    }

    Ok(())
}

// ============================================================================
// High-level Write Helper
// ============================================================================

/// Write a single top-level YAML section to config.yaml using section-level replacement.
///
/// This preserves comments and unrelated sections while only modifying the
/// target section.
fn write_yaml_section_to_config(
    section_key: &str,
    value: &serde_yaml::Value,
) -> Result<HermesWriteOutcome, AppError> {
    let _guard = hermes_write_lock().lock()?;
    write_yaml_section_to_config_locked(section_key, value)
}

/// Inner write helper — caller must already hold the write lock.
fn write_yaml_section_to_config_locked(
    section_key: &str,
    value: &serde_yaml::Value,
) -> Result<HermesWriteOutcome, AppError> {
    let config_path = get_hermes_config_path();
    let raw = if config_path.exists() {
        fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?
    } else {
        String::new()
    };

    let new_raw = replace_yaml_section(&raw, section_key, value)?;

    if new_raw == raw {
        return Ok(HermesWriteOutcome::default());
    }

    let backup_path = if !raw.is_empty() {
        Some(create_hermes_backup(&raw)?)
    } else {
        None
    };

    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent).map_err(|e| AppError::io(parent, e))?;
    }

    atomic_write(&config_path, new_raw.as_bytes())?;

    log::debug!(
        "Hermes config section '{}' written to {:?}",
        section_key,
        config_path
    );
    Ok(HermesWriteOutcome {
        backup_path: backup_path.map(|p| p.display().to_string()),
    })
}

// ============================================================================
// Provider Functions
// ============================================================================

/// Convert a provider's `models` field from a UI-friendly array to the YAML
/// dict shape that Hermes expects.
///
/// Input (from CC Switch UI / database):
/// ```json
/// "models": [{ "id": "foo", "context_length": 200000 }, { "id": "bar" }]
/// ```
///
/// Output (what we write to YAML):
/// ```json
/// "models": { "foo": { "context_length": 200000 }, "bar": {} }
/// ```
///
/// Entries with a missing or empty `id` are dropped. The top-level `id` key
/// is stripped from each value since it now lives on the parent as the map
/// key. Insertion order is preserved (serde_json uses IndexMap under the
/// `preserve_order` feature).
fn models_array_to_dict(array: Vec<serde_json::Value>) -> serde_json::Value {
    let mut map = serde_json::Map::new();
    for item in array {
        let serde_json::Value::Object(mut obj) = item else {
            continue;
        };
        let Some(id) = obj
            .remove("id")
            .and_then(|v| v.as_str().map(|s| s.trim().to_string()))
            .filter(|s| !s.is_empty())
        else {
            continue;
        };
        map.insert(id, serde_json::Value::Object(obj));
    }
    serde_json::Value::Object(map)
}

/// Inverse of [`models_array_to_dict`]. Converts the YAML dict shape back to
/// the UI-friendly ordered array, re-injecting `id` as an object field.
fn models_dict_to_array(dict: serde_json::Map<String, serde_json::Value>) -> serde_json::Value {
    let mut out = Vec::with_capacity(dict.len());
    for (id, value) in dict {
        let mut obj = match value {
            serde_json::Value::Object(obj) => obj,
            serde_json::Value::Null => serde_json::Map::new(),
            other => {
                log::warn!("Unexpected Hermes model entry for '{id}': {other:?}, skipping");
                continue;
            }
        };
        obj.insert("id".to_string(), serde_json::Value::String(id));
        out.push(serde_json::Value::Object(obj));
    }
    serde_json::Value::Array(out)
}

/// Rewrite historical camelCase keys to Hermes' snake_case schema.
///
/// Older DeepLink import paths emitted `baseUrl` / `apiKey` / `apiMode` /
/// `maxTokens` / `contextLength`, which do not belong to Hermes'
/// `_VALID_CUSTOM_PROVIDER_FIELDS` set. Writing those raw to YAML silently
/// poisons `custom_providers:` entries. This sanitiser runs defensively on
/// every `set_provider` call so stored data heals on the next activation;
/// unknown keys pass through untouched to keep forward-compat with new
/// Hermes fields (e.g. `request_timeout_seconds`).
fn sanitize_hermes_provider_keys(config: &mut serde_json::Value) {
    const KEY_ALIASES: &[(&str, &str)] = &[
        ("baseUrl", "base_url"),
        ("apiKey", "api_key"),
        ("apiMode", "api_mode"),
        ("maxTokens", "max_tokens"),
        ("contextLength", "context_length"),
    ];
    // Legacy DeepLink emitted `api: "openai-completions"` which is neither a
    // Hermes field nor mappable to `api_mode`. `_cc_source` / `provider_key`
    // are UI-only markers injected on read — they must never reach YAML.
    const LEGACY_FIELDS_TO_DROP: &[&str] = &["api", PROVIDER_SOURCE_FIELD, "provider_key"];

    let Some(obj) = config.as_object_mut() else {
        return;
    };

    for (from, to) in KEY_ALIASES {
        if let Some(val) = obj.remove(*from) {
            // snake_case wins when both are present; stale camelCase is dropped.
            obj.entry((*to).to_string()).or_insert(val);
        }
    }

    for field in LEGACY_FIELDS_TO_DROP {
        obj.remove(*field);
    }

    if let Some(models) = obj.get_mut("models") {
        match models {
            serde_json::Value::Array(models) => {
                for model in models {
                    sanitize_hermes_model_keys(model);
                }
            }
            serde_json::Value::Object(models) => {
                for model in models.values_mut() {
                    sanitize_hermes_model_keys(model);
                }
            }
            _ => {}
        }
    }
}

fn sanitize_hermes_model_keys(model: &mut serde_json::Value) {
    let Some(model) = model.as_object_mut() else {
        return;
    };
    for (from, to) in [
        ("contextWindow", "context_length"),
        ("context_window", "context_length"),
        ("contextLength", "context_length"),
        ("maxTokens", "max_tokens"),
    ] {
        if let Some(value) = model.remove(from) {
            model.entry(to.to_string()).or_insert(value);
        }
    }
}

fn canonical_hermes_provider_key(key: &str) -> &str {
    match key {
        "baseUrl" => "base_url",
        "apiKey" => "api_key",
        "apiMode" => "api_mode",
        "maxTokens" => "max_tokens",
        "contextLength" => "context_length",
        other => other,
    }
}

fn invalid_hermes_models(provider_id: &str, detail_zh: &str, detail_en: &str) -> AppError {
    AppError::localized(
        "provider.hermes.models.invalid",
        format!("Hermes 供应商 {provider_id} 的 models 配置无效:{detail_zh}"),
        format!("Hermes provider {provider_id} has invalid models: {detail_en}"),
    )
}

fn normalize_hermes_model_array(
    provider_id: &str,
    models: Vec<serde_json::Value>,
) -> Result<Vec<serde_json::Value>, AppError> {
    let mut normalized = Vec::with_capacity(models.len());
    let mut ids = HashSet::with_capacity(models.len());

    for (index, mut model) in models.into_iter().enumerate() {
        sanitize_hermes_model_keys(&mut model);
        let obj = model.as_object_mut().ok_or_else(|| {
            invalid_hermes_models(
                provider_id,
                &format!("{} 项必须是对象", index + 1),
                &format!("entry {} must be an object", index + 1),
            )
        })?;
        let id = obj
            .get("id")
            .and_then(serde_json::Value::as_str)
            .map(str::trim)
            .filter(|id| !id.is_empty())
            .map(str::to_string)
            .ok_or_else(|| {
                invalid_hermes_models(
                    provider_id,
                    &format!("{} 项缺少非空模型 ID", index + 1),
                    &format!("entry {} requires a non-empty model ID", index + 1),
                )
            })?;
        if !ids.insert(id.clone()) {
            return Err(invalid_hermes_models(
                provider_id,
                &format!("模型 ID `{id}` 重复"),
                &format!("model ID `{id}` is duplicated"),
            ));
        }
        obj.insert("id".to_string(), serde_json::Value::String(id));

        for (key, label_zh, label_en) in [
            ("context_length", "上下文长度", "context_length"),
            ("max_tokens", "最大输出 Token", "max_tokens"),
        ] {
            if obj
                .get(key)
                .is_some_and(|value| value.as_u64().is_none_or(|value| value == 0))
            {
                return Err(invalid_hermes_models(
                    provider_id,
                    &format!("模型 `{}` 的{label_zh}必须是正整数", obj["id"]),
                    &format!(
                        "model `{}` {label_en} must be a positive integer",
                        obj["id"]
                    ),
                ));
            }
        }
        normalized.push(model);
    }

    Ok(normalized)
}

/// Canonicalize provider settings before saving them to the database.
///
/// Both Hermes' YAML dictionary shape and CC Switch's ordered array shape are
/// accepted on input. The stored representation is always an array so the TUI
/// and database use one stable schema. Malformed entries are rejected instead
/// of being silently discarded by the YAML writer.
pub fn normalize_provider_settings_for_storage(
    provider_id: &str,
    config: &mut serde_json::Value,
) -> Result<(), AppError> {
    if !config.is_object() {
        return Err(AppError::localized(
            "provider.hermes.settings.not_object",
            "Hermes 供应商配置必须是 JSON 对象",
            "Hermes provider configuration must be a JSON object",
        ));
    }
    sanitize_hermes_provider_keys(config);

    let Some(models_value) = config
        .as_object_mut()
        .and_then(|settings| settings.get_mut("models"))
    else {
        return Ok(());
    };
    let models = match std::mem::take(models_value) {
        serde_json::Value::Array(models) => models,
        serde_json::Value::Object(models) => {
            let mut array = Vec::with_capacity(models.len());
            for (raw_id, value) in models {
                let id = raw_id.trim();
                if id.is_empty() {
                    return Err(invalid_hermes_models(
                        provider_id,
                        "模型字典包含空白 ID",
                        "the model dictionary contains a blank ID",
                    ));
                }
                let mut model = match value {
                    serde_json::Value::Object(model) => model,
                    serde_json::Value::Null => serde_json::Map::new(),
                    _ => {
                        return Err(invalid_hermes_models(
                            provider_id,
                            &format!("模型 `{id}` 的值必须是对象"),
                            &format!("model `{id}` must contain an object value"),
                        ));
                    }
                };
                model.insert("id".to_string(), serde_json::Value::String(id.to_string()));
                array.push(serde_json::Value::Object(model));
            }
            array
        }
        _ => {
            return Err(invalid_hermes_models(
                provider_id,
                "models 必须是数组或对象字典",
                "models must be an array or object dictionary",
            ));
        }
    };
    *models_value = serde_json::Value::Array(normalize_hermes_model_array(provider_id, models)?);
    Ok(())
}

pub fn validate_provider_settings(
    provider_id: &str,
    config: &serde_json::Value,
) -> Result<(), AppError> {
    let mut normalized = config.clone();
    normalize_provider_settings_for_storage(provider_id, &mut normalized)
}

/// Return canonical top-level fields that existed in the stored provider but
/// were explicitly omitted by an update. Live-only fields are not present in
/// the stored snapshot and therefore remain eligible for forward-compatible
/// preservation by the YAML merge.
pub(crate) fn removed_provider_fields(
    previous: &serde_json::Value,
    updated: &serde_json::Value,
) -> Vec<String> {
    let Some(previous) = previous.as_object() else {
        return Vec::new();
    };
    let updated_keys: HashSet<&str> = updated
        .as_object()
        .into_iter()
        .flat_map(|updated| updated.keys())
        .map(|key| canonical_hermes_provider_key(key))
        .collect();
    let mut removed: Vec<String> = previous
        .keys()
        .map(|key| canonical_hermes_provider_key(key))
        .filter(|key| {
            !matches!(
                *key,
                "name" | "model" | "models" | PROVIDER_SOURCE_FIELD | "provider_key"
            ) && !updated_keys.contains(*key)
        })
        .map(str::to_string)
        .collect();
    removed.sort();
    removed.dedup();
    removed
}

/// If `config.models` is a JSON array, convert it in-place to the dict shape.
/// No-op when `models` is absent or already a dict.
fn normalize_provider_models_for_write(config: &mut serde_json::Value) {
    let Some(obj) = config.as_object_mut() else {
        return;
    };
    let Some(models_val) = obj.get_mut("models") else {
        return;
    };
    if models_val.is_array() {
        let taken = std::mem::take(models_val);
        if let serde_json::Value::Array(arr) = taken {
            *models_val = models_array_to_dict(arr);
        }
    }
}

fn merge_existing_hermes_model_fields(
    existing_provider: &serde_yaml::Mapping,
    new_provider: &mut serde_yaml::Mapping,
) {
    let models_key = serde_yaml::Value::String("models".to_string());
    let Some(existing_models) = existing_provider
        .get(&models_key)
        .and_then(serde_yaml::Value::as_mapping)
    else {
        return;
    };
    let Some(new_models) = new_provider
        .get_mut(&models_key)
        .and_then(serde_yaml::Value::as_mapping_mut)
    else {
        return;
    };

    for (model_id, new_model) in new_models {
        let Some(existing_model) = existing_models
            .get(model_id)
            .and_then(serde_yaml::Value::as_mapping)
        else {
            continue;
        };
        let Some(new_model) = new_model.as_mapping_mut() else {
            continue;
        };
        for (key, value) in existing_model {
            if matches!(
                key.as_str(),
                Some(
                    "context_length"
                        | "context_window"
                        | "contextWindow"
                        | "contextLength"
                        | "max_tokens"
                        | "maxTokens"
                )
            ) {
                continue;
            }
            new_model
                .entry(key.clone())
                .or_insert_with(|| value.clone());
        }
    }
}

/// If `config.models` is a JSON dict, convert it in-place to the ordered array
/// shape. No-op when `models` is absent or already an array.
fn denormalize_provider_models_for_read(config: &mut serde_json::Value) {
    let Some(obj) = config.as_object_mut() else {
        return;
    };
    let Some(models_val) = obj.get_mut("models") else {
        return;
    };
    if models_val.is_object() {
        let has_invalid_entry = models_val.as_object().is_some_and(|models| {
            models
                .values()
                .any(|value| !(value.is_object() || value.is_null()))
        });
        if has_invalid_entry {
            log::warn!("Preserving malformed Hermes models dictionary so validation can report it");
            return;
        }
        let taken = std::mem::take(models_val);
        if let serde_json::Value::Object(map) = taken {
            *models_val = models_dict_to_array(map);
        }
    }
}

/// Marker field injected on provider payloads sourced from Hermes v12+
/// `providers:` dict. CC Switch treats those as read-only — writes have to
/// go through Hermes' own Web UI to keep its overlay semantics intact.
pub const PROVIDER_SOURCE_FIELD: &str = "_cc_source";
pub const PROVIDER_SOURCE_CUSTOM_LIST: &str = "custom_providers";
pub const PROVIDER_SOURCE_DICT: &str = "providers_dict";

/// Normalize a single entry from the v12+ `providers:` dict into the same
/// JSON shape that `custom_providers:` list entries take, mirroring upstream
/// `_normalize_custom_provider_entry` (hermes_cli/config.py).
///
/// Returns `None` when the entry is not a mapping or lacks any usable name.
fn normalize_providers_dict_entry(
    key: &str,
    entry: &serde_yaml::Value,
) -> Result<Option<serde_json::Value>, AppError> {
    if !entry.is_mapping() {
        return Ok(None);
    }
    let mut json_val = yaml_to_json(entry)?;
    let Some(obj) = json_val.as_object_mut() else {
        return Ok(None);
    };
    // Upstream prefers an explicit `name` when present, falling back to the
    // dict key. Always round-trip it to a trimmed non-empty string.
    let resolved_name = obj
        .get("name")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| key.trim().to_string());
    if resolved_name.is_empty() {
        return Ok(None);
    }
    obj.insert("name".to_string(), serde_json::json!(resolved_name));
    obj.insert("provider_key".to_string(), serde_json::json!(key));
    obj.insert(
        PROVIDER_SOURCE_FIELD.to_string(),
        serde_json::json!(PROVIDER_SOURCE_DICT),
    );
    Ok(Some(json_val))
}

/// Collect provider entries living under the v12+ `providers:` dict.
fn read_providers_dict_entries(config: &serde_yaml::Value) -> Vec<(String, serde_json::Value)> {
    let Some(mapping) = config.get("providers").and_then(|v| v.as_mapping()) else {
        return Vec::new();
    };
    let mut out = Vec::with_capacity(mapping.len());
    for (k, v) in mapping {
        let Some(key_str) = k.as_str().map(str::trim).filter(|s| !s.is_empty()) else {
            continue;
        };
        match normalize_providers_dict_entry(key_str, v) {
            Ok(Some(entry)) => {
                let name = entry
                    .get("name")
                    .and_then(|n| n.as_str())
                    .unwrap_or(key_str)
                    .to_string();
                out.push((name, entry));
            }
            Ok(None) => {
                log::debug!("Skipping Hermes providers['{key_str}']: not a mapping");
            }
            Err(e) => {
                log::warn!("Failed to normalize Hermes providers['{key_str}']: {e}");
            }
        }
    }
    out
}

/// Get all providers as a JSON map keyed by provider name.
///
/// Unions two on-disk sources, matching upstream `get_compatible_custom_providers`:
/// - `custom_providers:` list entries (writable by CC Switch)
/// - `providers:` dict entries (v12+ schema, surfaced read-only with
///   `_cc_source = "providers_dict"` so the UI can disable edit/delete)
///
/// When a name appears in both, the list entry wins (upstream dedup order),
/// keeping CC Switch free to edit it. Models are denormalized from the YAML
/// dict shape to the UI-friendly ordered array.
pub fn get_providers() -> Result<serde_json::Map<String, serde_json::Value>, AppError> {
    let config = read_hermes_config()?;
    let mut map = serde_json::Map::new();

    if let Some(seq) = config.get("custom_providers").and_then(|v| v.as_sequence()) {
        for item in seq {
            if let Some(name) = item.get("name").and_then(|n| n.as_str()) {
                match yaml_to_json(item) {
                    Ok(mut json_val) => {
                        // Heal legacy camelCase records (from older DeepLink
                        // imports) before the UI sees them, so editing doesn't
                        // reveal stale `baseUrl` / `apiKey` fields.
                        sanitize_hermes_provider_keys(&mut json_val);
                        denormalize_provider_models_for_read(&mut json_val);
                        if let Some(obj) = json_val.as_object_mut() {
                            obj.insert(
                                PROVIDER_SOURCE_FIELD.to_string(),
                                serde_json::json!(PROVIDER_SOURCE_CUSTOM_LIST),
                            );
                        }
                        map.insert(name.to_string(), json_val);
                    }
                    Err(e) => {
                        log::warn!("Failed to convert Hermes provider '{name}' to JSON: {e}");
                    }
                }
            }
        }
    }

    for (name, mut entry) in read_providers_dict_entries(&config) {
        if map.contains_key(&name) {
            continue; // list wins over dict on duplicate names
        }
        denormalize_provider_models_for_read(&mut entry);
        map.insert(name, entry);
    }

    // If model: section references a provider not yet in the list, surface it
    // so the UI always shows the active provider. Built-in providers (e.g.
    // xiaomi, openai) are not in custom_providers or providers dict.
    if let Some(model_section) = config.get("model").and_then(|v| v.as_mapping()) {
        let provider_name = model_section
            .get("provider")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty());
        if let Some(provider_name) = provider_name {
            if !map.contains_key(provider_name) {
                // Build a minimal provider entry from the model section
                let mut entry = serde_json::Map::new();
                entry.insert("name".to_string(), serde_json::json!(provider_name));
                if let Some(base_url) = model_section.get("base_url").and_then(|v| v.as_str()) {
                    entry.insert("base_url".to_string(), serde_json::json!(base_url));
                }
                if let Some(api_key) = model_section.get("api_key").and_then(|v| v.as_str()) {
                    entry.insert("api_key".to_string(), serde_json::json!(api_key));
                }
                if let Some(default_model) = model_section.get("default").and_then(|v| v.as_str()) {
                    entry.insert(
                        "default_model".to_string(),
                        serde_json::json!(default_model),
                    );
                    // Also add as a single-model entry for the UI
                    let mut models = serde_json::Map::new();
                    models.insert(
                        default_model.to_string(),
                        serde_json::json!({"name": default_model}),
                    );
                    entry.insert("models".to_string(), serde_json::Value::Object(models));
                }
                entry.insert(
                    PROVIDER_SOURCE_FIELD.to_string(),
                    serde_json::json!("model_section"),
                );
                map.insert(provider_name.to_string(), serde_json::Value::Object(entry));
            }
        }
    }

    Ok(map)
}

/// Reject writes that would target a dict-only overlay entry.
///
/// `verb` is inlined into the user-facing error so both "edit" and "remove"
/// callers can share one implementation.
fn ensure_provider_writable(
    config: &serde_yaml::Value,
    name: &str,
    verb: &str,
) -> Result<(), AppError> {
    if is_dict_only_provider(config, name) {
        return Err(AppError::Config(format!(
            "Provider '{name}' is managed by Hermes' 'providers:' dict — {verb} via Hermes Web UI"
        )));
    }
    Ok(())
}

/// True when `name` appears in `providers:` dict but not in `custom_providers:`
/// list — i.e. it is a read-only overlay CC Switch must not touch.
fn is_dict_only_provider(config: &serde_yaml::Value, name: &str) -> bool {
    let list_has = config
        .get("custom_providers")
        .and_then(|v| v.as_sequence())
        .map(|seq| {
            seq.iter()
                .any(|item| item.get("name").and_then(|n| n.as_str()) == Some(name))
        })
        .unwrap_or(false);
    if list_has {
        return false;
    }
    config
        .get("providers")
        .and_then(|v| v.as_mapping())
        .map(|m| {
            m.iter().any(|(k, v)| {
                let key_matches = k.as_str() == Some(name);
                let name_matches = v
                    .get("name")
                    .and_then(|n| n.as_str())
                    .map(|s| s == name)
                    .unwrap_or(false);
                (key_matches || name_matches) && v.is_mapping()
            })
        })
        .unwrap_or(false)
}

/// Get a single custom provider by name.
#[cfg(test)]
pub fn get_provider(name: &str) -> Result<Option<serde_json::Value>, AppError> {
    Ok(get_providers()?.get(name).cloned())
}

/// Set (upsert) a custom provider by name.
///
/// Upserts into the `custom_providers:` YAML sequence (matched by `name`).
/// The entry includes:
///   - `name:` field matching the provider id
///   - singular `model:` field set to the first model id from the `models:`
///     dict — the Hermes runtime and `/model` picker both read this field
///     (runtime_provider.py reads it via `_normalize_custom_provider_entry`;
///     main.py:1436/1450 uses it for picker hints)
///   - plural `models:` dict carrying per-model `context_length` etc.
///
/// The entire read-modify-write is done under the write lock to prevent
/// TOCTOU races.
pub fn set_provider(
    name: &str,
    provider_config: serde_json::Value,
) -> Result<HermesWriteOutcome, AppError> {
    set_provider_with_removed_fields(name, provider_config, &[])
}

/// Set a provider while honoring fields explicitly removed from the stored
/// snapshot. Missing fields not listed here are still preserved from live YAML
/// for forward compatibility with Hermes-managed settings.
pub fn set_provider_with_removed_fields(
    name: &str,
    provider_config: serde_json::Value,
    removed_fields: &[String],
) -> Result<HermesWriteOutcome, AppError> {
    let _guard = hermes_write_lock().lock()?;

    let config = read_hermes_config()?;
    ensure_provider_writable(&config, name, "edit")?;
    let mut providers: Vec<serde_yaml::Value> = config
        .get("custom_providers")
        .and_then(|v| v.as_sequence())
        .cloned()
        .unwrap_or_default();

    // Rewrite any historical camelCase keys (e.g. from older DeepLink imports)
    // before touching models / YAML — avoids writing non-Hermes fields back.
    let mut normalized = provider_config;
    normalize_provider_settings_for_storage(name, &mut normalized)?;
    let removed_fields: HashSet<&str> = removed_fields
        .iter()
        .map(|field| canonical_hermes_provider_key(field))
        .collect();
    let models_were_explicit = normalized
        .as_object()
        .is_some_and(|provider| provider.contains_key("models"));

    // Normalize `models` from UI array to Hermes YAML dict before serializing.
    normalize_provider_models_for_write(&mut normalized);

    // Extract the first model id (now a key in the normalized dict) so we can
    // propagate it to the singular `model:` field Hermes reads.
    let first_model_id = normalized
        .get("models")
        .and_then(|v| v.as_object())
        .and_then(|obj| obj.keys().next())
        .cloned();

    let mut yaml_val: serde_yaml::Value = json_to_yaml(&normalized)?;
    if let serde_yaml::Value::Mapping(ref mut m) = yaml_val {
        m.insert(
            serde_yaml::Value::String("name".to_string()),
            serde_yaml::Value::String(name.to_string()),
        );
        if let Some(model_id) = first_model_id {
            m.insert(
                serde_yaml::Value::String("model".to_string()),
                serde_yaml::Value::String(model_id),
            );
        } else {
            m.remove(serde_yaml::Value::String("model".to_string()));
        }
        if models_were_explicit
            && m.get("models")
                .and_then(serde_yaml::Value::as_mapping)
                .is_some_and(serde_yaml::Mapping::is_empty)
        {
            m.remove(serde_yaml::Value::String("models".to_string()));
        }
    }

    if let Some(existing) = providers
        .iter_mut()
        .find(|p| p.get("name").and_then(|n| n.as_str()) == Some(name))
    {
        // Forward-compat: carry over any on-disk fields the UI payload didn't
        // include. Hermes keeps evolving (e.g. `request_timeout_seconds`,
        // `key_env`), and users may set those via Hermes Web UI — without
        // this merge, a CC Switch edit to an unrelated field would silently
        // strip them on write-back.
        if let (Some(existing_map), serde_yaml::Value::Mapping(new_map)) =
            (existing.as_mapping(), &mut yaml_val)
        {
            if models_were_explicit {
                merge_existing_hermes_model_fields(existing_map, new_map);
            }
            for (k, v) in existing_map {
                if models_were_explicit && matches!(k.as_str(), Some("model") | Some("models")) {
                    continue;
                }
                if k.as_str()
                    .map(canonical_hermes_provider_key)
                    .is_some_and(|key| removed_fields.contains(key))
                {
                    continue;
                }
                new_map.entry(k.clone()).or_insert_with(|| v.clone());
            }
        }
        *existing = yaml_val;
    } else {
        providers.push(yaml_val);
    }

    let providers_value = serde_yaml::Value::Sequence(providers);
    write_yaml_section_to_config_locked("custom_providers", &providers_value)
}

/// Remove a custom provider by name.
///
/// Filters out the matching entry from the `custom_providers:` sequence.
/// No-op if the section is missing or no entry matches. The entire
/// read-modify-write is done under the write lock to prevent TOCTOU races.
pub fn remove_provider(name: &str) -> Result<HermesWriteOutcome, AppError> {
    let _guard = hermes_write_lock().lock()?;
    let config = read_hermes_config()?;

    ensure_provider_writable(&config, name, "remove")?;

    let mut providers: Vec<serde_yaml::Value> = config
        .get("custom_providers")
        .and_then(|v| v.as_sequence())
        .cloned()
        .unwrap_or_default();

    let original_len = providers.len();
    providers.retain(|p| p.get("name").and_then(|n| n.as_str()) != Some(name));
    if providers.len() == original_len {
        return Ok(HermesWriteOutcome::default());
    }

    let providers_value = serde_yaml::Value::Sequence(providers);
    write_yaml_section_to_config_locked("custom_providers", &providers_value)
}

// ============================================================================
// Model Config Functions
// ============================================================================

/// Get the `model` section as a typed config.
pub fn get_model_config() -> Result<Option<HermesModelConfig>, AppError> {
    let config = read_hermes_config()?;
    let Some(model_value) = config.get("model") else {
        return Ok(None);
    };
    let json_val = yaml_to_json(model_value)?;
    let model = serde_json::from_value(json_val)
        .map_err(|e| AppError::Config(format!("Failed to parse Hermes model config: {e}")))?;
    Ok(Some(model))
}

/// Set the `model` section.
pub fn set_model_config(model: &HermesModelConfig) -> Result<HermesWriteOutcome, AppError> {
    let json_val =
        serde_json::to_value(model).map_err(|e| AppError::JsonSerialize { source: e })?;
    let yaml_val = json_to_yaml(&json_val)?;
    write_yaml_section_to_config("model", &yaml_val)
}

fn provider_alias_string(
    settings_config: &serde_json::Value,
    primary_key: &str,
    alias_key: &str,
) -> Option<String> {
    settings_config
        .get(primary_key)
        .or_else(|| settings_config.get(alias_key))
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

/// Apply the top-level `model:` defaults when switching to a Hermes provider.
///
/// `model.provider` is **always** updated to the new provider id — without
/// this, switching to a provider whose settings lack a `models` list would
/// leave the runtime routing requests to the previously active provider.
///
/// `model.default` is only overwritten when the new provider declares at
/// least one model; otherwise the previous default is preserved so users
/// still have a runnable configuration (Hermes will surface a clear error
/// if the default no longer belongs to the active provider).
///
/// Existing model tuning fields (`context_length` / `max_tokens` / unknown
/// `extra`) are preserved via struct-update, but provider credentials are
/// replaced from the newly selected provider. Missing credentials clear the
/// previous provider's values so the top-level model config cannot leak an old
/// `base_url` / `api_key` across switches.
pub fn apply_switch_defaults(
    provider_id: &str,
    settings_config: &serde_json::Value,
) -> Result<HermesWriteOutcome, AppError> {
    let first_model_id = settings_config
        .get("models")
        .and_then(|v| v.as_array())
        .and_then(|arr| arr.first())
        .and_then(|m| m.get("id"))
        .and_then(|id| id.as_str())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());

    let new_base_url = provider_alias_string(settings_config, "base_url", "baseUrl");
    let new_api_key = provider_alias_string(settings_config, "api_key", "apiKey");

    let mut current = get_model_config()?.unwrap_or_default();

    current.base_url = new_base_url;
    current.extra.remove("baseUrl");
    current.extra.remove("apiKey");
    if let Some(key) = new_api_key {
        current
            .extra
            .insert("api_key".to_string(), serde_json::Value::String(key));
    } else {
        current.extra.remove("api_key");
    }

    let merged = HermesModelConfig {
        default: first_model_id.or(current.default.clone()),
        provider: Some(provider_id.to_string()),
        ..current
    };
    set_model_config(&merged)
}

// ============================================================================
// MCP Section Access (for mcp/hermes.rs to use in Phase 4)
// ============================================================================

/// Get the `mcp_servers` section as a YAML Mapping.
pub fn get_mcp_servers_yaml() -> Result<serde_yaml::Mapping, AppError> {
    let config = read_hermes_config()?;
    Ok(config
        .get("mcp_servers")
        .and_then(|v| v.as_mapping())
        .cloned()
        .unwrap_or_default())
}

/// Atomically read-modify-write the `mcp_servers` section under the write lock.
///
/// Prevents TOCTOU races when multiple sync operations run concurrently.
pub fn update_mcp_servers_yaml<F>(updater: F) -> Result<(), AppError>
where
    F: FnOnce(&mut serde_yaml::Mapping) -> Result<(), AppError>,
{
    let _guard = hermes_write_lock().lock()?;
    let config = read_hermes_config()?;
    let mut servers = config
        .get("mcp_servers")
        .and_then(|v| v.as_mapping())
        .cloned()
        .unwrap_or_default();
    updater(&mut servers)?;
    let value = serde_yaml::Value::Mapping(servers);
    write_yaml_section_to_config_locked("mcp_servers", &value)?;
    Ok(())
}

// ============================================================================
// YAML ↔ JSON Conversion Helpers
// ============================================================================

/// Convert a `serde_yaml::Value` to a `serde_json::Value`.
pub(crate) fn yaml_to_json(yaml: &serde_yaml::Value) -> Result<serde_json::Value, AppError> {
    // Serialize YAML value to string, then parse as JSON value.
    // This handles all type mappings correctly.
    let yaml_str = serde_yaml::to_string(yaml)
        .map_err(|e| AppError::Config(format!("Failed to serialize YAML value: {e}")))?;
    serde_yaml::from_str::<serde_json::Value>(&yaml_str)
        .map_err(|e| AppError::Config(format!("Failed to convert YAML to JSON: {e}")))
}

/// Convert a `serde_json::Value` to a `serde_yaml::Value`.
pub(crate) fn json_to_yaml(json: &serde_json::Value) -> Result<serde_yaml::Value, AppError> {
    let json_str = serde_json::to_string(json)
        .map_err(|e| AppError::Config(format!("Failed to serialize JSON value: {e}")))?;
    serde_yaml::from_str(&json_str)
        .map_err(|e| AppError::Config(format!("Failed to convert JSON to YAML: {e}")))
}

// ============================================================================
// Memory Files (~/.hermes/memories/{MEMORY,USER}.md)
// ============================================================================
//
// Hermes Agent persists two memory blobs on disk:
//   - `MEMORY.md` — agent's personal notes, snapshotted into the system prompt
//   - `USER.md`   — user profile, same treatment
// Entries are separated by a `§` on its own line. Hermes' own Web UI only
// exposes on/off toggles and character budgets — it has no content editor.
// CC Switch fills that gap by reading/writing the whole file as a markdown
// blob. Character budgets (`memory_char_limit`, `user_char_limit`) and enable
// flags (`memory_enabled`, `user_profile_enabled`) live at the top level of
// `config.yaml`; Hermes truncates over-budget content at load time.

/// Which of Hermes' two memory files to operate on. Tauri deserializes this
/// directly from the `"memory"` / `"user"` strings the frontend sends, so an
/// unknown value is rejected at the IPC boundary instead of deep in the stack.
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MemoryKind {
    Memory,
    User,
}

#[cfg(test)]
impl MemoryKind {
    fn filename(self) -> &'static str {
        match self {
            Self::Memory => "MEMORY.md",
            Self::User => "USER.md",
        }
    }
}

#[cfg(test)]
fn memories_dir() -> PathBuf {
    get_hermes_dir().join("memories")
}

/// Read a Hermes memory file as a markdown blob. Returns an empty string
/// when the file doesn't exist yet (first-run case).
#[cfg(test)]
pub fn read_memory(kind: MemoryKind) -> Result<String, AppError> {
    let path = memories_dir().join(kind.filename());
    match fs::read_to_string(&path) {
        Ok(content) => Ok(content),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(e) => Err(AppError::io(&path, e)),
    }
}

/// Atomically replace a Hermes memory file. `atomic_write` creates parent
/// directories as needed, so `~/.hermes/memories/` is materialized on first
/// write without a separate `create_dir_all` call.
#[cfg(test)]
pub fn write_memory(kind: MemoryKind, content: &str) -> Result<(), AppError> {
    let path = memories_dir().join(kind.filename());
    atomic_write(&path, content.as_bytes())
}

/// Character budget + enable flags for the two memory blobs, as configured
/// in Hermes' `config.yaml`. Defaults mirror `~/.hermes`'s own defaults so
/// callers get a usable budget bar even before the user edits config.yaml.
#[cfg(test)]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HermesMemoryLimits {
    pub memory: usize,
    pub user: usize,
    pub memory_enabled: bool,
    pub user_enabled: bool,
}

#[cfg(test)]
impl Default for HermesMemoryLimits {
    fn default() -> Self {
        Self {
            memory: 2200,
            user: 1375,
            memory_enabled: true,
            user_enabled: true,
        }
    }
}

/// Toggle the on/off flag for one of Hermes' two memory blobs, preserving all
/// other fields in the `memory:` section (character budgets, external provider
/// settings, etc.). Hermes stores the user-profile toggle under
/// `user_profile_enabled` (not `user_enabled`), so the mapping to on-disk keys
/// lives here rather than leaking to callers.
#[cfg(test)]
pub fn set_memory_enabled(kind: MemoryKind, enabled: bool) -> Result<HermesWriteOutcome, AppError> {
    let _guard = hermes_write_lock().lock()?;
    let config = read_hermes_config()?;

    let mut memory = match config.get("memory") {
        Some(serde_yaml::Value::Mapping(m)) => m.clone(),
        _ => serde_yaml::Mapping::new(),
    };

    let key = match kind {
        MemoryKind::Memory => "memory_enabled",
        MemoryKind::User => "user_profile_enabled",
    };
    memory.insert(
        serde_yaml::Value::String(key.to_string()),
        serde_yaml::Value::Bool(enabled),
    );

    write_yaml_section_to_config_locked("memory", &serde_yaml::Value::Mapping(memory))
}

/// Read memory budgets + toggles from `config.yaml`. Missing/unparsable
/// fields fall back to `HermesMemoryLimits::default()` rather than erroring,
/// so an empty or partially-populated config still yields a usable UI.
#[cfg(test)]
pub fn read_memory_limits() -> Result<HermesMemoryLimits, AppError> {
    let mut out = HermesMemoryLimits::default();
    let config = read_hermes_config()?;
    let Some(memory) = config.get("memory") else {
        return Ok(out);
    };

    if let Some(v) = memory.get("memory_char_limit").and_then(|v| v.as_u64()) {
        out.memory = v as usize;
    }
    if let Some(v) = memory.get("user_char_limit").and_then(|v| v.as_u64()) {
        out.user = v as usize;
    }
    if let Some(v) = memory.get("memory_enabled").and_then(|v| v.as_bool()) {
        out.memory_enabled = v;
    }
    if let Some(v) = memory.get("user_profile_enabled").and_then(|v| v.as_bool()) {
        out.user_enabled = v;
    }

    Ok(out)
}

// ============================================================================
// Tests
// ============================================================================

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

    /// Run a test with an isolated temp home directory.
    ///
    /// Saves and restores `CC_SWITCH_TEST_HOME` to avoid interfering with
    /// parallel tests in other modules.
    fn with_test_home<T>(test_fn: impl FnOnce() -> T) -> T {
        let _guard = crate::test_support::lock_test_home_and_settings();
        let tmp = tempfile::tempdir().unwrap();
        let old = crate::test_support::test_home_override();
        crate::test_support::set_test_home_override(Some(tmp.path()));
        let result = test_fn();
        crate::test_support::set_test_home_override(old.as_deref());
        result
    }

    // ---- sanitize_hermes_provider_keys tests ----

    #[test]
    fn sanitize_rewrites_camel_case_aliases() {
        let mut v = serde_json::json!({
            "name": "test",
            "baseUrl": "https://api.example.com",
            "apiKey": "sk-123",
            "apiMode": "chat_completions",
            "maxTokens": 8192,
            "contextLength": 200000,
        });
        sanitize_hermes_provider_keys(&mut v);
        let obj = v.as_object().unwrap();
        assert_eq!(obj.get("base_url").unwrap(), "https://api.example.com");
        assert_eq!(obj.get("api_key").unwrap(), "sk-123");
        assert_eq!(obj.get("api_mode").unwrap(), "chat_completions");
        assert_eq!(obj.get("max_tokens").unwrap(), 8192);
        assert_eq!(obj.get("context_length").unwrap(), 200000);
        assert!(obj.get("baseUrl").is_none());
        assert!(obj.get("apiKey").is_none());
    }

    #[test]
    fn sanitize_drops_stale_duplicate_when_snake_case_exists() {
        let mut v = serde_json::json!({
            "baseUrl": "https://old.example.com",
            "base_url": "https://new.example.com",
        });
        sanitize_hermes_provider_keys(&mut v);
        let obj = v.as_object().unwrap();
        // snake_case wins; stale camelCase is dropped
        assert_eq!(obj.get("base_url").unwrap(), "https://new.example.com");
        assert!(obj.get("baseUrl").is_none());
    }

    #[test]
    fn sanitize_drops_legacy_api_field() {
        let mut v = serde_json::json!({
            "base_url": "https://api.example.com",
            "api": "openai-completions",
        });
        sanitize_hermes_provider_keys(&mut v);
        let obj = v.as_object().unwrap();
        assert!(obj.get("api").is_none(), "legacy 'api' key must be removed");
        assert!(obj.get("base_url").is_some());
    }

    #[test]
    fn sanitize_preserves_unknown_fields() {
        let mut v = serde_json::json!({
            "base_url": "https://api.example.com",
            "request_timeout_seconds": 300,
            "rate_limit_delay": 1.5,
        });
        sanitize_hermes_provider_keys(&mut v);
        let obj = v.as_object().unwrap();
        // Forward-compat: Hermes' own new fields pass through untouched
        assert_eq!(obj.get("request_timeout_seconds").unwrap(), 300);
        assert_eq!(obj.get("rate_limit_delay").unwrap(), 1.5);
    }

    #[test]
    fn sanitize_noop_on_non_object() {
        let mut v = serde_json::json!(["not", "an", "object"]);
        sanitize_hermes_provider_keys(&mut v);
        assert!(v.is_array());
    }

    // ---- find_yaml_section_range tests ----

    #[test]
    fn find_section_in_multi_section_yaml() {
        let yaml = "\
model:
  default: gpt-4
  provider: openai
agent:
  max_turns: 10
custom_providers:
  - name: foo
";
        let (start, end) = find_yaml_section_range(yaml, "agent").unwrap();
        let section = &yaml[start..end];
        assert!(section.starts_with("agent:"));
        assert!(section.contains("max_turns"));
        assert!(!section.contains("custom_providers"));
    }

    #[test]
    fn find_section_at_end_of_file() {
        let yaml = "\
model:
  default: gpt-4
agent:
  max_turns: 10
";
        let (start, end) = find_yaml_section_range(yaml, "agent").unwrap();
        let section = &yaml[start..end];
        assert!(section.starts_with("agent:"));
        assert!(section.contains("max_turns"));
        assert_eq!(end, yaml.len());
    }

    #[test]
    fn find_section_not_found() {
        let yaml = "\
model:
  default: gpt-4
";
        assert!(find_yaml_section_range(yaml, "agent").is_none());
    }

    #[test]
    fn find_section_with_comments_between() {
        let yaml = "\
model:
  default: gpt-4

# This is a comment
  # indented comment

agent:
  max_turns: 10
";
        // model section should span from start to "agent:"
        let (start, end) = find_yaml_section_range(yaml, "model").unwrap();
        let section = &yaml[start..end];
        assert!(section.starts_with("model:"));
        // Comments and blank lines between sections are included in the prior section
        assert!(section.contains("# This is a comment"));
    }

    #[test]
    fn find_section_with_empty_lines() {
        let yaml = "\
model:
  default: gpt-4

agent:
  max_turns: 10
";
        let (start, end) = find_yaml_section_range(yaml, "model").unwrap();
        let section = &yaml[start..end];
        assert!(section.starts_with("model:"));
        // Empty lines don't terminate a section
        assert!(section.contains('\n'));
    }

    #[test]
    fn find_section_does_not_match_substring_key() {
        let yaml = "\
model_extra:
  foo: bar
model:
  default: gpt-4
";
        let (start, _end) = find_yaml_section_range(yaml, "model").unwrap();
        let section = &yaml[start..];
        // Should match "model:", not "model_extra:"
        assert!(section.starts_with("model:"));
        assert!(!section.starts_with("model_extra:"));
    }

    // ---- replace_yaml_section tests ----

    #[test]
    fn replace_existing_section() {
        let yaml = "\
model:
  default: gpt-4
  provider: openai
agent:
  max_turns: 10
";
        let new_model = serde_yaml::Value::Mapping({
            let mut m = serde_yaml::Mapping::new();
            m.insert(
                serde_yaml::Value::String("default".to_string()),
                serde_yaml::Value::String("claude-opus-4-7".to_string()),
            );
            m.insert(
                serde_yaml::Value::String("provider".to_string()),
                serde_yaml::Value::String("anthropic".to_string()),
            );
            m
        });

        let result = replace_yaml_section(yaml, "model", &new_model).unwrap();
        // The result should still contain the agent section
        assert!(result.contains("agent:"));
        assert!(result.contains("max_turns"));
        // And the model section should be updated
        assert!(result.contains("claude-opus-4-7"));
        assert!(result.contains("anthropic"));
        assert!(!result.contains("gpt-4"));
        assert!(!result.contains("openai"));
    }

    #[test]
    fn append_new_section() {
        let yaml = "\
model:
  default: gpt-4
";
        let new_agent = serde_yaml::Value::Mapping({
            let mut m = serde_yaml::Mapping::new();
            m.insert(
                serde_yaml::Value::String("max_turns".to_string()),
                serde_yaml::Value::Number(serde_yaml::Number::from(50)),
            );
            m
        });

        let result = replace_yaml_section(yaml, "agent", &new_agent).unwrap();
        assert!(result.contains("model:"));
        assert!(result.contains("gpt-4"));
        assert!(result.contains("agent:"));
        assert!(result.contains("max_turns: 50"));
    }

    #[test]
    fn replace_section_in_empty_file() {
        let yaml = "";
        let new_model = serde_yaml::Value::Mapping({
            let mut m = serde_yaml::Mapping::new();
            m.insert(
                serde_yaml::Value::String("default".to_string()),
                serde_yaml::Value::String("gpt-4".to_string()),
            );
            m
        });

        let result = replace_yaml_section(yaml, "model", &new_model).unwrap();
        assert!(result.contains("model:"));
        assert!(result.contains("gpt-4"));
        assert!(result.ends_with('\n'));
    }

    // ---- Provider CRUD via mock config ----

    #[test]
    #[serial]
    fn provider_crud_roundtrip() {
        with_test_home(|| {
            // Initially no providers
            let providers = get_providers().unwrap();
            assert!(providers.is_empty());

            // Add a provider
            let config = serde_json::json!({
                "base_url": "https://openrouter.ai/api/v1",
                "api_key": "sk-or-test"
            });
            set_provider("openrouter", config).unwrap();

            let providers = get_providers().unwrap();
            assert_eq!(providers.len(), 1);
            assert!(providers.contains_key("openrouter"));

            let provider = get_provider("openrouter").unwrap().unwrap();
            assert_eq!(provider["base_url"], "https://openrouter.ai/api/v1");
            assert_eq!(provider["name"], "openrouter");

            // Update the provider
            let config2 = serde_json::json!({
                "base_url": "https://openrouter.ai/api/v2",
                "api_key": "sk-or-updated"
            });
            set_provider("openrouter", config2).unwrap();

            let provider = get_provider("openrouter").unwrap().unwrap();
            assert_eq!(provider["base_url"], "https://openrouter.ai/api/v2");

            // Remove the provider
            remove_provider("openrouter").unwrap();
            let providers = get_providers().unwrap();
            assert!(providers.is_empty());
        });
    }

    #[test]
    #[serial]
    fn set_provider_preserves_unknown_fields_on_update() {
        // Hermes keeps adding provider-level fields (e.g.
        // `request_timeout_seconds`, `key_env`). Users may set those via
        // Hermes Web UI; a later CC Switch edit must not strip them — set_provider
        // carries over any existing on-disk fields that the UI payload didn't
        // submit.
        with_test_home(|| {
            let yaml = "\
custom_providers:
  - name: acme
    base_url: https://old.example.com
    api_key: sk-old
    request_timeout_seconds: 300
    key_env: ACME_API_KEY
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let update = serde_json::json!({
                "base_url": "https://new.example.com",
                "api_key": "sk-new"
            });
            set_provider("acme", update).unwrap();

            let provider = get_provider("acme").unwrap().unwrap();
            assert_eq!(provider["base_url"], "https://new.example.com");
            assert_eq!(provider["api_key"], "sk-new");
            assert_eq!(provider["request_timeout_seconds"], 300);
            assert_eq!(provider["key_env"], "ACME_API_KEY");
        });
    }

    #[test]
    #[serial]
    fn set_provider_explicit_empty_models_removes_live_models() {
        with_test_home(|| {
            let yaml = "\
custom_providers:
  - name: acme
    base_url: https://old.example.com
    model: old-model
    models:
      old-model:
        context_length: 64000
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            set_provider(
                "acme",
                serde_json::json!({
                    "base_url": "https://new.example.com",
                    "models": []
                }),
            )
            .unwrap();

            let provider = get_provider("acme").unwrap().unwrap();
            assert_eq!(provider["base_url"], "https://new.example.com");
            assert!(provider.get("model").is_none());
            assert!(provider.get("models").is_none());
        });
    }

    #[test]
    #[serial]
    fn set_provider_rejects_malformed_models_without_rewriting_live_config() {
        with_test_home(|| {
            let yaml = "\
custom_providers:
  - name: acme
    model: keep
    models:
      keep: {}
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let result = set_provider("acme", serde_json::json!({ "models": [{ "id": " " }] }));
            assert!(result.is_err());
            assert_eq!(fs::read_to_string(&config_path).unwrap(), yaml);
        });
    }

    #[test]
    #[serial]
    fn set_provider_preserves_unknown_fields_for_retained_models_only() {
        with_test_home(|| {
            let yaml = "\
custom_providers:
  - name: acme
    base_url: https://old.example.com
    model: keep
    models:
      keep:
        context_length: 64000
        maxTokens: 4096
        reasoning_effort: high
      remove:
        context_length: 32000
        live_only: true
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            set_provider(
                "acme",
                serde_json::json!({
                    "base_url": "https://new.example.com",
                    "models": [{
                        "id": "keep"
                    }]
                }),
            )
            .unwrap();

            let provider = get_provider("acme").unwrap().unwrap();
            let models = provider["models"].as_array().unwrap();
            assert_eq!(models.len(), 1);
            assert_eq!(models[0]["id"], "keep");
            assert!(models[0].get("context_length").is_none());
            assert!(models[0].get("maxTokens").is_none());
            assert_eq!(models[0]["reasoning_effort"], "high");
        });
    }

    #[test]
    #[serial]
    fn get_providers_surfaces_providers_dict_as_read_only() {
        with_test_home(|| {
            let yaml = "\
_config_version: 19
custom_providers:
  - name: mine
    base_url: https://mine.example.com
    api_key: sk-mine
providers:
  anthropic:
    base_url: https://api.anthropic.com
    api_key: sk-ant
    model: claude-opus-4.6
  ollama-local:
    base_url: http://localhost:11434/v1
    request_timeout_seconds: 300
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let providers = get_providers().unwrap();
            assert_eq!(providers.len(), 3);

            let mine = providers.get("mine").unwrap();
            assert_eq!(mine[PROVIDER_SOURCE_FIELD], PROVIDER_SOURCE_CUSTOM_LIST);

            let anthropic = providers.get("anthropic").unwrap();
            assert_eq!(anthropic[PROVIDER_SOURCE_FIELD], PROVIDER_SOURCE_DICT);
            assert_eq!(anthropic["provider_key"], "anthropic");
            assert_eq!(anthropic["base_url"], "https://api.anthropic.com");

            let ollama = providers.get("ollama-local").unwrap();
            assert_eq!(ollama[PROVIDER_SOURCE_FIELD], PROVIDER_SOURCE_DICT);
            // Forward-compat fields from the dict pass through untouched
            assert_eq!(ollama["request_timeout_seconds"], 300);
        });
    }

    #[test]
    #[serial]
    fn get_providers_list_wins_on_name_collision() {
        with_test_home(|| {
            let yaml = "\
_config_version: 19
custom_providers:
  - name: shared
    base_url: https://writable.example.com
providers:
  shared:
    base_url: https://overlay.example.com
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let providers = get_providers().unwrap();
            assert_eq!(providers.len(), 1);
            let shared = providers.get("shared").unwrap();
            assert_eq!(shared["base_url"], "https://writable.example.com");
            assert_eq!(shared[PROVIDER_SOURCE_FIELD], PROVIDER_SOURCE_CUSTOM_LIST);
        });
    }

    #[test]
    #[serial]
    fn set_provider_rejects_dict_only_entries() {
        with_test_home(|| {
            let yaml = "\
_config_version: 19
providers:
  anthropic:
    base_url: https://api.anthropic.com
    model: claude-opus-4.6
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let update = serde_json::json!({ "base_url": "https://hacked.example.com" });
            let err = set_provider("anthropic", update).unwrap_err();
            assert!(
                format!("{err}").contains("providers:"),
                "error message should point user at providers dict: {err}"
            );
        });
    }

    #[test]
    #[serial]
    fn remove_provider_rejects_dict_only_entries() {
        with_test_home(|| {
            let yaml = "\
_config_version: 19
providers:
  anthropic:
    base_url: https://api.anthropic.com
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            assert!(remove_provider("anthropic").is_err());
        });
    }

    #[test]
    fn sanitize_strips_ui_only_markers() {
        let mut v = serde_json::json!({
            "base_url": "https://api.example.com",
            "_cc_source": "providers_dict",
            "provider_key": "anthropic",
        });
        sanitize_hermes_provider_keys(&mut v);
        let obj = v.as_object().unwrap();
        assert!(obj.get("_cc_source").is_none());
        assert!(obj.get("provider_key").is_none());
        assert!(obj.get("base_url").is_some());
    }

    #[test]
    #[serial]
    fn get_providers_heals_legacy_camel_case_on_read() {
        // A DB may still hold records from older DeepLink imports that wrote
        // camelCase fields into `settings_config`. The read path must surface
        // them in Hermes' native snake_case so UI editors aren't lying to users.
        with_test_home(|| {
            let yaml = "\
custom_providers:
  - name: legacy
    baseUrl: https://legacy.example.com
    apiKey: sk-legacy
    apiMode: chat_completions
    api: openai-completions
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let provider = get_provider("legacy").unwrap().unwrap();
            assert_eq!(provider["base_url"], "https://legacy.example.com");
            assert_eq!(provider["api_key"], "sk-legacy");
            assert_eq!(provider["api_mode"], "chat_completions");
            assert!(provider.get("baseUrl").is_none());
            assert!(provider.get("apiKey").is_none());
            assert!(provider.get("api").is_none());
        });
    }

    #[test]
    #[serial]
    fn get_providers_preserves_malformed_model_dict_for_validation() {
        with_test_home(|| {
            let yaml = "\
custom_providers:
  - name: malformed
    models:
      broken-model: not-an-object
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let providers = get_providers().expect("read malformed provider without data loss");
            let models = &providers["malformed"]["models"];
            assert_eq!(models["broken-model"], "not-an-object");
        });
    }

    // ---- Model config tests ----

    #[test]
    #[serial]
    fn model_config_roundtrip() {
        with_test_home(|| {
            // Initially none
            assert!(get_model_config().unwrap().is_none());

            let model = HermesModelConfig {
                default: Some("anthropic/claude-opus-4-7".to_string()),
                provider: Some("openrouter".to_string()),
                base_url: Some("https://openrouter.ai/api/v1".to_string()),
                context_length: Some(200000),
                max_tokens: None,
                extra: HashMap::new(),
            };
            set_model_config(&model).unwrap();

            let read_model = get_model_config().unwrap().unwrap();
            assert_eq!(
                read_model.default.as_deref(),
                Some("anthropic/claude-opus-4-7")
            );
            assert_eq!(read_model.provider.as_deref(), Some("openrouter"));
            assert_eq!(read_model.context_length, Some(200000));
        });
    }

    // ---- yaml_to_json / json_to_yaml ----

    #[test]
    fn yaml_json_conversion_roundtrip() {
        let json = serde_json::json!({
            "name": "test",
            "count": 42,
            "nested": {
                "flag": true
            }
        });
        let yaml = json_to_yaml(&json).unwrap();
        let back = yaml_to_json(&yaml).unwrap();
        assert_eq!(json, back);
    }

    // ---- models array ↔ dict transforms ----

    #[test]
    fn models_array_to_dict_strips_id_and_preserves_order() {
        let arr = vec![
            serde_json::json!({ "id": "foo", "context_length": 100 }),
            serde_json::json!({ "id": "bar", "max_tokens": 2000 }),
            serde_json::json!({ "id": "baz" }),
        ];
        let dict = models_array_to_dict(arr);
        let obj = dict.as_object().unwrap();
        let keys: Vec<&String> = obj.keys().collect();
        assert_eq!(keys, vec!["bar", "baz", "foo"]);
        assert_eq!(obj["foo"]["context_length"], 100);
        assert_eq!(obj["bar"]["max_tokens"], 2000);
        assert!(obj["baz"].as_object().unwrap().is_empty());
        // id must not leak into values
        assert!(obj["foo"].get("id").is_none());
    }

    #[test]
    fn models_array_to_dict_drops_empty_and_missing_ids() {
        let arr = vec![
            serde_json::json!({ "id": "", "context_length": 1 }),
            serde_json::json!({ "id": "   ", "context_length": 2 }),
            serde_json::json!({ "context_length": 3 }),
            serde_json::json!({ "id": "kept" }),
        ];
        let dict = models_array_to_dict(arr);
        let obj = dict.as_object().unwrap();
        assert_eq!(obj.len(), 1);
        assert!(obj.contains_key("kept"));
    }

    #[test]
    fn models_dict_to_array_reinjects_id_and_preserves_order() {
        let mut map = serde_json::Map::new();
        map.insert(
            "alpha".to_string(),
            serde_json::json!({ "context_length": 10 }),
        );
        map.insert("beta".to_string(), serde_json::json!({ "max_tokens": 20 }));
        map.insert("gamma".to_string(), serde_json::Value::Null);
        let arr = models_dict_to_array(map);
        let list = arr.as_array().unwrap();
        assert_eq!(list.len(), 3);
        assert_eq!(list[0]["id"], "alpha");
        assert_eq!(list[0]["context_length"], 10);
        assert_eq!(list[1]["id"], "beta");
        assert_eq!(list[2]["id"], "gamma");
    }

    #[test]
    #[serial]
    fn provider_with_models_array_writes_dict_to_yaml() {
        with_test_home(|| {
            let config = serde_json::json!({
                "base_url": "https://api.example.com/v1",
                "api_key": "sk-test",
                "api_mode": "chat_completions",
                "models": [
                    { "id": "model-a", "context_length": 200000, "max_tokens": 32000 },
                    { "id": "model-b", "context_length": 100000 },
                ]
            });
            set_provider("demo", config).unwrap();

            // Read raw YAML to verify the on-disk shape is a sequence under `custom_providers:`.
            let raw = fs::read_to_string(get_hermes_config_path()).unwrap();
            let yaml: serde_yaml::Value = serde_yaml::from_str(&raw).unwrap();
            let providers = yaml
                .get("custom_providers")
                .and_then(|v| v.as_sequence())
                .unwrap();
            let provider = &providers[0];
            assert_eq!(
                provider.get("name").and_then(|v| v.as_str()),
                Some("demo"),
                "entry should carry a name field"
            );
            assert_eq!(
                provider.get("model").and_then(|v| v.as_str()),
                Some("model-a"),
                "entry should carry a singular `model:` field set to the first model id \
                 so Hermes runtime/picker reads it"
            );
            let models = provider.get("models").and_then(|v| v.as_mapping()).unwrap();
            assert_eq!(models.len(), 2);
            assert!(models.contains_key(serde_yaml::Value::String("model-a".into())));
            assert!(models.contains_key(serde_yaml::Value::String("model-b".into())));
            let model_a = models
                .get(serde_yaml::Value::String("model-a".into()))
                .unwrap();
            assert_eq!(
                model_a
                    .get("context_length")
                    .and_then(|v| v.as_u64())
                    .unwrap(),
                200000
            );
            // id should not leak into each model value
            assert!(model_a.get("id").is_none());
        });
    }

    #[test]
    #[serial]
    fn provider_models_roundtrip_array_dict_array_preserves_order() {
        with_test_home(|| {
            let input = serde_json::json!({
                "base_url": "https://api.example.com/v1",
                "api_key": "sk-test",
                "models": [
                    { "id": "first", "context_length": 1 },
                    { "id": "second", "context_length": 2 },
                    { "id": "third", "context_length": 3 },
                ]
            });
            set_provider("order", input).unwrap();

            let providers = get_providers().unwrap();
            let provider = providers.get("order").unwrap();
            let models = provider.get("models").and_then(|v| v.as_array()).unwrap();
            let ids: Vec<&str> = models
                .iter()
                .map(|m| m.get("id").and_then(|v| v.as_str()).unwrap())
                .collect();
            assert_eq!(ids, vec!["first", "second", "third"]);
            assert_eq!(models[0].get("context_length").unwrap(), 1);
        });
    }

    #[test]
    #[serial]
    fn provider_without_models_is_unaffected() {
        with_test_home(|| {
            let input = serde_json::json!({
                "base_url": "https://api.example.com/v1",
                "api_key": "sk-test"
            });
            set_provider("simple", input).unwrap();
            let providers = get_providers().unwrap();
            let provider = providers.get("simple").unwrap();
            assert!(provider.get("models").is_none());
            assert!(
                provider.get("model").is_none(),
                "singular `model:` should not appear when no models are declared"
            );
        });
    }

    // ---- apply_switch_defaults ----

    #[test]
    #[serial]
    fn apply_switch_defaults_sets_default_and_provider() {
        with_test_home(|| {
            let settings = serde_json::json!({
                "base_url": "https://api.example.com/v1",
                "models": [
                    { "id": "primary-model", "context_length": 200000 },
                    { "id": "fallback", "context_length": 100000 },
                ]
            });
            apply_switch_defaults("demo", &settings).unwrap();

            let model = get_model_config().unwrap().unwrap();
            assert_eq!(model.default.as_deref(), Some("primary-model"));
            assert_eq!(model.provider.as_deref(), Some("demo"));
        });
    }

    #[test]
    #[serial]
    fn apply_switch_defaults_accepts_camel_case_provider_credentials() {
        with_test_home(|| {
            let mut extra = HashMap::new();
            extra.insert("api_key".to_string(), serde_json::json!("sk-old"));
            let initial = HermesModelConfig {
                default: Some("old-model".to_string()),
                provider: Some("old-provider".to_string()),
                base_url: Some("https://old.example.com/v1".to_string()),
                extra,
                ..Default::default()
            };
            set_model_config(&initial).unwrap();

            let settings = serde_json::json!({
                "baseUrl": "https://new.example.com/v1",
                "apiKey": "sk-new",
                "models": [{ "id": "new-model" }]
            });
            apply_switch_defaults("new-provider", &settings).unwrap();

            let model = get_model_config().unwrap().unwrap();
            assert_eq!(model.default.as_deref(), Some("new-model"));
            assert_eq!(model.provider.as_deref(), Some("new-provider"));
            assert_eq!(
                model.base_url.as_deref(),
                Some("https://new.example.com/v1")
            );
            assert_eq!(
                model.extra.get("api_key").and_then(|value| value.as_str()),
                Some("sk-new")
            );
        });
    }

    #[test]
    #[serial]
    fn apply_switch_defaults_clears_stale_provider_credentials_when_missing() {
        with_test_home(|| {
            let mut extra = HashMap::new();
            extra.insert("api_key".to_string(), serde_json::json!("sk-old"));
            let initial = HermesModelConfig {
                default: Some("old-model".to_string()),
                provider: Some("old-provider".to_string()),
                base_url: Some("https://old.example.com/v1".to_string()),
                extra,
                ..Default::default()
            };
            set_model_config(&initial).unwrap();

            let settings = serde_json::json!({
                "models": [{ "id": "new-model" }]
            });
            apply_switch_defaults("new-provider", &settings).unwrap();

            let model = get_model_config().unwrap().unwrap();
            assert_eq!(model.default.as_deref(), Some("new-model"));
            assert_eq!(model.provider.as_deref(), Some("new-provider"));
            assert!(model.base_url.is_none());
            assert!(model.extra.get("api_key").is_none());
        });
    }

    #[test]
    #[serial]
    fn apply_switch_defaults_preserves_user_model_tuning() {
        with_test_home(|| {
            // User previously set a custom context_length via the Model panel.
            let initial = HermesModelConfig {
                default: Some("old-model".to_string()),
                provider: Some("old-provider".to_string()),
                base_url: Some("https://user-override.example.com".to_string()),
                context_length: Some(131072),
                max_tokens: Some(16384),
                extra: HashMap::new(),
            };
            set_model_config(&initial).unwrap();

            let settings = serde_json::json!({
                "models": [{ "id": "new-model" }]
            });
            apply_switch_defaults("new-provider", &settings).unwrap();

            let model = get_model_config().unwrap().unwrap();
            assert_eq!(model.default.as_deref(), Some("new-model"));
            assert_eq!(model.provider.as_deref(), Some("new-provider"));
            // Model tuning survives; provider credentials are replaced/cleared
            // by the active provider so old routes do not leak across switches.
            assert!(model.base_url.is_none());
            assert_eq!(model.context_length, Some(131072));
            assert_eq!(model.max_tokens, Some(16384));
        });
    }

    #[test]
    #[serial]
    fn apply_switch_defaults_updates_provider_even_without_models() {
        with_test_home(|| {
            // Seed an existing `model:` section — the user was already running
            // some provider before this switch.
            let initial = HermesModelConfig {
                default: Some("legacy-default".to_string()),
                provider: Some("legacy-provider".to_string()),
                ..Default::default()
            };
            set_model_config(&initial).unwrap();

            // New provider has no `models` list — previously this would no-op
            // and leave `model.provider` pointing at the legacy provider,
            // causing "switch succeeds but has no effect" bug.
            let settings = serde_json::json!({
                "base_url": "https://api.example.com/v1"
            });
            apply_switch_defaults("bare", &settings).unwrap();

            let model = get_model_config().unwrap().unwrap();
            assert_eq!(model.provider.as_deref(), Some("bare"));
            assert_eq!(model.default.as_deref(), Some("legacy-default"));
        });
    }

    #[test]
    #[serial]
    fn apply_switch_defaults_keeps_old_default_when_first_model_id_is_blank() {
        with_test_home(|| {
            let initial = HermesModelConfig {
                default: Some("prev-default".to_string()),
                provider: Some("prev-provider".to_string()),
                ..Default::default()
            };
            set_model_config(&initial).unwrap();

            let settings = serde_json::json!({
                "models": [{ "id": "   " }, { "id": "real" }]
            });
            apply_switch_defaults("edge", &settings).unwrap();

            let model = get_model_config().unwrap().unwrap();
            // Provider always updates.
            assert_eq!(model.provider.as_deref(), Some("edge"));
            // First entry's id is whitespace-only → blank → fall back to old default
            // (we intentionally don't scan past the first entry for a default).
            assert_eq!(model.default.as_deref(), Some("prev-default"));
        });
    }

    // ---- memory file tests ----

    #[test]
    #[serial]
    fn read_memory_returns_empty_when_file_missing() {
        with_test_home(|| {
            let memory = read_memory(MemoryKind::Memory).unwrap();
            let user = read_memory(MemoryKind::User).unwrap();
            assert!(memory.is_empty());
            assert!(user.is_empty());
        });
    }

    #[test]
    #[serial]
    fn write_then_read_memory_round_trip() {
        with_test_home(|| {
            let blob = "> note\n§\nfirst entry\n§\nsecond entry\n";
            write_memory(MemoryKind::Memory, blob).unwrap();
            assert_eq!(read_memory(MemoryKind::Memory).unwrap(), blob);

            // Writing USER.md doesn't clobber MEMORY.md.
            write_memory(MemoryKind::User, "user profile").unwrap();
            assert_eq!(read_memory(MemoryKind::Memory).unwrap(), blob);
            assert_eq!(read_memory(MemoryKind::User).unwrap(), "user profile");
        });
    }

    #[test]
    #[serial]
    fn memory_limits_fall_back_to_defaults_when_config_missing() {
        with_test_home(|| {
            let limits = read_memory_limits().unwrap();
            let defaults = HermesMemoryLimits::default();
            assert_eq!(limits.memory, defaults.memory);
            assert_eq!(limits.user, defaults.user);
            assert_eq!(limits.memory_enabled, defaults.memory_enabled);
            assert_eq!(limits.user_enabled, defaults.user_enabled);
        });
    }

    #[test]
    #[serial]
    fn set_memory_enabled_preserves_other_fields() {
        // Flipping one toggle must preserve character budgets and external
        // provider settings the user configured via Hermes Web UI — otherwise
        // a CC Switch toggle would silently wipe those fields.
        with_test_home(|| {
            let yaml = "\
memory:
  memory_char_limit: 4096
  user_char_limit: 2048
  memory_enabled: true
  user_profile_enabled: true
  provider: mem0
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            set_memory_enabled(MemoryKind::Memory, false).unwrap();

            let limits = read_memory_limits().unwrap();
            assert!(!limits.memory_enabled, "toggle applied");
            assert!(limits.user_enabled, "unrelated toggle untouched");
            assert_eq!(limits.memory, 4096, "budgets preserved");
            assert_eq!(limits.user, 2048);

            // Verify the external provider field survived the section replacement.
            let config = read_hermes_config().unwrap();
            let provider = config
                .get("memory")
                .and_then(|v| v.get("provider"))
                .and_then(|v| v.as_str());
            assert_eq!(provider, Some("mem0"));
        });
    }

    #[test]
    #[serial]
    fn memory_limits_read_from_config_yaml() {
        with_test_home(|| {
            let yaml = "\
memory:
  memory_char_limit: 4096
  user_char_limit: 2048
  memory_enabled: false
  user_profile_enabled: true
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let limits = read_memory_limits().unwrap();
            assert_eq!(limits.memory, 4096);
            assert_eq!(limits.user, 2048);
            assert!(!limits.memory_enabled);
            assert!(limits.user_enabled);
        });
    }

    #[test]
    #[serial]
    fn memory_limits_ignore_top_level_keys() {
        // Regression guard: Hermes nests memory settings under `memory:`, so
        // identically-named keys at the top level must be ignored rather than
        // silently consumed.
        with_test_home(|| {
            let yaml = "\
memory_char_limit: 9999
user_char_limit: 9999
memory_enabled: false
user_profile_enabled: false
";
            let config_path = get_hermes_config_path();
            fs::create_dir_all(config_path.parent().unwrap()).unwrap();
            fs::write(&config_path, yaml).unwrap();

            let limits = read_memory_limits().unwrap();
            let defaults = HermesMemoryLimits::default();
            assert_eq!(limits.memory, defaults.memory);
            assert_eq!(limits.user, defaults.user);
            assert_eq!(limits.memory_enabled, defaults.memory_enabled);
            assert_eq!(limits.user_enabled, defaults.user_enabled);
        });
    }

    #[test]
    fn memory_kind_deserializes_from_lowercase_strings() {
        let memory: MemoryKind = serde_json::from_str("\"memory\"").unwrap();
        let user: MemoryKind = serde_json::from_str("\"user\"").unwrap();
        assert_eq!(memory, MemoryKind::Memory);
        assert_eq!(user, MemoryKind::User);
        assert!(serde_json::from_str::<MemoryKind>("\"bogus\"").is_err());
    }
}