ragrig 1.1.2

RAG framework for research and prototyping. Zero dependencies, hot-swap any agent at runtime, hybrid BM25+vector retrieval. Default build compiles with cargo build --release and nothing else.
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
//! Domain types shared across the crate: document representations,
//! CLI arguments, search results, and provider enums.

use anyhow::Context;
use serde::{Deserialize, Serialize};
use serde_json;
use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

// `MemoryConfig.strategy` is typed with this enum — re-export it here so
// `ragrig::types::*` users get it alongside the config structs.
pub use crate::longterm_memory::MemoryStrategyKind;

// --- Newtype wrappers --------------------------------------------------------

/// The scale a [`RankScore`] is measured on.
///
/// Scores from different rankers live on different scales (RRF tops out
/// around 0.03, cosine is 0–1, BM25 is unbounded), so a bare `f64` is
/// meaningless without the scale.  Tagging it lets reports print comparable
/// numbers and lets code interpret magnitudes without knowing which ranker
/// produced them.
///
/// `#[non_exhaustive]`: new score scales can be added in minor releases —
/// downstream matches must keep a wildcard arm.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScoreKind {
    /// Reciprocal Rank Fusion score (≈0.0–0.033 with the default k=60).
    Rrf,
    /// Cosine similarity (0.0–1.0).
    Cosine,
    /// BM25 keyword score (unbounded, larger is better).
    Bm25,
    /// Min-max-normalised linear fusion of cosine and BM25 (0.0–1.0).
    Weighted,
    /// MMR diversity re-ranking — no meaningful absolute scale.
    Mmr,
}

impl std::fmt::Display for ScoreKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Rrf => "rrf",
            Self::Cosine => "cosine",
            Self::Bm25 => "bm25",
            Self::Weighted => "weighted",
            Self::Mmr => "mmr",
        })
    }
}

/// Ranker-agnostic score produced by hybrid search, tagged with the
/// [`ScoreKind`] scale it is measured on.
///
/// Scores from different kinds should not be compared numerically — the
/// tag makes the scale explicit so reports can print comparable numbers
/// and code can interpret magnitudes without knowing the producing ranker.
///
/// NaN-safe: `RankScore { value: NAN, .. }` compares equal to itself and
/// sorts before all finite values, matching `f64::total_cmp` semantics.
#[derive(Clone, Copy, Debug)]
pub struct RankScore {
    /// The numeric score.
    pub value: f64,
    /// The scale the score is measured on.
    pub kind: ScoreKind,
}

impl RankScore {
    /// Create a score tagged with its scale.
    pub fn new(value: f64, kind: ScoreKind) -> Self {
        Self { value, kind }
    }

    /// Reciprocal Rank Fusion score.
    pub fn rrf(value: f64) -> Self {
        Self::new(value, ScoreKind::Rrf)
    }

    /// Cosine similarity score.
    pub fn cosine(value: f64) -> Self {
        Self::new(value, ScoreKind::Cosine)
    }

    /// BM25 score.
    pub fn bm25(value: f64) -> Self {
        Self::new(value, ScoreKind::Bm25)
    }

    /// Min-max-normalised fusion score.
    pub fn weighted(value: f64) -> Self {
        Self::new(value, ScoreKind::Weighted)
    }

    /// MMR re-ranking score (no meaningful absolute scale).
    pub fn mmr(value: f64) -> Self {
        Self::new(value, ScoreKind::Mmr)
    }
}

impl std::fmt::Display for RankScore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:.4}", self.value)
    }
}

// ── NaN-safe equality and ordering ───────────────────────────────────
// IEEE 754 defines NaN != NaN and partial_cmp(NaN, _) == None.
// We override both so NaN scores sort consistently (before finite
// values) and compare equal to themselves, matching f64::total_cmp.

impl PartialEq for RankScore {
    fn eq(&self, other: &Self) -> bool {
        if self.value.is_nan() {
            return other.value.is_nan();
        }
        if other.value.is_nan() {
            return false;
        }
        self.value == other.value
    }
}

impl PartialOrd for RankScore {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.value.total_cmp(&other.value))
    }
}

impl PartialEq<f64> for RankScore {
    fn eq(&self, other: &f64) -> bool {
        if self.value.is_nan() {
            return other.is_nan();
        }
        if other.is_nan() {
            return false;
        }
        self.value == *other
    }
}

impl PartialOrd<f64> for RankScore {
    fn partial_cmp(&self, other: &f64) -> Option<std::cmp::Ordering> {
        Some(self.value.total_cmp(other))
    }
}

// --- Document Types ---
/// A document name (file name or URL within a corpus), used consistently
/// across the pipeline.
///
/// Replaces bare `String` fields named `document` or `file_name`
/// so consumers never have to guess which field name a struct uses.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default)]
pub struct DocumentId(pub String);

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

impl From<&str> for DocumentId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl From<String> for DocumentId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl Borrow<str> for DocumentId {
    fn borrow(&self) -> &str {
        &self.0
    }
}

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

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

// --- Document Types ---

/// A document file on disk, tagged with its format and path.
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum DocumentType {
    /// PDF document.
    Pdf(PathBuf),
    /// EPUB e-book.
    Epub(PathBuf),
    /// HTML file.
    Html(PathBuf),
    /// Word / DOCX document.
    Docx(PathBuf),
    /// Markdown file (`.md`, `.rmd`, `.qmd`).
    Markdown(PathBuf),
}

impl DocumentType {
    /// The filename component of the document path, or `"unknown"`.
    pub fn file_name(&self) -> &str {
        self.path()
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
    }
    /// The full filesystem path to the document.
    pub fn path(&self) -> &PathBuf {
        match self {
            Self::Pdf(p) => p,
            Self::Epub(p) => p,
            Self::Html(p) => p,
            Self::Docx(p) => p,
            Self::Markdown(p) => p,
        }
    }
}

impl DocumentType {
    /// Create a `DocumentType` from a file extension string.
    ///
    /// The extension is matched case-insensitively — `"PDF"`, `"Pdf"`,
    /// and `"pdf"` are all treated identically.
    ///
    /// Returns `None` for unsupported extensions.
    pub fn from_extension(ext: &str, path: impl Into<PathBuf>) -> Option<Self> {
        let path = path.into();
        match ext.to_lowercase().as_str() {
            "pdf" => Some(Self::Pdf(path)),
            "epub" => Some(Self::Epub(path)),
            "html" | "htm" => Some(Self::Html(path)),
            "docx" => Some(Self::Docx(path)),
            "md" | "rmd" | "qmd" => Some(Self::Markdown(path)),
            _ => None,
        }
    }
}

/// Metadata for a document file: filename + SHA-256 hash.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct FileHashEntry {
    /// Name of the document file.
    pub file_name: DocumentId,
    /// SHA-256 hex digest of the file contents.
    pub hash: String,
}

/// Reproducibility manifest recorded alongside the vector index.
///
/// Captures the full indexing configuration — embedding model, chunking
/// parameters, document hashes — so that results can be reproduced or
/// compared across runs.  Stored in [`BruteForceInner`](crate::store::BruteForceStore)
/// and exposed via [`VectorStore::manifest`](crate::store::VectorStore::manifest).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct IndexManifest {
    /// ISO 8601 timestamp of index creation, e.g. `"2026-07-11T14:30:00Z"`.
    pub created: String,
    /// Chunk size in tokens used for this index.
    pub chunk_size: usize,
    /// Chunk overlap in tokens.
    pub chunk_overlap: usize,
    /// Chunking strategy used for this index, e.g. `"markdown"` or
    /// `"chunkedrs-markdown"`.  Empty for manifests recorded before
    /// chunkers became pluggable.
    #[serde(default)]
    pub chunker: String,
    /// Embedding model name, e.g. `"nomic-embed-text"`.
    pub embedding_model: String,
    /// Embedding vector dimensionality.
    pub embedding_dimensions: usize,
    /// Number of documents indexed.
    pub document_count: usize,
    /// Total number of chunks stored.
    pub total_chunks: usize,
    /// SHA-256 hashes of every indexed document file.
    pub file_hashes: Vec<FileHashEntry>,
}

/// A single text chunk from a document, tagged with its document name
/// and optional positional metadata.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct DocumentChunk {
    /// The chunk's text content.
    pub text: String,
    /// Which document this chunk came from.
    pub document: DocumentId,
    /// Positional metadata (document ID, section heading, page/offset hints).
    /// Populated during chunking; `None` for chunks created before v0.9.8.
    #[serde(default)]
    pub meta: ChunkMeta,
    /// Which (parser, chunker, embedder) pipeline produced this chunk.
    /// Empty for chunks stored before provenance tracking existed.
    #[serde(default)]
    pub provenance: PipelineProvenance,
}

/// Identity of the document-processing pipeline that produced a chunk.
///
/// Every stored chunk records which [`DocumentParser`](crate::parsers::DocumentParser),
/// [`Chunker`](crate::chunker::Chunker), and [`Embedder`](crate::embed::Embedder) built it.
/// This lets a single vector store hold chunks from *multiple* pipelines
/// simultaneously, and lets retrieval be restricted to any subset at runtime —
/// the building block for pipeline benchmarking.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PipelineProvenance {
    /// Corpus the chunk was indexed from — a folder path, a curated
    /// URL list name, etc.  Part of the store's per-document identity, so two
    /// corpora can provide a document with the same file name without
    /// clobbering each other.  Empty for chunks stored before corpora
    /// became pluggable.  Deserialised from `"source"` in older stores.
    #[serde(default, alias = "source")]
    pub corpus: String,
    /// Parser backend that produced the Markdown, e.g. `"unpdf"`, `"epub-parser"`.
    #[serde(default)]
    pub parser: String,
    /// Chunker strategy name, e.g. `"markdown"`, `"chunkedrs-markdown"`.
    #[serde(default)]
    pub chunker: String,
    /// Embedder identity `"<provider>/<model>"`, e.g. `"Ollama/nomic-embed-text"`.
    #[serde(default)]
    pub embedder: String,
    /// Explicit pipeline id stamped at ingest time — identifies ONE ingest
    /// run's chunk set regardless of which parser handled each document
    /// (e.g. `"unpdf·markdown"` on a mixed corpus covers the `unpdf` chunks
    /// *and* the `html`-parsed chunks of that run).  Empty for chunks stored
    /// before pipeline ids existed.
    #[serde(default)]
    pub pipeline: String,
}

impl PipelineProvenance {
    /// Construct a provenance record without a document corpus (legacy
    /// records).  Prefer [`new_with_corpus`](Self::new_with_corpus) for new
    /// code.
    pub fn new(
        parser: impl Into<String>,
        chunker: impl Into<String>,
        embedder: impl Into<String>,
    ) -> Self {
        Self {
            corpus: String::new(),
            parser: parser.into(),
            chunker: chunker.into(),
            embedder: embedder.into(),
            pipeline: String::new(),
        }
    }

    /// Construct a provenance record including the document corpus.
    pub fn new_with_corpus(
        corpus: impl Into<String>,
        parser: impl Into<String>,
        chunker: impl Into<String>,
        embedder: impl Into<String>,
    ) -> Self {
        Self {
            corpus: corpus.into(),
            parser: parser.into(),
            chunker: chunker.into(),
            embedder: embedder.into(),
            pipeline: String::new(),
        }
    }

    /// Construct a provenance record including the document corpus and an
    /// explicit pipeline id — the discriminator for benchmarking several
    /// pipelines over mixed corpora (see [`PipelineFilter::for_pipeline`]).
    pub fn new_with_corpus_and_pipeline(
        corpus: impl Into<String>,
        parser: impl Into<String>,
        chunker: impl Into<String>,
        embedder: impl Into<String>,
        pipeline: impl Into<String>,
    ) -> Self {
        Self {
            corpus: corpus.into(),
            parser: parser.into(),
            chunker: chunker.into(),
            embedder: embedder.into(),
            pipeline: pipeline.into(),
        }
    }
}

/// Restriction on which pipeline's chunks a search may return.
///
/// Every field is optional: `None` means "any".  Build one with
/// [`PipelineFilter::for_chunker`] to compare chunking strategies,
/// or set multiple fields to pin down a full pipeline.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PipelineFilter {
    /// Only chunks indexed from this corpus (exact name match).
    /// Deserialised from `"source"` in older configs.
    #[serde(default, alias = "source")]
    pub corpus: Option<String>,
    /// Only chunks produced by this parser (exact name match).
    pub parser: Option<String>,
    /// Only chunks produced by this chunker (exact name match).
    pub chunker: Option<String>,
    /// Only chunks produced by this embedder (exact `provider/model` match).
    pub embedder: Option<String>,
    /// Only chunks stamped with this pipeline id at ingest time (exact
    /// match) — selects one ingest run's whole chunk set, including
    /// documents parsed by different parsers (the discriminator for
    /// mixed-corpus pipeline benchmarking).
    #[serde(default)]
    pub pipeline: Option<String>,
}

impl PipelineFilter {
    /// Filter that accepts every chunk (all fields `None`).
    pub fn any() -> Self {
        Self::default()
    }

    /// Filter that accepts only chunks produced by the given chunker.
    pub fn for_chunker(name: impl Into<String>) -> Self {
        Self {
            chunker: Some(name.into()),
            ..Self::default()
        }
    }

    /// Filter that accepts only chunks indexed from the given document corpus.
    pub fn for_corpus(name: impl Into<String>) -> Self {
        Self {
            corpus: Some(name.into()),
            ..Self::default()
        }
    }

    /// Filter that accepts only chunks produced by the given parser.
    pub fn for_parser(name: impl Into<String>) -> Self {
        Self {
            parser: Some(name.into()),
            ..Self::default()
        }
    }

    /// Filter that accepts only chunks produced by the given embedder.
    pub fn for_embedder(id: impl Into<String>) -> Self {
        Self {
            embedder: Some(id.into()),
            ..Self::default()
        }
    }

    /// Filter that accepts only chunks stamped with the given pipeline id.
    /// A pipeline id identifies one ingest run's whole chunk set — compare
    /// `(parser, chunker)` pipelines on mixed corpora without mixing their
    /// shared chunks, which parser/chunker-only filters cannot express.
    pub fn for_pipeline(id: impl Into<String>) -> Self {
        Self {
            pipeline: Some(id.into()),
            ..Self::default()
        }
    }

    /// `true` when every set field matches `provenance`.
    pub fn matches(&self, provenance: &PipelineProvenance) -> bool {
        self.corpus
            .as_deref()
            .is_none_or(|s| s == provenance.corpus)
            && self
                .parser
                .as_deref()
                .is_none_or(|p| p == provenance.parser)
            && self
                .chunker
                .as_deref()
                .is_none_or(|c| c == provenance.chunker)
            && self
                .embedder
                .as_deref()
                .is_none_or(|e| e == provenance.embedder)
            && self
                .pipeline
                .as_deref()
                .is_none_or(|p| p == provenance.pipeline)
    }

    /// `true` when no field is set (i.e. this filter accepts everything).
    pub fn is_empty(&self) -> bool {
        self.corpus.is_none()
            && self.parser.is_none()
            && self.chunker.is_none()
            && self.embedder.is_none()
            && self.pipeline.is_none()
    }
}

/// Positional metadata attached to every chunk for document citation.
///
/// All fields are optional — parsers populate what they can.
/// PDF page numbers require a parser that outputs page-aware markup;
/// section headings are extracted from Markdown ATX headings during chunking.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ChunkMeta {
    /// SHA-256 hex digest of the document's contents.
    pub document_id: Option<String>,
    /// Nearest section heading (ATX `# …` line) in the document.
    pub section: Option<String>,
    /// 1‑based page number (available when the parser supports it).
    pub page_number: Option<u32>,
    /// Byte offset of the chunk's start in the document.
    pub byte_offset: Option<u64>,
    /// Character offset of the chunk's start in the parsed Markdown.
    pub char_offset: Option<u64>,
    /// Opaque document-level bibliographic metadata (DOI, title, authors,
    /// …), copied from [`Document::meta`](crate::corpora::Document::meta)
    /// at ingest time.  ragrig never interprets the contents; consumers
    /// (e.g. a citation formatter) render it.  Empty for chunks stored
    /// before metadata existed.
    #[serde(default)]
    pub document_meta: BTreeMap<String, String>,
}

/// Configuration for text chunking — size and overlap in tokens.
///
/// This is the library-facing config struct.  It carries no CLI baggage
/// and can be constructed via [`new`](Self::new) (validated) or
/// [`Default`] without importing `clap`.  `#[non_exhaustive]` keeps the
/// struct open to future chunking knobs in 1.x — construct it with
/// [`new`](Self::new) / [`Default`], not a struct literal.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct ChunkConfig {
    /// Target chunk size in tokens.
    pub size: usize,
    /// Token overlap between adjacent chunks.
    pub overlap: usize,
}

impl Default for ChunkConfig {
    fn default() -> Self {
        Self {
            size: 1024,
            overlap: 128,
        }
    }
}

impl ChunkConfig {
    /// Create a validated `ChunkConfig`.
    ///
    /// Returns an error when `size == 0` or `overlap >= size` — malformed
    /// configurations that would cause undefined behaviour in the downstream
    /// chunker.  Prefer this over the struct literal; direct field access
    /// bypasses validation.
    pub fn new(size: usize, overlap: usize) -> anyhow::Result<Self> {
        let cfg = Self { size, overlap };
        cfg.validate()?;
        Ok(cfg)
    }

    /// Check that this configuration is well-formed.
    ///
    /// Returns `Ok(())` when `size > 0` and `overlap < size`.
    /// Call this before passing a manually-constructed `ChunkConfig` to
    /// the chunking pipeline.
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.size == 0 {
            return Err(anyhow::anyhow!(
                "ChunkConfig::size must be > 0, got {}",
                self.size
            ));
        }
        if self.overlap >= self.size {
            return Err(anyhow::anyhow!(
                "ChunkConfig::overlap ({}) must be less than size ({})",
                self.overlap,
                self.size
            ));
        }
        Ok(())
    }
}

/// An externally attached document — parsed text injected into the RAG prompt
/// alongside (or instead of) vector store results.  Not added to chat memory.
#[derive(Debug, Clone)]
pub struct AttachedDocument {
    /// Display name for the document (filename or label).
    pub name: String,
    /// Full parsed text content.
    pub content: String,
}

/// A paper result from academic search APIs (Semantic Scholar, arXiv).
#[derive(Deserialize, Debug, Clone)]
pub struct PaperResult {
    /// Paper title.
    pub title: String,
    /// List of author names.
    pub authors: Vec<String>,
    /// Publication year, if known.
    pub year: Option<i32>,
    /// arXiv identifier (e.g. `"2301.12345"`), if available.
    pub arxiv_id: Option<String>,
    /// DOI, if available.
    pub doi: Option<String>,
    /// Direct PDF URL, if available.
    pub pdf_url: Option<String>,
}

impl PaperResult {
    /// Short author list for display ("Smith, et al." if > 3).
    pub fn format_authors(&self) -> String {
        if self.authors.len() > 3 {
            format!("{}, et al.", self.authors[0])
        } else {
            self.authors.join(", ")
        }
    }

    /// " (2023)" or empty.
    pub fn format_year(&self) -> String {
        self.year.map(|y| format!(" ({})", y)).unwrap_or_default()
    }

    /// Best download URL: pdf_url, or arXiv fallback, or empty.
    pub fn best_pdf_url(&self) -> String {
        if let Some(ref url) = self.pdf_url {
            url.clone()
        } else if let Some(ref id) = self.arxiv_id {
            format!("https://arxiv.org/pdf/{}.pdf", id)
        } else {
            String::new()
        }
    }
}

/// Chat backend: local Ollama or cloud DeepSeek.
/// Chat generation provider.
///
/// Serialised lowercase (`"ollama"` / `"deepseek"`) to match the CLI and
/// spec layer; the historical PascalCase spellings remain accepted as
/// aliases for old profiles.
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum Provider {
    /// Local Ollama server.
    #[default]
    #[serde(alias = "Ollama")]
    Ollama,
    /// DeepSeek API (requires `DEEPSEEK_API_KEY`).
    #[serde(alias = "Deepseek")]
    Deepseek,
}

/// Model generation parameters shared across all providers.
///
/// Each field is optional — when `None` the provider's own default is used.
/// Applied via rig-core's `CompletionRequestBuilder` methods (`temperature`,
/// `max_tokens`) or injected through `additional_params` for
/// provider-specific knobs
/// (`top_p`, `seed`).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct GenerationParams {
    /// Sampling temperature (0.0 = deterministic, 1.0+ = more random).
    pub temperature: Option<f64>,
    /// Nucleus sampling cutoff.
    pub top_p: Option<f64>,
    /// Maximum tokens to generate.
    pub max_tokens: Option<usize>,
    /// Random seed for reproducible output (not supported by all providers).
    pub seed: Option<u64>,
}

impl GenerationParams {
    /// Return `true` when every field is `None` (no overrides set).
    pub fn is_empty(&self) -> bool {
        self.temperature.is_none()
            && self.top_p.is_none()
            && self.max_tokens.is_none()
            && self.seed.is_none()
    }

    /// Build the `additional_params` JSON value for rig-core's
    /// `CompletionRequestBuilder::additional_params()`.  Returns `None` when
    /// `top_p` and `seed` are both absent, since `temperature` and
    /// `max_tokens` are passed via dedicated builder methods.
    pub fn additional_json(&self) -> Option<serde_json::Value> {
        if self.top_p.is_none() && self.seed.is_none() {
            return None;
        }
        let mut extra = serde_json::Map::new();
        if let Some(p) = self.top_p
            && let Some(n) = serde_json::Number::from_f64(p)
        {
            extra.insert("top_p".into(), serde_json::Value::Number(n));
        }
        if let Some(s) = self.seed {
            extra.insert("seed".into(), serde_json::Value::Number(s.into()));
        }
        Some(serde_json::Value::Object(extra))
    }
}

/// Embedding backend: local Ollama or CPU-only Fastembed.
///
/// Serialised lowercase (`"ollama"` / `"fastembed"`) to match the CLI and
/// spec layer; the historical PascalCase spellings remain accepted as
/// aliases for old profiles.
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum EmbeddingProvider {
    /// Ollama server with an embedding model (e.g. `nomic-embed-text`).
    #[default]
    #[serde(alias = "Ollama")]
    Ollama,
    /// CPU-only embeddings via the `fastembed` crate.
    #[cfg(feature = "internal-embed")]
    #[serde(alias = "Fastembed")]
    Fastembed,
}

/// PDF parser backend.
///
/// Serialised lowercase (`"unpdf"`, `"extract"`, …) to match the CLI and
/// spec layer; the historical PascalCase spellings remain accepted as
/// aliases for old profiles.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PdfParserBackend {
    /// kreuzberg — docling-style layout-aware Markdown extraction
    #[cfg(feature = "kreuzberg")]
    #[serde(alias = "Kreuzberg")]
    Kreuzberg,
    /// unpdf — high-performance, direct Markdown output
    #[serde(alias = "Unpdf")]
    Unpdf,
    /// pdfsink-rs — structured, layout-aware
    #[serde(alias = "Sink")]
    Sink,
    /// pdf-extract — legacy flat-text (default)
    #[serde(alias = "Extract")]
    Extract,
    /// Binary scavenger — never panics
    #[serde(alias = "Internal")]
    Internal,
    /// Vision VLM — rasterise PDF pages and extract text via a vision-language model.
    /// The parser itself is only included when the `vision-pdf` feature is enabled.
    #[serde(alias = "Vision")]
    Vision,
}

/// EPUB parser backend.
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum EpubParserBackend {
    /// epub-parser crate
    Epub,
}

/// Controls how context-size overflow is handled.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ContextSizeMode {
    /// Auto-adjust the context budget when the model reports overflow.
    #[default]
    Auto,
    /// Treat overflow as a fatal error — do not retry.
    Forced,
}

// ── Sub-config groups ──────────────────────────────────────────────────────

/// Chat / generation configuration.
///
/// Missing fields deserialise from [`Default`] (`#[serde(default)]` on the
/// container), so hand-written JSON/TOML profiles only need to mention what
/// they change — e.g. `[chat] context_tokens = 2048` fills the rest from the
/// library defaults.  Serialisation still emits every field.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct ChatConfig {
    /// Chat backend: `ollama` (local) or `deepseek` (cloud API).
    pub provider: Provider,

    /// Model name for Ollama chat (ignored when `provider` is `Deepseek`).
    pub model: String,

    /// DeepSeek API key (required when `provider` is `Deepseek`).
    /// Can also be set via the `DEEPSEEK_API_KEY` env var.
    pub deepseek_api_key: Option<String>,

    /// Model name for DeepSeek (ignored when `provider` is `Ollama`).
    pub deepseek_model: String,

    /// Sampling temperature, top_p, max_tokens, seed.
    /// Each field is optional — when `None` the provider's own default is used.
    pub params: GenerationParams,

    /// Context window size of the current chat model (tokens).
    /// Used to calculate how much retrieved text fits in the prompt.
    pub context_tokens: usize,

    /// Controls context-overflow behaviour: `Auto` retries with fewer chunks,
    /// `Forced` treats overflow as a fatal error.
    pub context_size_mode: ContextSizeMode,

    /// Path to a Markdown file containing a custom system prompt for the
    /// chat agent.  Use `{context}` as placeholder for retrieved documents.
    pub system_prompt_path: Option<PathBuf>,

    /// Per-request timeout in seconds for Ollama/DeepSeek network calls.
    /// `None` means no timeout (default).
    pub request_timeout_secs: Option<u64>,
}

impl Default for ChatConfig {
    fn default() -> Self {
        Self {
            provider: Provider::default(),
            model: "qwen3.5:9b".into(),
            deepseek_api_key: None,
            deepseek_model: "deepseek-v4-pro".into(),
            params: GenerationParams::default(),
            context_tokens: 4096,
            context_size_mode: ContextSizeMode::default(),
            system_prompt_path: None,
            request_timeout_secs: None,
        }
    }
}

impl ChatConfig {
    /// Override fields where `cli` differs from `defaults` — used when
    /// merging CLI arguments on top of a profile file.
    pub fn override_with(&mut self, cli: &ChatConfig, defaults: &ChatConfig) {
        if cli.provider != defaults.provider {
            self.provider = cli.provider.clone();
        }
        if cli.model != defaults.model {
            self.model.clone_from(&cli.model);
        }
        if cli.deepseek_api_key != defaults.deepseek_api_key {
            self.deepseek_api_key.clone_from(&cli.deepseek_api_key);
        }
        if cli.deepseek_model != defaults.deepseek_model {
            self.deepseek_model.clone_from(&cli.deepseek_model);
        }
        if cli.params.temperature != defaults.params.temperature {
            self.params.temperature = cli.params.temperature;
        }
        if cli.params.top_p != defaults.params.top_p {
            self.params.top_p = cli.params.top_p;
        }
        if cli.params.max_tokens != defaults.params.max_tokens {
            self.params.max_tokens = cli.params.max_tokens;
        }
        if cli.params.seed != defaults.params.seed {
            self.params.seed = cli.params.seed;
        }
        if cli.context_tokens != defaults.context_tokens {
            self.context_tokens = cli.context_tokens;
        }
        if cli.context_size_mode != defaults.context_size_mode {
            self.context_size_mode = cli.context_size_mode;
        }
        if cli.system_prompt_path != defaults.system_prompt_path {
            self.system_prompt_path.clone_from(&cli.system_prompt_path);
        }
        if cli.request_timeout_secs != defaults.request_timeout_secs {
            self.request_timeout_secs = cli.request_timeout_secs;
        }
    }
}

/// Embedding / retrieval configuration.
///
/// Controls the embedding backend, search parameters, and the model used
/// for producing vector embeddings.  Missing fields deserialise from
/// [`Default`] (`#[serde(default)]` on the container).  Swappable at
/// runtime via `/embed`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbedConfig {
    /// Embedding backend.  `Ollama` uses the local Ollama server;
    /// `Fastembed` runs Nomic-Embed-Text-v1.5 directly on the CPU
    /// with zero network overhead (requires `internal-embed` feature).
    pub provider: EmbeddingProvider,

    /// Model name passed to Ollama when `provider` is `Ollama`
    /// (ignored for `Fastembed`).
    pub model: String,

    /// Maximum number of chunks to retrieve per search.
    pub top_k: usize,

    /// Minimum cosine similarity for a chunk to participate in hybrid search.
    /// Can be toggled at runtime via `/embed threshold <F>`.
    pub similarity_threshold: f64,

    /// Per-request timeout in seconds for Ollama embedding network calls.
    /// `None` means no timeout (default).
    pub request_timeout_secs: Option<u64>,
}

impl Default for EmbedConfig {
    fn default() -> Self {
        Self {
            provider: EmbeddingProvider::default(),
            model: "nomic-embed-text:latest".into(),
            top_k: 50,
            similarity_threshold: 0.04,
            request_timeout_secs: None,
        }
    }
}

impl EmbedConfig {
    /// Override fields where `cli` differs from `defaults`.
    pub fn override_with(&mut self, cli: &EmbedConfig, defaults: &EmbedConfig) {
        if cli.provider != defaults.provider {
            self.provider = cli.provider.clone();
        }
        if cli.model != defaults.model {
            self.model.clone_from(&cli.model);
        }
        if cli.top_k != defaults.top_k {
            self.top_k = cli.top_k;
        }
        if (cli.similarity_threshold - defaults.similarity_threshold).abs() > f64::EPSILON {
            self.similarity_threshold = cli.similarity_threshold;
        }
        if cli.request_timeout_secs != defaults.request_timeout_secs {
            self.request_timeout_secs = cli.request_timeout_secs;
        }
    }
}

/// Document parsing and chunking configuration.
///
/// Controls which PDF backend to use, the chunk size / overlap,
/// and whether the sloppy binary-scavenger fallback is enabled.
/// Missing fields deserialise from [`Default`] (`#[serde(default)]` on the
/// container).  Swappable at runtime via `/parser`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct ParseConfig {
    /// PDF parser backend: `kreuzberg` (docling-style, feature-gated),
    /// `unpdf` (Markdown-native), `sink` (structured), `extract` (legacy
    /// flat-text, default), or `internal` (sloppy binary scavenger, never panics).
    pub pdf_parser: PdfParserBackend,

    /// Use the sloppy PDF parser as fallback.  Never panics — scavenges
    /// raw text strings from the PDF binary when structured parsers fail.
    pub sloppy_pdf: bool,

    /// Target chunk size in tokens.
    pub chunk_size: usize,

    /// Token overlap between adjacent chunks.
    pub chunk_overlap: usize,
}

impl Default for ParseConfig {
    fn default() -> Self {
        Self {
            pdf_parser: PdfParserBackend::Extract,
            sloppy_pdf: false,
            chunk_size: 1024,
            chunk_overlap: 128,
        }
    }
}

impl ParseConfig {
    /// Override fields where `cli` differs from `defaults`.
    pub fn override_with(&mut self, cli: &ParseConfig, defaults: &ParseConfig) {
        if cli.pdf_parser != defaults.pdf_parser {
            self.pdf_parser = cli.pdf_parser.clone();
        }
        if cli.sloppy_pdf != defaults.sloppy_pdf {
            self.sloppy_pdf = cli.sloppy_pdf;
        }
        if cli.chunk_size != defaults.chunk_size {
            self.chunk_size = cli.chunk_size;
        }
        if cli.chunk_overlap != defaults.chunk_overlap {
            self.chunk_overlap = cli.chunk_overlap;
        }
    }
}

/// Memory / query-rewrite configuration.
///
/// Controls the model used for conversational query expansion
/// and the optional custom rewrite prompt.  Missing fields deserialise
/// from [`Default`] (`#[serde(default)]` on the container).  Swappable at
/// runtime via `/memory`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct MemoryConfig {
    /// Model used for conversational query expansion (via the
    /// `Generator` trait — any backend works).  Defaults to a small
    /// local model.  Swappable at runtime via `/memory`.
    pub model: String,

    /// Path to a Markdown file containing a custom system prompt for the
    /// memory / rewrite agent.  Use `{question}` as placeholder.
    pub rewrite_prompt_path: Option<PathBuf>,

    /// Memory handling strategy: query rewriting, transcript-only,
    /// cross-session history diffusion (`log`/`summary`), or fully off.
    /// See [`MemoryStrategyKind`].
    pub strategy: MemoryStrategyKind,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            model: "qwen2.5:1.5b".into(),
            rewrite_prompt_path: None,
            strategy: MemoryStrategyKind::default(),
        }
    }
}

impl MemoryConfig {
    /// Override fields where `cli` differs from `defaults`.
    pub fn override_with(&mut self, cli: &MemoryConfig, defaults: &MemoryConfig) {
        if cli.model != defaults.model {
            self.model.clone_from(&cli.model);
        }
        if cli.rewrite_prompt_path != defaults.rewrite_prompt_path {
            self.rewrite_prompt_path
                .clone_from(&cli.rewrite_prompt_path);
        }
        if cli.strategy != defaults.strategy {
            self.strategy = cli.strategy.clone();
        }
    }
}

/// Default workspace: the current directory.
fn default_workspace() -> PathBuf {
    PathBuf::from(".")
}

/// Top-level configuration for a ragrig session.
///
/// Composes [`ChatConfig`], [`EmbedConfig`], [`ParseConfig`], and
/// [`MemoryConfig`] into a single format-agnostic tree.  Serde support
/// enables JSON/TOML profile files; the CLI binary converts `clap`
/// arguments into this struct via `From`.
///
/// # Entry points
///
/// ```rust,ignore
/// // 1. From CLI (binary only)
/// let config = RagrigConfig::from(Cli::parse());
///
/// // 2. From a profile file (TOML / JSON)
/// let config: RagrigConfig = toml::from_str(&fs::read_to_string("profile.toml")?)?;
///
/// // 3. Programmatic construction
/// let config = RagrigConfig {
///     workspace: "./workspace".into(),
///     ..Default::default()
/// };
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RagrigConfig {
    /// Workspace directory holding the vector store (`.ragrig_store`),
    /// history, sessions, and profiles.  Not a document corpus by itself —
    /// documents come from [`corpus_dirs`](Self::corpus_dirs) and
    /// [`corpus_urls`](Self::corpus_urls).  Deserialised from `"folder"`
    /// in older profiles.
    #[serde(default = "default_workspace", alias = "folder")]
    pub workspace: PathBuf,

    /// Chat / generation settings.
    #[serde(default)]
    pub chat: ChatConfig,

    /// Embedding / search settings.
    #[serde(default)]
    pub embed: EmbedConfig,

    /// Document parsing and chunking settings.
    #[serde(default)]
    pub parse: ParseConfig,

    /// Memory / query-rewrite settings.
    #[serde(default)]
    pub memory: MemoryConfig,

    /// Named directory corpora in `name=path` form (repeatable
    /// `--corpus-dir`).  Deserialised from `"source_dirs"` in older profiles.
    #[serde(default, alias = "source_dirs")]
    pub corpus_dirs: Vec<String>,

    /// Named URL corpora in `name=url` form (repeatable `--corpus-urls`;
    /// repeating a name accumulates URLs into one curated list).
    /// Deserialised from `"source_urls"` in older profiles.
    #[serde(default, alias = "source_urls")]
    pub corpus_urls: Vec<String>,

    /// Semantic Scholar API key for higher rate limits (free).
    /// See <https://www.semanticscholar.org/product/api#api-key-form> for a key.
    pub semantic_scholar_api_key: Option<String>,
}

impl Default for RagrigConfig {
    fn default() -> Self {
        Self {
            workspace: default_workspace(),
            chat: ChatConfig::default(),
            embed: EmbedConfig::default(),
            parse: ParseConfig::default(),
            memory: MemoryConfig::default(),
            corpus_dirs: Vec::new(),
            corpus_urls: Vec::new(),
            semantic_scholar_api_key: None,
        }
    }
}

impl RagrigConfig {
    /// Parse a `RagrigConfig` from a TOML document (file contents or an
    /// inline string).  Missing sub-tables and fields fall back to the
    /// library defaults.
    pub fn from_toml(src: &str) -> anyhow::Result<Self> {
        Ok(toml::from_str(src)?)
    }

    /// Parse a `RagrigConfig` from a JSON document.  Missing sub-tables
    /// and fields fall back to the library defaults.
    pub fn from_json(src: &str) -> anyhow::Result<Self> {
        Ok(serde_json::from_str(src)?)
    }

    /// Merge `cli` overrides on top of this config (typically loaded from a profile).
    ///
    /// Fields where `cli` equals `RagrigConfig::default()` are left untouched —
    /// they were not explicitly set by the user.  Only explicitly-changed fields
    /// from the CLI override the profile base.
    pub fn override_with(&mut self, cli: &RagrigConfig) {
        let defaults = RagrigConfig::default();
        // workspace always comes from CLI
        self.workspace.clone_from(&cli.workspace);
        // Document corpora come from the CLI when given; otherwise a
        // profile's corpora are kept (unlike workspace, these are optional).
        if !cli.corpus_dirs.is_empty() {
            self.corpus_dirs.clone_from(&cli.corpus_dirs);
        }
        if !cli.corpus_urls.is_empty() {
            self.corpus_urls.clone_from(&cli.corpus_urls);
        }
        self.chat.override_with(&cli.chat, &defaults.chat);
        self.embed.override_with(&cli.embed, &defaults.embed);
        self.parse.override_with(&cli.parse, &defaults.parse);
        self.memory.override_with(&cli.memory, &defaults.memory);
        if cli.semantic_scholar_api_key != defaults.semantic_scholar_api_key {
            self.semantic_scholar_api_key
                .clone_from(&cli.semantic_scholar_api_key);
        }
    }

    /// Directory where profile JSON files live for a given document folder.
    pub fn profiles_dir(folder: &Path) -> PathBuf {
        folder.join(".ragrig").join("profiles")
    }

    /// Save this config as a named profile under `folder`.
    ///
    /// Creates `.ragrig/profiles/<name>.json`.  The `workspace` field of
    /// the config is **not written** — profiles are portable across
    /// machines; the caller's `folder` argument (the workspace) is what
    /// counts and is supplied again at load time.
    pub fn save_to_profile(&self, folder: &Path, name: &str) -> Result<(), anyhow::Error> {
        let dir = Self::profiles_dir(folder);
        std::fs::create_dir_all(&dir)?;
        let path = dir.join(format!("{}.json", name));
        let mut value = serde_json::to_value(self)?;
        if let serde_json::Value::Object(ref mut map) = value {
            map.remove("workspace");
        }
        let json = serde_json::to_string_pretty(&value)?;
        std::fs::write(&path, json)?;
        log::info!("Profile '{}' saved to {}", name, path.display());
        Ok(())
    }

    /// Load a named profile from `.ragrig/profiles/<name>.json`.
    ///
    /// The caller's `folder` (the workspace) is authoritative: a `workspace`
    /// value written into the file by an older version is ignored, so a
    /// profile copied from another machine can never re-point the workspace.
    pub fn load_from_profile(folder: &Path, name: &str) -> Result<Self, anyhow::Error> {
        let path = Self::profiles_dir(folder).join(format!("{}.json", name));
        let json = std::fs::read_to_string(&path)
            .with_context(|| format!("Profile '{}' not found at {}", name, path.display()))?;
        let mut config: Self = serde_json::from_str(&json)
            .with_context(|| format!("Profile '{}' is corrupt JSON", name))?;
        config.workspace = folder.to_path_buf();
        Ok(config)
    }

    /// List all saved profile names under `folder`.
    pub fn list_profiles(folder: &Path) -> Result<Vec<String>, anyhow::Error> {
        let dir = Self::profiles_dir(folder);
        if !dir.exists() {
            return Ok(Vec::new());
        }
        let mut names: Vec<String> = Vec::new();
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "json")
                && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
            {
                names.push(stem.to_string());
            }
        }
        names.sort();
        Ok(names)
    }
}

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

    #[test]
    fn document_type_file_name() {
        let dt = DocumentType::Pdf(PathBuf::from("/tmp/paper.pdf"));
        assert_eq!(dt.file_name(), "paper.pdf");
        assert_eq!(dt.path(), &PathBuf::from("/tmp/paper.pdf"));
    }

    #[test]
    fn document_type_file_name_unknown() {
        let dt = DocumentType::Epub(PathBuf::from("/"));
        assert_eq!(dt.file_name(), "unknown");
    }

    #[test]
    fn paper_result_format_authors_short() {
        let p = PaperResult {
            title: "Test".into(),
            authors: vec!["Smith".into(), "Jones".into()],
            year: Some(2023),
            arxiv_id: None,
            doi: None,
            pdf_url: None,
        };
        assert_eq!(p.format_authors(), "Smith, Jones");
    }

    #[test]
    fn paper_result_format_authors_long() {
        let p = PaperResult {
            title: "Test".into(),
            authors: vec!["A".into(), "B".into(), "C".into(), "D".into()],
            year: None,
            arxiv_id: None,
            doi: None,
            pdf_url: None,
        };
        assert_eq!(p.format_authors(), "A, et al.");
    }

    #[test]
    fn paper_result_format_year() {
        let p = PaperResult {
            title: "Test".into(),
            authors: vec![],
            year: Some(2023),
            arxiv_id: None,
            doi: None,
            pdf_url: None,
        };
        assert_eq!(p.format_year(), " (2023)");
    }

    #[test]
    fn paper_result_format_year_none() {
        let p = PaperResult {
            title: "Test".into(),
            authors: vec![],
            year: None,
            arxiv_id: None,
            doi: None,
            pdf_url: None,
        };
        assert!(p.format_year().is_empty());
    }

    #[test]
    fn paper_result_best_pdf_url_direct() {
        let p = PaperResult {
            title: "Test".into(),
            authors: vec![],
            year: None,
            arxiv_id: None,
            doi: None,
            pdf_url: Some("https://example.com/paper.pdf".into()),
        };
        assert_eq!(p.best_pdf_url(), "https://example.com/paper.pdf");
    }

    #[test]
    fn paper_result_best_pdf_url_arxiv_fallback() {
        let p = PaperResult {
            title: "Test".into(),
            authors: vec![],
            year: None,
            arxiv_id: Some("2301.12345".into()),
            doi: None,
            pdf_url: None,
        };
        assert_eq!(p.best_pdf_url(), "https://arxiv.org/pdf/2301.12345.pdf");
    }

    #[test]
    fn paper_result_best_pdf_url_empty() {
        let p = PaperResult {
            title: "Test".into(),
            authors: vec![],
            year: None,
            arxiv_id: None,
            doi: None,
            pdf_url: None,
        };
        assert!(p.best_pdf_url().is_empty());
    }

    #[test]
    fn config_default_context_tokens() {
        let config = RagrigConfig::default();
        assert_eq!(config.chat.context_tokens, 4096);
    }

    #[test]
    fn config_default_chat_model() {
        let config = RagrigConfig::default();
        assert_eq!(config.chat.model, "qwen3.5:9b");
    }

    #[test]
    fn config_default_embed_model() {
        let config = RagrigConfig::default();
        assert_eq!(config.embed.model, "nomic-embed-text:latest");
        assert_eq!(config.embed.top_k, 50);
        assert_eq!(config.chat.request_timeout_secs, None);
        assert_eq!(config.embed.request_timeout_secs, None);
    }

    #[test]
    fn config_default_parse() {
        let config = RagrigConfig::default();
        assert_eq!(config.parse.chunk_size, 1024);
        assert_eq!(config.parse.chunk_overlap, 128);
        assert_eq!(config.parse.pdf_parser, PdfParserBackend::Extract);
        assert!(!config.parse.sloppy_pdf);
    }

    #[test]
    fn config_default_memory() {
        let config = RagrigConfig::default();
        assert_eq!(config.memory.model, "qwen2.5:1.5b");
        assert!(config.memory.rewrite_prompt_path.is_none());
    }

    #[test]
    fn config_custom_chat() {
        let config = RagrigConfig {
            chat: ChatConfig {
                model: "gemma4:e4b".into(),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(config.chat.model, "gemma4:e4b");
        assert_eq!(config.chat.context_tokens, 4096);
    }

    #[test]
    fn config_serde_roundtrip() {
        let config = RagrigConfig {
            workspace: "/tmp/docs".into(),
            chat: ChatConfig {
                provider: Provider::Deepseek,
                model: "deepseek-v4-pro".into(),
                deepseek_api_key: Some("sk-test".into()),
                context_tokens: 16384,
                ..Default::default()
            },
            ..Default::default()
        };
        let json = serde_json::to_string_pretty(&config).unwrap();
        let roundtripped: RagrigConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtripped.workspace, PathBuf::from("/tmp/docs"));
        assert_eq!(roundtripped.chat.provider, Provider::Deepseek);
        assert_eq!(roundtripped.chat.deepseek_api_key, Some("sk-test".into()));
        assert_eq!(roundtripped.chat.context_tokens, 16384);
        assert_eq!(roundtripped.embed.model, "nomic-embed-text:latest");
        assert_eq!(roundtripped.chat.request_timeout_secs, None);
        assert_eq!(roundtripped.embed.request_timeout_secs, None);
    }

    #[test]
    fn config_serde_accepts_legacy_folder_key() {
        // Profiles saved before the folder → workspace rename still load.
        let legacy = serde_json::to_string_pretty(&RagrigConfig::default())
            .unwrap()
            .replace("\"workspace\"", "\"folder\"");
        let config: RagrigConfig = serde_json::from_str(&legacy).unwrap();
        assert_eq!(config.workspace, default_workspace());
    }

    #[test]
    fn config_serde_fills_missing_fields_from_defaults() {
        // Hand-written profiles only mention what they change — the rest
        // comes from Default, both at the top level and inside sub-tables.
        let partial = r#"{
            "chat": {"context_tokens": 2048},
            "embed": {"model": "my-embed"},
            "parse": {"chunk_size": 512},
            "memory": {}
        }"#;
        let config: RagrigConfig = serde_json::from_str(partial).unwrap();
        assert_eq!(config.chat.context_tokens, 2048);
        assert_eq!(config.chat.model, ChatConfig::default().model);
        assert_eq!(config.embed.model, "my-embed");
        assert_eq!(config.embed.top_k, EmbedConfig::default().top_k);
        assert_eq!(config.parse.chunk_size, 512);
        assert_eq!(config.parse.pdf_parser, PdfParserBackend::Extract);
        assert_eq!(config.memory.model, MemoryConfig::default().model);

        // The sub-configs default the same way on their own.
        let chat: ChatConfig = serde_json::from_str(r#"{"model": "x"}"#).unwrap();
        assert_eq!(chat.model, "x");
        assert_eq!(chat.context_tokens, ChatConfig::default().context_tokens);
    }

    #[test]
    fn config_serde_accepts_lowercase_backend_names() {
        // Canonical spelling is lowercase, matching the CLI/spec layer.
        let cfg: RagrigConfig = serde_json::from_str(
            r#"{"chat":{"provider":"deepseek"},"embed":{"provider":"ollama"},"parse":{"pdf_parser":"unpdf"}}"#,
        )
        .unwrap();
        assert_eq!(cfg.chat.provider, Provider::Deepseek);
        assert_eq!(cfg.embed.provider, EmbeddingProvider::Ollama);
        assert_eq!(cfg.parse.pdf_parser, PdfParserBackend::Unpdf);

        // Legacy PascalCase spellings from old profiles still load.
        let legacy: RagrigConfig = serde_json::from_str(
            r#"{"chat":{"provider":"Ollama"},"parse":{"pdf_parser":"Extract"}}"#,
        )
        .unwrap();
        assert_eq!(legacy.chat.provider, Provider::Ollama);
        assert_eq!(legacy.parse.pdf_parser, PdfParserBackend::Extract);

        // Serialisation always emits the canonical lowercase spelling.
        let roundtrip = serde_json::to_string(&cfg).unwrap();
        assert!(roundtrip.contains("\"deepseek\""));
        assert!(!roundtrip.contains("\"Deepseek\""));
    }

    #[test]
    fn config_from_toml_and_json_helpers() {
        let toml_src = "[chat]\nmodel = \"gemma2:latest\"\n";
        let cfg = RagrigConfig::from_toml(toml_src).unwrap();
        assert_eq!(cfg.chat.model, "gemma2:latest");
        assert_eq!(cfg.embed.top_k, EmbedConfig::default().top_k);

        let json_src = r#"{"chat": {"context_tokens": 2048}}"#;
        let cfg = RagrigConfig::from_json(json_src).unwrap();
        assert_eq!(cfg.chat.context_tokens, 2048);
    }

    #[test]
    fn provenance_serde_defaults_missing_corpus() {
        // Records from stores built before document corpora existed lack
        // the `corpus` field — it must default to empty.
        let legacy = r#"{"parser":"unpdf","chunker":"markdown","embedder":"Ollama/x"}"#;
        let p: PipelineProvenance = serde_json::from_str(legacy).unwrap();
        assert_eq!(p.corpus, "");
        assert_eq!(p.parser, "unpdf");

        let with = PipelineProvenance::new_with_corpus("docs", "unpdf", "markdown", "Ollama/x");
        let roundtripped: PipelineProvenance =
            serde_json::from_str(&serde_json::to_string(&with).unwrap()).unwrap();
        assert_eq!(roundtripped.corpus, "docs");
    }

    #[test]
    fn provenance_serde_accepts_legacy_source_key() {
        // Stores written before the source → corpus rename still load.
        let legacy =
            r#"{"source":"docs","parser":"unpdf","chunker":"markdown","embedder":"Ollama/x"}"#;
        let p: PipelineProvenance = serde_json::from_str(legacy).unwrap();
        assert_eq!(p.corpus, "docs");
    }

    #[test]
    fn filter_serde_accepts_legacy_source_key() {
        let legacy = r#"{"source":"docs","chunker":"markdown"}"#;
        let f: PipelineFilter = serde_json::from_str(legacy).unwrap();
        assert_eq!(f.corpus, Some("docs".to_string()));
        assert_eq!(f.chunker, Some("markdown".to_string()));
    }

    #[test]
    fn pipeline_filter_matches_semantics() {
        // A provenance record with every field set, plus a legacy one whose
        // corpus is empty (records written before corpora were pluggable).
        let prov = PipelineProvenance::new_with_corpus("papers", "unpdf", "markdown", "Ollama/x");
        let legacy = PipelineProvenance::new("unpdf", "markdown", "Ollama/x");

        // An empty filter accepts any provenance, including legacy records.
        let any = PipelineFilter::any();
        assert!(any.is_empty());
        assert!(any.matches(&prov));
        assert!(any.matches(&legacy));

        // Corpus-only: exact name match required; an empty corpus is not
        // "any" when the filter names a corpus.
        assert!(PipelineFilter::for_corpus("papers").matches(&prov));
        assert!(!PipelineFilter::for_corpus("urls").matches(&prov));
        assert!(!PipelineFilter::for_corpus("papers").matches(&legacy));

        // Parser-only.
        assert!(PipelineFilter::for_parser("unpdf").matches(&prov));
        assert!(!PipelineFilter::for_parser("epub-parser").matches(&prov));

        // Chunker-only.
        assert!(PipelineFilter::for_chunker("markdown").matches(&prov));
        assert!(!PipelineFilter::for_chunker("chunkedrs-markdown").matches(&prov));

        // Embedder-only: exact `provider/model` string comparison — a prefix
        // or a different model must not match.
        assert!(PipelineFilter::for_embedder("Ollama/x").matches(&prov));
        assert!(!PipelineFilter::for_embedder("Ollama/y").matches(&prov));
        assert!(!PipelineFilter::for_embedder("Ollama").matches(&prov));

        // Combined corpus+chunker: every set field must match.
        let combined = PipelineFilter {
            corpus: Some("papers".into()),
            chunker: Some("markdown".into()),
            ..PipelineFilter::default()
        };
        assert!(combined.matches(&prov));
        let wrong_chunker = PipelineFilter {
            corpus: Some("papers".into()),
            chunker: Some("other".into()),
            ..PipelineFilter::default()
        };
        assert!(!wrong_chunker.matches(&prov));
        let wrong_corpus = PipelineFilter {
            corpus: Some("urls".into()),
            chunker: Some("markdown".into()),
            ..PipelineFilter::default()
        };
        assert!(!wrong_corpus.matches(&prov));

        // Pipeline id: exact match; a wildcard filter still accepts chunks
        // with or without a pipeline id.
        let tagged = PipelineProvenance::new_with_corpus_and_pipeline(
            "papers", "unpdf", "markdown", "Ollama/x", "pipe-a",
        );
        assert!(PipelineFilter::for_pipeline("pipe-a").matches(&tagged));
        assert!(!PipelineFilter::for_pipeline("pipe-b").matches(&tagged));
        assert!(!PipelineFilter::for_pipeline("pipe-a").matches(&prov));
        assert!(any.matches(&tagged));
    }

    #[test]
    fn config_serde_accepts_legacy_source_keys() {
        // Profiles saved before the source → corpus rename still load.
        let legacy = serde_json::to_string_pretty(&RagrigConfig::default())
            .unwrap()
            .replace("\"corpus_dirs\"", "\"source_dirs\"")
            .replace("\"corpus_urls\"", "\"source_urls\"");
        let config: RagrigConfig = serde_json::from_str(&legacy).unwrap();
        assert!(config.corpus_dirs.is_empty());
        assert!(config.corpus_urls.is_empty());

        let mut named: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&RagrigConfig::default()).unwrap())
                .unwrap();
        named.as_object_mut().unwrap().remove("corpus_dirs");
        named.as_object_mut().unwrap().remove("corpus_urls");
        named["source_dirs"] = serde_json::json!(["a=./x"]);
        named["source_urls"] = serde_json::json!(["b=https://e.com/f.pdf"]);
        let config: RagrigConfig = serde_json::from_value(named).unwrap();
        assert_eq!(config.corpus_dirs, vec!["a=./x"]);
        assert_eq!(config.corpus_urls, vec!["b=https://e.com/f.pdf"]);
    }

    #[test]
    fn corpus_config_serde_roundtrip() {
        // Named corpora are stored as `name=path` / `name=url` strings.
        let config = RagrigConfig {
            corpus_dirs: vec!["papers=/tmp/papers".to_string()],
            corpus_urls: vec!["urls=https://example.com/a.pdf".to_string()],
            ..Default::default()
        };
        let json = serde_json::to_string(&config).unwrap();
        let roundtripped: RagrigConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(
            roundtripped.corpus_dirs,
            vec!["papers=/tmp/papers".to_string()]
        );
        assert_eq!(
            roundtripped.corpus_urls,
            vec!["urls=https://example.com/a.pdf".to_string()]
        );
    }

    #[test]
    fn generation_params_default_all_none() {
        let p = GenerationParams::default();
        assert!(p.temperature.is_none());
        assert!(p.top_p.is_none());
        assert!(p.max_tokens.is_none());
        assert!(p.seed.is_none());
    }

    #[test]
    fn generation_params_with_values() {
        let p = GenerationParams {
            temperature: Some(0.1),
            top_p: Some(0.9),
            max_tokens: Some(2048),
            seed: Some(42),
        };
        assert_eq!(p.temperature, Some(0.1));
        assert_eq!(p.top_p, Some(0.9));
        assert_eq!(p.max_tokens, Some(2048));
        assert_eq!(p.seed, Some(42));
    }

    #[test]
    fn params_is_empty_when_all_none() {
        assert!(GenerationParams::default().is_empty());
    }

    #[test]
    fn params_is_not_empty_when_temperature_set() {
        let p = GenerationParams {
            temperature: Some(0.5),
            ..Default::default()
        };
        assert!(!p.is_empty());
    }

    #[test]
    fn params_is_not_empty_when_seed_set() {
        let p = GenerationParams {
            seed: Some(1),
            ..Default::default()
        };
        assert!(!p.is_empty());
    }

    #[test]
    fn additional_json_none_when_top_p_and_seed_absent() {
        let p = GenerationParams {
            temperature: Some(0.5),
            max_tokens: Some(100),
            ..Default::default()
        };
        assert!(p.additional_json().is_none());
    }

    #[test]
    fn additional_json_none_for_default_params() {
        assert!(GenerationParams::default().additional_json().is_none());
    }

    #[test]
    fn additional_json_includes_top_p_when_set() {
        let p = GenerationParams {
            top_p: Some(0.9),
            ..Default::default()
        };
        let json = p.additional_json().unwrap();
        assert_eq!(json["top_p"].as_f64(), Some(0.9));
        assert!(json.get("seed").is_none());
    }

    #[test]
    fn additional_json_includes_seed_when_set() {
        let p = GenerationParams {
            seed: Some(42),
            ..Default::default()
        };
        let json = p.additional_json().unwrap();
        assert_eq!(json["seed"].as_u64(), Some(42));
        assert!(json.get("top_p").is_none());
    }

    #[test]
    fn additional_json_includes_both_when_set() {
        let p = GenerationParams {
            top_p: Some(0.8),
            seed: Some(123),
            ..Default::default()
        };
        let json = p.additional_json().unwrap();
        assert_eq!(json["top_p"].as_f64(), Some(0.8));
        assert_eq!(json["seed"].as_u64(), Some(123));
    }

    #[test]
    fn additional_json_f64_precision_preserved() {
        // Regression: f64 → Number::from_f64 round-trip should preserve reasonable values.
        let p = GenerationParams {
            top_p: Some(0.95),
            ..Default::default()
        };
        let json = p.additional_json().unwrap();
        let returned = json["top_p"].as_f64().unwrap();
        assert!((returned - 0.95).abs() < 1e-10);
    }

    // ── override_with tests ────────────────────────────────────────────

    #[test]
    fn override_chat_applies_changed_fields() {
        let mut base = ChatConfig::default();
        let cli = ChatConfig {
            model: "gemma4:e4b".into(),
            context_tokens: 16384,
            ..Default::default()
        };
        let defaults = ChatConfig::default();
        base.override_with(&cli, &defaults);
        assert_eq!(base.model, "gemma4:e4b");
        assert_eq!(base.context_tokens, 16384);
        // Unchanged fields stay at base values.
        assert_eq!(base.provider, Provider::Ollama);
    }

    #[test]
    fn override_chat_ignores_default_values() {
        let mut base = ChatConfig {
            model: "custom-from-profile".into(),
            ..Default::default()
        };
        let cli = ChatConfig::default(); // all defaults — nothing explicitly set
        let defaults = ChatConfig::default();
        base.override_with(&cli, &defaults);
        // Profile value preserved because CLI didn't override it.
        assert_eq!(base.model, "custom-from-profile");
    }

    #[test]
    fn override_embed_applies_changed_fields() {
        let mut base = EmbedConfig::default();
        let cli = EmbedConfig {
            top_k: 10,
            similarity_threshold: 0.1,
            request_timeout_secs: Some(30),
            ..Default::default()
        };
        let defaults = EmbedConfig::default();
        base.override_with(&cli, &defaults);
        assert_eq!(base.top_k, 10);
        assert!((base.similarity_threshold - 0.1).abs() < f64::EPSILON);
        assert_eq!(base.model, "nomic-embed-text:latest"); // unchanged
        assert_eq!(base.request_timeout_secs, Some(30));
    }

    #[test]
    fn override_parse_applies_changed_fields() {
        let mut base = ParseConfig::default();
        let cli = ParseConfig {
            chunk_size: 512,
            pdf_parser: PdfParserBackend::Unpdf,
            ..Default::default()
        };
        let defaults = ParseConfig::default();
        base.override_with(&cli, &defaults);
        assert_eq!(base.chunk_size, 512);
        assert_eq!(base.pdf_parser, PdfParserBackend::Unpdf);
        assert_eq!(base.chunk_overlap, 128); // unchanged
        assert!(!base.sloppy_pdf); // unchanged
    }

    #[test]
    fn override_memory_applies_changed_fields() {
        let mut base = MemoryConfig::default();
        let cli = MemoryConfig {
            model: "llama3.2:3b".into(),
            rewrite_prompt_path: Some(PathBuf::from("/tmp/prompt.md")),
            strategy: MemoryStrategyKind::Summary,
        };
        let defaults = MemoryConfig::default();
        base.override_with(&cli, &defaults);
        assert_eq!(base.model, "llama3.2:3b");
        assert_eq!(
            base.rewrite_prompt_path,
            Some(PathBuf::from("/tmp/prompt.md"))
        );
        assert_eq!(base.strategy, MemoryStrategyKind::Summary);
    }

    /// A CLI config with default values leaves the base strategy untouched
    /// — a profile's strategy survives `--profile` + CLI merging.
    #[test]
    fn override_memory_default_strategy_leaves_profile_untouched() {
        let mut base = MemoryConfig {
            strategy: MemoryStrategyKind::Log,
            ..Default::default()
        };
        let cli = MemoryConfig::default();
        let defaults = MemoryConfig::default();
        base.override_with(&cli, &defaults);
        assert_eq!(base.strategy, MemoryStrategyKind::Log);
    }

    #[test]
    fn override_ragrig_config_top_level() {
        let mut base = RagrigConfig {
            workspace: PathBuf::from("/tmp/base"),
            chat: ChatConfig {
                model: "profile-model".into(),
                ..Default::default()
            },
            ..Default::default()
        };
        let cli = RagrigConfig {
            workspace: PathBuf::from("/tmp/cli"),
            chat: ChatConfig {
                model: "gemma4:e4b".into(),
                ..Default::default()
            },
            ..Default::default()
        };
        base.override_with(&cli);
        // Workspace always comes from CLI.
        assert_eq!(base.workspace, PathBuf::from("/tmp/cli"));
        // Chat model overridden because it differs from default.
        assert_eq!(base.chat.model, "gemma4:e4b");
        // Other fields left at profile values.
        assert_eq!(base.embed.model, "nomic-embed-text:latest");
        assert_eq!(base.chat.request_timeout_secs, None);
        assert_eq!(base.embed.request_timeout_secs, None);
    }

    #[test]
    fn override_with_corpus_merge_semantics() {
        // (a) Profile corpora survive when the CLI did not pass any corpora
        // (unlike workspace, corpora are optional on the CLI).
        let mut profile = RagrigConfig {
            corpus_dirs: vec!["papers=/srv/papers".to_string()],
            corpus_urls: vec!["refs=https://example.com/a.pdf".to_string()],
            ..Default::default()
        };
        profile.override_with(&RagrigConfig::default());
        assert_eq!(profile.corpus_dirs, vec!["papers=/srv/papers".to_string()]);
        assert_eq!(
            profile.corpus_urls,
            vec!["refs=https://example.com/a.pdf".to_string()]
        );

        // (b) Non-empty CLI corpus_dirs replace the profile's.
        let mut profile = RagrigConfig {
            corpus_dirs: vec!["papers=/srv/papers".to_string()],
            ..Default::default()
        };
        let cli = RagrigConfig {
            corpus_dirs: vec!["notes=/home/mart/notes".to_string()],
            ..Default::default()
        };
        profile.override_with(&cli);
        assert_eq!(
            profile.corpus_dirs,
            vec!["notes=/home/mart/notes".to_string()]
        );

        // (c) corpus_urls follows the same merge rules as corpus_dirs.
        let mut profile = RagrigConfig {
            corpus_urls: vec!["refs=https://example.com/a.pdf".to_string()],
            ..Default::default()
        };
        profile.override_with(&RagrigConfig::default()); // empty CLI → kept
        assert_eq!(
            profile.corpus_urls,
            vec!["refs=https://example.com/a.pdf".to_string()]
        );
        let cli = RagrigConfig {
            corpus_urls: vec!["sota=https://example.com/b.pdf".to_string()],
            ..Default::default()
        };
        profile.override_with(&cli); // non-empty CLI → replaced
        assert_eq!(
            profile.corpus_urls,
            vec!["sota=https://example.com/b.pdf".to_string()]
        );
    }

    #[test]
    fn override_params_temperature_applied() {
        let mut base = ChatConfig::default();
        let cli = ChatConfig {
            params: GenerationParams {
                temperature: Some(0.1),
                ..Default::default()
            },
            ..Default::default()
        };
        let defaults = ChatConfig::default();
        base.override_with(&cli, &defaults);
        assert_eq!(base.params.temperature, Some(0.1));
        assert!(base.params.top_p.is_none());
        assert!(base.params.max_tokens.is_none());
    }

    // ── Profile I/O tests ────────────────────────────────────────────

    #[test]
    fn profile_save_and_load_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        let folder = tmp.path().to_path_buf();

        let config = RagrigConfig {
            workspace: folder.clone(),
            chat: ChatConfig {
                model: "gemma4:e4b".into(),
                context_tokens: 16384,
                params: GenerationParams {
                    temperature: Some(0.1),
                    ..Default::default()
                },
                ..Default::default()
            },
            embed: EmbedConfig {
                top_k: 10,
                request_timeout_secs: Some(60),
                ..Default::default()
            },
            ..Default::default()
        };

        config.save_to_profile(&folder, "test-roundtrip").unwrap();
        let loaded = RagrigConfig::load_from_profile(&folder, "test-roundtrip").unwrap();

        assert_eq!(loaded.chat.model, "gemma4:e4b");
        assert_eq!(loaded.chat.context_tokens, 16384);
        assert_eq!(loaded.chat.params.temperature, Some(0.1));
        assert_eq!(loaded.embed.top_k, 10);
        // Defaults preserved
        assert_eq!(loaded.embed.model, "nomic-embed-text:latest");
        assert_eq!(loaded.embed.request_timeout_secs, Some(60));
        assert_eq!(loaded.chat.request_timeout_secs, None);
    }

    #[test]
    fn profile_list_finds_saved_profiles() {
        let tmp = tempfile::tempdir().unwrap();
        let folder = tmp.path().to_path_buf();

        let config = RagrigConfig {
            workspace: folder.clone(),
            ..Default::default()
        };
        config.save_to_profile(&folder, "alpha").unwrap();
        config.save_to_profile(&folder, "beta").unwrap();

        let names = RagrigConfig::list_profiles(&folder).unwrap();
        assert_eq!(names, vec!["alpha", "beta"]);
    }

    #[test]
    fn profile_list_empty_when_no_profiles() {
        let tmp = tempfile::tempdir().unwrap();
        let names = RagrigConfig::list_profiles(tmp.path()).unwrap();
        assert!(names.is_empty());
    }

    #[test]
    fn profile_load_nonexistent_is_error() {
        let tmp = tempfile::tempdir().unwrap();
        let result = RagrigConfig::load_from_profile(tmp.path(), "nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn profile_json_is_valid_utf8() {
        let tmp = tempfile::tempdir().unwrap();
        let folder = tmp.path().to_path_buf();

        let config = RagrigConfig {
            workspace: folder.clone(),
            ..Default::default()
        };
        config.save_to_profile(&folder, "utf8").unwrap();

        let path = RagrigConfig::profiles_dir(&folder).join("utf8.json");
        let json = std::fs::read_to_string(&path).unwrap();
        // Should be valid UTF-8 JSON and parse back.
        let _parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    }

    /// Profiles are portable: the machine-specific workspace never reaches
    /// the file, even when the in-memory config points elsewhere.
    #[test]
    fn profile_save_strips_workspace() {
        let tmp = tempfile::tempdir().unwrap();
        let folder = tmp.path().to_path_buf();

        let config = RagrigConfig {
            workspace: PathBuf::from("/some/foreign/machine/path"),
            ..Default::default()
        };
        config.save_to_profile(&folder, "portable").unwrap();

        let path = RagrigConfig::profiles_dir(&folder).join("portable.json");
        let json = std::fs::read_to_string(&path).unwrap();
        assert!(
            !json.contains("workspace"),
            "saved profile must not contain a workspace, got: {json}"
        );

        let loaded = RagrigConfig::load_from_profile(&folder, "portable").unwrap();
        assert_eq!(loaded.workspace, folder);
    }

    /// A legacy profile with a foreign workspace baked in loads with the
    /// caller's folder — never the stale path from another machine.
    #[test]
    fn profile_load_ignores_foreign_workspace() {
        let tmp = tempfile::tempdir().unwrap();
        let folder = tmp.path().to_path_buf();

        let legacy = serde_json::json!({
            "workspace": "/home/someone-else/project",
            "chat": { "model": "legacy-model" }
        });
        let dir = RagrigConfig::profiles_dir(&folder);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("legacy.json"), legacy.to_string()).unwrap();

        let loaded = RagrigConfig::load_from_profile(&folder, "legacy").unwrap();
        assert_eq!(loaded.workspace, folder);
        assert_eq!(loaded.chat.model, "legacy-model");
    }

    /// The memory strategy is part of the profile round-trip.
    #[test]
    fn profile_roundtrip_preserves_memory_strategy() {
        let tmp = tempfile::tempdir().unwrap();
        let folder = tmp.path().to_path_buf();

        let config = RagrigConfig {
            workspace: folder.clone(),
            memory: MemoryConfig {
                model: "qwen2.5:1.5b".into(),
                strategy: MemoryStrategyKind::Summary,
                ..Default::default()
            },
            ..Default::default()
        };
        config.save_to_profile(&folder, "summary").unwrap();

        let loaded = RagrigConfig::load_from_profile(&folder, "summary").unwrap();
        assert_eq!(loaded.memory.strategy, MemoryStrategyKind::Summary);
        assert_eq!(loaded.memory.model, "qwen2.5:1.5b");
    }

    /// Profiles without a memory strategy (older versions, hand-written
    /// files) fall back to the rewrite default.
    #[test]
    fn memory_strategy_defaults_to_rewrite_on_partial_profile() {
        let partial = r#"{ "memory": { "model": "my-memory-model" } }"#;
        let config: RagrigConfig = serde_json::from_str(partial).unwrap();
        assert_eq!(config.memory.model, "my-memory-model");
        assert_eq!(config.memory.strategy, MemoryStrategyKind::Rewrite);
    }

    /// The strategy serialises lowercase and round-trips every variant.
    #[test]
    fn memory_strategy_serde_lowercase_roundtrip() {
        for (kind, name) in [
            (MemoryStrategyKind::Rewrite, "rewrite"),
            (MemoryStrategyKind::Transcript, "transcript"),
            (MemoryStrategyKind::Log, "log"),
            (MemoryStrategyKind::Summary, "summary"),
            (MemoryStrategyKind::Off, "off"),
        ] {
            let json = serde_json::to_string(&kind).unwrap();
            assert_eq!(json, format!("\"{name}\""));
            let back: MemoryStrategyKind = serde_json::from_str(&json).unwrap();
            assert_eq!(back, kind);
        }
    }

    // ── ChunkConfig validation ───────────────────────────────────────

    #[test]
    fn chunk_config_default_is_valid() {
        ChunkConfig::default().validate().unwrap();
    }

    #[test]
    fn chunk_config_new_valid() {
        ChunkConfig::new(512, 64).unwrap();
    }

    #[test]
    fn chunk_config_size_zero_is_invalid() {
        assert!(ChunkConfig::new(0, 0).is_err());
        let cfg = ChunkConfig {
            size: 0,
            overlap: 0,
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn chunk_config_overlap_equals_size_is_invalid() {
        assert!(ChunkConfig::new(100, 100).is_err());
        let cfg = ChunkConfig {
            size: 100,
            overlap: 100,
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn chunk_config_overlap_exceeds_size_is_invalid() {
        assert!(ChunkConfig::new(100, 500).is_err());
        let cfg = ChunkConfig {
            size: 100,
            overlap: 500,
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn chunk_config_zero_overlap_is_valid() {
        ChunkConfig::new(100, 0).unwrap();
    }
}