mahbot 0.7.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Configuration system with two independent resolution chains.
//!
//! # Architecture overview
//!
//! The config system has a layered structure: hardcoded defaults in this module
//! provide the base values, and the [`ConfigReload`] singleton is then overlayed
//! with persisted values from the consolidated domain `core.db` (via
//! [`crate::config_db`]).
//!
//! At startup, [`load_or_init`] seeds `ConfigData::STRUCT_FIELDS_DEFAULT` into the
//! global [`CONFIG`]. Then [`reload_from_db`] overlays persisted values from the
//! two config tables on top of those defaults.
//!
//! # Resolution chains
//!
//! The configuration system has two independent resolution chains. They are
//! **independent** — an entry in the `config_kv` chain cannot override a
//! per-model routing entry in the `config_model_routing` chain, and vice versa.
//! Each chain applies to different fields.
//!
//! ## Chain 1: KV-backed string fields and model slots
//!
//! `config_kv` table → hardcoded default (`const` in this module)
//!
//! Both the fields listed in the `string_config_fields!` invocation and the two
//! model slots (`manager_model`, `worker_model`) live in the `config_kv` table.
//! Their accessor methods (generated on
//! [`ConfigReload`]) each follow a per-field annotation:
//!
//! * `non_empty` — returns `Option<String>`, collapses empty/whitespace to `None`.
//! * `or(DEFAULT)` — returns `String`, falls back to a compile-time constant
//!   (e.g. `DEFAULT_PROVIDER_ENDPOINT`).
//! * `list_or(default = …)` — returns `Vec<String>`, parses a
//!   newline-separated list, falling back to a hardcoded default when unset.
//!
//! At reload time [`reload_from_db`] loads key–value pairs from the `config_kv`
//! table (via [`crate::config_db::ConfigStore::get_all_kv`]) and applies them
//! through [`ConfigData::set_string_field`]. Any key absent from the table
//! remains `None`, and the accessor resolves the hardcoded fallback.
//!
//! Fields **not** in this chain (e.g. `model_routings`) have their own
//! dedicated table and reload path.
//!
//! ### Custom chat-completions endpoint
//!
//! `provider_endpoint` is an `or(DEFAULT_PROVIDER_ENDPOINT)` field: a
//! persisted value (a self-hosted OpenAI-compatible endpoint — Ollama,
//! LM Studio, llama.cpp, vLLM, LiteLLM) is honored at runtime, falling back
//! to OpenRouter when unset. `provider_endpoint_key` is the custom
//! endpoint's own optional API key (many self-hosted servers are keyless) —
//! it is only ever sent to the custom endpoint, never to OpenRouter. Media
//! features (image/video generation, catalogs, media transcription) always
//! use `DEFAULT_PROVIDER_ENDPOINT` + `provider_key` regardless of the
//! custom chat endpoint.
//!
//! ### Model slots
//!
//! The two model slots share the `config_kv` storage of the ordinary fields
//! above, but [`ConfigReload::role_model`] maps every role onto exactly one of
//! them:
//!
//! > Manager group (`Role::Manager`, `Role::Assistant`, `Role::Discovery`,
//! > `Role::Engineer`, `Role::Maintainer`) → manager slot;
//! > every other role (Analyst, Coder, QA, Reviewer, Sanitation) →
//! > worker slot.
//!
//! Unset slots fall back to their `DEFAULT_*_MODEL` constant.
//!
//! ## Chain 2: Per-model provider routing
//!
//! `config_model_routing` row (stored override) → [`default_model_routing`]
//! (model default) → OpenRouter auto-routing
//!
//! Stored in [`ConfigData::model_routings`] as a [`Vec<ModelRouting>`][ModelRouting] and
//! loaded at reload time from the `config_model_routing` table; every chat
//! request is built through [`ConfigReload::model_routing`].
//!
//! # Persistence layer
//!
//! The tables live in the consolidated domain `core.db` and are managed by [`crate::config_db`]:
//!
//! | Table | Read | Write |
//! |---|---|---|
//! | `config_kv` | [`crate::config_db::ConfigStore::get_all_kv`] | [`crate::config_db::ConfigStore::set_kv`] |
//! | `config_model_routing` | [`crate::config_db::ConfigStore::get_all_model_routings`] | [`crate::config_db::ConfigStore::save_model_routing`] |
//!
//! # Orphaned database keys
//!
//! Rows in `config_kv` without a corresponding [`ConfigData`] field are
//! lazily purged on reload: [`reload_from_db`] logs each unknown key at
//! `debug`, then best-effort deletes garbage rows (debug on success, warn
//! on transient failure without failing boot) while the intentional shared
//! namespaces written by other subsystems (the nightly-discovery marker and
//! the temp-cleanup cadence state) are left untouched.
//! Downgrade resurrection is therefore lost — under the previous ghost policy
//! orphans were retained and would re-appear on downgrade, now they are deleted
//! on first reboot. New orphans cannot be created via the settings path because
//! [`write_kv_and_update_config`] rejects unknown keys before any DB write.
//!
//! # See also
//!
//! * [`crate::config_db`] — database persistence for both chains.
//! * [`crate::agent::role`] — [`crate::agent::role::RoleInfo`] definitions with per-role defaults.
//! * [`crate::providers::compatible`] — writes the resolved provider order into
//!   the OpenRouter request body (`None` sends no provider preference at all).

use crate::Role;
use crate::util::{UnwrapPoison, is_http_url};
use anyhow::{Context, Result};
use directories::UserDirs;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{OnceLock, RwLock, RwLockReadGuard};
use tokio::fs;

// ── Hardcoded defaults ───────────────────────────────────────────

pub(crate) const DEFAULT_PROVIDER_ENDPOINT: &str = "https://openrouter.ai/api/v1";

pub(crate) const DEFAULT_MANAGER_MODEL: &str = "deepseek/deepseek-v4.1-flash";
pub(crate) const DEFAULT_WORKER_MODEL: &str = "deepseek/deepseek-v4.1-flash";

// The previous compiled defaults for the manager/worker slots, kept only for
// the per-row migration in `migrate_old_default_models` (idempotent, run on
// every boot).
const OLD_DEFAULT_MANAGER_MODEL: &str = "z-ai/glm-5.3-flash";
const OLD_DEFAULT_WORKER_MODEL: &str = "deepseek/deepseek-v4-flash-vision-exp";
// Video-transcription model is fixed (not user-configurable) and always
// targets OpenRouter.
pub(crate) const VIDEO_TRANSCRIPTION_MODEL: &str = "qwen/qwen3.8-flash";

pub(crate) const DEFAULT_IMAGE_GEN_MODEL: &str = "google/gemini-3.1-flash-image";
pub(crate) const DEFAULT_VIDEO_MODEL: &str = "minimax/hailuo-3";

/// Fresh-install seeded image-generation model list (newline-separated, in
/// picker order). Mirrors the curated set the live install ships.
const FRESH_INSTALL_IMAGE_GEN_MODELS: &str =
    "google/gemini-3.1-flash-image\nmicrosoft/mai-image-2.5\nqwen/qwen-image-3-pro";

/// Fresh-install seeded video-generation model list (newline-separated, in
/// picker order). Mirrors the curated set the live install ships.
const FRESH_INSTALL_VIDEO_MODELS: &str = "bytedance/seedance-2.0-mini\nminimax/hailuo-3";

pub(crate) const DEFAULT_TTS_LANGUAGE: &str = "na";

// ── Named config structs ───────────────────────────────────────────

/// A per-model provider routing rule.
#[derive(Debug, Clone, PartialEq)]
pub struct ModelRouting {
    pub model: String,
    pub provider_order: Option<String>,
}

impl ModelRouting {
    /// Find-or-push: update a subset of fields on an existing entry matching
    /// `model`, or push a new entry (all fields defaulted to `None`).
    ///
    /// Only the field(s) mutated inside `set_field` are touched — if the
    /// entry already exists its other fields are preserved unchanged.
    pub(crate) fn upsert(
        routings: &mut Vec<ModelRouting>,
        model: impl Into<String>,
        set_field: impl FnOnce(&mut ModelRouting),
    ) {
        let model = model.into();
        if let Some(existing) = routings.iter_mut().find(|mr| mr.model == model) {
            set_field(existing);
        } else {
            let mut new = ModelRouting {
                model,
                provider_order: None,
            };
            set_field(&mut new);
            routings.push(new);
        }
    }
}

// ── ConfigData — the reloadable inner config ─────────────────────

/// All runtime-configurable fields, protected by an [`RwLock`] in [`ConfigReload`].
///
/// Every accessor returns an owned [`String`] (or [`Option<String>`]) because the
/// lock guard cannot escape the accessor's scope. Clone is cheap — these are
/// short strings read infrequently.
///
/// ## Adding a new persisted `Option<String>` field
///
/// Follow all three steps in order:
///
/// 1. **Field declaration** — add the field here on [`ConfigData`].
/// 2. **Macro** — add the field name to the `string_config_fields!` invocation in this file.
///    The macro generates `ConfigData::STRUCT_FIELDS_DEFAULT` (used by [`ConfigReload::const_new`]),
///    [`ConfigData::string_fields()`], [`ConfigData::set_string_field()`], and — for every field —
///    a `pub const CONFIG_KEY_<FIELD>: &str` key constant from this list.  The compiler
///    enforces that every field on [`ConfigData`] is present in `STRUCT_FIELDS_DEFAULT`,
///    so forgetting this step is a compile error.  Use the emitted `CONFIG_KEY_<FIELD>` consts
///    at write sites / match arms instead of raw string literals — a rename then stays
///    compiler-tied at every use site.
/// 3. **Typed accessor** — automatically generated. The `string_config_fields!` macro
///    produces typed accessor methods on [`ConfigReload`] based on each field's
///    annotation (`non_empty`, `or(DEFAULT)`, or `list_or(...)`) — no manual
///    accessor code is needed.
///
/// ## All `Option<String>` fields must be in the macro
///
/// EVERY `Option<String>` field on [`ConfigData`] **must** appear in the
/// `string_config_fields!` invocation — the compiler enforces this through
/// `STRUCT_FIELDS_DEFAULT` (a `const Self { … }` that initialises every
/// field).  There is no such thing as a "transient" `Option<String>` field
/// that lives outside the macro.
///
/// Fields that should NOT be persisted as config KV pairs (runtime-only
/// caches, reconstructed state) will still appear in `string_fields()`
/// and thus be written/read by the per-field persist paths / `reload_from_db`.
/// If you truly need an unpersisted value, use a different type or a
/// separate data structure — not an `Option<String>` on [`ConfigData`].
///
/// ## UX asymmetry warning
///
/// The GUI Settings page reads [`ConfigData`] directly via [`ConfigReload::snapshot`]
/// (all fields).  But the per-field persist functions persist fields **only** through
/// [`ConfigData::string_fields`], which is macro-generated.  A field missing from
/// the macro would appear editable in the GUI but silently discard its value on
/// every save.  The compiler guard on `ConfigData::STRUCT_FIELDS_DEFAULT` prevents this.
#[derive(Debug, Clone)]
pub struct ConfigData {
    /// API key for the LLM provider.
    pub provider_key: Option<String>,
    /// Base URL for the OpenAI-compatible LLM provider.
    pub provider_endpoint: Option<String>,
    /// API key for the custom chat-completions endpoint (optional — many
    /// self-hosted servers are keyless). Only ever sent to the custom endpoint,
    /// never to OpenRouter.
    pub provider_endpoint_key: Option<String>,
    /// Model slot for the Manager group (Manager, Assistant, Discovery,
    /// Engineer, Maintainer).
    pub manager_model: Option<String>,
    /// Model slot for all worker roles (Analyst, Coder, QA,
    /// Reviewer, Sanitation).
    pub worker_model: Option<String>,
    /// Newline-separated list of available image generation models (for selection UI).
    pub image_gen_models: Option<String>,
    /// Newline-separated list of available video models (for selection UI).
    pub video_models: Option<String>,
    /// Firecrawl API key for web search.
    pub firecrawl_key: Option<String>,
    /// Exa API key for web search (alternative to Firecrawl).
    pub exa_key: Option<String>,
    /// Web search provider selection: "firecrawl" or "exa" (case-insensitive).
    /// When `None`, auto-selects based on which keys are configured (Firecrawl wins on tie).
    pub web_search_provider: Option<String>,
    /// Telegram Bot API token (hot-reloaded on save).
    pub telegram_bot_token: Option<String>,
    /// Enable local Qwen3-ASR audio transcription (macOS only — the audio
    /// subsystem has no other platform support).
    ///
    /// When `true` (default) and the model is cached or can be downloaded, audio
    /// transcription runs fully locally via the `qwen-asr` crate with Qwen3-ASR-0.6B.
    /// Audio never leaves the machine.
    ///
    /// Set to `"false"` to disable audio transcription entirely — audio markers
    /// are replaced with just the icon combo and the temp file is deleted, so
    /// voice messages are not recoverable.
    pub audio_transcription_use_local: Option<String>,
    /// Enable voice assistant (wake word detection and voice commands) on
    /// macOS, where the audio subsystem lives. Set to `"true"` to enable voice
    /// mode.
    pub voice_enabled: Option<String>,
    /// Enable text-to-speech for the admin's assistant replies (default:
    /// `"false"`; macOS only). Set to `"true"` to enable. When enabled, the
    /// Assistant's replies in the admin's own conversation are spoken aloud
    /// through the audio output; every other account's messages stay silent.
    pub tts_enabled: Option<String>,
    /// Language tag for TTS synthesis (default: `"na"` — language-agnostic;
    /// macOS only).
    /// Supported codes: en, ko, ja, ar, bg, cs, da, de, el, es, et, fi, fr,
    /// hi, hr, hu, id, it, lt, lv, nl, pl, pt, ro, ru, sk, sl, sv, tr, uk,
    /// vi, na.
    ///
    /// The default `"na"` works well for any language. Set to `"en"` for
    /// optimal English pronunciation, or to your language's code for better
    /// results in that language.
    pub tts_language: Option<String>,
    /// JSON-serialized wake word enrollment (v2 schema: prototype + calibration)
    /// for the voice assistant (macOS only).  Owned exclusively by the voice
    /// pipeline.
    pub wake_word_templates: Option<String>,
    /// Onboarding state machine: "init" | "finished".
    /// Absent = Init (fresh install). Set by the onboarding flow; existing
    /// installs keep the `finished` value seeded by the retired catalog's
    /// one-time migration. A legacy `"welcomed"` value reads as `Finished`.
    pub onboarding_state: Option<String>,
    /// Per-model provider routing.
    pub model_routings: Vec<ModelRouting>,
}

// ── String config field mapping ──────────────────────────────────
//
// The four runtime sync items (`STRUCT_FIELDS_DEFAULT`, `string_fields()`,
// `set_string_field()`, `normalize_string_fields()`) plus the typed accessors
// on [`ConfigReload`]
// are all generated from a single annotated field-name declaration by the
// `string_config_fields!` macro — adding or removing a field in the
// macro invocation updates all items automatically, eliminating the
// entire class of sync bugs.
//
// The macro additionally emits a `pub const CONFIG_KEY_<FIELD>` constant per
// field, alongside the sync items, so hand-written persist paths reference
// keys by name instead of raw literals.
//
// ══ Structural protection ═════════════════════════════════════════
//
// `STRUCT_FIELDS_DEFAULT` is a `const Self { … }` that initialises every
// [`ConfigData`] field.  The compiler requires every field to be present,
// so adding a field to [`ConfigData`] without adding it to the macro is
// a **compile error**.  This eliminates the silent-drift class entirely
// — no manual count constants or runtime tests needed.
//
// ══ UX asymmetry ═══════════════════════════════════════════════════
//
// The GUI Settings page reads [`ConfigData`] via [`ConfigReload::snapshot`],
// which clones every struct field directly.  But the per-field persist
// functions persist **only** through [`ConfigData::string_fields`]
// (macro-generated).  A field missing from the macro would appear editable
// in the UI but silently discard on persist.  The compiler guard above
// prevents this.
//
// ══ Per-field accessor patterns ═════════════════════════════════════
//
// Each field is annotated with one of three patterns:
//
// * `non_empty` — returns `Option<String>`, collapses empty/whitespace to `None`.
// * `or(DEFAULT)` — returns `String`, falls back to the given default constant.
// * `list_or(default = <const>)` — returns `Vec<String>`, parses a
//   newline-separated list, falls back to a single-element list of the
//   default constant when unset/empty.
//
// Generated accessors live on `impl ConfigReload`, created by `string_config_fields!`.

/// Generate the runtime sync methods `string_fields()` and `set_string_field()`,
/// the const `STRUCT_FIELDS_DEFAULT`, **and** the typed accessors on [`ConfigReload`]
/// — all from a single annotated list of `Option<String>` field names.
///
/// Each field is declared as `$field [$annotation]` where `$annotation` is one of
/// `non_empty`, `or($default)`, or `list_or(default = $default)`.
///
/// All generated items are guaranteed to stay synchronised because they expand
/// from the same source.
///
/// The macro also emits one `pub const CONFIG_KEY_<FIELD>: &str` per field
/// (name pasted from the field token, value `stringify!` of the same token),
/// so write sites and match arms can reference the key without raw literals —
/// a rename in the invocation changes the constant and its value together.
///
/// ## Structural drift protection
///
/// The generated [`ConfigData::STRUCT_FIELDS_DEFAULT`] is a `const` value that
/// initialises **every** field on [`ConfigData`] — both the listed `Option<String>`
/// fields and the `Vec` fields.  Because `Self { ... }` in a const requires all
/// fields, the **compiler** catches a struct–macro mismatch: adding a field to
/// [`ConfigData`] without adding it to the macro invocation produces a compile
/// error.  This eliminates the entire class of silent-drift bugs without manual
/// count constants or runtime tests.
macro_rules! string_config_fields {
    // ── Entry point: parse annotated field list ─────────────────
    (
        $(
            $field:ident [ $($annotation:tt)* ]
        ),* $(,)?
    ) => {
        // ── Config-key constants — single source of truth ──────
        //
        // Each field emits a `CONFIG_KEY_<FIELD>` const: the name is pasted
        // from the field token (`:upper`), the value `stringify!`s the same
        // token, so a rename changes both together and stale use sites fail
        // to compile instead of silently dropping their side effect.
        ::paste::paste! {
            $(
                pub const [<CONFIG_KEY_ $field:upper>]: &str = stringify!($field);
            )*
        }

        impl ConfigData {
            /// Default-initialised [`ConfigData`] with all `Option<String>` fields
            /// set to `None` and `Vec` fields empty.
            ///
            /// Used by [`ConfigReload::const_new`] so that adding a new field to
            /// the struct **and** the macro invocation is the *only* step needed
            /// — the const automatically stays in sync.
            ///
            /// ## Compiler enforcement
            ///
            /// Because this is a `const Self { … }`, the compiler requires every
            /// field on [`ConfigData`] to be present.  Adding a field to the
            /// struct without adding it here (via the macro) is a **compile
            /// error** — the entire silent-drift class is caught before a test
            /// ever runs.
            pub(crate) const STRUCT_FIELDS_DEFAULT: Self = Self {
                $($field: None,)*
                model_routings: Vec::new(),
            };

            /// Return all string-valued config fields as (db_key, current_value) pairs.
            ///
            /// `model_routings` is **not** included here — it lives in a
            /// separate database table (`config_model_routing`).
            #[must_use]
            pub fn string_fields(&self) -> Vec<(&'static str, Option<&str>)> {
                vec![$((stringify!($field), self.$field.as_deref())),*]
            }

            /// Set a string field by its database key. Returns `true` if the key was
            /// recognised and the field was updated, `false` for unknown keys.
            ///
            /// The value is stored as-is without normalization — call [`Self::normalize`]
            /// before using the config to collapse empty/whitespace-only values to `None`.
            ///
            /// `model_routings` is **not** handled here — it lives in a separate
            /// database table (`config_model_routing`).
            #[must_use]
            pub fn set_string_field(&mut self, key: &str, value: &str) -> bool {
                match key {
                    $(stringify!($field) => self.$field = Some(value.to_owned()),)*
                    _ => return false,
                }
                true
            }

            /// Read a string field's raw value by its database key, returning
            /// `None` for unknown keys.
            ///
            /// This is the allocation-free read counterpart to [`set_string_field`]:
            /// it mirrors the setter's match arms so the two always agree on the
            /// exact generated key set. The value is returned as stored (not
            /// normalized) — call [`Self::normalize`] before using the config to
            /// collapse empty/whitespace-only values to `None`.
            ///
            /// `model_routings` is **not** handled here — it lives in a separate
            /// database table (`config_model_routing`).
            #[must_use]
            pub(crate) fn get_string_field(&self, key: &str) -> Option<&str> {
                match key {
                    $(stringify!($field) => self.$field.as_deref(),)*
                    _ => None,
                }
            }

            /// Whether `key` names a known string-field database key.
            ///
            /// Presence is checked against the generated field set, not against
            /// the field's current value — this is why it is a separate method
            /// rather than [`get_string_field(...).is_some()`]: on
            /// [`STRUCT_FIELDS_DEFAULT`] every value is `None`, so a value-based
            /// probe would always return `false`.
            #[must_use]
            fn has_string_field(&self, key: &str) -> bool {
                match key {
                    $(stringify!($field) => true,)*
                    _ => false,
                }
            }

            /// Normalise all string fields in place: trim whitespace and collapse
            /// empty or whitespace-only values to `None`.
            ///
            /// Unlike [`set_string_field`], which stores values as-is, this is the
            /// canonical normalization point — callers that set individual fields
            /// should ensure [`Self::normalize`] is called before using the config.
            fn normalize_string_fields(&mut self) {
                $(self.$field = non_empty(self.$field.take());)*
            }
        }

        // ── Generate typed accessors on ConfigReload ────────────
        //
        // Both passes needed: `normalize()` writes canonical values so
        // the per-field persist paths' `!=` comparisons against current
        // CONFIG accessors see no spurious diffs; accessors below
        // re-normalise raw values. See `config_reload_accessors_roundtrip`.
        impl ConfigReload {
            $(
                string_config_fields!(@accessor $field $($annotation)*);
            )*
        }
    };

    // ── Accessor pattern: non_empty ─────────────────────────────
    //
    // Returns Option<String>, collapses empty/whitespace to None.
    (@accessor $field:ident non_empty) => {
        #[doc = concat!(
            "Returns the configured `", stringify!($field),
            "`, with empty/whitespace values collapsed to `None`."
        )]
        #[must_use]
        pub fn $field(&self) -> Option<String> {
            non_empty(self.read().$field.clone())
        }
    };

    // ── Accessor pattern: or(DEFAULT) ───────────────────────────
    //
    // Returns String, falls back to the given default constant.
    (@accessor $field:ident or($default:expr)) => {
        #[doc = concat!(
            "Returns the configured `", stringify!($field),
            "`, falling back to the default if unset."
        )]
        #[must_use]
        pub fn $field(&self) -> String {
            resolve_or(self.read().$field.clone(), $default)
        }
    };

    // ── Accessor pattern: list_or(default = <const>) ──
    //
    // Returns Vec<String>. Tries parsing `$field` as a newline-separated list.
    // If non-empty, returns the parsed entries. Otherwise falls back to the
    // hardcoded `$default` constant. Used for the model picker lists, whose
    // active selection is now per-user (not a global config field) — the only
    // fallback is the default model.
    (@accessor $field:ident list_or(default = $default:expr)) => {
        #[doc = concat!(
            "Returns the list of available `", stringify!($field), "`.",
            "\n\nIf unset or the parsed newline-separated list is empty,",
            " falls back to a built-in default."
        )]
        #[must_use]
        pub fn $field(&self) -> Vec<String> {
            let guard = self.read();
            resolve_list_or(guard.$field.as_deref(), $default)
        }
    };
}

string_config_fields! {
    provider_key [non_empty],
    provider_endpoint [or(DEFAULT_PROVIDER_ENDPOINT)],
    provider_endpoint_key [non_empty],
    manager_model [or(DEFAULT_MANAGER_MODEL)],
    worker_model [or(DEFAULT_WORKER_MODEL)],
    image_gen_models [list_or(default = DEFAULT_IMAGE_GEN_MODEL)],
    video_models [list_or(default = DEFAULT_VIDEO_MODEL)],
    firecrawl_key [non_empty],
    exa_key [non_empty],
    web_search_provider [non_empty],
    telegram_bot_token [non_empty],
    audio_transcription_use_local [non_empty],
    voice_enabled [non_empty],
    tts_enabled [non_empty],
    tts_language [or(DEFAULT_TTS_LANGUAGE)],
    wake_word_templates [non_empty],
    onboarding_state [non_empty],
}

impl ConfigData {
    /// Normalise inner `Option<String>` fields of `Vec` entries in place:
    /// trim whitespace and collapse empty/whitespace-only values to `None`.
    ///
    /// This is the Vec-entry counterpart of [`normalize_string_fields()`] —
    /// the macro-generated method only touches top-level `Option<String>` fields,
    /// not the inner fields of [`ModelRouting`] entries.
    fn normalize_entries(&mut self) {
        for mr in &mut self.model_routings {
            mr.provider_order = non_empty(mr.provider_order.take());
        }
    }

    /// Apply canonical normalisation + sorting to the in-memory
    /// representation so it is consistent across all persistence paths.
    ///
    /// The sequence is:
    /// 1. Trim top-level `Option<String>` fields and collapse empty → `None`.
    /// 2. Trim inner fields on `Vec` entries (`[ModelRouting]`)
    ///    and collapse empty → `None`.
    /// 3. Sort `model_routings` by model name.
    ///
    /// Every caller that produces a newly-built [`ConfigData`] must call
    /// this before swapping into the global [`CONFIG`] so that the in-memory
    /// representation is the same regardless of which code path produced it.
    pub(crate) fn normalize(&mut self) {
        self.normalize_string_fields();
        self.normalize_entries();
        self.model_routings.sort_by(|a, b| a.model.cmp(&b.model));
    }
}

// ── Config value helpers ────────────────────────────────────────────

/// Trim a string and return `None` if empty or whitespace-only.
/// This is the canonical primitive for string trimming helpers.
#[must_use]
pub(crate) fn trimmed_or_none(s: &str) -> Option<String> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_owned())
    }
}

/// Parse a newline-separated string into a vector of non-empty, trimmed entries.
#[must_use]
pub(crate) fn parse_newline_list(s: &str) -> Vec<String> {
    s.split('\n')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

/// Treat an empty or whitespace-only string as `None`.
/// The value is trimmed before being returned.
/// Delegates to [`trimmed_or_none`].
#[must_use]
fn non_empty(val: Option<String>) -> Option<String> {
    val.and_then(|s| trimmed_or_none(&s))
}

/// Resolve a value with a fallback: use `val` if non-empty (after trimming), else `fallback`.
#[must_use]
pub(crate) fn resolve_or(val: Option<String>, fallback: &str) -> String {
    non_empty(val).unwrap_or(fallback.to_string())
}

/// Parse a newline-separated list field, falling back to a hardcoded default.
///
/// If `list_field` is `Some` and contains at least one non-empty line (after trimming), the parsed
/// lines are returned as a `Vec<String>`. Otherwise a single-element vec containing
/// `default_value` is returned.
#[must_use]
fn resolve_list_or(list_field: Option<&str>, default_value: &str) -> Vec<String> {
    if let Some(raw) = list_field {
        let parsed = parse_newline_list(raw);
        if !parsed.is_empty() {
            return parsed;
        }
    }
    vec![default_value.to_string()]
}

/// Normalize an endpoint URL for comparison: trim surrounding whitespace,
/// lowercase the scheme and host (not the path), strip trailing slashes, and
/// strip a trailing `/chat/completions` suffix. The default OpenRouter URL and
/// trivial variants (trailing slash, whitespace, scheme/host case,
/// chat-completions suffix) must never count as a custom endpoint.
///
/// Suffix matching is case-sensitive (`/Chat/Completions` is not stripped).
/// Scheme-less input is returned largely unchanged (no `://` → no lowercasing,
/// just trimmed/stripped); empty/whitespace-only input normalizes to `""`.
///
/// SSoT coupling: future changes here intentionally affect fetch URL
/// construction at all call sites (catalog, transcribe, compatible provider).
#[must_use]
pub(crate) fn normalize_endpoint_url(url: &str) -> String {
    let t = url.trim().trim_end_matches('/');
    // Strip one trailing `/chat/completions` suffix (after slash-stripping the
    // suffix has no trailing slash). Handles a URL ending exactly in
    // `/chat/completions`.
    let t = t
        .strip_suffix("/chat/completions")
        .unwrap_or(t)
        .trim_end_matches('/');
    // Lowercase scheme + host, preserve the path as-is.
    if let Some(scheme_end) = t.find("://") {
        let scheme_and_dots = &t[..scheme_end + 3];
        let rest = &t[scheme_end + 3..];
        let authority_end = rest.find('/').unwrap_or(rest.len());
        let authority = &rest[..authority_end];
        let path = &rest[authority_end..];
        format!(
            "{}{}{}",
            scheme_and_dots.to_ascii_lowercase(),
            authority.to_ascii_lowercase(),
            path
        )
    } else {
        // No scheme — validation rejects such values anyway; return unchanged.
        t.to_string()
    }
}

/// Whether `endpoint` is the default OpenRouter chat-completions endpoint
/// (modulo trivial variants — see [`normalize_endpoint_url`]).
#[must_use]
pub(crate) fn is_default_endpoint(endpoint: &str) -> bool {
    normalize_endpoint_url(endpoint) == normalize_endpoint_url(DEFAULT_PROVIDER_ENDPOINT)
}

/// Whether `endpoint` is a genuinely non-default (custom) endpoint.
#[must_use]
pub(crate) fn is_custom_endpoint(endpoint: &str) -> bool {
    !is_default_endpoint(endpoint)
}

/// Whether the LLM provider is configured: a non-empty OpenRouter key OR a
/// genuinely custom endpoint active in the global CONFIG — keyless custom
/// endpoints count too, while the default URL and trivial variants never do.
/// Used by the pipeline pickup gate and the GUI boot-to-Settings redirect.
#[must_use]
pub(crate) fn provider_configured() -> bool {
    is_custom_endpoint(&CONFIG.provider_endpoint()) || CONFIG.provider_key().is_some()
}

/// Effective chat-completions endpoint for a config snapshot: the persisted
/// endpoint when set (custom), else the default.
#[must_use]
pub(crate) fn effective_chat_endpoint(config: &ConfigData) -> String {
    resolve_or(config.provider_endpoint.clone(), DEFAULT_PROVIDER_ENDPOINT)
}

/// Credential for chat-completions requests under `config`: the custom
/// endpoint's own key when a custom endpoint is active (None = keyless, no
/// Authorization header), otherwise the OpenRouter key. The OpenRouter key is
/// NEVER sent to a custom endpoint.
#[must_use]
pub(crate) fn chat_credential(config: &ConfigData) -> Option<String> {
    let ep = effective_chat_endpoint(config);
    if is_custom_endpoint(&ep) {
        non_empty(config.provider_endpoint_key.clone())
    } else {
        non_empty(config.provider_key.clone())
    }
}

// ── ConfigReload — global singleton ──────────────────────────────

/// Global reloadable config singleton.
///
/// The `storage_root` is immutable after startup; all other fields live in an
/// `RwLock<ConfigData>` that can be atomically swapped at runtime.
pub static CONFIG: ConfigReload = ConfigReload::const_new();

/// Serializes all per-field config persistence (settings-page autosave).
///
/// Every settled-field persist runs inside this lock so that:
/// - read-modify-write sequences (routing rows, endpoint/key probes built
///   from the live config) never interleave with each other;
/// - side-effect settles (provider warmup + recreate, Telegram listener
///   restart) cannot race, which would let two full config rewrites with
///   stale snapshots clobber each other's freshly-written rows.
///
/// The lock is held across the entire persist — including the provider
/// warmup network call — so each settle validates and writes against the
/// latest committed state.
static CONFIG_PERSIST_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();

fn persist_lock() -> &'static tokio::sync::Mutex<()> {
    CONFIG_PERSIST_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}

/// Fresh-install discriminator: set during [`load_or_init`] to
/// whether the consolidated `core.db` did not exist on disk before the
/// config store was opened this boot. [`reload_from_db`] seeds the
/// fresh-install defaults into brand-new config databases only — existing
/// databases receive zero writes (hard constraint).
static CONFIG_DB_FRESH_AT_BOOT: AtomicBool = AtomicBool::new(false);

/// Reloadable configuration with atomic swap capability.
///
/// The inner [`ConfigData`] is protected by an [`RwLock`] so readers don't
/// block each other. Writes happen only during startup and GUI-driven config
/// saves.
pub struct ConfigReload {
    storage_root: OnceLock<PathBuf>,
    inner: RwLock<ConfigData>,
}

impl ConfigReload {
    #[must_use]
    pub const fn const_new() -> Self {
        Self {
            storage_root: OnceLock::new(),
            inner: RwLock::new(ConfigData::STRUCT_FIELDS_DEFAULT),
        }
    }

    // ── Storage root (set once at startup, immutable thereafter) ─

    /// # Panics
    /// Panics if storage root has not been set.
    pub fn global_storage_root(&self) -> PathBuf {
        self.storage_root
            .get()
            .expect("CONFIG storage_root not initialized")
            .clone()
    }

    /// Like [`Self::global_storage_root`], but returns `None` instead of panicking if
    /// storage root has not been set yet. Useful for code paths that can tolerate
    /// an uninitialized config (e.g., graceful degradation in tests).
    #[must_use]
    pub fn try_storage_root(&self) -> Option<PathBuf> {
        self.storage_root.get().cloned()
    }

    pub(crate) fn set_storage_root(&self, root: PathBuf) {
        self.storage_root
            .set(root)
            .expect("CONFIG storage_root already set");
    }

    /// Like [`set_storage_root`], but returns `Err` instead of panicking if
    /// already set. Useful in test environments where the root may have been
    /// set by a previously-running test.
    #[cfg(test)]
    pub(crate) fn try_set_storage_root(&self, root: PathBuf) -> std::result::Result<(), PathBuf> {
        self.storage_root.set(root)
    }

    // ── Snapshot access ─────────────────────────────────────────

    /// Get a read-locked snapshot of the current config.
    /// Prefer the typed accessors below for individual fields.
    fn read(&self) -> RwLockReadGuard<'_, ConfigData> {
        self.inner.read().unwrap_poison()
    }

    /// Replace the entire config atomically (used during startup and reload).
    pub(crate) fn swap(&self, new_config: ConfigData) {
        *self.inner.write().unwrap_poison() = new_config;
    }

    /// Get a full clone of the current config for serialisation / GUI display.
    #[must_use]
    pub fn snapshot(&self) -> ConfigData {
        self.read().clone()
    }

    /// The current onboarding state (derived from the `onboarding_state` field).
    #[must_use]
    pub fn onboarding_stage(&self) -> OnboardingState {
        OnboardingState::from_raw(self.onboarding_state().as_deref())
    }

    /// Update a single string config field in-memory.
    ///
    /// This is intentionally lightweight — it only mutates the in-memory
    /// [`ConfigData`] without touching the database or triggering provider
    /// warmup. Callers are responsible for persisting the change to the
    /// config DB separately (e.g. via [`crate::config_db::ConfigStore::set_kv`]).
    ///
    /// Returns `true` if the key was recognised, `false` otherwise (unknown
    /// keys are silently ignored for forward compatibility).
    #[must_use]
    pub fn set_string_field(&self, key: &str, value: &str) -> bool {
        let mut guard = self.inner.write().unwrap_poison();
        guard.set_string_field(key, value)
    }

    /// Apply a single model-routing row to the in-memory config (find-or-push).
    ///
    /// `None` on `provider_order` removes the row (mirroring the
    /// DELETE-if-empty persistence path).
    fn set_model_routing_row(&self, model: &str, provider_order: Option<String>) {
        let mut guard = self.inner.write().unwrap_poison();
        if provider_order.is_none() {
            guard.model_routings.retain(|mr| mr.model != model);
        } else {
            ModelRouting::upsert(&mut guard.model_routings, model, |mr| {
                mr.provider_order = provider_order;
            });
        }
    }

    // ── Provider routing (per-model) ──────────────────────────

    /// Find the per-model routing row by model key, if one exists.
    ///
    /// Unlike [`Self::model_routing`] (which returns the *effective* routing —
    /// a stored row, else the model's default provider), this returns the raw
    /// stored row, and `None` when there is none: the settings page uses it to
    /// tell "no override" apart from "override cleared" when mirroring settled
    /// rows.
    pub(crate) fn model_routing_by_key(&self, model: &str) -> Option<ModelRouting> {
        let guard = self.read();
        guard
            .model_routings
            .iter()
            .find(|mr| mr.model == model)
            .cloned()
    }

    /// Look up the effective provider routing for a model.
    ///
    /// The user's stored order (Settings → Provider Routing) wins when one is
    /// set; otherwise the model's [`default_model_routing`] applies, so an
    /// unset/cleared field behaves exactly as if that provider had been set.
    #[must_use]
    pub(crate) fn model_routing(&self, model: &str) -> ModelRouting {
        // No stored order → the model's default provider; see `default_model_routing`.
        let provider_order = self
            .model_routing_by_key(model)
            .and_then(|mr| mr.provider_order)
            .or_else(|| default_model_routing(model).map(str::to_string));
        ModelRouting {
            model: model.to_string(),
            provider_order,
        }
    }

    // ── Role model resolution (two slots) ─────────────────────

    /// Resolve the configured model for a role from the two model slots.
    ///
    /// The manager group (Manager, Assistant, Discovery, Engineer,
    /// Maintainer) uses the manager slot; every other role (Analyst, Coder,
    /// QA, Reviewer, Sanitation) uses the worker slot. Unset slots
    /// fall back to their code default.
    #[must_use]
    pub fn role_model(&self, role: Role) -> String {
        match role {
            Role::Manager
            | Role::Assistant
            | Role::Discovery
            | Role::Engineer
            | Role::Maintainer => self.manager_model(),
            _ => self.worker_model(),
        }
    }
}

// ── Startup / reload / save ──────────────────────────────────────

pub fn default_config_dir() -> Result<PathBuf> {
    if let Ok(home) = std::env::var("HOME")
        && !home.is_empty()
    {
        return Ok(PathBuf::from(home).join(".mahbot"));
    }

    let home = UserDirs::new()
        .map(|u| u.home_dir().to_path_buf())
        .context("Could not find home directory")?;
    Ok(home.join(".mahbot"))
}

/// Load (or initialise) the config system.
///
/// 1. Resolves `~/.mahbot` as the storage root.
/// 2. Creates the directory if needed.
/// 3. Seeds runtime config with hardcoded defaults.
/// 4. Stores the result in the global [`CONFIG`] singleton.
///
/// The caller must subsequently call [`reload_from_db`] to load any
/// persisted configuration from the consolidated database. Providers must be
/// initialised **after** `reload_from_db` so API keys and model
/// settings take effect.
pub async fn load_or_init() -> Result<()> {
    let mahbot_dir = default_config_dir()?;
    fs::create_dir_all(&mahbot_dir)
        .await
        .context("Failed to create config directory")?;

    CONFIG.set_storage_root(mahbot_dir.clone());

    // Fresh-install discriminator: capture whether the config store file exists
    // BEFORE any store open creates it, so reload_from_db() can seed
    // fresh-install defaults into brand-new databases only. In the consolidated
    // layout the config store lives in the single `core.db`; an existing
    // install is detected by that file. Probing any other location would
    // classify every existing install as fresh and re-seed it on each boot,
    // violating the zero-write hard constraint.
    CONFIG_DB_FRESH_AT_BOOT.store(config_db_is_fresh(&mahbot_dir), Ordering::Release);

    // Start with hardcoded defaults — reload_from_db() will overlay
    // any persisted values from the config store (called later in bootstrap).
    CONFIG.swap(ConfigData::STRUCT_FIELDS_DEFAULT);

    tracing::info!(
        "Config system initialised (storage root: {}).",
        mahbot_dir.display()
    );
    Ok(())
}

/// Fresh-install discriminator: `true` when the config store
/// file does not yet exist at its real location.
///
/// In the consolidated layout the config store lives in the single domain
/// database ([`crate::db::CONSOLIDATED_DB_NAME`]); the discriminator is simply
/// whether that consolidated file exists.
///
/// Must be probed BEFORE any store open creates the file, and must check the
/// exact path the open uses (`init_all_stores` → `open_store` →
/// `store_db_path`).
fn config_db_is_fresh(mahbot_dir: &std::path::Path) -> bool {
    !crate::db::store_db_path(mahbot_dir, "config").exists()
}

/// The provider that serves a model unless the user chose one for it: a
/// DeepSeek-family model (case-insensitive substring match on the model slug)
/// goes to OpenRouter's canonical lowercase `deepseek` slug; every other model
/// stays auto-routed.
///
/// **DO NOT DELETE, WEAKEN OR "SIMPLIFY" THIS RULE WITHOUT AN EXPLICIT USER
/// REQUEST.** Which host serves a model decides prompt-cache locality, so
/// auto-routing a DeepSeek model across hosts is a large billing regression.
pub(crate) fn default_model_routing(model: &str) -> Option<&'static str> {
    model
        .to_ascii_lowercase()
        .contains("deepseek")
        .then_some("deepseek")
}

/// Seed the fresh-install defaults into a brand-new config database
///
/// A fresh install must not load or download any audio model until the user
/// enables a feature, so `audio_transcription_use_local` is seeded to
/// `"false"` (the existing reading semantics are unchanged: absence of the
/// row = enabled, `"false"` = disabled). It must also show populated model
/// pickers: the Settings GUI reads the raw snapshot fields
/// (`config.image_gen_models` / `config.video_models`), not the
/// default-resolving `list_or` accessors, so the image/video generation model
/// lists are seeded too. The active selection is per-user (see
/// `crate::users`), not a config field, so no singular key is seeded. `fresh`
/// is the pre-open file-existence discriminator captured in [`load_or_init`] —
/// existing databases receive zero writes.
async fn seed_fresh_install_defaults(
    fresh: bool,
    store: &crate::config_db::ConfigStore,
) -> Result<()> {
    if !fresh {
        return Ok(());
    }
    store
        .set_kv(CONFIG_KEY_AUDIO_TRANSCRIPTION_USE_LOCAL, "false")
        .await?;
    store
        .set_kv(CONFIG_KEY_IMAGE_GEN_MODELS, FRESH_INSTALL_IMAGE_GEN_MODELS)
        .await?;
    store
        .set_kv(CONFIG_KEY_VIDEO_MODELS, FRESH_INSTALL_VIDEO_MODELS)
        .await?;
    // Default model slots with a known provider route through it on fresh
    // installs. The rows duplicate what an empty field resolves to, but are
    // kept so the Settings routing field renders the value; they are derived
    // from the default-model constants via `default_model_routing`, and only
    // the manager/worker slots are seeded.
    // Existing installs receive zero writes — the `fresh` guard above already
    // returned for them.
    for default_model in [DEFAULT_MANAGER_MODEL, DEFAULT_WORKER_MODEL] {
        if let Some(provider) = default_model_routing(default_model) {
            store
                .save_model_routing(default_model, Some(provider))
                .await?;
        }
    }
    tracing::info!(
        "Fresh config database: seeded fresh-install defaults (audio transcription off; image/video generation model sets; provider routing for the default model slots)"
    );
    Ok(())
}

/// Consume the boot fresh-install discriminator and seed the fresh-install
/// defaults when it fired.
///
/// Mirrors the `load_or_init` → `reload_from_db` handoff exactly: the flag is
/// set from [`config_db_is_fresh`] during boot and consumed (reset) here, so
/// the seed lands once per fresh boot only. Kept as a separate function so the
/// flag-consumption path is testable without the global store.
async fn seed_fresh_install_defaults_from_flag(
    store: &crate::config_db::ConfigStore,
) -> Result<()> {
    let fresh = CONFIG_DB_FRESH_AT_BOOT.swap(false, Ordering::AcqRel);
    seed_fresh_install_defaults(fresh, store).await
}

/// Idempotent migration: rewrite persisted
/// `config_kv` rows that still hold the *previous* manager/worker default
/// model to the current default. Matching is exact on the full
/// provider-prefixed string, so only rows the user never overrode are
/// touched; every other key is untouched. A slot rewrite also seeds the
/// routing row for the new default — the same order `default_model_routing`
/// resolves for an empty field, written so the Settings routing field renders
/// it. Safe to run on every boot — a no-op once no row matches.
async fn migrate_old_default_models(store: &crate::config_db::ConfigStore) -> Result<()> {
    let changed_manager = store
        .migrate_kv_if_equals(
            CONFIG_KEY_MANAGER_MODEL,
            OLD_DEFAULT_MANAGER_MODEL,
            DEFAULT_MANAGER_MODEL,
        )
        .await?;
    let changed_worker = store
        .migrate_kv_if_equals(
            CONFIG_KEY_WORKER_MODEL,
            OLD_DEFAULT_WORKER_MODEL,
            DEFAULT_WORKER_MODEL,
        )
        .await?;
    for (changed, model) in [
        (changed_manager, DEFAULT_MANAGER_MODEL),
        (changed_worker, DEFAULT_WORKER_MODEL),
    ] {
        if changed > 0
            && let Some(provider) = default_model_routing(model)
        {
            store.save_model_routing(model, Some(provider)).await?;
        }
    }
    if changed_manager > 0 || changed_worker > 0 {
        tracing::info!(
            manager_rows = changed_manager,
            worker_rows = changed_worker,
            "Migrated stored old default models to the current defaults"
        );
    }
    Ok(())
}

/// Reload config from the consolidated domain database, atomically swapping the
/// runtime config. Called at startup (after config_db init) to overlay
/// persisted settings on top of hardcoded defaults.
pub async fn reload_from_db() -> Result<()> {
    let store = crate::config_db::store();
    let mut config = ConfigData::STRUCT_FIELDS_DEFAULT;

    // Fresh-install seed: a brand-new config
    // database gets the transcription-off default (so no audio model is
    // downloaded or loaded at boot) plus the image/video generation model
    // lists (so the Settings GUI pickers are populated; the active selection
    // is per-user, not a config field).
    // Existing installs are never written (the flag is only set when the config
    // store did not exist before the store open).
    seed_fresh_install_defaults_from_flag(store).await?;

    // Rewrite persisted old-default manager/worker rows to the new default
    // before the overlay below, so this boot serves the migrated value.
    migrate_old_default_models(store).await?;

    let kvs = store.get_all_kv().await?;
    for (key, value) in &kvs {
        if !config.set_string_field(key, value) {
            tracing::debug!(key, "Unknown config key, ignoring");
        }
    }
    purge_unknown_kv_orphans(store, &kvs).await;

    let routings = store.get_all_model_routings().await?;
    config.model_routings = routings;

    // Normalise and sort so the in-memory representation matches the
    // per-field persistence paths (see the "Per-field persistence" section).
    config.normalize();

    CONFIG.swap(config);
    tracing::info!("Config reloaded from DB");
    Ok(())
}

/// Delete `config_kv` rows whose keys are no longer recognized config fields
/// (e.g. a setting removed in an upgrade), so stale values cannot resurface if
/// the key is ever reintroduced. The shared namespaces written by other
/// subsystems (the nightly-discovery marker and the temp-cleanup cadence
/// state) are left untouched. Delete failures are logged and tolerated
/// (transient, retried on the next reload).
async fn purge_unknown_kv_orphans(store: &crate::config_db::ConfigStore, kvs: &[(String, String)]) {
    let orphans: Vec<String> = kvs
        .iter()
        .filter(|(key, _)| {
            !ConfigData::STRUCT_FIELDS_DEFAULT.has_string_field(key)
                && key != crate::workspace::NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY
                && key != crate::temp::TEMP_CLEANUP_LAST_RUN_KV_KEY
                && key != crate::temp::TEMP_CLEANUP_MODE_KV_KEY
        })
        .map(|(key, _)| key.clone())
        .collect();
    if !orphans.is_empty() {
        tracing::debug!(keys=?orphans, "Purging unknown config_kv orphans");
    }
    for key in orphans {
        match store.delete_kv(&key).await {
            Ok(()) => tracing::debug!(key, "Purged unknown config_kv orphan"),
            Err(e) => {
                tracing::warn!(key, error=%e, "Failed to purge unknown config_kv orphan (transient, ignoring)");
            }
        }
    }
}

// ── Per-field persistence (settings-page autosave) ─────────────────
//
// Each settled config field is persisted individually — a single KV row or a
// single routing row — instead of a whole-config rewrite. Every function
// in this section:
//
// 1. Runs under [`persist_lock`] so read-modify-write sequences and
//    side-effect settles never interleave (see the lock's doc comment).
// 2. Validates the settled value BEFORE anything is written; on failure the
//    DB and the in-memory CONFIG are untouched and the error propagates to
//    the caller for inline display.
// 3. Applies targeted side effects only for the fields that need them
//    (provider/transcriber re-init, Telegram listener reload) — never per
//    keystroke, only when a value settles.
// 4. Returns the canonical persisted value (trimmed, `None` collapsed to
//    `""`) so the caller can re-sync its display snapshot — the settings
//    page writes exactly this value back into the editable snapshot for
//    every field type.
//
// `wake_word_templates` is excluded from every path: it is owned exclusively
// by the voice pipeline (`persist_enrollment` in `voice.rs`), which writes
// the key directly, and any GUI write would create a dual-writer race.

/// Outcome of persisting a settled config field: the canonical persisted value
/// plus an optional non-fatal warning (e.g. an unreachable custom endpoint that
/// was saved anyway).
///
/// `pub` (not `pub(crate)`) because it flows through the public
/// [`crate::gui::settings::SettingsMessage`] enum's persist-result variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersistOutcome {
    pub value: String,
    pub warning: Option<String>,
}

/// Persist a single settled string config field.
///
/// `key` must be a `config_kv` key (see [`ConfigData::string_fields`]).
/// Returns the canonical persisted value plus an optional non-fatal warning.
pub async fn persist_settled_string_field(key: &str, value: &str) -> Result<PersistOutcome> {
    let _guard = persist_lock().lock().await;
    let trimmed = value.trim().to_string();

    // Defense in depth: the settings page renders no control for this key, but
    // refuse it structurally so no future caller can ever write it here.
    if key == CONFIG_KEY_WAKE_WORD_TEMPLATES {
        return Ok(PersistOutcome {
            value: CONFIG.wake_word_templates().unwrap_or_default(),
            warning: None,
        });
    }

    let canonical = trimmed_or_none(&trimmed).unwrap_or_default();

    match key {
        // Provider endpoint changes re-init the provider and transcriber. The
        // probe→validate→write step is shared with the key arm via
        // `probe_validate_write`; the endpoint-specific cascade, warmup, and
        // recreate follow.
        //
        // Note: the active image model is per-user (see `crate::users`) and is
        // not re-validated here. The image-model catalog is endpoint-keyed;
        // validating committed models against the new endpoint could deadlock
        // a provider switch to a disjoint catalog (endpoint rejects until the
        // model changes, model rejects until the endpoint changes). Telegram
        // picker taps validate image models against the default endpoint
        // instead — so a switch is two steps (endpoint first, then model),
        // each independently valid.
        CONFIG_KEY_PROVIDER_ENDPOINT => {
            let probe = probe_validate_write(key, &trimmed).await?;

            // Cascade: settling a default or empty endpoint removes the custom
            // endpoint's key row — the key is only meaningful while a custom
            // endpoint is active. Covers both the toggle-off "" and typing the
            // default URL back. The endpoint row is written FIRST so a failure
            // on the write leaves the key row intact (consistent state); a
            // failure on the cascade leaves a stale key row, which is never
            // read (harmless per the orphaned-key policy) — so the cleanup is
            // best-effort and never fails the save.
            if trimmed.is_empty() || crate::config::is_default_endpoint(&trimmed) {
                let store = crate::config_db::store();
                match store.delete_kv(CONFIG_KEY_PROVIDER_ENDPOINT_KEY).await {
                    Ok(()) => {
                        let _ = CONFIG.set_string_field(CONFIG_KEY_PROVIDER_ENDPOINT_KEY, "");
                    }
                    Err(e) => {
                        tracing::warn!(
                            error = %e,
                            "failed to clear custom endpoint key row (harmless orphan)"
                        );
                    }
                }
            }

            // Warmup is best-effort AND custom-only: an unreachable custom
            // endpoint is saved anyway (with a warning) so a self-hosted
            // server can be configured before it is reachable. Reverting to
            // the default (empty or default URL — toggle-off / typing the
            // default back) is NOT probed: a transient OpenRouter outage
            // must not surface an 'unreachable' warning on a deliberate
            // revert.
            let effective = effective_chat_endpoint(&probe);
            let warning = if crate::config::is_custom_endpoint(&effective) {
                match crate::providers::warmup_provider_from_config(&probe).await {
                    Ok(()) => None,
                    Err(e) => {
                        let msg = format!("Saved, but {effective} is unreachable right now: {e:#}");
                        tracing::warn!(key, endpoint = %effective, "Provider warmup failed (non-fatal, value saved): {e:#}");
                        Some(msg)
                    }
                }
            } else {
                None
            };

            // The foreground warmup above (or its deliberate skip on revert)
            // is the only warmup this save performs — recreate_all must not
            // fire a second background warmup of the same endpoint.
            crate::providers::recreate_all(&CONFIG.snapshot(), false).await;
            return Ok(PersistOutcome {
                value: canonical,
                warning,
            });
        }
        // Provider key changes re-init the provider with the new credential.
        // No warn-and-save here: warmup is a connection-pool pre-warm that
        // never validates keys (a GET that ignores auth status), so key saves
        // are structurally validated + written, and `recreate_all` rebuilds the
        // provider with the new credential (warmup runs as a non-fatal
        // background task inside it). This keeps the custom-endpoint
        // warning channel off the key fields — a warmup failure while a custom
        // endpoint is active must not surface an 'unreachable' warning under
        // the OpenRouter key field.
        CONFIG_KEY_PROVIDER_KEY | CONFIG_KEY_PROVIDER_ENDPOINT_KEY => {
            let _ = probe_validate_write(key, &trimmed).await?;
            crate::providers::recreate_all(&CONFIG.snapshot(), true).await;
            return Ok(PersistOutcome {
                value: canonical,
                warning: None,
            });
        }
        // Telegram token change hot-reloads the listener after the write.
        CONFIG_KEY_TELEGRAM_BOT_TOKEN => {
            let old_token = CONFIG.telegram_bot_token();
            let new_token = trimmed_or_none(&trimmed);
            if new_token != old_token
                && let Some(ref token) = new_token
            {
                crate::channels::telegram::TelegramChannel::validate_token(token).await?;
            }
            write_kv_and_update_config(CONFIG_KEY_TELEGRAM_BOT_TOKEN, &trimmed).await?;
            let persisted = CONFIG.telegram_bot_token();
            if persisted != old_token {
                crate::channels::telegram::restart_telegram_listener(persisted.as_deref()).await?;
            }
        }
        // Everything else is read dynamically at use time — persist only.
        _ => {
            write_kv_and_update_config(key, &trimmed).await?;
        }
    }

    Ok(PersistOutcome {
        value: canonical,
        warning: None,
    })
}

/// Probe→validate→write for the provider arms: snapshot the live CONFIG, apply
/// `key = trimmed`, normalize, structurally validate, then write the KV row and
/// mirror it into CONFIG. Returns the normalized probe — the live config with
/// only this field applied, so concurrent changes to other fields are never
/// clobbered.
///
/// # Precondition
/// The caller holds [`persist_lock`] — this helper does not acquire it,
/// matching [`write_kv_and_update_config`] and [`save_routing_row`].
///
/// This is the provider-arms-only probe contract, not the universal persist
/// path (telegram/image_model/others use different validation). The returned
/// probe is consumed only by the endpoint arm (for warmup); the key arm
/// discards it via `let _ = …`.
async fn probe_validate_write(key: &str, trimmed: &str) -> Result<ConfigData> {
    let mut probe = CONFIG.snapshot();
    let _ = probe.set_string_field(key, trimmed);
    probe.normalize();
    validate_config(&probe)?;
    write_kv_and_update_config(key, trimmed).await?;
    Ok(probe)
}

/// Persist a settled per-model routing `provider_order` (`""` clears it).
///
/// Returns the canonical order value. Routing applies only to the manager and
/// worker model slots.
pub async fn persist_settled_routing_order(model: &str, order: &str) -> Result<String> {
    let _guard = persist_lock().lock().await;
    let order = trimmed_or_none(order);
    save_routing_row(model, order).await
}

/// Write a single routing row (UPSERT or DELETE-if-empty) and mirror it into
/// the in-memory CONFIG. Caller holds [`persist_lock`].
async fn save_routing_row(model: &str, order: Option<String>) -> Result<String> {
    let store = crate::config_db::store();
    store.save_model_routing(model, order.as_deref()).await?;
    CONFIG.set_model_routing_row(model, order.clone());
    Ok(order.unwrap_or_default())
}

/// Write a single `config_kv` row (delete when the value is empty after
/// trimming) and mirror it into the in-memory CONFIG. Caller holds
/// [`persist_lock`].
async fn write_kv_and_update_config(key: &str, trimmed: &str) -> Result<()> {
    // Reject unknown keys BEFORE touching the DB: `set_string_field` is
    // deliberately lenient (returns `false` for unrecognised keys, leaving
    // CONFIG untouched), and writing a row the in-memory config never
    // mirrors would create an orphaned DB entry. Defensive — the settings
    // page only renders known keys — but keeps a typo'd or future key from
    // silently diverging the DB and CONFIG.
    if !ConfigData::STRUCT_FIELDS_DEFAULT.has_string_field(key) {
        anyhow::bail!("unknown config field: {key}");
    }
    let store = crate::config_db::store();
    if trimmed.is_empty() {
        store.delete_kv(key).await?;
    } else {
        store.set_kv(key, trimmed).await?;
    }
    let _ = CONFIG.set_string_field(key, trimmed);
    Ok(())
}

/// The onboarding state machine's durable value (stored as a lowercase string
/// in `config_kv` under `onboarding_state`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OnboardingState {
    /// Fresh install, no provider configured yet / first-time onboarding.
    Init,
    /// Onboarding complete: "hi mah bot" has been auto-sent and the admin
    /// Assistant is active (the Assistant now drives onboarding).
    Finished,
}

impl OnboardingState {
    #[must_use]
    pub fn from_raw(s: Option<&str>) -> Self {
        match s {
            // Legacy `"welcomed"` (written before the Support role was removed,
            // when Support ran the onboarding) is surfaced as `Finished`.
            // Nothing writes it anymore, and a mid-onboarding user stuck at
            // 'welcomed' is deliberately NOT migrated back to `Init` — they're
            // treated as finished (the Assistant stays active). Any other
            // unknown/corrupt value still fails toward `Init`, as before.
            Some("welcomed" | "finished") => Self::Finished,
            _ => Self::Init,
        }
    }
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Init => "init",
            Self::Finished => "finished",
        }
    }
}

/// Validate a [`ConfigData`] before persisting — rejecting common misconfigurations.
///
/// # Precondition
/// [`ConfigData::normalize`] MUST have been called before this function.
/// All `Option<String>` fields are assumed to be already trimmed, with
/// empty/whitespace-only values collapsed to `None` by
/// [`normalize_string_fields`][ConfigData::normalize_string_fields] (which `normalize` calls unconditionally for **every** field regardless
/// of its per-field annotation — `non_empty`, `or(…)`, or `list_or(…)`).
fn validate_config(config: &ConfigData) -> Result<()> {
    if let Some(ref ep) = config.provider_endpoint {
        if !is_http_url(ep) {
            anyhow::bail!(
                "Provider endpoint must be a valid URL starting with https:// or http://"
            );
        }
        // Empty-host rejection — only in config validation, not in
        // `is_http_url` (which intentionally stays prefix-only). For values
        // where `is_http_url(ep)` is true (scheme is case-sensitive
        // `http://`/`https://`), extract authority = substring after `://` up
        // to first `/`, `?`, `#` or end, trim, and reject if empty or
        // starts-with `:`.
        //
        // Intentionally NOT rejected here beyond the empty-host check:
        // `https://exa mple.com` (embedded space) passes this check and is
        // deferred to warmup — do not over-tighten to reject it here.
        // IPv6 literals (`[::1]`) and userinfo (`user:pass@host`) are out of
        // scope for this check.
        // The authority double-trim (overall `normalize` trim + this
        // `authority.trim()`) is required to catch `https://   /v1` where the
        // authority is whitespace-only.
        let rest = ep
            .strip_prefix("https://")
            .or_else(|| ep.strip_prefix("http://"))
            .unwrap();
        let auth_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
        let authority = rest[..auth_end].trim();
        if authority.is_empty() || authority.starts_with(':') {
            anyhow::bail!(
                "Provider endpoint must be a valid URL starting with https:// or http://"
            );
        }
    }

    if let Some(ref key) = config.provider_key
        && key.contains("...")
    {
        anyhow::bail!("Provider key is still the placeholder value — please set a real key");
    }

    Ok(())
}

// ── Test helpers ──────────────────────────────────────────────

/// Construct a [`ModelRouting`] for tests.
#[cfg(test)]
pub(crate) fn model_routing(model: &str, provider_order: Option<&str>) -> ModelRouting {
    ModelRouting {
        model: model.into(),
        provider_order: provider_order.map(String::from),
    }
}

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

    #[test]
    fn onboarding_from_raw_maps_legacy_welcomed_to_finished() {
        // Legacy `"welcomed"` (pre-Support-removal) surfaces as `Finished`, not
        // migrated back to `Init`. `"finished"` maps to `Finished`; anything
        // else (absent or corrupt) fails toward `Init`.
        assert_eq!(
            OnboardingState::from_raw(Some("welcomed")),
            OnboardingState::Finished
        );
        assert_eq!(
            OnboardingState::from_raw(Some("finished")),
            OnboardingState::Finished
        );
        assert_eq!(
            OnboardingState::from_raw(Some("garbage")),
            OnboardingState::Init
        );
        assert_eq!(OnboardingState::from_raw(None), OnboardingState::Init);
    }

    /// All string keys that [`ConfigData::string_fields`] returns must be
    /// round-trippable through [`ConfigData::set_string_field`]: setting each
    /// individually and reading back via [`ConfigData::string_fields`] must
    /// produce the same value.
    ///
    /// The test is self-maintaining: it generates synthetic values from each
    /// field's key, so adding a field to `string_config_fields!` automatically
    /// covers it without manual test-data upkeep.
    #[test]
    fn string_fields_roundtrip() {
        let mut config = ConfigData::STRUCT_FIELDS_DEFAULT;

        // Verify the initial state: all fields are None.
        for (_key, value) in config.string_fields() {
            assert!(value.is_none(), "field should start as None");
        }

        // Set each field to a synthetic value derived from its key and verify
        // it round-trips back through string_fields.  Using synthetic values
        // keeps the test self-maintaining — adding a field to the macro
        // automatically covers it without separate test-data upkeep.
        let keys: Vec<&str> = config.string_fields().iter().map(|(k, _)| *k).collect();
        for &key in &keys {
            let test_value = format!("test-{key}");
            let recognized = config.set_string_field(key, &test_value);
            assert!(recognized, "key '{key}' should be recognized");

            // Find this key in string_fields and verify the value matches.
            let found = config.get_string_field(key);
            assert_eq!(
                found,
                Some(test_value.as_str()),
                "value for '{key}' should match after set"
            );
        }

        // ── Normalization is handled by normalize(), not set_string_field ──
        // set_string_field stores the raw value as-is.
        let _ = config.set_string_field("provider_key", "");
        let pk = config.get_string_field("provider_key");
        assert_eq!(
            pk,
            Some(""),
            "empty string stored as-is by set_string_field"
        );

        let _ = config.set_string_field("provider_key", "   ");
        let pk = config.get_string_field("provider_key");
        assert_eq!(
            pk,
            Some("   "),
            "whitespace-only string stored as-is by set_string_field"
        );

        // After normalize(), empty/whitespace values are collapsed to None.
        config.normalize();
        let pk = config.get_string_field("provider_key");
        assert!(pk.is_none(), "normalize() collapses empty string to None");

        // Unknown key returns false.
        assert!(!config.set_string_field("nonexistent_key", "value"));
    }

    /// Smoke test: macro-generated accessors roundtrip correctly for one
    /// representative field of each pattern (`non_empty`, `or`, `list_or`).
    ///
    /// Structural sync (every field has a correctly-typed accessor) is guaranteed
    /// at compile time by the macro — this test only verifies runtime semantics.
    #[test]
    fn config_reload_accessors_roundtrip() {
        let reload = ConfigReload::const_new();

        // ── non_empty: returns None when unset, Some(value) when set ──
        assert_eq!(reload.provider_key(), None, "unset provider_key is None");
        let mut config = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(config.set_string_field("provider_key", "sk-test"));
        reload.swap(config);
        assert_eq!(reload.provider_key(), Some("sk-test".to_string()));

        // ── or: falls back to default when unset ──
        reload.swap(ConfigData::STRUCT_FIELDS_DEFAULT);
        assert_eq!(
            reload.manager_model(),
            DEFAULT_MANAGER_MODEL,
            "unset manager_model falls back to default"
        );
        assert_eq!(
            reload.worker_model(),
            DEFAULT_WORKER_MODEL,
            "unset worker_model falls back to default"
        );

        // ── or: persisted provider_endpoint is honored (custom endpoint) ──
        let mut custom_cfg = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(custom_cfg.set_string_field("provider_endpoint", "https://custom.example/v1"));
        reload.swap(custom_cfg);
        assert_eq!(
            reload.provider_endpoint(),
            "https://custom.example/v1",
            "or field honors a persisted custom value"
        );
        // and falls back to the default when unset
        reload.swap(ConfigData::STRUCT_FIELDS_DEFAULT);
        assert_eq!(reload.provider_endpoint(), DEFAULT_PROVIDER_ENDPOINT);

        // ── non_empty: empty/whitespace → None ──
        let mut empty = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(empty.set_string_field("provider_key", ""));
        reload.swap(empty);
        assert_eq!(
            reload.provider_key(),
            None,
            "empty string is collapsed to None"
        );

        // ── list_or: falls back to default when list is unset ──
        reload.swap(ConfigData::STRUCT_FIELDS_DEFAULT);
        assert_eq!(
            reload.image_gen_models(),
            vec![DEFAULT_IMAGE_GEN_MODEL.to_string()],
            "unset image_gen_models falls back to default"
        );

        // When list is set, returns parsed entries
        let mut list_config = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(list_config.set_string_field("image_gen_models", "model-a\nmodel-b\nmodel-c"));
        reload.swap(list_config);
        assert_eq!(
            reload.image_gen_models(),
            vec!["model-a", "model-b", "model-c"]
        );
    }

    #[test]
    fn role_model_maps_roles_to_slots() {
        let reload = ConfigReload::const_new();
        let mut config = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(config.set_string_field("manager_model", "manager-slot-model"));
        assert!(config.set_string_field("worker_model", "worker-slot-model"));
        reload.swap(config);

        for role in [
            Role::Manager,
            Role::Assistant,
            Role::Discovery,
            Role::Engineer,
            Role::Maintainer,
        ] {
            assert_eq!(reload.role_model(role), "manager-slot-model");
        }
        for role in [
            Role::Analyst,
            Role::Coder,
            Role::Qa,
            Role::Reviewer,
            Role::Sanitation,
        ] {
            assert_eq!(reload.role_model(role), "worker-slot-model");
        }
    }

    #[test]
    fn trimmed_or_none_trims_whitespace() {
        // trimmed_or_none is the canonical primitive — trims and returns None
        // for empty or whitespace-only strings.
        assert_eq!(trimmed_or_none("  value  "), Some("value".to_string()));
        assert_eq!(trimmed_or_none(" "), None);
        assert_eq!(trimmed_or_none(""), None);
    }

    /// Endpoint normalization: trivial variants of the default
    /// OpenRouter URL — trailing slash, surrounding whitespace, uppercase
    /// scheme/host, a trailing `/chat/completions` suffix — must never count
    /// as a custom endpoint, while a genuinely different URL must.
    #[test]
    fn endpoint_normalization_default_vs_custom() {
        // Exact default.
        assert!(is_default_endpoint(DEFAULT_PROVIDER_ENDPOINT));
        // Trailing slash.
        assert!(is_default_endpoint("https://openrouter.ai/api/v1/"));
        // Surrounding whitespace.
        assert!(is_default_endpoint("  https://openrouter.ai/api/v1  "));
        // Uppercase scheme/host.
        assert!(is_default_endpoint("HTTPS://OPENROUTER.AI/api/v1"));
        // Chat-completions suffix (both bare and trailing-slash variants).
        assert!(is_default_endpoint(
            "https://openrouter.ai/api/v1/chat/completions"
        ));
        assert!(is_default_endpoint(
            "https://openrouter.ai/api/v1/chat/completions/"
        ));
        // A genuinely custom endpoint.
        assert!(is_custom_endpoint("http://localhost:8080/v1"));
        assert!(is_custom_endpoint("https://custom.example/v1"));
        assert!(!is_custom_endpoint(DEFAULT_PROVIDER_ENDPOINT));
    }

    /// Chat-credential key isolation: the OpenRouter key is
    /// only ever used for the default endpoint. A custom endpoint uses its
    /// own key; when that key is empty NO Authorization header is sent
    /// (keyless servers) — the OpenRouter key must never reach a custom
    /// endpoint.
    #[test]
    fn chat_credential_isolates_keys_per_endpoint() {
        // Default endpoint → OpenRouter key.
        let mut cfg = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(cfg.set_string_field("provider_key", "sk-or"));
        assert_eq!(chat_credential(&cfg).as_deref(), Some("sk-or"));

        // Custom endpoint with its own key → the custom key (OR key ignored).
        let mut cfg = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(cfg.set_string_field("provider_key", "sk-or"));
        assert!(cfg.set_string_field("provider_endpoint", "http://localhost:8080/v1"));
        assert!(cfg.set_string_field("provider_endpoint_key", "sk-custom"));
        assert_eq!(chat_credential(&cfg).as_deref(), Some("sk-custom"));

        // Custom endpoint, keyless (empty custom key), OR key set → None:
        // the OR key must never be sent to a custom endpoint.
        let mut cfg = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(cfg.set_string_field("provider_key", "sk-or"));
        assert!(cfg.set_string_field("provider_endpoint", "http://localhost:8080/v1"));
        assert!(cfg.set_string_field("provider_endpoint_key", ""));
        assert_eq!(chat_credential(&cfg), None);

        // Custom endpoint, keyless, no OR key → None (keyless operation).
        let mut cfg = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(cfg.set_string_field("provider_endpoint", "http://localhost:8080/v1"));
        assert_eq!(chat_credential(&cfg), None);

        // Default endpoint, no key → None.
        assert_eq!(chat_credential(&ConfigData::STRUCT_FIELDS_DEFAULT), None);
    }

    // NOTE: Per-struct normalize tests (`model_routing_normalize`) have been
    // intentionally removed as redundant.  The `normalize()` method is a
    // one-line delegation to `non_empty()` with no conditional logic.  The
    // `non_empty` / `trimmed_or_none` primitive is covered exhaustively by
    // `trimmed_or_none_trims_whitespace` above, and the end-to-end integration
    // through `normalize_entries()` is covered by `normalize_entries_works`
    // below.  If a new normalization scenario is added, it should be added to
    // the primitive test AND exercised through the integration test — there is
    // no need for per-struct test duplication.

    /// Verify that [`ConfigData::normalize_entries`] normalises every entry in
    /// `model_routings`.
    #[test]
    fn normalize_entries_works() {
        let mut config = ConfigData {
            model_routings: vec![
                ModelRouting {
                    model: "test-model".into(),
                    provider_order: Some("   ".into()),
                },
                ModelRouting {
                    model: "test-model-2".into(),
                    provider_order: Some("  OpenAi,  Anthropic  ".into()),
                },
            ],
            ..ConfigData::STRUCT_FIELDS_DEFAULT
        };

        config.normalize_entries();

        // Routing: whitespace-only provider_order → None
        assert_eq!(config.model_routings[0].provider_order, None);

        // Routing: trimmed provider_order preserved
        assert_eq!(
            config.model_routings[1].provider_order,
            Some("OpenAi,  Anthropic".into())
        );
    }

    // ── Upsert three-scenario tests ─────────────────────────
    //
    // `ModelRouting::upsert` is tested across three scenarios:
    //   1. updates_existing — existing entry, upsert sets the target field
    //   2. pushes_new_entry — empty vec, new entry is pushed with the
    //      target field set
    //   3. can_set_none — existing entry has the field set to non-None;
    //      clearing it via None removes the value

    #[test]
    fn upsert_model_routing_fields() {
        // 1. updates_existing — set provider_order
        {
            let mut items = vec![model_routing("test-model", Some("OpenAi"))];
            ModelRouting::upsert(&mut items, "test-model", |item| {
                item.provider_order = Some("Anthropic".into());
            });
            assert_eq!(items.len(), 1);
            assert_eq!(
                items[0].provider_order,
                Some("Anthropic".into()),
                "[provider_order] target field updated"
            );
        }

        // 2. pushes_new_entry
        {
            let mut items = vec![];
            ModelRouting::upsert(&mut items, "test-model", |item| {
                item.provider_order = Some("OpenAi".into());
            });
            assert_eq!(items.len(), 1);
            assert_eq!(items[0].model, "test-model");
            assert_eq!(
                items[0].provider_order,
                Some("OpenAi".into()),
                "[provider_order] set on new entry"
            );
        }

        // 3. can_set_none — clear provider_order
        {
            let mut items = vec![model_routing("test-model", Some("OpenAi"))];
            ModelRouting::upsert(&mut items, "test-model", |item| item.provider_order = None);
            assert_eq!(
                items[0].provider_order, None,
                "[provider_order] cleared to None"
            );
        }
    }

    #[test]
    fn upsert_multiple_entries_independent_keys() {
        let mut routings = vec![
            model_routing("test-router-a", Some("OpenAi")),
            model_routing("test-router-b", Some("Anthropic")),
        ];

        // Each upsert targets exactly one entry by key.
        ModelRouting::upsert(&mut routings, "test-router-a", |mr| {
            mr.provider_order = Some("Google".into());
        });
        assert_eq!(routings[0].provider_order, Some("Google".into()));
        assert_eq!(routings[1].provider_order, Some("Anthropic".into()));

        ModelRouting::upsert(&mut routings, "test-router-b", |mr| {
            mr.provider_order = Some("OpenAi".into());
        });
        assert_eq!(routings[0].provider_order, Some("Google".into()));
        assert_eq!(routings[1].provider_order, Some("OpenAi".into()));

        // Total entries unchanged — no spurious pushes.
        assert_eq!(routings.len(), 2);
    }

    // ── validate_config tests ──────────────────────────────────────

    /// A valid URL (trimmed) passes validation.
    #[test]
    fn validate_config_accepts_valid_url() {
        let mut config = ConfigData {
            provider_endpoint: Some("https://openrouter.ai/api/v1".into()),
            ..ConfigData::STRUCT_FIELDS_DEFAULT
        };
        config.normalize();
        validate_config(&config).unwrap();
    }

    /// A whitespace-padded URL passes validation after `normalize` normalises
    /// it.  This is a regression test for the latent ordering bug where
    /// `validate_config` (which used untrimmed `starts_with`) ran *before*
    /// `normalize` (which trims).  The fix ensures `normalize` always runs
    /// first, so validation only ever sees canonical values.
    #[test]
    fn validate_config_accepts_whitespace_padded_url_after_normalize() {
        let mut config = ConfigData {
            provider_endpoint: Some("  https://openrouter.ai/api/v1   ".into()),
            ..ConfigData::STRUCT_FIELDS_DEFAULT
        };
        config.normalize();
        // After normalize the value is trimmed — validation sees the canonical form.
        validate_config(&config).unwrap();
    }

    /// A URL without scheme is rejected regardless of whitespace.
    #[test]
    fn validate_config_rejects_url_without_scheme() {
        let mut config = ConfigData {
            provider_endpoint: Some("not-a-url".into()),
            ..ConfigData::STRUCT_FIELDS_DEFAULT
        };
        config.normalize();
        let err = validate_config(&config).unwrap_err();
        assert!(
            err.to_string()
                .contains("Provider endpoint must be a valid URL"),
            "expected URL scheme error, got: {err}",
        );
    }

    /// A placeholder provider key is rejected.
    #[test]
    fn validate_config_rejects_placeholder_key() {
        let mut config = ConfigData {
            provider_key: Some("sk-or-v1-...".into()),
            ..ConfigData::STRUCT_FIELDS_DEFAULT
        };
        config.normalize();
        let err = validate_config(&config).unwrap_err();
        assert!(
            err.to_string().contains("placeholder"),
            "expected placeholder error, got: {err}",
        );
    }

    /// The per-field persist path must never write or delete
    /// `wake_word_templates` — the key is owned exclusively by the voice
    /// pipeline (`persist_enrollment`), and `persist_settled_string_field`
    /// refuses it structurally (defense in depth) so no future caller can
    /// accidentally create a dual-writer race.
    ///
    /// This test swaps the shared global CONFIG, so it joins the
    /// `config_persist` serial group used by the config_db persist tests —
    /// an unserialized restore swap could clobber a concurrent serialized
    /// test's CONFIG writes and fail its asserts nondeterministically.
    #[tokio::test]
    #[serial_test::serial(config_persist)]
    async fn persist_settled_string_field_refuses_wake_word_templates() {
        // Templates enrolled by the voice pipeline.
        let template_json = r#"{"classifier":null}"#;
        let original = CONFIG.snapshot();
        let mut enrolled = ConfigData::STRUCT_FIELDS_DEFAULT;
        assert!(enrolled.set_string_field("wake_word_templates", template_json));
        CONFIG.swap(enrolled);

        // The guard returns the current templates and never touches the DB —
        // the call must not error and must not alter CONFIG.
        let result = persist_settled_string_field("wake_word_templates", "garbage").await;
        assert_eq!(
            result.unwrap().value,
            template_json,
            "guard must return the current templates unchanged"
        );
        assert_eq!(
            CONFIG.wake_word_templates(),
            Some(template_json.to_string()),
            "CONFIG wake_word_templates must be untouched"
        );

        CONFIG.swap(original);
    }

    /// The persist side-effect arms and the `wake_word_templates` guard are
    /// wired through `CONFIG_KEY_*` constants (compile-tied: a rename in
    /// `string_config_fields!` changes both the constant name and its value,
    /// so every arm referencing the old name fails to compile). This test
    /// pins the vocabulary contract: every key that carries a persist side
    /// effect (or the structural guard) must still be a real config field,
    /// and documents the exact set a rename must keep in sync.
    #[test]
    fn side_effect_config_keys_are_real_fields() {
        let known: Vec<&'static str> = ConfigData::STRUCT_FIELDS_DEFAULT
            .string_fields()
            .iter()
            .map(|(k, _)| *k)
            .collect();
        for key in [
            CONFIG_KEY_PROVIDER_ENDPOINT,
            CONFIG_KEY_PROVIDER_KEY,
            CONFIG_KEY_PROVIDER_ENDPOINT_KEY,
            CONFIG_KEY_TELEGRAM_BOT_TOKEN,
            CONFIG_KEY_WAKE_WORD_TEMPLATES,
        ] {
            assert!(
                known.contains(&key),
                "side-effect key '{key}' must be a real config field"
            );
        }
    }

    /// Fresh-install seed: the fresh-install
    /// defaults land in brand-new config databases only — existing databases
    /// receive zero writes.
    ///
    /// The seeded set is the transcription-off default (so no audio model is
    /// downloaded or loaded at boot) plus the image/video generation model
    /// lists (so the Settings GUI model pickers, which read the raw snapshot
    /// fields, are populated on fresh installs). The active selection is
    /// per-user (see `crate::users`), not a config field.
    ///
    /// This test drives the real boot chain end-to-end instead of hand-picking
    /// `fresh` values: the discriminator probe (`config_db_is_fresh` — the
    /// exact function `load_or_init` uses), the boot flag it feeds, the store
    /// open that creates the consolidated `core.db`, and the flag-consumption + seed
    /// (`seed_fresh_install_defaults_from_flag`, the `reload_from_db` path).
    ///
    /// Regression guard for the wrong-path probe: opening the config store
    /// must flip the discriminator to "not fresh" — a probe of any other
    /// location (e.g. a top-level `<root>/config.db`) would still report
    /// "fresh" here and re-seed every existing install on every boot.
    #[tokio::test]
    async fn fresh_config_db_seeds_defaults_only_when_new() {
        // ── Fresh install: the store file does not exist yet ──
        let fresh_root = tempfile::TempDir::new().unwrap();
        let fresh = config_db_is_fresh(fresh_root.path());
        assert!(
            fresh,
            "a storage root with no config store file must be classified fresh"
        );
        CONFIG_DB_FRESH_AT_BOOT.store(fresh, Ordering::Release);

        // Opening the config store creates the consolidated core.db — the
        // exact file the probe must check. This is the regression pin for the
        // original bug: probing a top-level <root>/config.db would still report
        // "fresh" here and re-seed existing installs on every boot.
        let fresh_store = crate::config_db::ConfigStore::open(fresh_root.path())
            .await
            .unwrap();
        assert!(
            !config_db_is_fresh(fresh_root.path()),
            "an existing config store file must not be classified fresh"
        );

        // reload_from_db's path: consume the boot flag and seed.
        seed_fresh_install_defaults_from_flag(&fresh_store)
            .await
            .unwrap();
        assert!(
            !CONFIG_DB_FRESH_AT_BOOT.load(Ordering::Acquire),
            "the boot discriminator must be consumed by the seed"
        );
        assert_eq!(
            fresh_store.get_all_kv().await.unwrap(),
            vec![
                (
                    "audio_transcription_use_local".to_string(),
                    "false".to_string()
                ),
                (
                    "image_gen_models".to_string(),
                    "google/gemini-3.1-flash-image\nmicrosoft/mai-image-2.5\nqwen/qwen-image-3-pro"
                        .to_string()
                ),
                (
                    "video_models".to_string(),
                    "bytedance/seedance-2.0-mini\nminimax/hailuo-3".to_string()
                ),
            ],
            "a fresh config database must be seeded with the fresh-install defaults"
        );
        // Manager and worker share the same default model, so the two seed
        // passes collapse into a single routing row.
        assert_eq!(
            fresh_store.get_all_model_routings().await.unwrap(),
            vec![model_routing(DEFAULT_MANAGER_MODEL, Some("deepseek"))],
            "a fresh config database must seed routing rows for default models \
             with a known provider (others get none)"
        );

        // ── Existing install: the store file already exists ──
        let (existing_store, existing_dir) =
            crate::open_test_store!(crate::config_db::ConfigStore, "config");
        let fresh_existing = config_db_is_fresh(existing_dir.path());
        assert!(
            !fresh_existing,
            "an existing install must not be classified fresh"
        );
        CONFIG_DB_FRESH_AT_BOOT.store(fresh_existing, Ordering::Release);
        seed_fresh_install_defaults_from_flag(&existing_store)
            .await
            .unwrap();
        assert!(
            existing_store.get_all_kv().await.unwrap().is_empty(),
            "an existing config database must receive zero writes"
        );
        assert!(
            existing_store
                .get_all_model_routings()
                .await
                .unwrap()
                .is_empty(),
            "an existing config database must receive zero routing rows (no backfill)"
        );
    }

    /// One-time migration: persisted `config_kv` rows holding the previous
    /// manager/worker default model are rewritten to the current default, and
    /// only those rows (and only when they match the exact old default) are
    /// touched; each rewritten slot also seeds the new default's routing row.
    /// Re-running is a no-op.
    #[tokio::test]
    async fn migrate_old_default_models_rewrites_only_stale_slot_rows() {
        let (store, _dir) = crate::open_test_store!(crate::config_db::ConfigStore, "config");

        // Existing-install snapshot at the time of the default swap: both slots
        // still hold the previous defaults; a stale video-transcription row and
        // an unrelated key remain untouched.
        store
            .set_kv(CONFIG_KEY_MANAGER_MODEL, OLD_DEFAULT_MANAGER_MODEL)
            .await
            .unwrap();
        store
            .set_kv(CONFIG_KEY_WORKER_MODEL, OLD_DEFAULT_WORKER_MODEL)
            .await
            .unwrap();
        store
            .set_kv("video_transcription_model", "qwen/qwen3.7-flash")
            .await
            .unwrap();
        store
            .set_kv(CONFIG_KEY_PROVIDER_KEY, "sk-example")
            .await
            .unwrap();

        migrate_old_default_models(&store).await.unwrap();

        assert_eq!(
            store
                .get_kv(CONFIG_KEY_MANAGER_MODEL)
                .await
                .unwrap()
                .as_deref(),
            Some(DEFAULT_MANAGER_MODEL),
            "manager slot holding the old default must be migrated"
        );
        assert_eq!(
            store
                .get_kv(CONFIG_KEY_WORKER_MODEL)
                .await
                .unwrap()
                .as_deref(),
            Some(DEFAULT_WORKER_MODEL),
            "worker slot holding the old default must be migrated"
        );
        assert_eq!(
            store
                .get_kv("video_transcription_model")
                .await
                .unwrap()
                .as_deref(),
            Some("qwen/qwen3.7-flash"),
            "migrate only rewrites manager/worker old-default rows"
        );
        assert_eq!(
            store
                .get_kv(CONFIG_KEY_PROVIDER_KEY)
                .await
                .unwrap()
                .as_deref(),
            Some("sk-example"),
            "unrelated config keys must never be touched"
        );
        // Both slots migrated to the same default model: one shared routing row.
        assert_eq!(
            store.get_all_model_routings().await.unwrap(),
            vec![model_routing(DEFAULT_MANAGER_MODEL, Some("deepseek"))],
            "migrating a slot to the new default must upsert its routing row"
        );

        // Idempotent: a second run changes nothing.
        migrate_old_default_models(&store).await.unwrap();
        assert_eq!(
            store
                .get_kv(CONFIG_KEY_MANAGER_MODEL)
                .await
                .unwrap()
                .as_deref(),
            Some(DEFAULT_MANAGER_MODEL),
            "re-running the migration must be a no-op"
        );
        assert_eq!(
            store
                .get_kv(CONFIG_KEY_WORKER_MODEL)
                .await
                .unwrap()
                .as_deref(),
            Some(DEFAULT_WORKER_MODEL),
            "re-running the migration must be a no-op"
        );
        assert_eq!(
            store.get_all_model_routings().await.unwrap(),
            vec![model_routing(DEFAULT_MANAGER_MODEL, Some("deepseek"))],
            "re-running the migration must not add or drop the migrated routing row"
        );
    }

    /// Regression for the retired `video_transcription_model` slot: a row
    /// persisted by a pre-hardcode install must be deleted by the reload-time
    /// orphan purge, so a stale stored value can never resurface if the key is
    /// ever reintroduced. Known keys and preserved shared namespaces survive.
    #[tokio::test]
    async fn purge_unknown_kv_orphans_deletes_stale_video_transcription_row() {
        let (store, _dir) = crate::open_test_store!(crate::config_db::ConfigStore, "config");
        store
            .set_kv("video_transcription_model", "qwen/qwen3.7-flash")
            .await
            .unwrap();
        store
            .set_kv(CONFIG_KEY_PROVIDER_KEY, "sk-example")
            .await
            .unwrap();
        store
            .set_kv(
                crate::workspace::NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY,
                "2026-08-29",
            )
            .await
            .unwrap();
        store
            .set_kv(
                crate::temp::TEMP_CLEANUP_LAST_RUN_KV_KEY,
                "2026-08-29T00:00:00Z",
            )
            .await
            .unwrap();
        store
            .set_kv(crate::temp::TEMP_CLEANUP_MODE_KV_KEY, "daily")
            .await
            .unwrap();

        let kvs = store.get_all_kv().await.unwrap();
        purge_unknown_kv_orphans(&store, &kvs).await;

        assert_eq!(
            store.get_kv("video_transcription_model").await.unwrap(),
            None,
            "the stale video-transcription row must be purged"
        );
        assert_eq!(
            store
                .get_kv(CONFIG_KEY_PROVIDER_KEY)
                .await
                .unwrap()
                .as_deref(),
            Some("sk-example"),
            "known config keys must survive the purge"
        );
        assert_eq!(
            store
                .get_kv(crate::workspace::NIGHTLY_DISCOVERY_LAST_PASS_KV_KEY)
                .await
                .unwrap()
                .as_deref(),
            Some("2026-08-29"),
            "preserved shared namespaces must survive the purge"
        );
        assert_eq!(
            store
                .get_kv(crate::temp::TEMP_CLEANUP_LAST_RUN_KV_KEY)
                .await
                .unwrap()
                .as_deref(),
            Some("2026-08-29T00:00:00Z"),
            "temp-cleanup cadence state must survive the purge"
        );
        assert_eq!(
            store
                .get_kv(crate::temp::TEMP_CLEANUP_MODE_KV_KEY)
                .await
                .unwrap()
                .as_deref(),
            Some("daily"),
            "temp-cleanup mode must survive the purge"
        );
    }

    /// The migration must be a no-op when a slot already holds the target
    /// default or a genuine user override — it must never overwrite a
    /// user-configured model.
    #[tokio::test]
    async fn migrate_old_default_models_noop_for_target_and_user_overrides() {
        let (store, _dir) = crate::open_test_store!(crate::config_db::ConfigStore, "config");

        // Already at the target default.
        store
            .set_kv(CONFIG_KEY_MANAGER_MODEL, DEFAULT_MANAGER_MODEL)
            .await
            .unwrap();
        // A genuine user override (not the old default) must be preserved.
        store
            .set_kv(CONFIG_KEY_WORKER_MODEL, "user/private-model")
            .await
            .unwrap();

        migrate_old_default_models(&store).await.unwrap();

        assert_eq!(
            store
                .get_kv(CONFIG_KEY_MANAGER_MODEL)
                .await
                .unwrap()
                .as_deref(),
            Some(DEFAULT_MANAGER_MODEL),
            "a slot already at the target must be untouched"
        );
        assert_eq!(
            store
                .get_kv(CONFIG_KEY_WORKER_MODEL)
                .await
                .unwrap()
                .as_deref(),
            Some("user/private-model"),
            "a genuine user override must be preserved"
        );
        assert!(
            store.get_all_model_routings().await.unwrap().is_empty(),
            "no routing writes may happen when nothing was migrated"
        );
    }

    /// Effective routing on a private [`ConfigReload`]: a stored override wins,
    /// an unset/cleared field falls back to the model's default provider, a
    /// non-DeepSeek model stays auto-routed.
    #[test]
    fn model_routing_applies_the_default_provider_when_unset() {
        let config = ConfigReload::const_new();
        let mut data = ConfigData::STRUCT_FIELDS_DEFAULT;
        data.model_routings = vec![
            model_routing("deepseek/deepseek-v4.1-flash", Some("GMICloud")),
            model_routing("deepseek/deepseek-v4-flash-0731", Some("")),
        ];
        data.normalize();
        config.swap(data);

        assert_eq!(
            config
                .model_routing("deepseek/deepseek-v4.1-flash")
                .provider_order
                .as_deref(),
            Some("GMICloud"),
            "an explicitly set provider must win, unchanged"
        );
        for model in [
            "deepseek/deepseek-v4.1-pro",
            "deepseek-ai/DeepSeek-V3",
            "deepseek/deepseek-v4-flash-0731",
        ] {
            assert_eq!(
                config.model_routing(model).provider_order.as_deref(),
                Some("deepseek"),
                "{model} has no explicit setting and must fall back to the \
                 canonical DeepSeek slug"
            );
        }
        assert_eq!(
            config.model_routing("qwen/qwen3.8-flash").provider_order,
            None,
            "a non-DeepSeek model must stay auto-routed"
        );
    }
}