zeph-config 0.19.1

Pure-data configuration types for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::fmt;

use serde::{Deserialize, Serialize};
use zeph_llm::{GeminiThinkingLevel, ThinkingConfig};

/// Newtype wrapper for a provider name referencing an entry in `[[llm.providers]]`.
///
/// Using a dedicated type instead of bare `String` makes provider cross-references
/// explicit in the type system and enables validation at config load time.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProviderName(String);

impl ProviderName {
    /// Create a new `ProviderName` from any string-like value.
    ///
    /// An empty string is a sentinel meaning "use the primary provider" and is the
    /// default value. Check [`is_empty`](Self::is_empty) before using in routing.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_config::providers::ProviderName;
    ///
    /// let name = ProviderName::new("fast");
    /// assert_eq!(name.as_str(), "fast");
    /// ```
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    /// Return `true` when this is the empty sentinel (use primary provider).
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_config::providers::ProviderName;
    ///
    /// assert!(ProviderName::default().is_empty());
    /// assert!(!ProviderName::new("fast").is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Return the inner string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_config::providers::ProviderName;
    ///
    /// let name = ProviderName::new("quality");
    /// assert_eq!(name.as_str(), "quality");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ProviderName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl AsRef<str> for ProviderName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::ops::Deref for ProviderName {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for ProviderName {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for ProviderName {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

fn default_response_cache_ttl_secs() -> u64 {
    3600
}

fn default_semantic_cache_threshold() -> f32 {
    0.95
}

fn default_semantic_cache_max_candidates() -> u32 {
    10
}

fn default_router_ema_alpha() -> f64 {
    0.1
}

fn default_router_reorder_interval() -> u64 {
    10
}

fn default_embedding_model() -> String {
    "qwen3-embedding".into()
}

fn default_candle_source() -> String {
    "huggingface".into()
}

fn default_chat_template() -> String {
    "chatml".into()
}

fn default_candle_device() -> String {
    "cpu".into()
}

fn default_temperature() -> f64 {
    0.7
}

fn default_max_tokens() -> usize {
    2048
}

fn default_seed() -> u64 {
    42
}

fn default_repeat_penalty() -> f32 {
    1.1
}

fn default_repeat_last_n() -> usize {
    64
}

fn default_cascade_quality_threshold() -> f64 {
    0.5
}

fn default_cascade_max_escalations() -> u8 {
    2
}

fn default_cascade_window_size() -> usize {
    50
}

fn default_reputation_decay_factor() -> f64 {
    0.95
}

fn default_reputation_weight() -> f64 {
    0.3
}

fn default_reputation_min_observations() -> u64 {
    5
}

/// Returns the default STT provider name (empty string — auto-detect).
#[must_use]
pub fn default_stt_provider() -> String {
    String::new()
}

/// Returns the default STT transcription language hint (`"auto"`).
#[must_use]
pub fn default_stt_language() -> String {
    "auto".into()
}

/// Returns the default embedding model name used by `[llm] embedding_model`.
#[must_use]
pub fn get_default_embedding_model() -> String {
    default_embedding_model()
}

/// Returns the default response cache TTL in seconds.
#[must_use]
pub fn get_default_response_cache_ttl_secs() -> u64 {
    default_response_cache_ttl_secs()
}

/// Returns the default EMA alpha for the router latency estimator.
#[must_use]
pub fn get_default_router_ema_alpha() -> f64 {
    default_router_ema_alpha()
}

/// Returns the default router reorder interval (turns between provider re-ranking).
#[must_use]
pub fn get_default_router_reorder_interval() -> u64 {
    default_router_reorder_interval()
}

/// LLM provider backend selector.
///
/// Used in `[[llm.providers]]` entries as the `type` field.
///
/// # Example (TOML)
///
/// ```toml
/// [[llm.providers]]
/// type = "openai"
/// model = "gpt-4o"
/// name = "quality"
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderKind {
    /// Local Ollama server (default base URL: `http://localhost:11434`).
    Ollama,
    /// Anthropic Claude API.
    Claude,
    /// `OpenAI` API.
    OpenAi,
    /// Google Gemini API.
    Gemini,
    /// Local Candle inference (CPU/GPU, no external server required).
    Candle,
    /// OpenAI-compatible third-party API (e.g. Groq, Together AI, LM Studio).
    Compatible,
}

impl ProviderKind {
    /// Return the lowercase string identifier for this provider kind.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_config::ProviderKind;
    ///
    /// assert_eq!(ProviderKind::Claude.as_str(), "claude");
    /// assert_eq!(ProviderKind::OpenAi.as_str(), "openai");
    /// ```
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ollama => "ollama",
            Self::Claude => "claude",
            Self::OpenAi => "openai",
            Self::Gemini => "gemini",
            Self::Candle => "candle",
            Self::Compatible => "compatible",
        }
    }
}

impl std::fmt::Display for ProviderKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// LLM configuration, nested under `[llm]` in TOML.
///
/// Declares the provider pool and controls routing, embedding, caching, and STT.
/// All providers are declared in `[[llm.providers]]`; subsystems reference them by
/// the `name` field using a `*_provider` config key.
///
/// # Example (TOML)
///
/// ```toml
/// [[llm.providers]]
/// name = "fast"
/// type = "openai"
/// model = "gpt-4o-mini"
///
/// [[llm.providers]]
/// name = "quality"
/// type = "claude"
/// model = "claude-opus-4-5"
///
/// [llm]
/// routing = "none"
/// embedding_model = "qwen3-embedding"
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct LlmConfig {
    /// Provider pool. First entry is default unless one is marked `default = true`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub providers: Vec<ProviderEntry>,

    /// Routing strategy for multi-provider configs.
    #[serde(default, skip_serializing_if = "is_routing_none")]
    pub routing: LlmRoutingStrategy,

    /// Task-based routes (only used when `routing = "task"`).
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub routes: std::collections::HashMap<String, Vec<String>>,

    #[serde(default = "default_embedding_model_opt")]
    pub embedding_model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub candle: Option<CandleConfig>,
    #[serde(default)]
    pub stt: Option<SttConfig>,
    #[serde(default)]
    pub response_cache_enabled: bool,
    #[serde(default = "default_response_cache_ttl_secs")]
    pub response_cache_ttl_secs: u64,
    /// Enable semantic similarity-based response caching. Requires embedding support.
    #[serde(default)]
    pub semantic_cache_enabled: bool,
    /// Cosine similarity threshold for semantic cache hits (0.0–1.0).
    ///
    /// Only the highest-scoring candidate above this threshold is returned.
    /// Lower values produce more cache hits but risk returning less relevant responses.
    /// Recommended range: 0.92–0.98; default: 0.95.
    #[serde(default = "default_semantic_cache_threshold")]
    pub semantic_cache_threshold: f32,
    /// Maximum cached entries to examine per semantic lookup (SQL `LIMIT` clause in
    /// `ResponseCache::get_semantic()`). Controls the recall-vs-performance tradeoff:
    ///
    /// - **Higher values** (e.g. 50): scan more entries, better chance of finding a
    ///   semantically similar cached response, but slower queries.
    /// - **Lower values** (e.g. 5): faster queries, but may miss relevant cached entries
    ///   when the cache is large.
    /// - **Default (10)**: balanced middle ground for typical workloads.
    ///
    /// Tuning guidance: set to 50+ when recall matters more than latency (e.g. long-running
    /// sessions with many cached responses); reduce to 5 for low-latency interactive use.
    /// Env override: `ZEPH_LLM_SEMANTIC_CACHE_MAX_CANDIDATES`.
    #[serde(default = "default_semantic_cache_max_candidates")]
    pub semantic_cache_max_candidates: u32,
    #[serde(default)]
    pub router_ema_enabled: bool,
    #[serde(default = "default_router_ema_alpha")]
    pub router_ema_alpha: f64,
    #[serde(default = "default_router_reorder_interval")]
    pub router_reorder_interval: u64,
    /// Routing configuration for Thompson/Cascade strategies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub router: Option<RouterConfig>,
    /// Provider-specific instruction file to inject into the system prompt.
    /// Merged with `agent.instruction_files` at startup.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instruction_file: Option<std::path::PathBuf>,
    /// Shorthand model spec for tool-pair summarization and context compaction.
    /// Format: `ollama/<model>`, `claude[/<model>]`, `openai[/<model>]`, `compatible/<name>`, `candle`.
    /// Ignored when `[llm.summary_provider]` is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary_model: Option<String>,
    /// Structured provider config for summarization. Takes precedence over `summary_model`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary_provider: Option<ProviderEntry>,

    /// Complexity triage routing configuration. Required when `routing = "triage"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub complexity_routing: Option<ComplexityRoutingConfig>,
}

fn default_embedding_model_opt() -> String {
    default_embedding_model()
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_routing_none(s: &LlmRoutingStrategy) -> bool {
    *s == LlmRoutingStrategy::None
}

impl LlmConfig {
    /// Effective provider kind for the primary (first/default) provider in the pool.
    #[must_use]
    pub fn effective_provider(&self) -> ProviderKind {
        self.providers
            .first()
            .map_or(ProviderKind::Ollama, |e| e.provider_type)
    }

    /// Effective base URL for the primary provider.
    #[must_use]
    pub fn effective_base_url(&self) -> &str {
        self.providers
            .first()
            .and_then(|e| e.base_url.as_deref())
            .unwrap_or("http://localhost:11434")
    }

    /// Effective model for the primary provider.
    #[must_use]
    pub fn effective_model(&self) -> &str {
        self.providers
            .first()
            .and_then(|e| e.model.as_deref())
            .unwrap_or("qwen3:8b")
    }

    /// Find the provider entry designated for STT.
    ///
    /// Resolution priority:
    /// 1. `[llm.stt].provider` matches `[[llm.providers]].name` and the entry has `stt_model`
    /// 2. `[llm.stt].provider` is empty — fall through to auto-detect
    /// 3. First provider with `stt_model` set (auto-detect fallback)
    /// 4. `None` — STT disabled
    #[must_use]
    pub fn stt_provider_entry(&self) -> Option<&ProviderEntry> {
        let name_hint = self.stt.as_ref().map_or("", |s| s.provider.as_str());
        if name_hint.is_empty() {
            self.providers.iter().find(|p| p.stt_model.is_some())
        } else {
            self.providers
                .iter()
                .find(|p| p.effective_name() == name_hint && p.stt_model.is_some())
        }
    }

    /// Validate that the config uses the new `[[llm.providers]]` format.
    ///
    /// # Errors
    ///
    /// Returns `ConfigError::Validation` when no providers are configured.
    pub fn check_legacy_format(&self) -> Result<(), crate::error::ConfigError> {
        Ok(())
    }

    /// Validate STT config cross-references.
    ///
    /// # Errors
    ///
    /// Returns `ConfigError::Validation` when the referenced STT provider does not exist.
    pub fn validate_stt(&self) -> Result<(), crate::error::ConfigError> {
        use crate::error::ConfigError;

        let Some(stt) = &self.stt else {
            return Ok(());
        };
        if stt.provider.is_empty() {
            return Ok(());
        }
        let found = self
            .providers
            .iter()
            .find(|p| p.effective_name() == stt.provider);
        match found {
            None => {
                return Err(ConfigError::Validation(format!(
                    "[llm.stt].provider = {:?} does not match any [[llm.providers]] entry",
                    stt.provider
                )));
            }
            Some(entry) if entry.stt_model.is_none() => {
                tracing::warn!(
                    provider = stt.provider,
                    "[[llm.providers]] entry exists but has no `stt_model` — STT will not be activated"
                );
            }
            _ => {}
        }
        Ok(())
    }
}

/// Speech-to-text configuration, nested under `[llm.stt]` in TOML.
///
/// When set, Zeph uses the referenced provider for voice transcription.
/// The provider must have an `stt_model` field set in its `[[llm.providers]]` entry.
///
/// # Example (TOML)
///
/// ```toml
/// [llm.stt]
/// provider = "fast"
/// language = "en"
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SttConfig {
    /// Provider name from `[[llm.providers]]`. Empty string means auto-detect first provider
    /// with `stt_model` set.
    #[serde(default = "default_stt_provider")]
    pub provider: String,
    /// Language hint for transcription (e.g. `"en"`, `"auto"`).
    #[serde(default = "default_stt_language")]
    pub language: String,
}

/// Routing strategy selection for multi-provider routing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RouterStrategyConfig {
    /// Exponential moving average latency-aware ordering.
    #[default]
    Ema,
    /// Thompson Sampling with Beta distributions (persistence-backed).
    Thompson,
    /// Cascade routing: try cheapest provider first, escalate on degenerate output.
    Cascade,
    /// PILOT: `LinUCB` contextual bandit with online learning and cost-aware reward.
    Bandit,
}

/// Agent Stability Index (ASI) configuration.
///
/// Tracks per-provider response coherence via a sliding window of response embeddings.
/// When coherence drops below `coherence_threshold`, the provider's routing prior is
/// penalized by `penalty_weight`. Disabled by default; session-only (no persistence).
///
/// # Known Limitation
///
/// ASI embeddings are computed in a background `tokio::spawn` task after the response is
/// returned to the caller. Under high request rates, the coherence score used for routing
/// may lag 1–2 responses behind due to this fire-and-forget design. With the default
/// `window = 5`, this lag is tolerable — coherence is a slow-moving signal.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AsiConfig {
    /// Enable ASI coherence tracking. Default: false.
    #[serde(default)]
    pub enabled: bool,

    /// Sliding window size for response embeddings per provider. Default: 5.
    #[serde(default = "default_asi_window")]
    pub window: usize,

    /// Coherence score [0.0, 1.0] below which the provider is penalized. Default: 0.7.
    #[serde(default = "default_asi_coherence_threshold")]
    pub coherence_threshold: f32,

    /// Penalty weight applied to Thompson beta / EMA score on low coherence. Default: 0.3.
    ///
    /// For Thompson, this shifts the beta prior: `beta += penalty_weight * (threshold - coherence)`.
    /// For EMA, the score is multiplied by `max(0.5, coherence / threshold)`.
    #[serde(default = "default_asi_penalty_weight")]
    pub penalty_weight: f32,
}

fn default_asi_window() -> usize {
    5
}

fn default_asi_coherence_threshold() -> f32 {
    0.7
}

fn default_asi_penalty_weight() -> f32 {
    0.3
}

impl Default for AsiConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            window: default_asi_window(),
            coherence_threshold: default_asi_coherence_threshold(),
            penalty_weight: default_asi_penalty_weight(),
        }
    }
}

/// Routing configuration for multi-provider setups.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RouterConfig {
    /// Routing strategy: `"ema"` (default), `"thompson"`, `"cascade"`, or `"bandit"`.
    #[serde(default)]
    pub strategy: RouterStrategyConfig,
    /// Path for persisting Thompson Sampling state. Defaults to `~/.zeph/router_thompson_state.json`.
    ///
    /// # Security
    ///
    /// This path is user-controlled. The application writes and reads a JSON file at
    /// this location. Ensure the path is within a directory that is not world-writable
    /// (e.g., avoid `/tmp`). The file is created with mode `0o600` on Unix.
    #[serde(default)]
    pub thompson_state_path: Option<String>,
    /// Cascade routing configuration. Only used when `strategy = "cascade"`.
    #[serde(default)]
    pub cascade: Option<CascadeConfig>,
    /// Bayesian reputation scoring configuration (RAPS). Disabled by default.
    #[serde(default)]
    pub reputation: Option<ReputationConfig>,
    /// PILOT bandit routing configuration. Only used when `strategy = "bandit"`.
    #[serde(default)]
    pub bandit: Option<BanditConfig>,
    /// Embedding-based quality gate threshold for Thompson/EMA routing. Default: disabled.
    ///
    /// When set, after provider selection, the cosine similarity between the query embedding
    /// and the response embedding is computed. If below this threshold, the next provider in
    /// the ordered list is tried. On exhaustion, the best response seen is returned.
    ///
    /// Only applies to Thompson and EMA strategies. Cascade uses its own quality classifier.
    /// Fail-open: embedding errors disable the gate for that request.
    #[serde(default)]
    pub quality_gate: Option<f32>,
    /// Agent Stability Index configuration. Disabled by default.
    #[serde(default)]
    pub asi: Option<AsiConfig>,
    /// Maximum number of concurrent `embed_batch` calls through the router.
    ///
    /// Limits simultaneous embedding HTTP requests to prevent provider rate-limiting
    /// and memory pressure during indexing or high-frequency recall. Default: 4.
    /// Set to 0 to disable the semaphore (unlimited concurrency).
    #[serde(default = "default_embed_concurrency")]
    pub embed_concurrency: usize,
}

fn default_embed_concurrency() -> usize {
    4
}

/// Configuration for Bayesian reputation scoring (RAPS — Reputation-Adjusted Provider Selection).
///
/// When enabled, quality outcomes from tool execution shift the routing scores over time,
/// giving an advantage to providers that consistently produce valid tool arguments.
///
/// Default: disabled. Set `enabled = true` to activate.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ReputationConfig {
    /// Enable reputation scoring. Default: false.
    #[serde(default)]
    pub enabled: bool,
    /// Session-level decay factor applied on each load. Range: (0.0, 1.0]. Default: 0.95.
    /// Lower values make reputation forget faster; 1.0 = no decay.
    #[serde(default = "default_reputation_decay_factor")]
    pub decay_factor: f64,
    /// Weight of reputation in routing score blend. Range: [0.0, 1.0]. Default: 0.3.
    ///
    /// **Warning**: values above 0.5 can aggressively suppress low-reputation providers.
    /// At `weight = 1.0` with `rep_factor = 0.0` (all failures), the routing score
    /// drops to zero — the provider becomes unreachable for that session. Stick to
    /// the default (0.3) unless you intentionally want strong reputation gating.
    #[serde(default = "default_reputation_weight")]
    pub weight: f64,
    /// Minimum quality observations before reputation influences routing. Default: 5.
    #[serde(default = "default_reputation_min_observations")]
    pub min_observations: u64,
    /// Path for persisting reputation state. Defaults to `~/.config/zeph/router_reputation_state.json`.
    #[serde(default)]
    pub state_path: Option<String>,
}

/// Configuration for cascade routing (`strategy = "cascade"`).
///
/// Cascade routing tries providers in chain order (cheapest first), escalating to
/// the next provider when the response is classified as degenerate (empty, repetitive,
/// incoherent). Chain order determines cost order: first provider = cheapest.
///
/// # Limitations
///
/// The heuristic classifier detects degenerate outputs only, not semantic failures.
/// Use `classifier_mode = "judge"` for semantic quality gating (adds LLM call cost).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CascadeConfig {
    /// Minimum quality score [0.0, 1.0] to accept a response without escalating.
    /// Responses scoring below this threshold trigger escalation.
    #[serde(default = "default_cascade_quality_threshold")]
    pub quality_threshold: f64,

    /// Maximum number of quality-based escalations per request.
    /// Network/API errors do not count against this budget.
    /// Default: 2 (allows up to 3 providers: cheap → mid → expensive).
    #[serde(default = "default_cascade_max_escalations")]
    pub max_escalations: u8,

    /// Quality classifier mode: `"heuristic"` (default) or `"judge"`.
    /// Heuristic is zero-cost but detects only degenerate outputs.
    /// Judge requires a configured `summary_model` and adds one LLM call per evaluation.
    #[serde(default)]
    pub classifier_mode: CascadeClassifierMode,

    /// Rolling quality history window size per provider. Default: 50.
    #[serde(default = "default_cascade_window_size")]
    pub window_size: usize,

    /// Maximum cumulative input+output tokens across all escalation levels.
    /// When exceeded, returns the best-seen response instead of escalating further.
    /// `None` disables the budget (unbounded escalation cost).
    #[serde(default)]
    pub max_cascade_tokens: Option<u32>,

    /// Explicit cost ordering of provider names (cheapest first).
    /// When set, cascade routing sorts providers by their position in this list before
    /// trying them. Providers not in the list are appended after listed ones in their
    /// original chain order. When unset, chain order is used (default behavior).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost_tiers: Option<Vec<String>>,
}

impl Default for CascadeConfig {
    fn default() -> Self {
        Self {
            quality_threshold: default_cascade_quality_threshold(),
            max_escalations: default_cascade_max_escalations(),
            classifier_mode: CascadeClassifierMode::default(),
            window_size: default_cascade_window_size(),
            max_cascade_tokens: None,
            cost_tiers: None,
        }
    }
}

/// Quality classifier mode for cascade routing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CascadeClassifierMode {
    /// Zero-cost heuristic: detects degenerate outputs (empty, repetitive, incoherent).
    /// Does not detect semantic failures (hallucinations, wrong answers).
    #[default]
    Heuristic,
    /// LLM-based judge: more accurate but adds latency. Falls back to heuristic on failure.
    /// Requires `summary_model` to be configured.
    Judge,
}

fn default_bandit_alpha() -> f32 {
    1.0
}

fn default_bandit_dim() -> usize {
    32
}

fn default_bandit_cost_weight() -> f32 {
    0.1
}

fn default_bandit_decay_factor() -> f32 {
    1.0
}

fn default_bandit_embedding_timeout_ms() -> u64 {
    50
}

fn default_bandit_cache_size() -> usize {
    512
}

/// Configuration for PILOT bandit routing (`strategy = "bandit"`).
///
/// PILOT (Provider Intelligence via Learned Online Tuning) uses a `LinUCB` contextual
/// bandit to learn which provider performs best for a given query context. The feature
/// vector is derived from the query embedding (first `dim` components, L2-normalised).
///
/// **Cold start**: the bandit falls back to Thompson sampling for the first
/// `10 * num_providers` queries (configurable). After warmup, `LinUCB` takes over.
///
/// **Embedding**: an `embedding_provider` must be set for feature vectors. If the embed
/// call exceeds `embedding_timeout_ms` or fails, the bandit falls back to Thompson/uniform.
/// Use a local provider (Ollama, Candle) to avoid network latency on the hot path.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BanditConfig {
    /// `LinUCB` exploration parameter. Default: 1.0.
    /// Higher values increase exploration; lower values favour exploitation.
    #[serde(default = "default_bandit_alpha")]
    pub alpha: f32,

    /// Feature vector dimension (first `dim` components of the embedding).
    ///
    /// This is simple truncation, not PCA. The first raw embedding dimensions do not
    /// necessarily capture the most variance. For `OpenAI` `text-embedding-3-*` models,
    /// consider using the `dimensions` API parameter (Matryoshka embeddings) instead.
    /// Default: 32.
    #[serde(default = "default_bandit_dim")]
    pub dim: usize,

    /// Cost penalty weight in the reward signal: `reward = quality - cost_weight * cost_fraction`.
    /// Default: 0.1. Increase to penalise expensive providers more aggressively.
    #[serde(default = "default_bandit_cost_weight")]
    pub cost_weight: f32,

    /// Session-level decay applied to arm state on startup: `A = I + decay*(A-I)`, `b = decay*b`.
    /// Values < 1.0 cause re-exploration after provider quality changes. Default: 1.0 (no decay).
    #[serde(default = "default_bandit_decay_factor")]
    pub decay_factor: f32,

    /// Provider name from `[[llm.providers]]` used for query embeddings.
    ///
    /// SLM recommended: prefer a fast local model (e.g. Ollama `nomic-embed-text`,
    /// Candle, or `text-embedding-3-small`) — this is called on every bandit request.
    /// Empty string disables `LinUCB` (bandit always falls back to Thompson/uniform).
    #[serde(default)]
    pub embedding_provider: ProviderName,

    /// Hard timeout for the embedding call in milliseconds. Default: 50.
    /// If exceeded, the request falls back to Thompson/uniform selection.
    #[serde(default = "default_bandit_embedding_timeout_ms")]
    pub embedding_timeout_ms: u64,

    /// Maximum cached embeddings (keyed by query text hash). Default: 512.
    #[serde(default = "default_bandit_cache_size")]
    pub cache_size: usize,

    /// Path for persisting bandit state. Defaults to `~/.config/zeph/router_bandit_state.json`.
    ///
    /// # Security
    ///
    /// This path is user-controlled. The file is created with mode `0o600` on Unix.
    /// Do not place it in world-writable directories.
    #[serde(default)]
    pub state_path: Option<String>,

    /// MAR (Memory-Augmented Routing) confidence threshold.
    ///
    /// When the top-1 semantic recall score for the current query is >= this value,
    /// the bandit biases toward cheaper providers (the answer is likely in memory).
    /// Set to 1.0 to disable MAR. Default: 0.9.
    #[serde(default = "default_bandit_memory_confidence_threshold")]
    pub memory_confidence_threshold: f32,

    /// Minimum number of queries before `LinUCB` takes over from Thompson warmup.
    ///
    /// When unset or `0`, defaults to `10 × number of providers` (computed at startup).
    /// Set explicitly to control how long the bandit explores uniformly before
    /// switching to context-aware routing. Setting `0` preserves the computed default.
    #[serde(default)]
    pub warmup_queries: Option<u64>,
}

fn default_bandit_memory_confidence_threshold() -> f32 {
    0.9
}

impl Default for BanditConfig {
    fn default() -> Self {
        Self {
            alpha: default_bandit_alpha(),
            dim: default_bandit_dim(),
            cost_weight: default_bandit_cost_weight(),
            decay_factor: default_bandit_decay_factor(),
            embedding_provider: ProviderName::default(),
            embedding_timeout_ms: default_bandit_embedding_timeout_ms(),
            cache_size: default_bandit_cache_size(),
            state_path: None,
            memory_confidence_threshold: default_bandit_memory_confidence_threshold(),
            warmup_queries: None,
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct CandleConfig {
    #[serde(default = "default_candle_source")]
    pub source: String,
    #[serde(default)]
    pub local_path: String,
    #[serde(default)]
    pub filename: Option<String>,
    #[serde(default = "default_chat_template")]
    pub chat_template: String,
    #[serde(default = "default_candle_device")]
    pub device: String,
    #[serde(default)]
    pub embedding_repo: Option<String>,
    /// Resolved `HuggingFace` Hub API token for authenticated model downloads.
    ///
    /// Must be the **token value** — resolved by the caller before constructing this config.
    #[serde(default)]
    pub hf_token: Option<String>,
    #[serde(default)]
    pub generation: GenerationParams,
    /// Maximum seconds to wait for each half of a single inference request.
    ///
    /// The timeout is applied **twice** per `chat()` call: once for the channel send
    /// (waiting for a free slot) and once for the oneshot reply (waiting for the worker
    /// to finish). The effective maximum wall-clock wait per request is therefore
    /// `2 × inference_timeout_secs`. CPU inference can be slow; 120s is a conservative
    /// default for large models, giving up to 240s total before an error is returned.
    /// Values of 0 are silently promoted to 1 at bootstrap.
    #[serde(default = "default_inference_timeout_secs")]
    pub inference_timeout_secs: u64,
}

fn default_inference_timeout_secs() -> u64 {
    120
}

/// Sampling / generation parameters for Candle local inference.
///
/// Used inside `[llm.candle.generation]` or a `[[llm.providers]]` Candle entry.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GenerationParams {
    /// Sampling temperature. Higher values produce more creative outputs. Default: `0.7`.
    #[serde(default = "default_temperature")]
    pub temperature: f64,
    /// Nucleus sampling threshold. When set, tokens with cumulative probability above
    /// this value are excluded. Default: `None` (disabled).
    #[serde(default)]
    pub top_p: Option<f64>,
    /// Top-k sampling. When set, only the top-k most probable tokens are considered.
    /// Default: `None` (disabled).
    #[serde(default)]
    pub top_k: Option<usize>,
    /// Maximum number of tokens to generate per response. Capped at [`MAX_TOKENS_CAP`].
    /// Default: `2048`.
    #[serde(default = "default_max_tokens")]
    pub max_tokens: usize,
    /// Random seed for reproducible outputs. Default: `42`.
    #[serde(default = "default_seed")]
    pub seed: u64,
    /// Repetition penalty applied during sampling. Default: `1.1`.
    #[serde(default = "default_repeat_penalty")]
    pub repeat_penalty: f32,
    /// Number of last tokens to consider for the repetition penalty window. Default: `64`.
    #[serde(default = "default_repeat_last_n")]
    pub repeat_last_n: usize,
}

/// Hard upper bound on `GenerationParams::max_tokens` to prevent unbounded generation.
pub const MAX_TOKENS_CAP: usize = 32768;

impl GenerationParams {
    /// Returns `max_tokens` clamped to [`MAX_TOKENS_CAP`].
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_config::GenerationParams;
    ///
    /// let params = GenerationParams::default();
    /// assert!(params.capped_max_tokens() <= 32768);
    /// ```
    #[must_use]
    pub fn capped_max_tokens(&self) -> usize {
        self.max_tokens.min(MAX_TOKENS_CAP)
    }
}

impl Default for GenerationParams {
    fn default() -> Self {
        Self {
            temperature: default_temperature(),
            top_p: None,
            top_k: None,
            max_tokens: default_max_tokens(),
            seed: default_seed(),
            repeat_penalty: default_repeat_penalty(),
            repeat_last_n: default_repeat_last_n(),
        }
    }
}

// ─── Unified config types ─────────────────────────────────────────────────────

/// Routing strategy for the `[[llm.providers]]` pool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum LlmRoutingStrategy {
    /// Single provider or first-in-pool (default).
    #[default]
    None,
    /// Exponential moving average latency-aware ordering.
    Ema,
    /// Thompson Sampling with Beta distributions.
    Thompson,
    /// Cascade: try cheapest provider first, escalate on degenerate output.
    Cascade,
    /// Task-based routing using `[llm.routes]` map.
    Task,
    /// Complexity triage routing: pre-classify each request, delegate to appropriate tier.
    Triage,
    /// PILOT: `LinUCB` contextual bandit with online learning and budget-aware reward.
    Bandit,
}

fn default_triage_timeout_secs() -> u64 {
    5
}

fn default_max_triage_tokens() -> u32 {
    50
}

fn default_true() -> bool {
    true
}

/// Tier-to-provider name mapping for complexity routing.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct TierMapping {
    pub simple: Option<String>,
    pub medium: Option<String>,
    pub complex: Option<String>,
    pub expert: Option<String>,
}

/// Configuration for complexity-based triage routing (`routing = "triage"`).
///
/// When `[llm] routing = "triage"` is set, a cheap triage model classifies each request
/// and routes it to the appropriate tier provider. Requires at least one tier mapping.
///
/// # Example
///
/// ```toml
/// [llm]
/// routing = "triage"
///
/// [llm.complexity_routing]
/// triage_provider = "local-fast"
///
/// [llm.complexity_routing.tiers]
/// simple = "local-fast"
/// medium = "haiku"
/// complex = "sonnet"
/// expert = "opus"
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ComplexityRoutingConfig {
    /// Provider name from `[[llm.providers]]` used for triage classification.
    #[serde(default)]
    pub triage_provider: Option<ProviderName>,

    /// Skip triage when all tiers map to the same provider.
    #[serde(default = "default_true")]
    pub bypass_single_provider: bool,

    /// Tier-to-provider name mapping.
    #[serde(default)]
    pub tiers: TierMapping,

    /// Max output tokens for the triage classification call. Default: 50.
    #[serde(default = "default_max_triage_tokens")]
    pub max_triage_tokens: u32,

    /// Timeout in seconds for the triage classification call. Default: 5.
    /// On timeout, falls back to the default (first) tier provider.
    #[serde(default = "default_triage_timeout_secs")]
    pub triage_timeout_secs: u64,

    /// Optional fallback strategy when triage misclassifies.
    /// Only `"cascade"` is currently supported (Phase 4).
    #[serde(default)]
    pub fallback_strategy: Option<String>,
}

impl Default for ComplexityRoutingConfig {
    fn default() -> Self {
        Self {
            triage_provider: None,
            bypass_single_provider: true,
            tiers: TierMapping::default(),
            max_triage_tokens: default_max_triage_tokens(),
            triage_timeout_secs: default_triage_timeout_secs(),
            fallback_strategy: None,
        }
    }
}

/// Inline candle config for use inside `ProviderEntry`.
/// Re-uses the generation params from `CandleConfig`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CandleInlineConfig {
    #[serde(default = "default_candle_source")]
    pub source: String,
    #[serde(default)]
    pub local_path: String,
    #[serde(default)]
    pub filename: Option<String>,
    #[serde(default = "default_chat_template")]
    pub chat_template: String,
    #[serde(default = "default_candle_device")]
    pub device: String,
    #[serde(default)]
    pub embedding_repo: Option<String>,
    /// Resolved `HuggingFace` Hub API token for authenticated model downloads.
    #[serde(default)]
    pub hf_token: Option<String>,
    #[serde(default)]
    pub generation: GenerationParams,
    /// Maximum wall-clock seconds to wait for a single inference request.
    ///
    /// Effective timeout is `2 × inference_timeout_secs` (send + recv each have this budget).
    /// CPU inference can be slow; 120s is a conservative default. Floored at 1s.
    #[serde(default = "default_inference_timeout_secs")]
    pub inference_timeout_secs: u64,
}

impl Default for CandleInlineConfig {
    fn default() -> Self {
        Self {
            source: default_candle_source(),
            local_path: String::new(),
            filename: None,
            chat_template: default_chat_template(),
            device: default_candle_device(),
            embedding_repo: None,
            hf_token: None,
            generation: GenerationParams::default(),
            inference_timeout_secs: default_inference_timeout_secs(),
        }
    }
}

/// Unified provider entry: one struct replaces `CloudLlmConfig`, `OpenAiConfig`,
/// `GeminiConfig`, `OllamaConfig`, `CompatibleConfig`, and `OrchestratorProviderConfig`.
///
/// Provider-specific fields use `#[serde(default)]` and are ignored by backends
/// that do not use them (flat-union pattern).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct ProviderEntry {
    /// Required: provider backend type.
    #[serde(rename = "type")]
    pub provider_type: ProviderKind,

    /// Optional name for multi-provider configs. Auto-generated from type if absent.
    #[serde(default)]
    pub name: Option<String>,

    /// Model identifier. Required for most types.
    #[serde(default)]
    pub model: Option<String>,

    /// API base URL. Each type has its own default.
    #[serde(default)]
    pub base_url: Option<String>,

    /// Max output tokens.
    #[serde(default)]
    pub max_tokens: Option<u32>,

    /// Embedding model. When set, this provider supports `embed()` calls.
    #[serde(default)]
    pub embedding_model: Option<String>,

    /// STT model. When set, this provider supports speech-to-text via the Whisper API or
    /// Candle-local inference.
    #[serde(default)]
    pub stt_model: Option<String>,

    /// Mark this entry as the embedding provider (handles `embed()` calls).
    #[serde(default)]
    pub embed: bool,

    /// Mark this entry as the default chat provider (overrides position-based default).
    #[serde(default)]
    pub default: bool,

    // --- Claude-specific ---
    #[serde(default)]
    pub thinking: Option<ThinkingConfig>,
    #[serde(default)]
    pub server_compaction: bool,
    #[serde(default)]
    pub enable_extended_context: bool,

    // --- OpenAI-specific ---
    #[serde(default)]
    pub reasoning_effort: Option<String>,

    // --- Gemini-specific ---
    #[serde(default)]
    pub thinking_level: Option<GeminiThinkingLevel>,
    #[serde(default)]
    pub thinking_budget: Option<i32>,
    #[serde(default)]
    pub include_thoughts: Option<bool>,

    // --- Compatible-specific: optional inline api_key ---
    #[serde(default)]
    pub api_key: Option<String>,

    // --- Candle-specific ---
    #[serde(default)]
    pub candle: Option<CandleInlineConfig>,

    // --- Vision ---
    #[serde(default)]
    pub vision_model: Option<String>,

    /// Provider-specific instruction file.
    #[serde(default)]
    pub instruction_file: Option<std::path::PathBuf>,
}

impl Default for ProviderEntry {
    fn default() -> Self {
        Self {
            provider_type: ProviderKind::Ollama,
            name: None,
            model: None,
            base_url: None,
            max_tokens: None,
            embedding_model: None,
            stt_model: None,
            embed: false,
            default: false,
            thinking: None,
            server_compaction: false,
            enable_extended_context: false,
            reasoning_effort: None,
            thinking_level: None,
            thinking_budget: None,
            include_thoughts: None,
            api_key: None,
            candle: None,
            vision_model: None,
            instruction_file: None,
        }
    }
}

impl ProviderEntry {
    /// Resolve the effective name: explicit `name` field or type string.
    #[must_use]
    pub fn effective_name(&self) -> String {
        self.name
            .clone()
            .unwrap_or_else(|| self.provider_type.as_str().to_owned())
    }

    /// Resolve the effective model: explicit `model` field or the provider-type default.
    ///
    /// Defaults mirror those used in `build_provider_from_entry` so that `runtime.model_name`
    /// always reflects the actual model being used rather than the provider type string.
    #[must_use]
    pub fn effective_model(&self) -> String {
        if let Some(ref m) = self.model {
            return m.clone();
        }
        match self.provider_type {
            ProviderKind::Ollama => "qwen3:8b".to_owned(),
            ProviderKind::Claude => "claude-haiku-4-5-20251001".to_owned(),
            ProviderKind::OpenAi => "gpt-4o-mini".to_owned(),
            ProviderKind::Gemini => "gemini-2.0-flash".to_owned(),
            ProviderKind::Compatible | ProviderKind::Candle => String::new(),
        }
    }

    /// Validate this entry for cross-field consistency.
    ///
    /// # Errors
    ///
    /// Returns `ConfigError` when a fatal invariant is violated (e.g. compatible provider
    /// without a name).
    pub fn validate(&self) -> Result<(), crate::error::ConfigError> {
        use crate::error::ConfigError;

        // B2: compatible provider MUST have name set.
        if self.provider_type == ProviderKind::Compatible && self.name.is_none() {
            return Err(ConfigError::Validation(
                "[[llm.providers]] entry with type=\"compatible\" must set `name`".into(),
            ));
        }

        // B1: warn on irrelevant fields.
        match self.provider_type {
            ProviderKind::Ollama => {
                if self.thinking.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "field `thinking` is only used by Claude providers"
                    );
                }
                if self.reasoning_effort.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "field `reasoning_effort` is only used by OpenAI providers"
                    );
                }
                if self.thinking_level.is_some() || self.thinking_budget.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "fields `thinking_level`/`thinking_budget` are only used by Gemini providers"
                    );
                }
            }
            ProviderKind::Claude => {
                if self.reasoning_effort.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "field `reasoning_effort` is only used by OpenAI providers"
                    );
                }
                if self.thinking_level.is_some() || self.thinking_budget.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "fields `thinking_level`/`thinking_budget` are only used by Gemini providers"
                    );
                }
            }
            ProviderKind::OpenAi => {
                if self.thinking.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "field `thinking` is only used by Claude providers"
                    );
                }
                if self.thinking_level.is_some() || self.thinking_budget.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "fields `thinking_level`/`thinking_budget` are only used by Gemini providers"
                    );
                }
            }
            ProviderKind::Gemini => {
                if self.thinking.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "field `thinking` is only used by Claude providers"
                    );
                }
                if self.reasoning_effort.is_some() {
                    tracing::warn!(
                        provider = self.effective_name(),
                        "field `reasoning_effort` is only used by OpenAI providers"
                    );
                }
            }
            _ => {}
        }

        // W6: Candle STT-only provider (stt_model set, no model) is valid — no warning needed.
        // Warn if Ollama has stt_model set (Ollama does not support Whisper API).
        if self.stt_model.is_some() && self.provider_type == ProviderKind::Ollama {
            tracing::warn!(
                provider = self.effective_name(),
                "field `stt_model` is set on an Ollama provider; Ollama does not support the \
                 Whisper STT API — use OpenAI, compatible, or candle instead"
            );
        }

        Ok(())
    }
}

/// Validate a pool of `ProviderEntry` items.
///
/// # Errors
///
/// Returns `ConfigError` for fatal validation failures:
/// - Empty pool
/// - Duplicate names
/// - Multiple entries marked `default = true`
/// - Individual entry validation errors
pub fn validate_pool(entries: &[ProviderEntry]) -> Result<(), crate::error::ConfigError> {
    use crate::error::ConfigError;
    use std::collections::HashSet;

    if entries.is_empty() {
        return Err(ConfigError::Validation(
            "at least one LLM provider must be configured in [[llm.providers]]".into(),
        ));
    }

    let default_count = entries.iter().filter(|e| e.default).count();
    if default_count > 1 {
        return Err(ConfigError::Validation(
            "only one [[llm.providers]] entry can be marked `default = true`".into(),
        ));
    }

    let mut seen_names: HashSet<String> = HashSet::new();
    for entry in entries {
        let name = entry.effective_name();
        if !seen_names.insert(name.clone()) {
            return Err(ConfigError::Validation(format!(
                "duplicate provider name \"{name}\" in [[llm.providers]]"
            )));
        }
        entry.validate()?;
    }

    Ok(())
}

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

    fn ollama_entry() -> ProviderEntry {
        ProviderEntry {
            provider_type: ProviderKind::Ollama,
            name: Some("ollama".into()),
            model: Some("qwen3:8b".into()),
            ..Default::default()
        }
    }

    fn claude_entry() -> ProviderEntry {
        ProviderEntry {
            provider_type: ProviderKind::Claude,
            name: Some("claude".into()),
            model: Some("claude-sonnet-4-6".into()),
            max_tokens: Some(8192),
            ..Default::default()
        }
    }

    // ─── ProviderEntry::validate ─────────────────────────────────────────────

    #[test]
    fn validate_ollama_valid() {
        assert!(ollama_entry().validate().is_ok());
    }

    #[test]
    fn validate_claude_valid() {
        assert!(claude_entry().validate().is_ok());
    }

    #[test]
    fn validate_compatible_without_name_errors() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::Compatible,
            name: None,
            ..Default::default()
        };
        let err = entry.validate().unwrap_err();
        assert!(
            err.to_string().contains("compatible"),
            "error should mention compatible: {err}"
        );
    }

    #[test]
    fn validate_compatible_with_name_ok() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::Compatible,
            name: Some("my-proxy".into()),
            base_url: Some("http://localhost:8080".into()),
            model: Some("gpt-4o".into()),
            max_tokens: Some(4096),
            ..Default::default()
        };
        assert!(entry.validate().is_ok());
    }

    #[test]
    fn validate_openai_valid() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::OpenAi,
            name: Some("openai".into()),
            model: Some("gpt-4o".into()),
            max_tokens: Some(4096),
            ..Default::default()
        };
        assert!(entry.validate().is_ok());
    }

    #[test]
    fn validate_gemini_valid() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::Gemini,
            name: Some("gemini".into()),
            model: Some("gemini-2.0-flash".into()),
            ..Default::default()
        };
        assert!(entry.validate().is_ok());
    }

    // ─── validate_pool ───────────────────────────────────────────────────────

    #[test]
    fn validate_pool_empty_errors() {
        let err = validate_pool(&[]).unwrap_err();
        assert!(err.to_string().contains("at least one"), "{err}");
    }

    #[test]
    fn validate_pool_single_entry_ok() {
        assert!(validate_pool(&[ollama_entry()]).is_ok());
    }

    #[test]
    fn validate_pool_duplicate_names_errors() {
        let a = ollama_entry();
        let b = ollama_entry(); // same effective name "ollama"
        let err = validate_pool(&[a, b]).unwrap_err();
        assert!(err.to_string().contains("duplicate"), "{err}");
    }

    #[test]
    fn validate_pool_multiple_defaults_errors() {
        let mut a = ollama_entry();
        let mut b = claude_entry();
        a.default = true;
        b.default = true;
        let err = validate_pool(&[a, b]).unwrap_err();
        assert!(err.to_string().contains("default"), "{err}");
    }

    #[test]
    fn validate_pool_two_different_providers_ok() {
        assert!(validate_pool(&[ollama_entry(), claude_entry()]).is_ok());
    }

    #[test]
    fn validate_pool_propagates_entry_error() {
        let bad = ProviderEntry {
            provider_type: ProviderKind::Compatible,
            name: None, // invalid: compatible without name
            ..Default::default()
        };
        assert!(validate_pool(&[bad]).is_err());
    }

    // ─── ProviderEntry::effective_model ──────────────────────────────────────

    #[test]
    fn effective_model_returns_explicit_when_set() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::Claude,
            model: Some("claude-sonnet-4-6".into()),
            ..Default::default()
        };
        assert_eq!(entry.effective_model(), "claude-sonnet-4-6");
    }

    #[test]
    fn effective_model_ollama_default_when_none() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::Ollama,
            model: None,
            ..Default::default()
        };
        assert_eq!(entry.effective_model(), "qwen3:8b");
    }

    #[test]
    fn effective_model_claude_default_when_none() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::Claude,
            model: None,
            ..Default::default()
        };
        assert_eq!(entry.effective_model(), "claude-haiku-4-5-20251001");
    }

    #[test]
    fn effective_model_openai_default_when_none() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::OpenAi,
            model: None,
            ..Default::default()
        };
        assert_eq!(entry.effective_model(), "gpt-4o-mini");
    }

    #[test]
    fn effective_model_gemini_default_when_none() {
        let entry = ProviderEntry {
            provider_type: ProviderKind::Gemini,
            model: None,
            ..Default::default()
        };
        assert_eq!(entry.effective_model(), "gemini-2.0-flash");
    }

    // ─── LlmConfig::check_legacy_format ──────────────────────────────────────

    // Parse a complete TOML snippet that includes the [llm] header.
    fn parse_llm(toml: &str) -> LlmConfig {
        #[derive(serde::Deserialize)]
        struct Wrapper {
            llm: LlmConfig,
        }
        toml::from_str::<Wrapper>(toml).unwrap().llm
    }

    #[test]
    fn check_legacy_format_new_format_ok() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "ollama"
model = "qwen3:8b"
"#,
        );
        assert!(cfg.check_legacy_format().is_ok());
    }

    #[test]
    fn check_legacy_format_empty_providers_no_legacy_ok() {
        // No providers, no legacy fields — passes (empty [llm] is acceptable here)
        let cfg = parse_llm("[llm]\n");
        assert!(cfg.check_legacy_format().is_ok());
    }

    // ─── LlmConfig::effective_* helpers ──────────────────────────────────────

    #[test]
    fn effective_provider_falls_back_to_ollama_when_no_providers() {
        let cfg = parse_llm("[llm]\n");
        assert_eq!(cfg.effective_provider(), ProviderKind::Ollama);
    }

    #[test]
    fn effective_provider_reads_from_providers_first() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "claude"
model = "claude-sonnet-4-6"
"#,
        );
        assert_eq!(cfg.effective_provider(), ProviderKind::Claude);
    }

    #[test]
    fn effective_model_reads_from_providers_first() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "ollama"
model = "qwen3:8b"
"#,
        );
        assert_eq!(cfg.effective_model(), "qwen3:8b");
    }

    #[test]
    fn effective_base_url_default_when_absent() {
        let cfg = parse_llm("[llm]\n");
        assert_eq!(cfg.effective_base_url(), "http://localhost:11434");
    }

    #[test]
    fn effective_base_url_from_providers_entry() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "ollama"
base_url = "http://myhost:11434"
"#,
        );
        assert_eq!(cfg.effective_base_url(), "http://myhost:11434");
    }

    // ─── ComplexityRoutingConfig / LlmRoutingStrategy::Triage TOML parsing ──

    #[test]
    fn complexity_routing_defaults() {
        let cr = ComplexityRoutingConfig::default();
        assert!(
            cr.bypass_single_provider,
            "bypass_single_provider must default to true"
        );
        assert_eq!(cr.triage_timeout_secs, 5);
        assert_eq!(cr.max_triage_tokens, 50);
        assert!(cr.triage_provider.is_none());
        assert!(cr.tiers.simple.is_none());
    }

    #[test]
    fn complexity_routing_toml_round_trip() {
        let cfg = parse_llm(
            r#"
[llm]
routing = "triage"

[llm.complexity_routing]
triage_provider = "fast"
bypass_single_provider = false
triage_timeout_secs = 10
max_triage_tokens = 100

[llm.complexity_routing.tiers]
simple = "fast"
medium = "medium"
complex = "large"
expert = "opus"
"#,
        );
        assert!(matches!(cfg.routing, LlmRoutingStrategy::Triage));
        let cr = cfg
            .complexity_routing
            .expect("complexity_routing must be present");
        assert_eq!(cr.triage_provider.as_deref(), Some("fast"));
        assert!(!cr.bypass_single_provider);
        assert_eq!(cr.triage_timeout_secs, 10);
        assert_eq!(cr.max_triage_tokens, 100);
        assert_eq!(cr.tiers.simple.as_deref(), Some("fast"));
        assert_eq!(cr.tiers.medium.as_deref(), Some("medium"));
        assert_eq!(cr.tiers.complex.as_deref(), Some("large"));
        assert_eq!(cr.tiers.expert.as_deref(), Some("opus"));
    }

    #[test]
    fn complexity_routing_partial_tiers_toml() {
        // Only simple + complex configured; medium and expert are None.
        let cfg = parse_llm(
            r#"
[llm]
routing = "triage"

[llm.complexity_routing.tiers]
simple = "haiku"
complex = "sonnet"
"#,
        );
        let cr = cfg
            .complexity_routing
            .expect("complexity_routing must be present");
        assert_eq!(cr.tiers.simple.as_deref(), Some("haiku"));
        assert!(cr.tiers.medium.is_none());
        assert_eq!(cr.tiers.complex.as_deref(), Some("sonnet"));
        assert!(cr.tiers.expert.is_none());
        // Defaults still applied.
        assert!(cr.bypass_single_provider);
        assert_eq!(cr.triage_timeout_secs, 5);
    }

    #[test]
    fn routing_strategy_triage_deserialized() {
        let cfg = parse_llm(
            r#"
[llm]
routing = "triage"
"#,
        );
        assert!(matches!(cfg.routing, LlmRoutingStrategy::Triage));
    }

    // ─── stt_provider_entry ───────────────────────────────────────────────────

    #[test]
    fn stt_provider_entry_by_name_match() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "quality"
model = "gpt-5.4"
stt_model = "gpt-4o-mini-transcribe"

[llm.stt]
provider = "quality"
"#,
        );
        let entry = cfg.stt_provider_entry().expect("should find stt provider");
        assert_eq!(entry.effective_name(), "quality");
        assert_eq!(entry.stt_model.as_deref(), Some("gpt-4o-mini-transcribe"));
    }

    #[test]
    fn stt_provider_entry_auto_detect_when_provider_empty() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "openai-stt"
stt_model = "whisper-1"

[llm.stt]
provider = ""
"#,
        );
        let entry = cfg.stt_provider_entry().expect("should auto-detect");
        assert_eq!(entry.effective_name(), "openai-stt");
    }

    #[test]
    fn stt_provider_entry_auto_detect_no_stt_section() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "openai-stt"
stt_model = "whisper-1"
"#,
        );
        // No [llm.stt] section — should still find first provider with stt_model.
        let entry = cfg.stt_provider_entry().expect("should auto-detect");
        assert_eq!(entry.effective_name(), "openai-stt");
    }

    #[test]
    fn stt_provider_entry_none_when_no_stt_model() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "quality"
model = "gpt-5.4"
"#,
        );
        assert!(cfg.stt_provider_entry().is_none());
    }

    #[test]
    fn stt_provider_entry_name_mismatch_falls_back_to_none() {
        // Named provider exists but has no stt_model; another unnamed has stt_model.
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "quality"
model = "gpt-5.4"

[[llm.providers]]
type = "openai"
name = "openai-stt"
stt_model = "whisper-1"

[llm.stt]
provider = "quality"
"#,
        );
        // "quality" has no stt_model — returns None for name-based lookup.
        assert!(cfg.stt_provider_entry().is_none());
    }

    #[test]
    fn stt_config_deserializes_new_slim_format() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "quality"
stt_model = "whisper-1"

[llm.stt]
provider = "quality"
language = "en"
"#,
        );
        let stt = cfg.stt.as_ref().expect("stt section present");
        assert_eq!(stt.provider, "quality");
        assert_eq!(stt.language, "en");
    }

    #[test]
    fn stt_config_default_provider_is_empty() {
        // Verify that W4 fix: default_stt_provider() returns "" not "whisper".
        assert_eq!(default_stt_provider(), "");
    }

    #[test]
    fn validate_stt_missing_provider_ok() {
        let cfg = parse_llm("[llm]\n");
        assert!(cfg.validate_stt().is_ok());
    }

    #[test]
    fn validate_stt_valid_reference() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "quality"
stt_model = "whisper-1"

[llm.stt]
provider = "quality"
"#,
        );
        assert!(cfg.validate_stt().is_ok());
    }

    #[test]
    fn validate_stt_nonexistent_provider_errors() {
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "quality"
model = "gpt-5.4"

[llm.stt]
provider = "nonexistent"
"#,
        );
        assert!(cfg.validate_stt().is_err());
    }

    #[test]
    fn validate_stt_provider_exists_but_no_stt_model_returns_ok_with_warn() {
        // MEDIUM: provider is found but has no stt_model — should return Ok (warn path, not error).
        let cfg = parse_llm(
            r#"
[llm]

[[llm.providers]]
type = "openai"
name = "quality"
model = "gpt-5.4"

[llm.stt]
provider = "quality"
"#,
        );
        // validate_stt must succeed (only a tracing::warn is emitted — not an error).
        assert!(cfg.validate_stt().is_ok());
        // stt_provider_entry must return None because no stt_model is set.
        assert!(
            cfg.stt_provider_entry().is_none(),
            "stt_provider_entry must be None when provider has no stt_model"
        );
    }

    // ─── BanditConfig::warmup_queries deserialization ─────────────────────────

    #[test]
    fn bandit_warmup_queries_explicit_value_is_deserialized() {
        let cfg = parse_llm(
            r#"
[llm]

[llm.router]
strategy = "bandit"

[llm.router.bandit]
warmup_queries = 50
"#,
        );
        let bandit = cfg
            .router
            .expect("router section must be present")
            .bandit
            .expect("bandit section must be present");
        assert_eq!(
            bandit.warmup_queries,
            Some(50),
            "warmup_queries = 50 must deserialize to Some(50)"
        );
    }

    #[test]
    fn bandit_warmup_queries_explicit_null_is_none() {
        // Explicitly writing the field as absent: field simply not present is
        // equivalent due to #[serde(default)]. Test that an explicit 0 is Some(0).
        let cfg = parse_llm(
            r#"
[llm]

[llm.router]
strategy = "bandit"

[llm.router.bandit]
warmup_queries = 0
"#,
        );
        let bandit = cfg
            .router
            .expect("router section must be present")
            .bandit
            .expect("bandit section must be present");
        // 0 is a valid explicit value — it means "preserve computed default".
        assert_eq!(
            bandit.warmup_queries,
            Some(0),
            "warmup_queries = 0 must deserialize to Some(0)"
        );
    }

    #[test]
    fn bandit_warmup_queries_missing_field_defaults_to_none() {
        // When warmup_queries is omitted entirely, #[serde(default)] must produce None.
        let cfg = parse_llm(
            r#"
[llm]

[llm.router]
strategy = "bandit"

[llm.router.bandit]
alpha = 1.5
"#,
        );
        let bandit = cfg
            .router
            .expect("router section must be present")
            .bandit
            .expect("bandit section must be present");
        assert_eq!(
            bandit.warmup_queries, None,
            "omitted warmup_queries must default to None"
        );
    }

    #[test]
    fn provider_name_new_and_as_str() {
        let n = ProviderName::new("fast");
        assert_eq!(n.as_str(), "fast");
        assert!(!n.is_empty());
    }

    #[test]
    fn provider_name_default_is_empty() {
        let n = ProviderName::default();
        assert!(n.is_empty());
        assert_eq!(n.as_str(), "");
    }

    #[test]
    fn provider_name_deref_to_str() {
        let n = ProviderName::new("quality");
        let s: &str = &n;
        assert_eq!(s, "quality");
    }

    #[test]
    fn provider_name_partial_eq_str() {
        let n = ProviderName::new("fast");
        assert_eq!(n, "fast");
        assert_ne!(n, "slow");
    }

    #[test]
    fn provider_name_serde_roundtrip() {
        let n = ProviderName::new("my-provider");
        let json = serde_json::to_string(&n).expect("serialize");
        assert_eq!(json, "\"my-provider\"");
        let back: ProviderName = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, n);
    }

    #[test]
    fn provider_name_serde_empty_roundtrip() {
        let n = ProviderName::default();
        let json = serde_json::to_string(&n).expect("serialize");
        assert_eq!(json, "\"\"");
        let back: ProviderName = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, n);
        assert!(back.is_empty());
    }
}