hallouminate 0.2.2

A markdown corpus indexer for LLMs to build and query their own per-repo wikis.
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
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::domain::common::{CorpusConfig, HallouminateError, Result};
use crate::domain::discovery::{DEFAULT_MAX_DEPTH, IgnoreRules, discover_wiki_roots};
use crate::domain::embeddings::{DEFAULT_EMBED_MODEL, canonical_model_name};
use crate::domain::repository::{
    RepositoryConfig, effective_corpora, repository_for_discovered_wiki,
    union_discovered_repositories,
};

const DEFAULT_TOP_FILES: usize = 10;
const DEFAULT_CHUNKS_PER_FILE: usize = 3;
const DEFAULT_DEBOUNCE_MS: u64 = 500;
const DEFAULT_EMBED_CACHE: &str = "~/.cache/hallouminate/fastembed";
const DEFAULT_GROUND_DIR: &str = "~/.local/share/hallouminate/ground";

/// Search and ranking defaults applied when a query does not override them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchConfig {
    /// Number of files returned per query by default (default `10`).
    #[serde(default = "default_top_files")]
    pub top_files_default: usize,
    /// Number of chunks shown per file by default (default `3`).
    #[serde(default = "default_chunks_per_file")]
    pub chunks_per_file_default: usize,
    /// Crossencoder model identifier (e.g. `"jina-reranker-v1-turbo-en"`).
    /// `None` (the default) disables the rerank step entirely; the
    /// FTS+vector+rg fusion result is returned as-is. Names map to
    /// `domain::search::crossencoder::canonical_crossencoder_model`.
    #[serde(default)]
    pub crossencoder: Option<String>,
}

impl Default for SearchConfig {
    fn default() -> Self {
        Self {
            top_files_default: DEFAULT_TOP_FILES,
            chunks_per_file_default: DEFAULT_CHUNKS_PER_FILE,
            crossencoder: None,
        }
    }
}

/// Dense-embedding settings: which model to load, whether to load one at all,
/// and where to cache it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmbeddingsConfig {
    /// Switch for dense embeddings. On by default: hallouminate downloads the
    /// embedding model on first use and fuses the dense (vector) signal into
    /// retrieval. Set `false` to run a lexical-only path (FTS + ripgrep +
    /// rerank) that loads no embedding model — only the tokenizer needed for
    /// chunking.
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    /// Embedding model identifier (default Snowflake Arctic-S). Legacy aliases
    /// are normalized to a canonical name at load time; unknown names are
    /// rejected before any download.
    #[serde(default = "default_model")]
    pub model: String,
    /// Select the fastembed `*Q` quantized variant of `model` when one
    /// exists. Errors at load time for models with no quantized ONNX
    /// (multilingual-e5-small).
    #[serde(default)]
    pub quantized: bool,
    /// Directory where fastembed caches downloaded model files
    /// (default `~/.cache/hallouminate/fastembed`).
    #[serde(default = "default_embed_cache")]
    pub cache_dir: String,
    /// Seconds of embed-call inactivity before the ORT session (and its
    /// `BFCArena` memory) is dropped. The session is lazy-reloaded on the
    /// next embed request, paying the model-load cost again (~4 s cold).
    /// `0` disables eviction — the arena is never released while the daemon
    /// lives. Due to sleep-then-check timing the actual eviction lag is
    /// `[idle_evict_secs, 2×idle_evict_secs]` from the last embed call.
    /// Default: `300` (5 minutes).
    #[serde(default = "default_idle_evict_secs")]
    pub idle_evict_secs: u64,
}

impl Default for EmbeddingsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            model: DEFAULT_EMBED_MODEL.into(),
            quantized: false,
            cache_dir: DEFAULT_EMBED_CACHE.into(),
            idle_evict_secs: default_idle_evict_secs(),
        }
    }
}

/// File-watcher settings for incremental re-indexing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WatchConfig {
    /// Milliseconds to wait after the last filesystem event before re-indexing,
    /// coalescing bursts of changes (default `500`).
    #[serde(default = "default_debounce_ms")]
    pub debounce_ms: u64,
}

impl Default for WatchConfig {
    fn default() -> Self {
        Self {
            debounce_ms: DEFAULT_DEBOUNCE_MS,
        }
    }
}

/// On-disk storage locations for hallouminate's persistent state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StorageConfig {
    /// Directory holding the ground (markdown wiki) store
    /// (default `~/.local/share/hallouminate/ground`).
    #[serde(default = "default_ground_dir")]
    pub ground_dir: String,
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            ground_dir: DEFAULT_GROUND_DIR.into(),
        }
    }
}

/// The fully-resolved hallouminate configuration.
///
/// Assembled by merging the XDG baseline layer with the discovered per-repo
/// layer; every nested section falls back to its `Default` when omitted, so an
/// empty config decodes to a fully-defaulted `Config`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Config {
    /// User-defined corpora, declared as `[[corpus]]` entries.
    #[serde(rename = "corpus", default)]
    pub corpora: Vec<CorpusConfig>,
    /// Indexed code repositories, declared as `[[repository]]` entries.
    // Accept the legacy `[[code_repo]]` plural too so configs written
    // before the rename (PR #21) keep loading instead of silently dropping
    // every repository entry. `config validate` still warns on the legacy
    // key so users have a clear nudge to migrate.
    #[serde(rename = "repository", alias = "code_repo", default)]
    pub repositories: Vec<RepositoryConfig>,
    /// Search and ranking defaults.
    #[serde(default)]
    pub search: SearchConfig,
    /// Dense-embedding settings.
    #[serde(default)]
    pub embeddings: EmbeddingsConfig,
    /// File-watcher settings.
    #[serde(default)]
    pub watch: WatchConfig,
    /// On-disk storage locations.
    #[serde(default)]
    pub storage: StorageConfig,
}

impl Config {
    /// All corpora visible to the daemon: explicit `[[corpus]]` entries plus
    /// `repo:{name}:wiki` / `repo:{name}:corpus` derived from
    /// `[[repository]]` entries. Fails on duplicate final names so a
    /// `[[corpus]]` cannot shadow a derived repository corpus.
    pub fn effective_corpora(&self) -> Result<Vec<CorpusConfig>> {
        effective_corpora(&self.corpora, &self.repositories)
    }
}

/// Per-request diagnostic struct used by `config validate` / `config show`.
///
/// `xdg_path` is `None` when the baseline came from `--config PATH`; otherwise
/// it carries the XDG location actually consulted (even if the file was
/// absent — `load_xdg` defaults silently on `NotFound`). `repo_path` is
/// `None` when discovery reached the filesystem root with no `.git` boundary
/// and `resolve_for_cwd` resolved baseline-only (issue #102); otherwise it
/// carries the discovered repo config.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ResolvedLayers {
    pub xdg_path: Option<PathBuf>,
    pub repo_path: Option<PathBuf>,
    /// Non-fatal advisories raised while resolving corpora — currently only
    /// the cross-repo union (#106) name-collision warning, when a
    /// walk-discovered sub-repo wiki shadows a baseline `[[repository]]` of
    /// the same derived corpus name. `handle_ground` surfaces these on the
    /// `GroundResponse.warnings` list. Empty in the common case.
    pub warnings: Vec<String>,
}

/// Load the XDG baseline (or `--config PATH`).
///
/// A confirmed `NotFound` on the resolved path degrades to `Config::default()`
/// so a fresh install boots without a config file. Other io errors propagate.
pub fn load_xdg(path: Option<&Path>) -> Result<Config> {
    let resolved = match path {
        Some(p) => p.to_path_buf(),
        None => xdg_config_path(),
    };
    // Only treat a confirmed `NotFound` as "no config file, use defaults".
    // Other io errors (permission denied, broken symlink, unreadable dir)
    // must propagate so the user isn't silently dropped to an empty
    // configuration when the actual problem is filesystem state.
    let text = match std::fs::read_to_string(&resolved) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Ok(Config::default());
        }
        Err(e) => return Err(HallouminateError::from(e)),
    };
    parse(&text, Some(&resolved))
}

/// Backwards-compatible alias for `load_xdg`. Callers outside this module
/// (CLI subcommands, the daemon entry point) still use `config::load`, so
/// the alias stays until those call sites migrate.
pub fn load(path: Option<&Path>) -> Result<Config> {
    load_xdg(path)
}

/// Walk from `cwd` up looking for `.hallouminate/config.toml`.
///
/// First-match-wins; never composes multiple repo configs. Three outcomes:
///   - found a config → `Ok(Some(path))`.
///   - hit a `.git` entry (file *or* directory — git worktrees use a file)
///     with no config in between → `Err`. Inside a repo, the daemon refuses
///     to fall back to baseline-only; explicit repo config is required.
///   - reached the filesystem root without ever hitting a `.git` boundary →
///     `Ok(None)`. There is no repo context to be strict about, so callers
///     degrade to baseline-only instead of failing (issue #102).
///
/// Relative `cwd` is normalized to an absolute path against the process'
/// `current_dir()` before walking, so `Path::parent()` walks reliably reach
/// the real filesystem root (a relative path bottoms out at the empty
/// component instead, producing a misleading "reached filesystem root"
/// error).
pub fn discover_repo_config(cwd: &Path) -> Result<Option<PathBuf>> {
    let absolute_cwd = if cwd.is_absolute() {
        cwd.to_path_buf()
    } else {
        let here = std::env::current_dir().map_err(HallouminateError::from)?;
        absolutize_cwd(cwd, &here)
    };
    let mut current: Option<&Path> = Some(&absolute_cwd);
    while let Some(level) = current {
        let candidate = level.join(".hallouminate").join("config.toml");
        // `is_file` returns false on io errors (permission denied, broken
        // symlink), which is the right call here — we want to continue
        // walking instead of erroring out partway up the tree.
        if candidate.is_file() {
            return Ok(Some(candidate));
        }
        let git_marker = level.join(".git");
        if git_marker.is_dir() {
            // Normal clone: `.git` directory is the hard repo-root boundary.
            return Err(HallouminateError::Config(format!(
                "no .hallouminate/config.toml found walking up from {} \
                 (stopped at repo root {})",
                cwd.display(),
                level.display(),
            )));
        }
        if git_marker.is_file() {
            // `.git` file: either a linked worktree or a submodule.
            // Only linked worktrees have a gitdir pointer containing `/worktrees/`;
            // for those, hop to the main checkout and continue searching there.
            // Submodule pointers (containing `/modules/`) fall through to the
            // hard-error below so they never inherit the superproject's config.
            if let Some(main_root) = worktree_main_root(&git_marker) {
                return discover_repo_config_from(cwd, &main_root);
            }
            return Err(HallouminateError::Config(format!(
                "no .hallouminate/config.toml found walking up from {} \
                 (stopped at repo root {})",
                cwd.display(),
                level.display(),
            )));
        }
        current = level.parent();
    }
    // Reached the filesystem root without a `.git` boundary: no repo context
    // at all. Soft-fall-back to baseline-only rather than stranding the
    // baseline-declared corpora (issue #102).
    Ok(None)
}

/// Normalize a relative `cwd` to an absolute path by joining it against `base`
/// (the process `current_dir()` in production). Pulled out of
/// `discover_repo_config` so the join can be asserted hermetically against a
/// controlled base, without depending on the process' real working directory
/// (which, when the test runs inside a repo that ships its own
/// `.hallouminate/config.toml`, would make the discovery walk find that config
/// instead of exercising the normalization).
fn absolutize_cwd(cwd: &Path, base: &Path) -> PathBuf {
    base.join(cwd)
}

/// If `git_file` is a linked-worktree `.git` file (i.e. its `gitdir:` pointer
/// contains a `/.git/worktrees/` segment), return the main checkout root.
///
/// The pointer looks like `<common-gitdir>/worktrees/<name>`; stripping
/// `worktrees/<name>` gives `<common-gitdir>` (e.g. `/repo/.git`), and the
/// main checkout root is its parent (`/repo`).
///
/// Relative pointers (written by `git worktree add --relative-paths` or when
/// `extensions.relativeWorktrees = true`) are resolved against the worktree
/// root (the parent directory of the `.git` FILE) before stripping.
///
/// Returns `None` for submodule pointers (`/modules/` but no `.git/worktrees/`
/// structural segment) or any file that can't be parsed, so callers treat
/// those as a hard stop.
fn worktree_main_root(git_file: &Path) -> Option<PathBuf> {
    let content = std::fs::read_to_string(git_file).ok()?;
    let gitdir_line = content.lines().find(|l| l.starts_with("gitdir:"))?;
    let ptr = gitdir_line.trim_start_matches("gitdir:").trim();
    let ptr_path = Path::new(ptr);
    // Resolve relative pointers against the worktree root (the directory that
    // contains the `.git` FILE) so that `--relative-paths` worktrees work the
    // same as those written with absolute pointers.
    let resolved: PathBuf = if ptr_path.is_relative() {
        let wt_root = git_file.parent()?;
        wt_root.join(ptr_path)
    } else {
        ptr_path.to_path_buf()
    };
    // Only hop for worktree pointers; submodule pointers must not inherit the
    // superproject config (issue #132 guard).
    //
    // Structural guard: require the `worktrees` component to be IMMEDIATELY
    // preceded by a `.git` component so a superproject directory literally
    // named "worktrees" (e.g. `gitdir: /home/me/worktrees/.git/modules/sub`)
    // is not mistaken for a linked-worktree pointer.
    let components: Vec<_> = resolved.components().collect();
    let worktrees_pos = components
        .windows(2)
        .position(|w| w[0].as_os_str() == ".git" && w[1].as_os_str() == "worktrees")
        .map(|i| i + 1)?; // position of the `worktrees` component itself
    // Strip `worktrees/<name>` to get the common gitdir, then take its parent.
    let common_gitdir = components[..worktrees_pos].iter().collect::<PathBuf>();
    common_gitdir.parent().map(|p| p.to_path_buf())
}

/// Walk upward from `start` looking for `.hallouminate/config.toml`, treating
/// any `.git` marker (file or directory) as the hard repo-root boundary. Used after a worktree
/// hop so that the original `cwd` still appears in any error message.
fn discover_repo_config_from(cwd: &Path, start: &Path) -> Result<Option<PathBuf>> {
    let mut current: Option<&Path> = Some(start);
    while let Some(level) = current {
        let candidate = level.join(".hallouminate").join("config.toml");
        if candidate.is_file() {
            return Ok(Some(candidate));
        }
        let git_marker = level.join(".git");
        if git_marker.exists() {
            return Err(HallouminateError::Config(format!(
                "no .hallouminate/config.toml found walking up from {} \
                 (stopped at repo root {})",
                cwd.display(),
                level.display(),
            )));
        }
        current = level.parent();
    }
    Ok(None)
}
/// Parse a repo-layer TOML file, resolving relative paths against the
/// **repo root** (the parent of `.hallouminate/`, i.e. the directory the
/// user would `cd` into when working on the repo).
///
/// Same schema as `load_xdg`. Differences:
///   - `[[repository]].path`, `[[repository]].corpus_paths[*]`,
///     `[[corpus]].paths[*]`, `[storage].ground_dir`, and
///     `[embeddings].cache_dir` get resolved against the repo root and
///     stored as absolute strings. Resolving against the repo root (not the
///     `.hallouminate/` directory) matches user intuition — writing
///     `paths = ["docs"]` in `.hallouminate/config.toml` means
///     `<repo>/docs`, and `[[repository]] path = "."` means the repo root
///     itself (so `wiki_directory` lands at `<repo>/.hallouminate/wiki`,
///     not `<repo>/.hallouminate/.hallouminate/wiki`).
///   - Absolute paths and `~`-prefixed paths pass through untouched —
///     tilde expansion happens at consumption time via `expand_tilde`,
///     identical to the XDG layer's behavior today.
///   - The same `validate()` rules apply (post-resolution).
pub fn load_repo_layer(config_path: &Path) -> Result<Config> {
    let text = std::fs::read_to_string(config_path).map_err(HallouminateError::from)?;
    let mut cfg: Config = toml::from_str(&text).map_err(|e| {
        HallouminateError::Config(format!("parsing config at {}: {e}", config_path.display()))
    })?;
    // Resolve against the parent of `.hallouminate/`, i.e. the repo root.
    // `discover_repo_config` only returns paths ending in
    // `<repo_root>/.hallouminate/config.toml`, so two `parent()` hops are
    // always defined for paths produced by discovery. For programmatic
    // callers that hand us a flatter path we fall back to a single hop
    // rather than panic.
    let hallouminate_dir = config_path.parent().ok_or_else(|| {
        HallouminateError::Config(format!(
            "repo config path has no parent directory: {}",
            config_path.display(),
        ))
    })?;
    let repo_root = hallouminate_dir.parent().unwrap_or(hallouminate_dir);
    resolve_repo_layer_paths(&mut cfg, repo_root);
    normalize(&mut cfg)?;
    validate(&cfg)?;
    Ok(cfg)
}

/// Merge a baseline `Config` with a repo-layer `Config`.
///
/// List sections (`corpora`, `repositories`) are appended baseline-first
/// then repo-layer; cross-layer name collisions surface via
/// `effective_corpora`'s duplicate-name detection on the combined list.
///
/// Scalar sections (`search`, `embeddings`, `watch`, `storage`) merge field
/// by field. "Explicitly set" is determined by comparison against
/// `Config::default()` — the practical "sentinel" form sanctioned by the
/// spec, since `&Config` carries no per-field provenance. The single
/// consequence is that a layer that explicitly re-states the default cannot
/// trigger a conflict against an *other* layer holding the default; both
/// resolve to the default anyway, so behavior is unchanged.
pub fn merge_layers(baseline: &Config, repo: &Config) -> Result<Config> {
    merge_layers_with_sources(baseline, repo, None, None)
}

/// Variant of `merge_layers` that names source paths in conflict messages.
/// Internal helper so `resolve_for_cwd` can produce richer diagnostics
/// without inflating the public API surface.
fn merge_layers_with_sources(
    baseline: &Config,
    repo: &Config,
    baseline_path: Option<&Path>,
    repo_path: Option<&Path>,
) -> Result<Config> {
    let defaults = Config::default();
    let mut corpora = baseline.corpora.clone();
    corpora.extend(repo.corpora.iter().cloned());
    let mut repositories = baseline.repositories.clone();
    repositories.extend(repo.repositories.iter().cloned());

    let search = SearchConfig {
        top_files_default: merge_scalar(
            "search.top_files_default",
            baseline.search.top_files_default,
            repo.search.top_files_default,
            defaults.search.top_files_default,
            baseline_path,
            repo_path,
        )?,
        chunks_per_file_default: merge_scalar(
            "search.chunks_per_file_default",
            baseline.search.chunks_per_file_default,
            repo.search.chunks_per_file_default,
            defaults.search.chunks_per_file_default,
            baseline_path,
            repo_path,
        )?,
        crossencoder: merge_scalar(
            "search.crossencoder",
            baseline.search.crossencoder.clone(),
            repo.search.crossencoder.clone(),
            defaults.search.crossencoder.clone(),
            baseline_path,
            repo_path,
        )?,
    };
    let embeddings = EmbeddingsConfig {
        enabled: merge_scalar(
            "embeddings.enabled",
            baseline.embeddings.enabled,
            repo.embeddings.enabled,
            defaults.embeddings.enabled,
            baseline_path,
            repo_path,
        )?,
        model: merge_scalar(
            "embeddings.model",
            baseline.embeddings.model.clone(),
            repo.embeddings.model.clone(),
            defaults.embeddings.model.clone(),
            baseline_path,
            repo_path,
        )?,
        quantized: merge_scalar(
            "embeddings.quantized",
            baseline.embeddings.quantized,
            repo.embeddings.quantized,
            defaults.embeddings.quantized,
            baseline_path,
            repo_path,
        )?,
        cache_dir: merge_scalar(
            "embeddings.cache_dir",
            baseline.embeddings.cache_dir.clone(),
            repo.embeddings.cache_dir.clone(),
            defaults.embeddings.cache_dir.clone(),
            baseline_path,
            repo_path,
        )?,
        idle_evict_secs: merge_scalar(
            "embeddings.idle_evict_secs",
            baseline.embeddings.idle_evict_secs,
            repo.embeddings.idle_evict_secs,
            defaults.embeddings.idle_evict_secs,
            baseline_path,
            repo_path,
        )?,
    };
    let watch = WatchConfig {
        debounce_ms: merge_scalar(
            "watch.debounce_ms",
            baseline.watch.debounce_ms,
            repo.watch.debounce_ms,
            defaults.watch.debounce_ms,
            baseline_path,
            repo_path,
        )?,
    };
    let storage = StorageConfig {
        ground_dir: merge_scalar(
            "storage.ground_dir",
            baseline.storage.ground_dir.clone(),
            repo.storage.ground_dir.clone(),
            defaults.storage.ground_dir.clone(),
            baseline_path,
            repo_path,
        )?,
    };

    let merged = Config {
        corpora,
        repositories,
        search,
        embeddings,
        watch,
        storage,
    };
    // Re-run cross-layer validation on the combined lists; the inner
    // `effective_corpora` call covers duplicate-name detection across
    // baseline and repo entries.
    validate(&merged)?;
    Ok(merged)
}

/// Per-request top-level: discover the repo config under `cwd`, load it,
/// and merge with the supplied `baseline`. `xdg_path` is the location the
/// baseline came from (`None` when the caller used `--config PATH`); it
/// only feeds the returned `ResolvedLayers` diagnostic and the conflict
/// messages in `merge_layers`.
pub fn resolve_for_cwd(
    baseline: &Config,
    cwd: &Path,
    xdg_path: Option<&Path>,
) -> Result<(Config, ResolvedLayers)> {
    // No `.git` boundary anywhere up the walk: there is no repo context to
    // merge, so resolve baseline-only instead of erroring. This keeps the
    // baseline-declared corpora reachable from a parent-of-repos directory
    // (issue #102). A `.git` boundary with no config still errors via `?`.
    let Some(repo_path) = discover_repo_config(cwd)? else {
        // Baseline-only mode: cwd sits above all repos. Walk downward for
        // sub-repo wikis and union them with the baseline `[[repository]]`
        // entries (#106) so a `cd ~/Dev && ground "..."` searches every
        // repo's wiki at once, not just baseline-registered ones.
        let mut baseline_only = baseline.clone();
        let discovered: Vec<RepositoryConfig> =
            discover_wiki_roots(cwd, DEFAULT_MAX_DEPTH, &IgnoreRules::default())
                .into_iter()
                .filter_map(|w| repository_for_discovered_wiki(&w.repo_root))
                .collect();
        let (repositories, warnings) =
            union_discovered_repositories(&baseline_only.repositories, discovered);
        baseline_only.repositories = repositories;
        validate(&baseline_only)?;
        return Ok((
            baseline_only,
            ResolvedLayers {
                xdg_path: xdg_path.map(Path::to_path_buf),
                repo_path: None,
                warnings,
            },
        ));
    };
    let repo = load_repo_layer(&repo_path)?;
    let effective = merge_layers_with_sources(baseline, &repo, xdg_path, Some(&repo_path))?;
    Ok((
        effective,
        ResolvedLayers {
            xdg_path: xdg_path.map(Path::to_path_buf),
            repo_path: Some(repo_path),
            warnings: Vec::new(),
        },
    ))
}

fn merge_scalar<T>(
    field: &str,
    baseline: T,
    repo: T,
    default: T,
    baseline_path: Option<&Path>,
    repo_path: Option<&Path>,
) -> Result<T>
where
    T: PartialEq + std::fmt::Debug,
{
    let baseline_set = baseline != default;
    let repo_set = repo != default;
    match (baseline_set, repo_set) {
        (false, false) => Ok(default),
        (true, false) => Ok(baseline),
        (false, true) => Ok(repo),
        (true, true) => {
            if baseline == repo {
                Ok(baseline)
            } else {
                let baseline_src = baseline_path
                    .map(|p| format!(" (baseline at {})", p.display()))
                    .unwrap_or_else(|| " (baseline)".into());
                let repo_src = repo_path
                    .map(|p| format!(" (repo at {})", p.display()))
                    .unwrap_or_else(|| " (repo layer)".into());
                Err(HallouminateError::Config(format!(
                    "scalar conflict on {field}: baseline = {baseline:?}{baseline_src}, \
                     repo = {repo:?}{repo_src}"
                )))
            }
        }
    }
}

/// Rewrite every relative non-tilde path in `cfg` as `base.join(path)`.
/// `.` / `..` segments are preserved as written — `Path::join` does not
/// normalize, and we don't post-process via `Path::components` because
/// canonicalization would require the path to exist on disk. Absolute
/// paths and `~`-prefixed paths are left alone.
fn resolve_repo_layer_paths(cfg: &mut Config, base: &Path) {
    for corpus in cfg.corpora.iter_mut() {
        for p in corpus.paths.iter_mut() {
            *p = resolve_repo_path(p, base);
        }
    }
    for repo in cfg.repositories.iter_mut() {
        repo.path = resolve_repo_path(&repo.path, base);
        for p in repo.corpus_paths.iter_mut() {
            *p = resolve_repo_path(p, base);
        }
    }
    cfg.storage.ground_dir = resolve_repo_path(&cfg.storage.ground_dir, base);
    cfg.embeddings.cache_dir = resolve_repo_path(&cfg.embeddings.cache_dir, base);
}

fn resolve_repo_path(raw: &str, base: &Path) -> String {
    if raw.is_empty() {
        return raw.to_string();
    }
    if raw.starts_with('~') {
        return raw.to_string();
    }
    let candidate = Path::new(raw);
    if candidate.is_absolute() {
        return raw.to_string();
    }
    base.join(candidate).to_string_lossy().into_owned()
}

pub fn xdg_config_path() -> PathBuf {
    crate::app::xdg::xdg_path(
        "XDG_CONFIG_HOME",
        "~/.config",
        &["hallouminate", "config.toml"],
    )
}

/// Pure resolver kept as a thin wrapper so the existing test suite can
/// exercise both branches without touching process env (unsafe on edition
/// 2024) or relying on the developer's local shell environment.
#[cfg(test)]
fn xdg_config_path_from(xdg_config_home: Option<&std::ffi::OsStr>) -> PathBuf {
    crate::app::xdg::xdg_path_from(
        xdg_config_home,
        "~/.config",
        &["hallouminate", "config.toml"],
    )
}

fn parse(text: &str, source: Option<&Path>) -> Result<Config> {
    let mut cfg: Config = toml::from_str(text).map_err(|e| {
        let where_ = source
            .map(|p| format!(" at {}", p.display()))
            .unwrap_or_default();
        HallouminateError::Config(format!("parsing config{where_}: {e}"))
    })?;
    normalize(&mut cfg)?;
    validate(&cfg)?;
    Ok(cfg)
}

fn normalize(cfg: &mut Config) -> Result<()> {
    cfg.embeddings.model = canonical_model_name(&cfg.embeddings.model)?.to_string();
    Ok(())
}

fn validate(cfg: &Config) -> Result<()> {
    for (idx, c) in cfg.corpora.iter().enumerate() {
        if c.name.trim().is_empty() {
            return Err(HallouminateError::Config(format!(
                "corpus #{idx} has empty name"
            )));
        }
        if c.paths.is_empty() {
            return Err(HallouminateError::Config(format!(
                "corpus '{}' has no paths",
                c.name
            )));
        }
    }
    for (idx, r) in cfg.repositories.iter().enumerate() {
        if r.name.trim().is_empty() {
            return Err(HallouminateError::Config(format!(
                "repository #{idx} has empty name"
            )));
        }
        if r.path.trim().is_empty() {
            return Err(HallouminateError::Config(format!(
                "repository '{}' has empty path",
                r.name
            )));
        }
    }
    // At most one corpus may carry `global = true`. A single global corpus
    // must be unambiguous; two would make the target nondeterministic, so
    // reject the config outright rather than picking one at request time.
    let globals: Vec<&str> = cfg
        .corpora
        .iter()
        .filter(|c| c.global)
        .map(|c| c.name.as_str())
        .collect();
    if globals.len() > 1 {
        return Err(HallouminateError::Config(format!(
            "more than one corpus marked global = true: {}; exactly one is allowed",
            globals.join(", "),
        )));
    }
    // Surface duplicate-name and bad-name failures at config-load time
    // instead of waiting for the daemon to enumerate corpora at request
    // time.
    cfg.effective_corpora()?;
    Ok(())
}

fn default_top_files() -> usize {
    DEFAULT_TOP_FILES
}
fn default_chunks_per_file() -> usize {
    DEFAULT_CHUNKS_PER_FILE
}
fn default_debounce_ms() -> u64 {
    DEFAULT_DEBOUNCE_MS
}
fn default_enabled() -> bool {
    true
}
fn default_model() -> String {
    DEFAULT_EMBED_MODEL.into()
}
fn default_embed_cache() -> String {
    DEFAULT_EMBED_CACHE.into()
}
fn default_idle_evict_secs() -> u64 {
    300
}
fn default_ground_dir() -> String {
    DEFAULT_GROUND_DIR.into()
}

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

    #[test]
    fn parse_rejects_two_global_corpora() {
        // The single corpus with `global = true` must be unambiguous; two
        // would be ambiguous, so config validation must reject the file
        // outright.
        let err = parse(
            r#"
[[corpus]]
name = "a"
paths = ["/a"]
global = true

[[corpus]]
name = "b"
paths = ["/b"]
global = true
"#,
            None,
        )
        .expect_err("two global corpora must fail validation");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("global"), "got: {msg}");
                assert!(
                    msg.contains('a') && msg.contains('b'),
                    "must name both: {msg}"
                );
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn parse_accepts_single_global_corpus() {
        let cfg = parse(
            r#"
[[corpus]]
name = "global"
paths = ["/g"]
global = true

[[corpus]]
name = "local"
paths = ["/l"]
"#,
            None,
        )
        .expect("one global corpus is valid");
        let global = cfg
            .corpora
            .iter()
            .find(|c| c.global)
            .expect("global corpus present");
        assert_eq!(global.name, "global");
        assert!(
            !cfg.corpora
                .iter()
                .find(|c| c.name == "local")
                .unwrap()
                .global
        );
    }

    #[test]
    fn parse_defaults_corpus_global_to_false() {
        let cfg = parse("[[corpus]]\nname = \"docs\"\npaths = [\"/x\"]\n", None).expect("parse");
        assert!(!cfg.corpora[0].global, "global must default to false");
    }

    const SPEC_EXAMPLE: &str = r#"
[[corpus]]
name = "claude-config"
paths = ["~/.claude/skills", "~/.claude/agents", "~/.claude/CLAUDE.md"]
globs = ["**/*.md"]
exclude = ["**/.git/**", "**/node_modules/**"]

[[repository]]
name = "tern"
path = "~/Dev/tern"

[search]
top_files_default       = 10
chunks_per_file_default = 3

[embeddings]
enabled   = true
model     = "BAAI/bge-small-en-v1.5"
quantized = false
cache_dir = "~/.cache/hallouminate/fastembed"

[watch]
debounce_ms = 500

[storage]
ground_dir = "~/.local/share/hallouminate/ground"
"#;

    #[test]
    fn parse_spec_example_decodes_every_field() {
        let cfg = parse(SPEC_EXAMPLE, None).expect("spec example parses");

        assert_eq!(cfg.corpora.len(), 1);
        let corpus = &cfg.corpora[0];
        assert_eq!(corpus.name, "claude-config");
        assert_eq!(
            corpus.paths,
            vec![
                "~/.claude/skills".to_string(),
                "~/.claude/agents".into(),
                "~/.claude/CLAUDE.md".into(),
            ]
        );
        assert_eq!(corpus.globs, vec!["**/*.md".to_string()]);
        assert_eq!(
            corpus.exclude,
            vec!["**/.git/**".to_string(), "**/node_modules/**".into()]
        );

        assert_eq!(cfg.repositories.len(), 1);
        assert_eq!(cfg.repositories[0].name, "tern");
        assert_eq!(cfg.repositories[0].path, "~/Dev/tern");

        assert_eq!(cfg.search.top_files_default, 10);
        assert_eq!(cfg.search.chunks_per_file_default, 3);

        assert!(cfg.embeddings.enabled);
        assert_eq!(cfg.embeddings.model, "BAAI/bge-small-en-v1.5");
        assert!(!cfg.embeddings.quantized);
        assert_eq!(cfg.embeddings.cache_dir, "~/.cache/hallouminate/fastembed");

        assert_eq!(cfg.watch.debounce_ms, 500);
        assert_eq!(cfg.storage.ground_dir, "~/.local/share/hallouminate/ground");
    }

    #[test]
    fn parse_empty_string_yields_full_defaults() {
        let cfg = parse("", None).expect("empty toml parses");
        assert!(cfg.corpora.is_empty());
        assert!(cfg.repositories.is_empty());
        assert_eq!(cfg.search, SearchConfig::default());
        assert_eq!(cfg.embeddings, EmbeddingsConfig::default());
        assert_eq!(cfg.watch, WatchConfig::default());
        assert_eq!(cfg.storage, StorageConfig::default());
    }

    #[test]
    fn embeddings_default_is_on_snowflake_and_full_precision() {
        // The headline contract: dense embeddings are on by default, using the
        // snowflake arctic model, and quantization is off by default.
        let cfg = EmbeddingsConfig::default();
        assert!(cfg.enabled, "embeddings must default to enabled");
        assert!(!cfg.quantized, "quantization must default to off");
        assert_eq!(cfg.model, "snowflake/snowflake-arctic-embed-s");
    }

    #[test]
    fn idle_evict_secs_defaults_to_300() {
        assert_eq!(EmbeddingsConfig::default().idle_evict_secs, 300);
    }

    #[test]
    fn parse_idle_evict_secs_can_be_disabled_with_zero() {
        let cfg =
            parse("[embeddings]\nidle_evict_secs = 0\n", None).expect("idle_evict_secs = 0 parses");
        assert_eq!(cfg.embeddings.idle_evict_secs, 0);
    }

    #[test]
    fn parse_idle_evict_secs_custom_timeout() {
        let cfg = parse("[embeddings]\nidle_evict_secs = 600\n", None)
            .expect("idle_evict_secs = 600 parses");
        assert_eq!(cfg.embeddings.idle_evict_secs, 600);
    }

    #[test]
    fn parse_embeddings_section_omitting_enabled_defaults_to_enabled() {
        let cfg = parse("[embeddings]\nmodel = \"BAAI/bge-small-en-v1.5\"\n", None)
            .expect("partial embeddings section parses");
        assert!(
            cfg.embeddings.enabled,
            "absent `enabled` must default to true, not false"
        );
    }

    #[test]
    fn parse_rejects_dropped_bare_bge_alias() {
        // The bare `bge-small-en-v1.5` alias was torched in Curd A. A config
        // using it now fails the unsupported-model gate at parse time; the
        // full `BAAI/bge-small-en-v1.5` id stays valid.
        let err = parse("[embeddings]\nmodel = \"bge-small-en-v1.5\"\n", None)
            .expect_err("bare bge alias must no longer parse");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("unsupported embedding model"), "got: {msg}");
                assert!(msg.contains("BAAI/bge-small-en-v1.5"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn default_embeddings_model_is_the_honest_snowflake_default() {
        // Pins the actual default behaviour: omitting `embeddings.model`
        // selects snowflake (ARCTIC_S_MODEL), and the honest-default alias
        // points at it. Guards against a regression that would reintroduce
        // the old lie where the const said bge but the default was snowflake.
        assert_eq!(
            EmbeddingsConfig::default().model,
            crate::domain::embeddings::ARCTIC_S_MODEL
        );
        assert_eq!(
            DEFAULT_EMBED_MODEL,
            crate::domain::embeddings::ARCTIC_S_MODEL
        );
        let cfg = parse("[embeddings]\nenabled = true\n", None).expect("partial parses");
        assert_eq!(
            cfg.embeddings.model,
            crate::domain::embeddings::ARCTIC_S_MODEL
        );
    }

    #[test]
    fn parse_rejects_unknown_embedding_model_before_runtime_downloads() {
        let err = parse("[embeddings]\nmodel = \"clip-vit-b32\"\n", None)
            .expect_err("unsupported model must fail during config parse");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("unsupported embedding model"), "got: {msg}");
                assert!(msg.contains("BAAI/bge-small-en-v1.5"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn parse_partial_search_section_uses_defaults_for_missing_fields() {
        let cfg = parse("[search]\ntop_files_default = 5\n", None).expect("partial search parses");
        assert_eq!(cfg.search.top_files_default, 5);
        assert_eq!(cfg.search.chunks_per_file_default, DEFAULT_CHUNKS_PER_FILE);
    }

    #[test]
    fn parse_rejects_corpus_with_empty_name() {
        let err = parse("[[corpus]]\nname = \"\"\npaths = [\"/x\"]\n", None)
            .expect_err("empty corpus name");
        match err {
            HallouminateError::Config(msg) => assert!(msg.contains("empty name"), "got: {msg}"),
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_corpus_with_no_paths() {
        let err = parse("[[corpus]]\nname = \"docs\"\n", None).expect_err("no paths");
        match err {
            HallouminateError::Config(msg) => assert!(msg.contains("no paths"), "got: {msg}"),
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_repository_with_empty_name() {
        let err = parse("[[repository]]\nname = \"\"\npath = \"/r\"\n", None)
            .expect_err("empty repository name");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("empty name"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_repository_with_empty_path() {
        let err = parse("[[repository]]\nname = \"tern\"\npath = \"\"\n", None)
            .expect_err("empty repository path");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("empty path"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_repository_name_containing_colon() {
        let err = parse("[[repository]]\nname = \"bad:name\"\npath = \"/r\"\n", None)
            .expect_err("colon in repo name must surface during validate");
        match err {
            HallouminateError::Config(msg) => assert!(msg.contains("bad:name"), "got: {msg}"),
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn effective_corpora_includes_repository_wiki_after_user_corpora() {
        let cfg = parse(
            r#"
[[corpus]]
name = "docs"
paths = ["/docs"]

[[repository]]
name = "tern"
path = "/repos/tern"
"#,
            None,
        )
        .expect("parses");
        let all = cfg.effective_corpora().expect("derive");
        let names: Vec<&str> = all.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["docs", "repo:tern:wiki"]);
    }

    #[test]
    fn effective_corpora_includes_repository_source_corpus_when_paths_set() {
        let cfg = parse(
            r#"
[[repository]]
name = "tern"
path = "/repos/tern"
corpus_paths = ["docs"]
"#,
            None,
        )
        .expect("parses");
        let all = cfg.effective_corpora().expect("derive");
        let names: Vec<&str> = all.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["repo:tern:wiki", "repo:tern:corpus"]);
        let source = &all[1];
        assert_eq!(source.paths, vec!["/repos/tern/docs".to_string()]);
    }

    #[test]
    fn parse_rejects_duplicate_user_corpus_shadowing_repository_wiki() {
        let err = parse(
            r#"
[[corpus]]
name = "repo:tern:wiki"
paths = ["/x"]

[[repository]]
name = "tern"
path = "/r"
"#,
            None,
        )
        .expect_err("duplicate must fail");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("duplicate"), "got: {msg}");
                assert!(msg.contains("repo:tern:wiki"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_two_repositories_with_same_name_via_derived_corpus_collision() {
        // Two `[[repository]]` entries with the same name both derive
        // `repo:{name}:wiki`, so the second entry must surface as a
        // duplicate-name failure at config-load time — not at the first
        // daemon request that happens to enumerate corpora.
        let err = parse(
            r#"
[[repository]]
name = "tern"
path = "/r1"

[[repository]]
name = "tern"
path = "/r2"
"#,
            None,
        )
        .expect_err("two repos with the same name must fail");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("duplicate"), "got: {msg}");
                assert!(msg.contains("repo:tern:wiki"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn load_xdg_with_explicit_missing_path_returns_defaults() {
        let dir = tempfile::tempdir().expect("tempdir");
        let missing = dir.path().join("does-not-exist.toml");
        let cfg = load_xdg(Some(&missing)).expect("missing file → defaults");
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn load_xdg_reads_file_from_explicit_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let cfg_path = dir.path().join("config.toml");
        std::fs::write(&cfg_path, SPEC_EXAMPLE).expect("write");
        let cfg = load_xdg(Some(&cfg_path)).expect("load");
        assert_eq!(cfg.corpora[0].name, "claude-config");
    }

    #[test]
    fn load_is_alias_for_load_xdg() {
        // The legacy `load` name stays as a thin alias for outside callers;
        // pin the equivalence so future renames notice the contract.
        let dir = tempfile::tempdir().expect("tempdir");
        let cfg_path = dir.path().join("config.toml");
        std::fs::write(&cfg_path, SPEC_EXAMPLE).expect("write");
        assert_eq!(
            load(Some(&cfg_path)).expect("load"),
            load_xdg(Some(&cfg_path)).expect("load_xdg"),
        );
    }

    #[test]
    fn parse_silently_ignores_legacy_fusion_fields() {
        // A user upgrading from the SQLite era may still have a config with
        // `[search].fusion`, `convex_alpha`, `rrf_k`. The restack removed the
        // knob; serde defaults to ignoring unknown fields, so the load must
        // succeed and the SearchConfig must come back as defaults rather than
        // failing with an "unknown field" error.
        let legacy = r#"
[search]
top_files_default       = 7
chunks_per_file_default = 2
fusion                  = "convex"
convex_alpha            = 0.65
rrf_k                   = 60
"#;
        let cfg = parse(legacy, None).expect("legacy config must still parse");
        assert_eq!(cfg.search.top_files_default, 7);
        assert_eq!(cfg.search.chunks_per_file_default, 2);
        assert_eq!(
            cfg.search,
            SearchConfig {
                top_files_default: 7,
                chunks_per_file_default: 2,
                crossencoder: None,
            },
            "SearchConfig must hold only the surviving fields"
        );
    }

    #[test]
    fn xdg_config_path_falls_back_to_dot_config_when_xdg_env_absent() {
        let path = xdg_config_path_from(None);
        assert!(
            path.ends_with(".config/hallouminate/config.toml"),
            "got {}",
            path.display()
        );
        assert!(path.is_absolute(), "tilde must expand: {}", path.display());
    }

    #[test]
    fn xdg_config_path_falls_back_when_xdg_env_is_empty_string() {
        // POSIX/XDG: an empty XDG_CONFIG_HOME is treated as unset.
        let path = xdg_config_path_from(Some(std::ffi::OsStr::new("")));
        assert!(
            path.ends_with(".config/hallouminate/config.toml"),
            "empty XDG_CONFIG_HOME must fall back; got {}",
            path.display()
        );
    }

    #[test]
    fn xdg_config_path_honors_custom_xdg_config_home() {
        // Regression for PR #7 Copilot review: the loader must honor a
        // custom XDG_CONFIG_HOME instead of always resolving to ~/.config.
        let custom = std::path::PathBuf::from("/var/tmp/custom-xdg");
        let path = xdg_config_path_from(Some(custom.as_os_str()));
        assert_eq!(path, custom.join("hallouminate").join("config.toml"));
    }

    #[test]
    fn load_xdg_missing_path_returns_defaults_without_error() {
        // A confirmed NotFound on an explicit path must still degrade to
        // defaults — the NotFound-only filter shouldn't regress this case.
        let dir = tempfile::tempdir().expect("tempdir");
        let missing = dir.path().join("nope.toml");
        let cfg = load_xdg(Some(&missing)).expect("missing -> defaults");
        assert_eq!(cfg, Config::default());
    }

    #[cfg(unix)]
    #[test]
    fn load_xdg_propagates_non_notfound_io_error() {
        // Regression for PR #7 Copilot review: a non-NotFound io error
        // (here: unreadable directory → EACCES on read_to_string) must
        // propagate as HallouminateError::Io, not silently default.
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().expect("tempdir");
        let unreadable = dir.path().join("locked");
        std::fs::create_dir(&unreadable).expect("mkdir");
        let cfg_path = unreadable.join("config.toml");
        std::fs::write(&cfg_path, "").expect("write");
        // 0o000 on parent dir → read of the file inside fails with EACCES.
        // root can bypass this; skip the assertion when running as root.
        let is_root = nix_getuid_is_zero();
        std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000))
            .expect("chmod");
        let result = load_xdg(Some(&cfg_path));
        // Restore perms before any potential test failure unwind, so the
        // tempdir can be cleaned up.
        let _ = std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755));
        if is_root {
            return; // root reads through 0o000; the negative test is meaningless.
        }
        let err = result.expect_err("unreadable parent must surface an io error");
        match err {
            HallouminateError::Io(io) => {
                assert_ne!(
                    io.kind(),
                    std::io::ErrorKind::NotFound,
                    "must NOT classify as NotFound: {io}"
                );
            }
            other => panic!("expected HallouminateError::Io, got {other:?}"),
        }
    }

    #[cfg(unix)]
    fn nix_getuid_is_zero() -> bool {
        // Avoid a libc dep just for this; read /proc/self/status on Linux,
        // shell out to `id -u` everywhere else (macOS, BSDs). The test
        // tolerates either path failing — worst case we run the assertion
        // when we shouldn't, which only false-positives in CI containers
        // running as root, where the assertion is a no-op anyway.
        if let Ok(s) = std::fs::read_to_string("/proc/self/status")
            && let Some(line) = s.lines().find(|l| l.starts_with("Uid:"))
        {
            return line.split_whitespace().nth(1) == Some("0");
        }
        std::process::Command::new("id")
            .arg("-u")
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim() == "0")
            .unwrap_or(false)
    }

    // ── discover_repo_config ────────────────────────────────────────────

    /// Canonicalize a tempdir so comparisons survive macOS's `/var → /private/var`
    /// symlink. Without this, paths returned by the walker may not equal-string
    /// the path we built locally even though they point at the same inode.
    fn canon(p: &Path) -> PathBuf {
        std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
    }

    fn write_repo_config(dir: &Path, body: &str) -> PathBuf {
        let cfg_dir = dir.join(".hallouminate");
        std::fs::create_dir_all(&cfg_dir).expect("mkdir .hallouminate");
        let cfg_path = cfg_dir.join("config.toml");
        std::fs::write(&cfg_path, body).expect("write repo config");
        cfg_path
    }

    #[test]
    fn discover_repo_config_finds_at_cwd_itself() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = canon(dir.path());
        let expected = write_repo_config(&root, "");
        let found = discover_repo_config(&root)
            .expect("found at cwd")
            .expect("config present");
        assert_eq!(canon(&found), canon(&expected));
    }

    #[test]
    fn discover_repo_config_finds_at_ancestor() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = canon(dir.path());
        let expected = write_repo_config(&root, "");
        let nested = root.join("a").join("b").join("c");
        std::fs::create_dir_all(&nested).expect("mkdir nested");
        let found = discover_repo_config(&nested)
            .expect("walked up to ancestor")
            .expect("config present");
        assert_eq!(canon(&found), canon(&expected));
    }

    #[test]
    fn discover_repo_config_stops_at_git_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = canon(dir.path());
        std::fs::create_dir(root.join(".git")).expect("mkdir .git");
        let nested = root.join("src");
        std::fs::create_dir_all(&nested).expect("mkdir nested");
        let err = discover_repo_config(&nested).expect_err("stop at repo root");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("stopped at repo root"), "got: {msg}");
                // The CWD we walked from must appear in the error so a user can
                // tell at a glance which directory failed to resolve.
                assert!(msg.contains(&nested.display().to_string()), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn discover_repo_config_treats_git_file_as_repo_boundary() {
        // A `.git` *file* whose gitdir pointer does NOT contain `/worktrees/`
        // (i.e. not a linked worktree — could be an old-style external gitdir or
        // a bare repo) must still stop the walk with a hard error.
        let dir = tempfile::tempdir().expect("tempdir");
        let root = canon(dir.path());
        std::fs::write(root.join(".git"), "gitdir: /elsewhere\n").expect("write .git file");
        let err = discover_repo_config(&root).expect_err("non-worktree git file stops walk");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("stopped at repo root"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn discover_repo_config_worktree_resolves_to_main_checkout() {
        // A linked worktree's `.git` file contains `gitdir: <main>/.git/worktrees/<name>`.
        // Discovery must hop to the main checkout root and find the config there
        // rather than hard-erroring at the worktree boundary.
        //
        // Layout:
        //   <tmpdir>/main-repo/.hallouminate/config.toml  ← the config
        //   <tmpdir>/main-repo/.git/                      ← main gitdir (directory)
        //   <tmpdir>/main-repo/.git/worktrees/wt1/        ← per-worktree dir
        //   <tmpdir>/wt1/                                 ← linked worktree
        //   <tmpdir>/wt1/.git                             ← file: "gitdir: .../worktrees/wt1"
        let outer = tempfile::tempdir().expect("tempdir");
        let outer = canon(outer.path());

        // Main checkout
        let main_repo = outer.join("main-repo");
        let main_gitdir = main_repo.join(".git");
        let worktrees_dir = main_gitdir.join("worktrees").join("wt1");
        std::fs::create_dir_all(&worktrees_dir).expect("mkdir worktrees/wt1");
        write_repo_config(&main_repo, "");

        // Linked worktree root
        let wt = outer.join("wt1");
        std::fs::create_dir_all(&wt).expect("mkdir wt1");
        let gitdir_ptr = format!("gitdir: {}\n", worktrees_dir.display());
        std::fs::write(wt.join(".git"), &gitdir_ptr).expect("write worktree .git file");

        let found = discover_repo_config(&wt)
            .expect("worktree discovery must not error")
            .expect("config must be found in main checkout");
        let expected = main_repo.join(".hallouminate").join("config.toml");
        assert_eq!(canon(&found), canon(&expected), "resolved to wrong path");
    }

    #[test]
    fn discover_repo_config_submodule_git_file_does_not_hop() {
        // A submodule's `.git` file contains `gitdir: <super>/.git/modules/<name>` —
        // no `/worktrees/` segment. Discovery must NOT hop; it must hard-error at
        // the submodule boundary (no .hallouminate/config.toml present).
        let dir = tempfile::tempdir().expect("tempdir");
        let outer = canon(dir.path());
        // Super-repo gitdir lives separately; the submodule's `.git` file points there.
        let super_modules = outer.join("super-git").join("modules").join("sub");
        std::fs::create_dir_all(&super_modules).expect("mkdir modules/sub");
        // The submodule root has a `.git` file (not a directory) pointing at modules/sub.
        let sub_root = outer.join("sub-root");
        std::fs::create_dir_all(&sub_root).expect("mkdir sub-root");
        let gitdir_ptr = format!("gitdir: {}\n", super_modules.display());
        std::fs::write(sub_root.join(".git"), &gitdir_ptr).expect("write submodule .git file");
        let err = discover_repo_config(&sub_root).expect_err("submodule git file must stop walk");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("stopped at repo root"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn discover_repo_config_relative_gitdir_pointer_resolves_to_main_checkout() {
        // `git worktree add --relative-paths` (or `extensions.relativeWorktrees = true`)
        // writes a RELATIVE `gitdir:` pointer in the worktree's `.git` file, e.g.
        // `gitdir: ../../.git/worktrees/wt1`. Discovery must resolve that pointer
        // against the worktree root (not the process cwd) and still hop to the
        // main checkout root where the config lives.
        //
        // Layout:
        //   <tmpdir>/main-repo/.hallouminate/config.toml  ← the config
        //   <tmpdir>/main-repo/.git/                      ← main gitdir (directory)
        //   <tmpdir>/main-repo/.git/worktrees/wt1/        ← per-worktree dir
        //   <tmpdir>/wt1/                                 ← linked worktree
        //   <tmpdir>/wt1/.git                             ← file: "gitdir: ../../main-repo/.git/worktrees/wt1"
        let outer = tempfile::tempdir().expect("tempdir");
        let outer = canon(outer.path());

        let main_repo = outer.join("main-repo");
        let main_gitdir = main_repo.join(".git");
        let worktrees_dir = main_gitdir.join("worktrees").join("wt1");
        std::fs::create_dir_all(&worktrees_dir).expect("mkdir worktrees/wt1");
        write_repo_config(&main_repo, "");

        let wt = outer.join("wt1");
        std::fs::create_dir_all(&wt).expect("mkdir wt1");
        // Relative pointer: from <tmpdir>/wt1/.git → <tmpdir>/main-repo/.git/worktrees/wt1
        let gitdir_ptr = "gitdir: ../main-repo/.git/worktrees/wt1\n";
        std::fs::write(wt.join(".git"), gitdir_ptr).expect("write worktree .git file");

        let found = discover_repo_config(&wt)
            .expect("relative-pointer worktree discovery must not error")
            .expect("config must be found in main checkout");
        let expected = main_repo.join(".hallouminate").join("config.toml");
        assert_eq!(
            canon(&found),
            canon(&expected),
            "relative pointer resolved to wrong path"
        );
    }

    #[test]
    fn discover_repo_config_worktrees_dir_name_in_superproject_does_not_hop() {
        // Structural guard for Finding 2: a superproject whose checkout lives
        // inside a directory literally named "worktrees" must NOT be treated as
        // a linked-worktree hop. A submodule pointer such as
        // `gitdir: /home/me/worktrees/.git/modules/sub` contains "worktrees"
        // as a path component, but it is NOT immediately preceded by ".git", so
        // it must fall through to the hard-error branch (no hop).
        let dir = tempfile::tempdir().expect("tempdir");
        let outer = canon(dir.path());
        // A directory literally named "worktrees" hosts the superproject's gitdir.
        // The submodule pointer points at modules/sub inside it.
        let super_git = outer
            .join("worktrees")
            .join(".git")
            .join("modules")
            .join("sub");
        std::fs::create_dir_all(&super_git).expect("mkdir worktrees/.git/modules/sub");
        let sub_root = outer.join("sub-root");
        std::fs::create_dir_all(&sub_root).expect("mkdir sub-root");
        let gitdir_ptr = format!("gitdir: {}\n", super_git.display());
        std::fs::write(sub_root.join(".git"), &gitdir_ptr).expect("write submodule .git file");
        // Must NOT hop — must hard-error at the submodule boundary.
        let err = discover_repo_config(&sub_root)
            .expect_err("superproject-in-worktrees-dir submodule must stop walk");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("stopped at repo root"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn discover_repo_config_relative_cwd_resolves_against_current_dir() {
        // The relative-cwd normalization fix: a relative `cwd` must be joined
        // against the base directory (`std::env::current_dir()` in production)
        // before walking, so `Path::parent()` walks reach the real filesystem
        // root rather than bottoming out at the empty path.
        //
        // This is asserted hermetically against a controlled, config-free base
        // dir rather than the process' real working directory. This repo ships
        // its own committed `.hallouminate/config.toml`, so normalizing a
        // relative input against the *real* cwd would make the walk find that
        // config and return Ok before the normalization behavior could be
        // observed. Driving the normalization through `absolutize_cwd` with a
        // tempdir base isolates the relative→absolute join from repo-root
        // config discovery while still asserting exactly the join the
        // production path performs.
        let dir = tempfile::tempdir().expect("tempdir");
        let base = canon(dir.path());

        let rel = Path::new("nested/leaf");
        // The relative input, normalized against the base, must equal the
        // absolute path you'd get by joining the base yourself. This is the
        // contract `discover_repo_config` relies on so a relative cwd ascends
        // the same parent chain as its absolute equivalent.
        let normalized = absolutize_cwd(rel, &base);
        assert_eq!(
            normalized,
            base.join(rel),
            "a relative cwd must resolve by joining against the base dir",
        );
        assert!(
            normalized.is_absolute(),
            "normalization against an absolute base must yield an absolute path \
             so the walk reaches the real filesystem root, not the empty component",
        );

        // End-to-end against the absolute, normalized path: walking it must
        // ascend a real parent chain and bottom out at a boundary — either the
        // filesystem-root exhaust branch (`Ok(None)` soft-fallback, the base
        // tempdir has no `.git` and no `.hallouminate/config.toml` ancestor) or
        // a `.git` boundary in an unusual CI sandbox (`Err`). This is the
        // regression the fix guards: before normalization, a relative cwd's
        // `Path::parent()` walk bottomed out at the empty component, which would
        // surface as a (misleading) filesystem-root result without ascending to
        // the real root. What it must NOT do is find a config.
        match discover_repo_config(&normalized) {
            Ok(None) => {}
            Err(HallouminateError::Config(m)) => {
                assert!(
                    m.contains("stopped at repo root"),
                    "the only non-fallback outcome here is a `.git` boundary; got: {m}",
                );
            }
            other => panic!("normalized relative input must not find a config: {other:?}"),
        }
    }

    #[test]
    fn discover_repo_config_soft_falls_back_walking_past_no_git_no_config() {
        // A subtree with no `.git` and no `.hallouminate/config.toml` anywhere
        // up to the filesystem root must soft-fall-back (`Ok(None)`) rather than
        // error — there is no repo context to be strict about, and erroring
        // would strand the baseline-declared corpora (issue #102). We can't
        // realistically test "all the way to /" so simulate by walking from a
        // tempdir whose ancestors are guaranteed not to host
        // `.hallouminate/config.toml` (the system tmp tree).
        let dir = tempfile::tempdir().expect("tempdir");
        // The system tmp dir on macOS *might* have a `.git` ancestor in weird
        // CI sandboxes; that path is the still-strict `.git`-boundary error.
        let cwd = canon(dir.path());
        match discover_repo_config(&cwd) {
            // The expected outcome: no `.git` boundary, so baseline-only.
            Ok(None) => {}
            // Unusual CI sandbox with a `.git` ancestor: still a hard error.
            Err(HallouminateError::Config(msg)) => {
                assert!(msg.contains("stopped at repo root"), "got: {msg}");
            }
            Ok(Some(p)) => panic!("did not expect to find a config; got {}", p.display()),
            Err(other) => panic!("unexpected error: {other:?}"),
        }
    }

    // ── load_repo_layer ─────────────────────────────────────────────────

    #[test]
    fn load_repo_layer_resolves_relative_paths_against_repo_root() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo_root = canon(dir.path());
        let cfg = r#"
[[corpus]]
name = "docs"
paths = ["docs", "specs/cur"]

[[repository]]
name = "self"
path = "."
corpus_paths = ["sub/docs"]

[storage]
ground_dir = "var/ground"

[embeddings]
cache_dir = "var/fastembed"
"#;
        let cfg_path = write_repo_config(&repo_root, cfg);

        let parsed = load_repo_layer(&cfg_path).expect("load_repo_layer");
        // Repo-layer relative paths are resolved against the repo root
        // (the parent of `.hallouminate/`), not against `.hallouminate/`
        // itself. This matches user intuition: `paths = ["docs"]` written
        // in `.hallouminate/config.toml` means `<repo>/docs`.
        let base = &repo_root;

        assert_eq!(
            parsed.corpora[0].paths,
            vec![
                base.join("docs").to_string_lossy().into_owned(),
                base.join("specs/cur").to_string_lossy().into_owned(),
            ]
        );
        // Repository `path = "."` resolves to the repo root itself, so
        // `wiki_directory` lands at `<repo>/.hallouminate/wiki` (no double
        // `.hallouminate/`).
        assert_eq!(
            parsed.repositories[0].path,
            base.join(".").to_string_lossy().into_owned(),
        );
        assert_eq!(
            parsed.repositories[0].corpus_paths,
            vec![base.join("sub/docs").to_string_lossy().into_owned()],
        );
        assert_eq!(
            parsed.storage.ground_dir,
            base.join("var/ground").to_string_lossy().into_owned(),
        );
        assert_eq!(
            parsed.embeddings.cache_dir,
            base.join("var/fastembed").to_string_lossy().into_owned(),
        );
    }

    #[test]
    fn load_repo_layer_preserves_absolute_paths_untouched() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo_root = canon(dir.path());
        let cfg = r#"
[[corpus]]
name = "abs"
paths = ["/abs/docs"]

[[repository]]
name = "absrepo"
path = "/abs/repo"
corpus_paths = ["/abs/repo/docs"]

[storage]
ground_dir = "/abs/ground"

[embeddings]
cache_dir = "/abs/cache"
"#;
        let cfg_path = write_repo_config(&repo_root, cfg);
        let parsed = load_repo_layer(&cfg_path).expect("load_repo_layer");

        assert_eq!(parsed.corpora[0].paths, vec!["/abs/docs".to_string()]);
        assert_eq!(parsed.repositories[0].path, "/abs/repo");
        assert_eq!(
            parsed.repositories[0].corpus_paths,
            vec!["/abs/repo/docs".to_string()],
        );
        assert_eq!(parsed.storage.ground_dir, "/abs/ground");
        assert_eq!(parsed.embeddings.cache_dir, "/abs/cache");
    }

    #[test]
    fn load_repo_layer_preserves_tilde_paths_untouched() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo_root = canon(dir.path());
        let cfg = r#"
[[corpus]]
name = "home"
paths = ["~/docs"]

[[repository]]
name = "homerepo"
path = "~/repo"
corpus_paths = ["~/repo/docs"]

[storage]
ground_dir = "~/ground"

[embeddings]
cache_dir = "~/cache"
"#;
        let cfg_path = write_repo_config(&repo_root, cfg);
        let parsed = load_repo_layer(&cfg_path).expect("load_repo_layer");

        // Tilde expansion happens at consumption time via `expand_tilde`;
        // the loader must NOT rewrite tilde-prefixed strings.
        assert_eq!(parsed.corpora[0].paths, vec!["~/docs".to_string()]);
        assert_eq!(parsed.repositories[0].path, "~/repo");
        assert_eq!(
            parsed.repositories[0].corpus_paths,
            vec!["~/repo/docs".to_string()],
        );
        assert_eq!(parsed.storage.ground_dir, "~/ground");
        assert_eq!(parsed.embeddings.cache_dir, "~/cache");
    }

    // ── merge_layers ────────────────────────────────────────────────────

    #[test]
    fn merge_layers_appends_repo_corpora_after_baseline() {
        let baseline = parse(
            r#"
[[corpus]]
name = "global"
paths = ["/global"]
"#,
            None,
        )
        .expect("baseline parses");
        let repo = parse(
            r#"
[[corpus]]
name = "local"
paths = ["/local"]
"#,
            None,
        )
        .expect("repo parses");
        let merged = merge_layers(&baseline, &repo).expect("merge");
        let names: Vec<&str> = merged.corpora.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["global", "local"]);
    }

    #[test]
    fn merge_layers_appends_repo_repositories_after_baseline() {
        let baseline = parse(
            r#"
[[repository]]
name = "a"
path = "/a"
"#,
            None,
        )
        .expect("baseline parses");
        let repo = parse(
            r#"
[[repository]]
name = "b"
path = "/b"
"#,
            None,
        )
        .expect("repo parses");
        let merged = merge_layers(&baseline, &repo).expect("merge");
        let names: Vec<&str> = merged
            .repositories
            .iter()
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(names, vec!["a", "b"]);
    }

    #[test]
    fn merge_layers_uses_baseline_scalar_when_repo_left_default() {
        let baseline = parse("[search]\ntop_files_default = 20\n", None).expect("baseline");
        let repo = parse("", None).expect("repo default");
        let merged = merge_layers(&baseline, &repo).expect("merge");
        assert_eq!(merged.search.top_files_default, 20);
    }

    #[test]
    fn merge_layers_idle_evict_secs_propagates_baseline_value_over_repo_default() {
        // Regression trap: if the merge_scalar call for idle_evict_secs is
        // removed and the field is hardcoded to its default, this fails.
        let baseline = parse("[embeddings]\nidle_evict_secs = 600\n", None).expect("baseline");
        let repo = parse("", None).expect("repo default");
        let merged = merge_layers(&baseline, &repo).expect("merge");
        assert_eq!(merged.embeddings.idle_evict_secs, 600);
    }

    #[test]
    fn merge_layers_uses_repo_scalar_when_baseline_left_default() {
        let baseline = parse("", None).expect("baseline default");
        let repo = parse("[search]\ntop_files_default = 30\n", None).expect("repo");
        let merged = merge_layers(&baseline, &repo).expect("merge");
        assert_eq!(merged.search.top_files_default, 30);
    }

    #[test]
    fn merge_layers_accepts_both_sides_explicit_equal() {
        let cfg = "[embeddings]\nmodel = \"BAAI/bge-small-en-v1.5\"\ncache_dir = \"/shared\"\n";
        let baseline = parse(cfg, None).expect("baseline");
        let repo = parse(cfg, None).expect("repo");
        let merged = merge_layers(&baseline, &repo).expect("merge");
        assert_eq!(merged.embeddings.cache_dir, "/shared");
        assert_eq!(merged.embeddings.model, "BAAI/bge-small-en-v1.5");
    }

    #[test]
    fn merge_layers_fails_on_scalar_conflict_with_field_name_in_message() {
        // AC #7: scalar conflict produces HallouminateError::Config naming
        // the field. We assert on `embeddings.cache_dir` because both layers
        // can set it to genuinely different non-default values without
        // running into the `canonical_model_name` normalization that would
        // collapse two "different" model strings.
        let baseline = parse("[embeddings]\ncache_dir = \"/a\"\n", None).expect("baseline");
        let repo = parse("[embeddings]\ncache_dir = \"/b\"\n", None).expect("repo");
        let err = merge_layers(&baseline, &repo).expect_err("conflict must fail");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("embeddings.cache_dir"), "got: {msg}");
                assert!(msg.contains("\"/a\""), "got: {msg}");
                assert!(msg.contains("\"/b\""), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn merge_layers_conflict_names_both_source_paths_when_supplied() {
        // The internal `merge_layers_with_sources` carries source paths so
        // `resolve_for_cwd` can produce a richer error. Pin both paths in
        // the message — AC #7 wants this for the user-facing flow.
        let baseline = parse("[embeddings]\ncache_dir = \"/a\"\n", None).expect("baseline");
        let repo = parse("[embeddings]\ncache_dir = \"/b\"\n", None).expect("repo");
        let xdg = Path::new("/etc/hallouminate/config.toml");
        let repo_p = Path::new("/work/.hallouminate/config.toml");
        let err = merge_layers_with_sources(&baseline, &repo, Some(xdg), Some(repo_p))
            .expect_err("conflict must fail");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("/etc/hallouminate/config.toml"), "got: {msg}");
                assert!(
                    msg.contains("/work/.hallouminate/config.toml"),
                    "got: {msg}"
                );
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    // ── resolve_for_cwd ─────────────────────────────────────────────────

    #[test]
    fn resolve_for_cwd_walks_finds_and_merges_repo_layer() {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo_root = canon(dir.path());
        write_repo_config(
            &repo_root,
            r#"
[[corpus]]
name = "repo-docs"
paths = ["docs"]
"#,
        );
        let baseline = parse(
            r#"
[[corpus]]
name = "global"
paths = ["/g"]
"#,
            None,
        )
        .expect("baseline");

        let nested = repo_root.join("src").join("inner");
        std::fs::create_dir_all(&nested).expect("mkdir nested");

        let xdg = PathBuf::from("/etc/hallouminate/config.toml");
        let (effective, layers) = resolve_for_cwd(&baseline, &nested, Some(&xdg)).expect("resolve");

        let names: Vec<&str> = effective.corpora.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["global", "repo-docs"]);
        assert_eq!(layers.xdg_path, Some(xdg));
        let repo_path = layers.repo_path.expect("repo config discovered");
        assert_eq!(
            canon(&repo_path),
            canon(&repo_root.join(".hallouminate").join("config.toml")),
        );
    }

    #[test]
    fn resolve_for_cwd_with_repository_dot_path_derives_corpora_against_repo_root() {
        // AC #8: `[[repository]] name="X" path="."` must derive
        // `repo:X:wiki` and `repo:X:corpus` with paths resolved against the
        // repo root (the parent of `.hallouminate/`, i.e. the directory the
        // user `cd`s into).
        let dir = tempfile::tempdir().expect("tempdir");
        let repo_root = canon(dir.path());
        write_repo_config(
            &repo_root,
            r#"
[[repository]]
name = "X"
path = "."
corpus_paths = ["docs"]
"#,
        );

        let baseline = Config::default();
        let (effective, _layers) = resolve_for_cwd(&baseline, &repo_root, None).expect("resolve");

        let all = effective.effective_corpora().expect("derive corpora");
        let names: Vec<&str> = all.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["repo:X:wiki", "repo:X:corpus"]);

        // The wiki corpus resolves under the repo root — no double
        // `.hallouminate/.hallouminate/` segment.
        let wiki_expected = repo_root
            .join(".")
            .join(".hallouminate")
            .join("wiki")
            .to_string_lossy()
            .into_owned();
        assert_eq!(all[0].paths, vec![wiki_expected]);

        // The repo source corpus resolves "docs" against the repo root at
        // `load_repo_layer` time, then `resolve_under` sees it as already
        // absolute and passes it through verbatim — so the final path is
        // `<repo_root>/docs` with no extra `.` segment.
        let docs_expected = repo_root.join("docs").to_string_lossy().into_owned();
        assert_eq!(all[1].paths, vec![docs_expected]);
    }

    #[test]
    fn resolve_for_cwd_returns_hard_error_when_no_repo_config_found() {
        // A `.git` boundary with no config in between must surface as a
        // hard error — the daemon refuses to fall back to baseline-only.
        let dir = tempfile::tempdir().expect("tempdir");
        let repo_root = canon(dir.path());
        std::fs::create_dir(repo_root.join(".git")).expect("mkdir .git");
        let nested = repo_root.join("src");
        std::fs::create_dir_all(&nested).expect("mkdir nested");

        let baseline = Config::default();
        let err = resolve_for_cwd(&baseline, &nested, None).expect_err("must error");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("stopped at repo root"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn resolve_for_cwd_falls_back_to_baseline_when_cwd_above_all_repos() {
        // Issue #102: from a parent-of-repos directory — no `.hallouminate/`,
        // no `.git`, the walk reaches the filesystem root — `resolve_for_cwd`
        // must resolve *baseline-only* instead of hard-erroring. Otherwise the
        // baseline-declared corpora become unreachable the moment the cwd sits
        // above all repos, stranding stateless ops (`list_corpora`, `ground`).
        let dir = tempfile::tempdir().expect("tempdir");
        let above_repos = canon(dir.path());

        // A baseline that declares a globally-searchable corpus, mirroring the
        // XDG `cheese-global` / `cheez-wiki` entries in the issue repro.
        let baseline = parse(
            r#"
[[corpus]]
name = "cheese-global"
paths = ["/srv/cheese-global"]
"#,
            None,
        )
        .expect("baseline parse");

        let (effective, layers) =
            resolve_for_cwd(&baseline, &above_repos, None).expect("baseline-only must resolve");

        // The baseline corpus is reachable from above-all-repos.
        let corpora = effective.effective_corpora().expect("derive corpora");
        let names: Vec<&str> = corpora.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["cheese-global"]);

        // No repo config was discovered, so the diagnostic records `None`
        // rather than fabricating a path.
        assert_eq!(layers.repo_path, None);
    }

    #[test]
    fn resolve_for_cwd_unions_discovered_sub_repo_wikis_from_above_all_repos() {
        // #106: from a parent-of-repos dir, the downward walk discovers each
        // sub-repo's local `.hallouminate` wiki and unions them with the
        // baseline corpora, so a no-corpus ground searches all of them.
        let dir = tempfile::tempdir().expect("tempdir");
        let above_repos = canon(dir.path());

        // Two sub-repos, each with only a LOCAL `.hallouminate/config.toml`
        // (and wiki dir) — neither is a baseline `[[repository]]`.
        for repo in ["alpha", "beta"] {
            let repo_root = above_repos.join(repo);
            std::fs::create_dir_all(repo_root.join(".hallouminate").join("wiki"))
                .expect("mkdir wiki");
            std::fs::write(repo_root.join(".hallouminate").join("config.toml"), "")
                .expect("write local config");
        }

        let baseline = parse(
            r#"
[[corpus]]
name = "cheese-global"
paths = ["/srv/cheese-global"]
"#,
            None,
        )
        .expect("baseline parse");

        let (effective, layers) =
            resolve_for_cwd(&baseline, &above_repos, None).expect("baseline-only must resolve");

        let corpora = effective.effective_corpora().expect("derive corpora");
        let names: Vec<&str> = corpora.iter().map(|c| c.name.as_str()).collect();
        assert!(
            names.contains(&"cheese-global"),
            "baseline corpus preserved: {names:?}"
        );
        assert!(
            names.contains(&"repo:alpha:wiki") && names.contains(&"repo:beta:wiki"),
            "both discovered sub-repo wikis must be unioned in: {names:?}"
        );
        assert_eq!(
            layers.repo_path, None,
            "no single repo discovered above all"
        );
        assert!(
            layers.warnings.is_empty(),
            "no name collision => no warnings: {:?}",
            layers.warnings
        );
    }

    #[test]
    fn resolve_for_cwd_keeps_both_same_basename_sibling_wikis_and_warns() {
        // #106 regression: two discovered sub-repos sharing a directory
        // basename at different paths (`work/tern` and `personal/tern`) both
        // derive `repo:tern:wiki`. The earlier union dropped one silently,
        // contradicting "search the union of ALL discovered wikis". Both must
        // survive end-to-end through `resolve_for_cwd` -> `effective_corpora`,
        // and a `cross-repo-union` warning (the payload the dispatch copy-loop
        // surfaces verbatim) must be generated naming the discovered sibling.
        let dir = tempfile::tempdir().expect("tempdir");
        let above_repos = canon(dir.path());

        for parent in ["work", "personal"] {
            let repo_root = above_repos.join(parent).join("tern");
            std::fs::create_dir_all(repo_root.join(".hallouminate").join("wiki"))
                .expect("mkdir wiki");
            std::fs::write(repo_root.join(".hallouminate").join("config.toml"), "")
                .expect("write local config");
        }

        let baseline = parse("", None).expect("empty baseline parse");

        let (effective, layers) =
            resolve_for_cwd(&baseline, &above_repos, None).expect("baseline-only must resolve");

        // `effective_corpora` must NOT collapse or reject the pair: the
        // disambiguated names round-trip through the duplicate-name guard.
        let corpora = effective.effective_corpora().expect("derive corpora");
        let wiki_names: Vec<&str> = corpora
            .iter()
            .map(|c| c.name.as_str())
            .filter(|n| n.starts_with("repo:") && n.ends_with(":wiki"))
            .collect();
        assert_eq!(
            wiki_names.len(),
            2,
            "both same-basename sibling wikis must survive, not one: {wiki_names:?}"
        );
        assert!(
            wiki_names.contains(&"repo:tern:wiki"),
            "the first sibling keeps the canonical corpus name: {wiki_names:?}"
        );
        assert!(
            wiki_names
                .iter()
                .any(|n| n.contains("tern") && *n != "repo:tern:wiki"),
            "the second sibling is parent-qualified to stay distinct: {wiki_names:?}"
        );

        // The collision is surfaced as a `cross-repo-union` advisory, and its
        // text names the discovered sibling rather than a (non-existent)
        // baseline shadow.
        assert_eq!(
            layers.warnings.len(),
            1,
            "one sibling collision => exactly one warning: {:?}",
            layers.warnings
        );
        let w = &layers.warnings[0];
        assert!(
            w.contains("another discovered sub-repo") && !w.contains("baseline"),
            "warning must name the discovered sibling, not a baseline shadow: {w:?}"
        );
    }

    #[test]
    fn resolve_for_cwd_passes_xdg_path_into_conflict_messages() {
        // Verifies the source-path threading: a scalar conflict between
        // baseline (XDG) and the repo layer should name *both* paths.
        let dir = tempfile::tempdir().expect("tempdir");
        let repo_root = canon(dir.path());
        let cfg_path = write_repo_config(&repo_root, "[embeddings]\ncache_dir = \"/repo-cache\"\n");
        let baseline =
            parse("[embeddings]\ncache_dir = \"/xdg-cache\"\n", None).expect("baseline parse");
        let xdg = PathBuf::from("/etc/hallouminate/config.toml");

        let err =
            resolve_for_cwd(&baseline, &repo_root, Some(&xdg)).expect_err("conflict must fail");
        match err {
            HallouminateError::Config(msg) => {
                assert!(msg.contains("embeddings.cache_dir"), "got: {msg}");
                assert!(msg.contains("/etc/hallouminate/config.toml"), "got: {msg}");
                assert!(msg.contains(&cfg_path.display().to_string()), "got: {msg}");
                assert!(msg.contains("/xdg-cache"), "got: {msg}");
                assert!(msg.contains("/repo-cache"), "got: {msg}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }
}