hallouminate 0.1.3

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
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::domain::common::{CorpusConfig, HallouminateError, Result};

use crate::domain::embeddings::{DEFAULT_EMBED_MODEL, canonical_model_name};
use crate::domain::repository::{RepositoryConfig, effective_corpora};

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,
}

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

/// 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
/// always populated because `resolve_for_cwd` errors when discovery fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedLayers {
    pub xdg_path: Option<PathBuf>,
    pub repo_path: PathBuf,
}

/// 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. Stops at the first
/// `.git` entry (file *or* directory — git worktrees use a file) and returns
/// an error. Stops at the filesystem root and returns an error.
///
/// 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<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(candidate);
        }
        let git_marker = level.join(".git");
        // `exists` matches both `.git` directories (normal clone) and `.git`
        // files (git worktrees and submodules).
        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();
    }
    Err(HallouminateError::Config(format!(
        "no .hallouminate/config.toml found walking up from {} \
         (reached filesystem root without hitting a .git boundary)",
        cwd.display(),
    )))
}

/// 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)
}

/// 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,
        )?,
    };
    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)> {
    let repo_path = discover_repo_config(cwd)?;
    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,
        },
    ))
}

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`. `globalize_markdown`
    // resolves its destination by finding the single global corpus; two
    // would make the target ambiguous, so reject the config outright rather
    // than picking one nondeterministically 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_ground_dir() -> String {
    DEFAULT_GROUND_DIR.into()
}

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

    #[test]
    fn parse_rejects_two_global_corpora() {
        // Curd 4: globalize resolves its destination by finding the single
        // corpus with `global = true`; 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 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");
        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");
        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() {
        // git worktrees and submodules use a `.git` *file* (containing
        // `gitdir: ...`) rather than a directory; the walk must still stop.
        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("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_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 the filesystem-root
        // exhaust branch (the base tempdir has no `.git` and no
        // `.hallouminate/config.toml` ancestor). This is the regression the fix
        // guards: before normalization, a relative cwd's `Path::parent()` walk
        // bottomed out at the empty component, producing a misleading error
        // rather than ascending to the real root.
        match discover_repo_config(&normalized) {
            Err(HallouminateError::Config(m)) => {
                assert!(
                    m.contains("reached filesystem root") || m.contains("stopped at repo root"),
                    "the normalized path must walk a real parent chain to a \
                     boundary, not bottom out at an empty component; got: {m}",
                );
                assert!(
                    m.contains(&normalized.display().to_string()),
                    "the error must name the normalized cwd it walked from; got: {m}",
                );
            }
            other => panic!("normalized relative input must error: {other:?}"),
        }
    }

    #[test]
    fn discover_repo_config_errors_walking_past_no_git_no_config() {
        // A subtree with no `.git` and no `.hallouminate/config.toml`
        // anywhere up to the filesystem root must error rather than walk
        // forever or silently succeed. 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). The error message must mention the filesystem-root
        // exhaust path because we never hit a `.git`.
        let dir = tempfile::tempdir().expect("tempdir");
        // The system tmp dir on macOS *might* have a `.git` ancestor in
        // weird CI sandboxes; skip the assertion if it does. The point of
        // this test is the message-shape contract.
        let cwd = canon(dir.path());
        match discover_repo_config(&cwd) {
            Err(HallouminateError::Config(msg)) => {
                // Either we hit FS root (unusual CI sandboxes) or a `.git`
                // somewhere up the chain. Both are valid "no config here"
                // outcomes; the message just has to be non-empty.
                assert!(
                    msg.contains("filesystem root") || msg.contains("stopped at repo root"),
                    "got: {msg}"
                );
            }
            Ok(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_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));
        assert_eq!(
            canon(&layers.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_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:?}"),
        }
    }
}