khive-runtime 0.5.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
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
//! TOML-based embedding engine configuration for khive.
//!
//! Loads `.khive/config.toml` (or `--config` / `KHIVE_CONFIG`) and exposes an
//! `[[engines]]` array for arbitrary-N embedding engine registration. Falls back
//! to `KHIVE_EMBEDDING_MODEL` env vars when no config file is present.

use std::path::{Path, PathBuf};

use khive_types::namespace::Namespace;
use serde::Deserialize;
use thiserror::Error;

use crate::presentation::OutputFormat;

// ---- Error type ----

/// Errors produced while loading or validating a `KhiveConfig`.
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("config file I/O: {0}")]
    Io(#[from] std::io::Error),

    #[error("config TOML parse error in {path}: {source}")]
    Parse {
        path: PathBuf,
        #[source]
        source: toml::de::Error,
    },

    #[error("exactly one engine must be marked `default = true`; found {found}")]
    DefaultCount { found: usize },

    #[error("duplicate engine name: {name:?}")]
    DuplicateName { name: String },

    #[error(
        "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
    )]
    UnknownModel { name: String, model: String },

    #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
    InvalidFusionWeight { name: String, value: f64 },

    #[error("actor.id {id:?} is not a valid namespace: {reason}")]
    InvalidActorId { id: String, reason: String },

    #[error("duplicate backend name: {name:?}")]
    DuplicateBackendName { name: String },

    #[error(
        "[packs.{pack}].backend = {backend:?} references an unknown backend; \
         defined backends: {defined}"
    )]
    UnknownPackBackend {
        pack: String,
        backend: String,
        defined: String,
    },

    #[error(
        "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
         remove it from the config or wait for a future release that implements it"
    )]
    UnsupportedBackendField { name: String, field: &'static str },

    #[error(
        "top-level `db = {value:?}` is not a supported config-file key; \
         use `--db` / `KHIVE_DB` to select a single-file database, or \
         `[[backends]].path` to declare storage backend topology"
    )]
    UnsupportedTopLevelDb { value: String },

    #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
    InvalidGitWriteEntry { repo: String, reason: String },
}

// ---- Config structs ----

/// Configuration for a single embedding engine.
#[derive(Debug, Clone, Deserialize)]
pub struct EngineConfig {
    /// Logical name used to reference this engine in logs and fusion.
    pub name: String,

    /// Lattice-embed model name (e.g. `"all-minilm-l6-v2"`).
    ///
    /// Must be parseable via `lattice_embed::EmbeddingModel::from_str` (or a
    /// recognised short alias handled by `parse_embedding_model_alias`).
    pub model: String,

    /// When `true`, this engine's model becomes the primary (`RuntimeConfig::embedding_model`).
    /// Exactly one engine in the list must set this. If absent, defaults to `false`.
    #[serde(default)]
    pub default: bool,

    /// RRF fusion weight for weighted multi-engine fusion.
    ///
    /// Only meaningful when multiple engines are loaded. Must be `> 0` when
    /// present. `None` means the engine participates in fusion with equal weight
    /// to other engines that also lack a `fusion_weight`.
    ///
    /// For RRF: `fusion_weight` provides per-engine relative importance during
    /// weighted RRF; it does NOT apply to rank-based unweighted RRF (the weights
    /// are injected into `FusionStrategy::Weighted` only).
    pub fusion_weight: Option<f64>,

    /// Expected output dimensionality (optional sanity check).
    ///
    /// Not used at runtime — dimensions are authoritative from
    /// `EmbeddingModel::dimensions()`. Present so operators can document the
    /// expected shape alongside the model name.
    pub dims: Option<u32>,
}

/// Actor configuration — the default namespace / identity for this khive instance.
///
/// Corresponds to the `[actor]` TOML section. `id` is used as the
/// `default_namespace` for gate/attribution policy input. OSS dispatch pins
/// writes to the shared `local` namespace regardless of this value (ADR-007
/// Rev 4 Rule 0); cloud deployments derive the namespace from an authenticated
/// `NamespaceToken` instead.
///
/// ```toml
/// [actor]
/// id = "lambda:leo"                          # attribution identity (required)
/// display_name = "example actor"   # human label (optional)
/// visible_namespaces = ["lambda:khive", "local"]  # widens default read scope (ADR-007 Rev 4 Rule 3b)
/// ```
///
/// `visible_namespaces` is consumed by OSS dispatch to widen the DEFAULT
/// multi-record read scope to `['local'] ∪ visible_namespaces` (ADR-007 Rev 4
/// Rule 3b). Writes remain pinned to `'local'`. An explicit `namespace=` request
/// param is a precise single-namespace escape and is not widened. A cloud gate
/// may also consult this list as policy input at its own layer.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ActorConfig {
    /// Namespace identifier used as the default actor for all operations.
    ///
    /// Must be a valid `Namespace` string (e.g. `"local"`, `"lambda:khive"`).
    /// Defaults to `"local"` when absent — backward-compatible with pre-actor
    /// deployments.
    #[serde(default)]
    pub id: Option<String>,

    /// Optional human-readable label for this actor. Not used by the runtime;
    /// surfaced in introspection and log output only.
    #[serde(default)]
    pub display_name: Option<String>,

    /// Additional namespaces that widen the DEFAULT multi-record read scope
    /// to `['local'] ∪ visible_namespaces` (ADR-007 Rev 4 Rule 3b). Each string
    /// must be a valid `Namespace`. Writes remain pinned to `'local'`. An
    /// explicit `namespace=` request param is a precise escape and is not widened
    /// by this list. A cloud gate may also consult it as policy input.
    #[serde(default)]
    pub visible_namespaces: Option<Vec<String>>,

    /// Namespaces this actor's comm.send/reply may deliver messages INTO
    /// (outbound, sender-side). Empty by default — cross-namespace delivery
    /// denied unless explicitly declared. The comm handler uses an ordinary
    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
    /// the token itself is NOT type-enforced write-only. The recipient-side
    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
    /// a future cloud-path authorization ADR (not yet written).
    ///
    /// Each entry must be a valid `Namespace` string; validated at
    /// config-load time. An empty list preserves the prior deny-all behavior
    /// for any actor that does not add this field.
    #[serde(default)]
    pub allowed_outbound_namespaces: Vec<String>,
}

// ---- Per-pack backend config (ADR-028) ----

/// Storage backend kind.
#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum BackendKind {
    /// SQLite file-backed database (default).
    #[default]
    Sqlite,
    /// In-memory database — for testing only; state is lost on restart.
    Memory,
}

/// Configuration for a named storage backend.
///
/// Corresponds to a `[[backends]]` entry in `khive.toml`.
/// When no `[[backends]]` section is present, a single implicit `main` backend
/// is synthesised from the existing `--db` / `KHIVE_DB` / default-path resolution.
/// All packs fall back to `main` when their name is absent from `[packs]`.
///
/// ```toml
/// [[backends]]
/// name = "knowledge"
/// kind = "sqlite"
/// path = "~/.khive/knowledge.db"
/// cache_mb = 128
/// journal_mode = "wal"
/// read_only = false
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct BackendConfig {
    /// Unique backend name. Referenced by `[packs.<name>].backend`.
    pub name: String,
    /// Storage backend kind. Defaults to `sqlite`.
    #[serde(default)]
    pub kind: BackendKind,
    /// Filesystem path for `sqlite` kind. Tilde is expanded to `$HOME`.
    /// `None` for `memory` kind (path is ignored when present).
    pub path: Option<std::path::PathBuf>,
    /// SQLite page-cache size in MiB.
    pub cache_mb: Option<u32>,
    /// SQLite journal mode (e.g. `"wal"`).
    pub journal_mode: Option<String>,
    /// Open the backend read-only. Defaults to `false`.
    #[serde(default)]
    pub read_only: bool,
}

/// Per-pack backend assignment.
///
/// Corresponds to a `[packs.<pack-name>]` entry in `khive.toml`.
/// Packs whose name is absent from `[packs]` fall back to the `main` backend.
///
/// ```toml
/// [packs.knowledge]
/// backend = "knowledge"
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct PackConfig {
    /// Backend name this pack is assigned to. Must match a `[[backends]].name`.
    pub backend: String,
}

// ---- Blob store config (ADR-111 Amendment 2) ----

/// `[storage.blob]` section: a closed `backend = "fs" | "s3"` selector.
///
/// Internally tagged on `backend` with `deny_unknown_fields`: an unknown
/// top-level key, a field that belongs to the other backend variant (e.g.
/// `bucket` under `backend = "fs"`), or an S3 credential field (never
/// accepted in TOML -- ADR-111 Amendment 2 reads credentials from the
/// process environment only) are all rejected at config-load time by the
/// same mechanism, since each variant only declares its own fields.
///
/// ```toml
/// [storage.blob]
/// backend = "fs"
/// root = "/var/lib/khive/blobs"
/// floor_bytes = 100000000000
/// ```
///
/// ```toml
/// [storage.blob]
/// backend = "s3"
/// bucket = "khive-blobs"
/// region = "us-east-1"
/// endpoint = "https://objects.example.invalid"
/// prefix = "blobs"
/// ```
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
pub enum BlobConfig {
    /// Filesystem-backed blob storage (`FsBlobStore`). Root resolution is
    /// unchanged from khive#292: `KHIVE_BLOB_ROOT` env var, then this
    /// `root`, then `<db_dir>/blobs`.
    Fs {
        #[serde(default)]
        root: Option<String>,
        #[serde(default)]
        floor_bytes: Option<u64>,
    },
    /// S3-compatible blob storage (`S3BlobStore`). `KHIVE_BLOB_ROOT` has no
    /// effect for this backend. Credentials always come from
    /// `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`/`AWS_SESSION_TOKEN` in the
    /// process environment, never from this section.
    S3 {
        bucket: String,
        region: String,
        #[serde(default)]
        endpoint: Option<String>,
        #[serde(default)]
        prefix: Option<String>,
        #[serde(default)]
        allow_http: Option<bool>,
    },
}

/// `[storage]` section in `khive.toml`. Holds storage-layer config not
/// already covered by `[[backends]]` (ADR-028).
#[derive(Debug, Clone, Deserialize, Default)]
pub struct StorageSectionConfig {
    /// Blob store backend selector (ADR-111 Amendment 2). Absent means
    /// `FsBlobStore` at the existing root-resolution precedence, unchanged
    /// from khive#292 -- existing configurations keep behaving exactly as
    /// they did before this section existed.
    #[serde(default)]
    pub blob: Option<BlobConfig>,
}

// ---- git-write policy (ADR-108 Amendment) ----

/// One `[[git_write.allowed]]` entry: a repo this operator has declared
/// trusted for khive-mediated git writes, plus the branches on it a write
/// verb (`git.commit`/`git.branch`/`git.push`) may target.
///
/// ```toml
/// [[git_write.allowed]]
/// repo = "/abs/path/repo"
/// branches = ["feat/*", "fix/*"]
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct GitWriteEntryConfig {
    /// Absolute local path to the allowlisted repository.
    pub repo: String,
    /// Non-empty list of exact branch names or single-`*`-wildcard globs
    /// this repo entry permits writes against.
    pub branches: Vec<String>,
}

/// `[git_write]` section — the closed repo/branch allowlist consulted by
/// `khive-pack-git`'s write verbs at the handler level (ADR-108 Amendment),
/// independent of Gate policy. Absent or empty `allowed` is the fail-closed
/// default: the write verbs report themselves unavailable rather than
/// defaulting open.
///
/// ```toml
/// [[git_write.allowed]]
/// repo = "/abs/path/repo"
/// branches = ["feat/*", "fix/*"]
/// ```
#[derive(Debug, Clone, Deserialize, Default)]
pub struct GitWriteSectionConfig {
    #[serde(default)]
    pub allowed: Vec<GitWriteEntryConfig>,
}

/// Top-level khive configuration loaded from `khive.toml` or `config.toml`.
///
/// Sections consumed today:
/// - `[[engines]]`: embedding engine declarations
/// - `[actor]`: default namespace / identity (OSS actor model)
/// - `[runtime]`: runtime knobs (namespace, brain_profile)
/// - `[[backends]]`: storage backend declarations (ADR-028)
/// - `[packs.<name>]`: per-pack backend assignments (ADR-028)
///
/// Unknown keys are silently ignored by serde — forward-compatible.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct KhiveConfig {
    /// Typed only so a top-level `db` key can be rejected loudly by
    /// [`KhiveConfig::validate`] instead of being silently ignored as an
    /// unknown key. Not a supported config-file storage selector: single-file
    /// database selection is `--db`/`KHIVE_DB`, and storage topology is
    /// `[[backends]].path`.
    #[serde(default)]
    pub db: Option<String>,

    /// Embedding engine declarations.
    #[serde(default)]
    pub engines: Vec<EngineConfig>,

    /// Default actor identity for this khive instance.
    ///
    /// When present, `actor.id` feeds configuration identity and gate/attribution
    /// policy input.  A non-`'local'` `actor.id` is folded into the default READ
    /// visible-set at config load (ADR-007 Rev 4 Rule 3b) — it widens what default
    /// multi-record reads return, but never routes writes or sets `default_namespace`.
    /// Cloud model derives actor identity from an authenticated token.
    #[serde(default)]
    pub actor: ActorConfig,

    /// Runtime knobs: namespace overrides, brain profile, etc.
    #[serde(default)]
    pub runtime: RuntimeSectionConfig,

    /// Named storage backends (ADR-028).
    ///
    /// When absent or empty, a single implicit `main` backend is used and all
    /// packs share it — identical to pre-ADR-028 behavior.
    #[serde(default)]
    pub backends: Vec<BackendConfig>,

    /// Per-pack backend assignments (ADR-028).
    ///
    /// Maps pack name to backend name. Packs absent from this map fall back to
    /// the `main` backend. Validated at load time: every referenced backend name
    /// must appear in `backends`.
    #[serde(default)]
    pub packs: std::collections::HashMap<String, PackConfig>,

    /// Git-write policy allowlist (ADR-108 Amendment). Absent or empty
    /// `allowed` fails closed — `khive-pack-git`'s write verbs are
    /// unavailable until this section is populated.
    #[serde(default)]
    pub git_write: GitWriteSectionConfig,

    /// Storage-layer config not covered by `[[backends]]` (ADR-111
    /// Amendment 2: `[storage.blob]`'s `fs`/`s3` selector).
    #[serde(default)]
    pub storage: StorageSectionConfig,
}

/// `[runtime]` section in `khive.toml`.
///
/// Carries runtime knobs that mirror the CLI flag / env var tier.
/// All fields are optional; absent keys fall through to env vars or built-in
/// defaults.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct RuntimeSectionConfig {
    /// Brain profile ID to use for `memory.feedback` / `knowledge.feedback`
    /// and recall-time score boosting (ADR-035 §Brain profile configuration).
    ///
    /// Mirrors `--brain-profile` / `KHIVE_BRAIN_PROFILE`. When absent, the
    /// namespace-bound profile (via `brain.resolve`) is tried, then the
    /// global tuning prior is used as the final fallback.
    #[serde(default)]
    pub brain_profile: Option<String>,

    /// Default output serialization format (ADR-078).
    ///
    /// Mirrors `--output-format` / `KHIVE_OUTPUT_FORMAT`. Precedence (highest to lowest):
    /// per-request `format` field → `KHIVE_OUTPUT_FORMAT` → this field → builtin `json`.
    ///
    /// Accepted values: `"json"` (default), `"auto"`, `"table"`.
    #[serde(default)]
    pub default_output_format: Option<OutputFormat>,
}

impl KhiveConfig {
    /// Load and validate a `KhiveConfig` from an explicit path.
    ///
    /// Search order:
    /// 1. `path` argument (explicit override — e.g. from `--config` / `KHIVE_CONFIG`)
    /// 2. `./.khive/config.toml` (project-local config, relative to the MCP server cwd)
    ///
    /// The project-local default collocates config with the `khive-test.db` that already
    /// lives under `.khive/` in each project directory. `~/.khive/config.toml` is searched
    /// by [`KhiveConfig::load_with_home_fallback`] when the project-local file is absent.
    ///
    /// If the resolved file does **not exist**, returns `Ok(None)`.
    /// A missing config is not an error — callers fall back to the env-var path.
    ///
    /// If the file exists but cannot be parsed, returns a `ConfigError`.
    /// After parsing, `validate()` runs and any logical errors are returned.
    pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
        let resolved = match path {
            Some(p) => p.to_path_buf(),
            None => PathBuf::from(".khive/config.toml"),
        };

        if !resolved.exists() {
            return Ok(None);
        }

        let raw = std::fs::read_to_string(&resolved)?;
        let cfg: KhiveConfig = toml::from_str(&raw).map_err(|source| ConfigError::Parse {
            path: resolved,
            source,
        })?;
        cfg.validate()?;
        Ok(Some(cfg))
    }

    /// Load config with the full resolution order:
    ///
    /// 1. Explicit `path` (from `--config` / `KHIVE_CONFIG`)
    /// 2. `./khive.toml` (project-local, project root)
    /// 3. `<db-dir>/config.toml` (project-local, anchored to the resolved database's
    ///    own directory — see `project_config_anchor_dir`)
    /// 4. `~/.khive/config.toml` (user-global)
    ///
    /// Returns the first file found, or `Ok(None)` when none exist.
    /// Parse errors are propagated immediately — a malformed config is always
    /// an error regardless of which tier it came from.
    ///
    /// `db_path` should be the same database path the caller is about to open
    /// (or has already resolved). Passing it makes tier 3 resolve identically
    /// for any two processes that target the same database, regardless of
    /// their process working directory — this is what lets a thin client and
    /// a warm daemon serving the same database agree on one config file. Pass
    /// `None` when no database path is known yet; tier 3 then falls back to
    /// the process cwd, matching the pre-existing behavior.
    pub fn load_with_home_fallback(
        path: Option<&Path>,
        db_path: Option<&Path>,
    ) -> Result<Option<Self>, ConfigError> {
        // Tier 1: explicit path (highest priority).
        if let Some(p) = path {
            return Self::load(Some(p));
        }

        // Tiers 2-4: search project root, db-anchored hidden dir, user-global.
        let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let home_root = std::env::var_os("HOME").map(PathBuf::from);
        Self::load_with_roots(&project_root, home_root.as_deref(), db_path)
    }

    /// Testable inner search: tiers 2-4, given explicit roots instead of
    /// reading `cwd` and `HOME` from process state.
    ///
    /// - Tier 2: `<project_root>/khive.toml` (still cwd-anchored — unchanged)
    /// - Tier 3: `<db_dir>/config.toml`, anchored to `db_path` rather than
    ///   `project_root` (see `project_config_anchor_dir`); falls back to
    ///   `<project_root>/.khive/config.toml` when `db_path` is `None`
    /// - Tier 4: `<home_root>/.khive/config.toml` (skipped when `None`)
    pub(crate) fn load_with_roots(
        project_root: &Path,
        home_root: Option<&Path>,
        db_path: Option<&Path>,
    ) -> Result<Option<Self>, ConfigError> {
        // Tier 2: project root khive.toml.
        let tier2 = project_root.join("khive.toml");
        if tier2.exists() {
            return Self::load(Some(&tier2));
        }

        // Tier 3: project-local hidden dir, anchored to the resolved database's
        // own directory instead of the process cwd.
        let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
        if tier3.exists() {
            return Self::load(Some(&tier3));
        }

        // Tier 4: user-global ~/.khive/config.toml.
        if let Some(home) = home_root {
            let tier4 = home.join(".khive/config.toml");
            if tier4.exists() {
                return Self::load(Some(&tier4));
            }
        }

        Ok(None)
    }

    /// Resolve the directory searched for the tier-3 project-local config file.
    ///
    /// Anchored to the directory containing the resolved database file, not the
    /// process cwd: two processes at different working directories that open the
    /// same database agree on this directory, which is what keeps their
    /// `config_id` fingerprints in sync (a client and a warm daemon serving the
    /// same database must resolve identical config so the daemon accepts the
    /// client's forwarded requests instead of rejecting them on a config
    /// mismatch).
    ///
    /// `db_path` is canonicalized first so symlinks/relative components collapse
    /// to the same absolute directory regardless of caller cwd. The database file
    /// may not exist yet (first run before anything has been written) — in that
    /// case canonicalization fails and the path is absolutized against
    /// `project_root` instead (or used as-is if already absolute); this must
    /// never panic, it is the expected cold-start case.
    ///
    /// If `db_dir` (the resolved database's parent directory) is itself named
    /// `.khive`, the config lives directly inside it (`<db_dir>/config.toml`) —
    /// this is the common case where the database is `<root>/.khive/khive.db`.
    /// Otherwise the config lives in a `.khive` subdirectory of `db_dir`.
    ///
    /// `db_path == None` (e.g. an in-memory database, or no database path known
    /// yet) falls back to `<project_root>/.khive`, preserving the pre-existing
    /// cwd-anchored behavior for callers with no database to anchor on.
    fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
        let Some(db_path) = db_path else {
            return project_root.join(".khive");
        };

        let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
            if db_path.is_absolute() {
                db_path.to_path_buf()
            } else {
                project_root.join(db_path)
            }
        });

        let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);

        if db_dir.file_name().is_some_and(|name| name == ".khive") {
            db_dir
        } else {
            db_dir.join(".khive")
        }
    }

    /// Validate the parsed config for logical consistency.
    ///
    /// Checks:
    /// - Exactly one engine has `default = true` (when the list is non-empty).
    /// - Engine names are unique.
    /// - `fusion_weight`, when present, is `> 0`.
    ///
    /// Model name validity is checked lazily at runtime (the config loader does
    /// not import `lattice_embed` directly to keep the dep surface minimal).
    pub fn validate(&self) -> Result<(), ConfigError> {
        // Reject a top-level `db` key loudly instead of letting serde's
        // forward-compatible unknown-key tolerance silently swallow it: a
        // config author expecting `db=` to select the database would
        // otherwise get silent divergence from `--db`/`KHIVE_DB`.
        if let Some(value) = self.db.as_deref() {
            if !value.is_empty() {
                return Err(ConfigError::UnsupportedTopLevelDb {
                    value: value.to_string(),
                });
            }
        }

        // Validate actor.id when present — an invalid namespace is a startup error,
        // not a silent fallback.
        if let Some(id) = self.actor.id.as_deref() {
            if id.is_empty() {
                return Err(ConfigError::InvalidActorId {
                    id: id.to_string(),
                    reason: "actor.id must not be empty; remove the key or provide a value"
                        .to_string(),
                });
            }
            Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
                id: id.to_string(),
                reason: e.to_string(),
            })?;
        }

        if let Some(ref vis) = self.actor.visible_namespaces {
            for ns_str in vis {
                if ns_str.is_empty() {
                    return Err(ConfigError::InvalidActorId {
                        id: ns_str.clone(),
                        reason: "visible_namespaces entries must not be empty".to_string(),
                    });
                }
                Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
                    id: ns_str.clone(),
                    reason: format!("invalid visible namespace: {e}"),
                })?;
            }
        }

        // Validate actor.allowed_outbound_namespaces (fail-closed at startup on malformed entry).
        for ns_str in &self.actor.allowed_outbound_namespaces {
            if ns_str.is_empty() {
                return Err(ConfigError::InvalidActorId {
                    id: ns_str.clone(),
                    reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
                });
            }
            Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
                id: ns_str.clone(),
                reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
            })?;
        }

        // Backend names must be unique.
        if !self.backends.is_empty() {
            let mut seen_backends = std::collections::HashSet::new();
            for backend in &self.backends {
                if !seen_backends.insert(backend.name.clone()) {
                    return Err(ConfigError::DuplicateBackendName {
                        name: backend.name.clone(),
                    });
                }

                // Reject fields that are parsed but not yet implemented: silently
                // accepting them would let misconfiguration slip past startup.
                if backend.cache_mb.is_some() {
                    return Err(ConfigError::UnsupportedBackendField {
                        name: backend.name.clone(),
                        field: "cache_mb",
                    });
                }
                if backend.journal_mode.is_some() {
                    return Err(ConfigError::UnsupportedBackendField {
                        name: backend.name.clone(),
                        field: "journal_mode",
                    });
                }
            }

            // Every pack-referenced backend name must be declared in `backends`.
            let defined: Vec<&str> = self.backends.iter().map(|b| b.name.as_str()).collect();
            for (pack_name, pack_cfg) in &self.packs {
                if !defined.contains(&pack_cfg.backend.as_str()) {
                    return Err(ConfigError::UnknownPackBackend {
                        pack: pack_name.clone(),
                        backend: pack_cfg.backend.clone(),
                        defined: defined.join(", "),
                    });
                }
            }
        }

        // Validate [[git_write.allowed]] entries (ADR-108 Amendment): each
        // repo must be a non-empty absolute path, and each entry must carry
        // at least one branch pattern — an entry with an empty `branches`
        // list would silently allowlist a repo for no branch at all, which
        // reads as "configured" while behaving identically to "not
        // allowlisted"; reject it loudly instead of leaving that trap.
        for entry in &self.git_write.allowed {
            if entry.repo.trim().is_empty() {
                return Err(ConfigError::InvalidGitWriteEntry {
                    repo: entry.repo.clone(),
                    reason: "repo must not be empty".to_string(),
                });
            }
            if !Path::new(&entry.repo).is_absolute() {
                return Err(ConfigError::InvalidGitWriteEntry {
                    repo: entry.repo.clone(),
                    reason: "repo must be an absolute path".to_string(),
                });
            }
            if entry.branches.is_empty() {
                return Err(ConfigError::InvalidGitWriteEntry {
                    repo: entry.repo.clone(),
                    reason: "branches must not be empty".to_string(),
                });
            }
            if entry.branches.iter().any(|b| b.trim().is_empty()) {
                return Err(ConfigError::InvalidGitWriteEntry {
                    repo: entry.repo.clone(),
                    reason: "branches entries must not be empty".to_string(),
                });
            }
            // ADR-108 specifies exact name or a SINGLE-star wildcard per
            // branch pattern -- a pattern with two or more `*` (e.g. `**`,
            // `rel-*-*-final`) is a wider grammar than the ADR authorizes
            // and must be rejected at config load, not silently accepted.
            if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
                return Err(ConfigError::InvalidGitWriteEntry {
                    repo: entry.repo.clone(),
                    reason: format!(
                        "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
                    ),
                });
            }
        }

        if self.engines.is_empty() {
            return Ok(());
        }

        let mut seen_names = std::collections::HashSet::new();
        for engine in &self.engines {
            if !seen_names.insert(engine.name.clone()) {
                return Err(ConfigError::DuplicateName {
                    name: engine.name.clone(),
                });
            }
        }

        let default_count = self.engines.iter().filter(|e| e.default).count();
        if default_count != 1 {
            return Err(ConfigError::DefaultCount {
                found: default_count,
            });
        }

        // Reject non-finite fusion_weight explicitly: NaN doesn't satisfy `w <= 0.0`
        // and +inf is unbounded, so neither is caught by the range check alone.
        for engine in &self.engines {
            if let Some(w) = engine.fusion_weight {
                if !w.is_finite() || w <= 0.0 {
                    return Err(ConfigError::InvalidFusionWeight {
                        name: engine.name.clone(),
                        value: w,
                    });
                }
            }
        }

        Ok(())
    }

    /// Return the engine flagged `default = true`, or `None` if the list is empty.
    pub fn default_engine(&self) -> Option<&EngineConfig> {
        self.engines.iter().find(|e| e.default)
    }
}

// ---- Env-var fallback ----

/// Build an in-memory `KhiveConfig` from the legacy env-var path.
///
/// Used when no config file is present. Emits `tracing::info!` directing
/// operators to migrate to `~/.khive/config.toml`.
///
/// The primary model (`KHIVE_EMBEDDING_MODEL`) becomes the `default = true`
/// engine; additional models become non-default secondary engines.
pub fn config_from_env() -> KhiveConfig {
    let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
        .ok()
        .filter(|s| !s.trim().is_empty());
    let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
        .ok()
        .unwrap_or_default();
    let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
        .into_iter()
        .filter(|s| !s.is_empty())
        .collect();

    if primary_model.is_none() && additional.is_empty() {
        return KhiveConfig::default();
    }

    tracing::info!(
        "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
    );

    let mut engines = Vec::new();

    if let Some(model) = primary_model {
        engines.push(EngineConfig {
            name: "default".to_string(),
            model,
            default: true,
            fusion_weight: None,
            dims: None,
        });
    }

    for (i, model) in additional.into_iter().enumerate() {
        engines.push(EngineConfig {
            name: format!("engine-{}", i + 1),
            model,
            default: false,
            fusion_weight: None,
            dims: None,
        });
    }

    // If no primary was specified but there are additional models, promote the
    // first additional model as the default so the list stays valid.
    if !engines.is_empty() && !engines.iter().any(|e| e.default) {
        engines[0].default = true;
    }

    KhiveConfig {
        engines,
        ..KhiveConfig::default()
    }
}

// ---- Tests ----

// Kept inline (not tests/): exercises private ConfigError variants not part
// of the public API.
#[cfg(test)]
mod tests {
    use super::*;

    fn write_toml(dir: &tempfile::TempDir, content: &str) -> PathBuf {
        let path = dir.path().join("config.toml");
        std::fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn test_load_minimal_config() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "x"
model = "all-minilm-l6-v2"
default = true
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be found");
        assert_eq!(cfg.engines.len(), 1);
        assert_eq!(cfg.engines[0].name, "x");
        assert_eq!(cfg.engines[0].model, "all-minilm-l6-v2");
        assert!(cfg.engines[0].default);
    }

    #[test]
    fn test_default_engine_required_when_engines_present() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "a"
model = "all-minilm-l6-v2"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with no default flagged");
        assert!(
            matches!(err, ConfigError::DefaultCount { found: 0 }),
            "expected DefaultCount {{ found: 0 }}, got {err:?}"
        );
    }

    #[test]
    fn test_multiple_default_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "a"
model = "all-minilm-l6-v2"
default = true

[[engines]]
name = "b"
model = "paraphrase-multilingual-minilm-l12-v2"
default = true
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with two defaults");
        assert!(
            matches!(err, ConfigError::DefaultCount { found: 2 }),
            "expected DefaultCount {{ found: 2 }}, got {err:?}"
        );
    }

    #[test]
    fn test_fusion_weight_validation() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "a"
model = "all-minilm-l6-v2"
default = true
fusion_weight = -0.5
"#,
        );
        let err =
            KhiveConfig::load(Some(&path)).expect_err("should fail with negative fusion_weight");
        assert!(
            matches!(err, ConfigError::InvalidFusionWeight { .. }),
            "expected InvalidFusionWeight, got {err:?}"
        );

        let path2 = write_toml(
            &dir,
            r#"
[[engines]]
name = "a"
model = "all-minilm-l6-v2"
default = true
fusion_weight = 0.0
"#,
        );
        let err2 =
            KhiveConfig::load(Some(&path2)).expect_err("should fail with zero fusion_weight");
        assert!(
            matches!(err2, ConfigError::InvalidFusionWeight { .. }),
            "expected InvalidFusionWeight, got {err2:?}"
        );
    }

    #[test]
    fn test_env_var_fallback() {
        let dir = tempfile::tempdir().unwrap();
        let absent = dir.path().join("missing.toml");

        let loaded = KhiveConfig::load(Some(&absent)).unwrap();
        assert!(loaded.is_none());

        // Can't safely set env vars in a parallel test suite, so exercise the
        // direct construction path instead.
        let primary = "all-minilm-l6-v2".to_string();
        let additional = vec!["paraphrase-multilingual-minilm-l12-v2".to_string()];

        let mut engines = vec![EngineConfig {
            name: "default".to_string(),
            model: primary,
            default: true,
            fusion_weight: None,
            dims: None,
        }];
        for (i, model) in additional.into_iter().enumerate() {
            engines.push(EngineConfig {
                name: format!("engine-{}", i + 1),
                model,
                default: false,
                fusion_weight: None,
                dims: None,
            });
        }
        let cfg = KhiveConfig {
            engines,
            ..KhiveConfig::default()
        };
        cfg.validate().expect("env-derived config should be valid");
        assert_eq!(cfg.engines.len(), 2);
        assert!(cfg.default_engine().is_some());
        assert_eq!(cfg.default_engine().unwrap().name, "default");
    }

    #[test]
    fn test_file_overrides_env() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "file-engine"
model = "all-minilm-l6-v2"
default = true
"#,
        );

        // KhiveConfig::load returns the file config regardless of env vars;
        // warning-on-conflict is the caller's responsibility.
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be present");
        assert_eq!(cfg.engines[0].name, "file-engine");
    }

    #[test]
    fn test_duplicate_engine_names_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "shared"
model = "all-minilm-l6-v2"
default = true

[[engines]]
name = "shared"
model = "paraphrase-multilingual-minilm-l12-v2"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
        assert!(
            matches!(err, ConfigError::DuplicateName { .. }),
            "expected DuplicateName, got {err:?}"
        );
    }

    #[test]
    fn test_empty_config_is_valid() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(&dir, "# no engines\n");
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be found");
        assert!(cfg.engines.is_empty());
        cfg.validate().expect("empty config should be valid");
    }

    #[test]
    fn test_multi_engine_positive_fusion_weight() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "primary"
model = "all-minilm-l6-v2"
default = true
fusion_weight = 0.7

[[engines]]
name = "secondary"
model = "paraphrase-multilingual-minilm-l12-v2"
fusion_weight = 0.3
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be found");
        assert_eq!(cfg.engines.len(), 2);
        assert_eq!(cfg.engines[0].fusion_weight, Some(0.7));
        assert_eq!(cfg.engines[1].fusion_weight, Some(0.3));
    }

    #[test]
    fn test_actor_id_parsed() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[actor]
id = "lambda:khive"
display_name = "example actor"
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be found");
        assert_eq!(cfg.actor.id.as_deref(), Some("lambda:khive"));
        assert_eq!(cfg.actor.display_name.as_deref(), Some("example actor"));
        assert!(cfg.engines.is_empty());
    }

    #[test]
    fn test_actor_and_engines_together() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[actor]
id = "lambda:test"

[[engines]]
name = "default"
model = "all-minilm-l6-v2"
default = true
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be found");
        assert_eq!(cfg.actor.id.as_deref(), Some("lambda:test"));
        assert_eq!(cfg.engines.len(), 1);
    }

    #[test]
    fn test_actor_absent_defaults_to_none() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "x"
model = "all-minilm-l6-v2"
default = true
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be found");
        assert!(
            cfg.actor.id.is_none(),
            "actor.id must be None when [actor] section is absent"
        );
    }

    #[test]
    fn test_load_with_home_fallback_no_files() {
        let project_dir = tempfile::tempdir().unwrap();
        let home_dir = tempfile::tempdir().unwrap();
        let result = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None);
        assert!(
            result.expect("no error expected").is_none(),
            "should return None when no config files exist in the given roots"
        );
    }

    #[test]
    fn test_load_with_home_fallback_explicit_path() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[actor]
id = "lambda:explicit"
"#,
        );
        let cfg = KhiveConfig::load_with_home_fallback(Some(&path), None)
            .expect("no error expected")
            .expect("file found");
        assert_eq!(cfg.actor.id.as_deref(), Some("lambda:explicit"));
    }

    #[test]
    fn test_invalid_actor_id_rejected_at_load() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[actor]
id = "bad namespace"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with invalid actor.id");
        assert!(
            matches!(err, ConfigError::InvalidActorId { .. }),
            "expected InvalidActorId, got {err:?}"
        );
    }

    #[test]
    fn test_empty_actor_id_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[actor]
id = ""
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("empty actor.id should be rejected");
        assert!(
            matches!(err, ConfigError::InvalidActorId { .. }),
            "expected InvalidActorId for empty string, got {err:?}"
        );
    }

    #[test]
    fn test_malformed_actor_id_lambda_colon_only() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[actor]
id = "lambda:"
"#,
        );
        let err =
            KhiveConfig::load(Some(&path)).expect_err("lambda: with no slug should be rejected");
        assert!(
            matches!(err, ConfigError::InvalidActorId { .. }),
            "expected InvalidActorId for 'lambda:', got {err:?}"
        );
    }

    // actor.id must not become default_namespace: writes stay pinned to `local`
    // even though a non-local actor.id widens the default read visible-set.
    #[test]
    fn test_runtime_config_actor_id_does_not_override_namespace() {
        use crate::runtime::runtime_config_from_khive_config;
        use crate::RuntimeConfig;
        use khive_types::namespace::Namespace;

        let cfg = KhiveConfig {
            engines: vec![],
            actor: ActorConfig {
                id: Some("lambda:test-actor".to_string()),
                display_name: None,
                ..Default::default()
            },
            ..KhiveConfig::default()
        };
        cfg.validate().expect("valid config");

        let base = RuntimeConfig::default();
        let result = runtime_config_from_khive_config(&cfg, base);
        assert_eq!(
            result.default_namespace,
            Namespace::local(),
            "actor.id must NOT become default_namespace (ADR-007 Rev 4 Rule 0); \
             writes stay pinned to local"
        );
        // actor.id must also appear in visible_namespaces: the load-bearing
        // side effect that widens default reads to {local} ∪ {actor namespace}.
        assert!(
            result
                .visible_namespaces
                .contains(&Namespace::parse("lambda:test-actor").unwrap()),
            "actor.id must be folded into visible_namespaces (ADR-007 Rev 4 Rule 3b fold-in); \
             got: {:?}",
            result.visible_namespaces
        );
    }

    #[test]
    fn test_runtime_config_no_actor_preserves_base() {
        use crate::runtime::runtime_config_from_khive_config;
        use crate::RuntimeConfig;
        use khive_types::namespace::Namespace;

        let cfg = KhiveConfig {
            engines: vec![],
            actor: ActorConfig {
                id: None,
                display_name: None,
                ..Default::default()
            },
            ..KhiveConfig::default()
        };
        cfg.validate().expect("valid config");

        let base_ns = Namespace::parse("lambda:base").unwrap();
        let base = RuntimeConfig {
            default_namespace: base_ns.clone(),
            ..RuntimeConfig::default()
        };
        let result = runtime_config_from_khive_config(&cfg, base);
        assert_eq!(
            result.default_namespace, base_ns,
            "no actor.id must leave base namespace unchanged"
        );
    }

    #[test]
    fn test_load_with_home_fallback_project_root_over_hidden() {
        let dir = tempfile::tempdir().unwrap();

        // Write .khive/config.toml (tier 3).
        std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
        std::fs::write(
            dir.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:hidden\"\n",
        )
        .unwrap();

        // Write khive.toml (tier 2) — should win.
        std::fs::write(
            dir.path().join("khive.toml"),
            "[actor]\nid = \"lambda:project-root\"\n",
        )
        .unwrap();

        let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
            .expect("no error expected")
            .expect("file should be found");
        assert_eq!(
            cfg.actor.id.as_deref(),
            Some("lambda:project-root"),
            "khive.toml (tier 2) must win over .khive/config.toml (tier 3)"
        );
    }

    #[test]
    fn test_load_with_home_fallback_hidden_over_absent_root() {
        let dir = tempfile::tempdir().unwrap();

        std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
        std::fs::write(
            dir.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:hidden-config\"\n",
        )
        .unwrap();
        // No khive.toml.

        let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
            .expect("no error expected")
            .expect("file should be found");
        assert_eq!(
            cfg.actor.id.as_deref(),
            Some("lambda:hidden-config"),
            ".khive/config.toml (tier 3) must be found when khive.toml is absent"
        );
    }

    #[test]
    fn test_load_with_roots_home_tier_found() {
        let project_dir = tempfile::tempdir().unwrap();
        let home_dir = tempfile::tempdir().unwrap();

        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
        std::fs::write(
            home_dir.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:user-global\"\n",
        )
        .unwrap();
        // No project-level files.

        let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
            .expect("no error expected")
            .expect("file should be found");
        assert_eq!(
            cfg.actor.id.as_deref(),
            Some("lambda:user-global"),
            "~/.khive/config.toml (tier 4) must be found when project files absent"
        );
    }

    #[test]
    fn test_load_with_roots_project_wins_over_home() {
        let project_dir = tempfile::tempdir().unwrap();
        let home_dir = tempfile::tempdir().unwrap();

        // Home has a config.
        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
        std::fs::write(
            home_dir.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:user-global\"\n",
        )
        .unwrap();

        // Project also has a config — should win.
        std::fs::create_dir_all(project_dir.path().join(".khive")).unwrap();
        std::fs::write(
            project_dir.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:project-wins\"\n",
        )
        .unwrap();

        let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
            .expect("no error expected")
            .expect("file should be found");
        assert_eq!(
            cfg.actor.id.as_deref(),
            Some("lambda:project-wins"),
            "project .khive/config.toml (tier 3) must win over ~/.khive/config.toml (tier 4)"
        );
    }

    // ── tier-3 db-dir anchor tests (config discovery canonicalization) ─────

    // Two different process working directories, targeting the same database,
    // must resolve the identical tier-3 config file. Each cwd also carries its
    // own decoy `.khive/config.toml` so the test fails loudly (mismatched
    // actor ids) if the resolver ever falls back to the old cwd anchor instead
    // of the db-dir anchor.
    #[test]
    fn test_load_with_roots_same_db_different_cwd_resolves_identical_config() {
        let cwd_a = tempfile::tempdir().unwrap();
        let cwd_b = tempfile::tempdir().unwrap();

        // Decoy cwd-anchored configs — must NOT be picked up once anchoring
        // moves to the db directory.
        std::fs::create_dir_all(cwd_a.path().join(".khive")).unwrap();
        std::fs::write(
            cwd_a.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:wrong-cwd-a\"\n",
        )
        .unwrap();
        std::fs::create_dir_all(cwd_b.path().join(".khive")).unwrap();
        std::fs::write(
            cwd_b.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:wrong-cwd-b\"\n",
        )
        .unwrap();

        // The database and its co-located config live under a THIRD root,
        // distinct from either simulated cwd.
        let db_root = tempfile::tempdir().unwrap();
        let khive_dir = db_root.path().join(".khive");
        std::fs::create_dir_all(&khive_dir).unwrap();
        let db_path = khive_dir.join("khive.db");
        std::fs::write(&db_path, b"").unwrap(); // must exist for canonicalize to succeed
        std::fs::write(
            khive_dir.join("config.toml"),
            "[actor]\nid = \"lambda:db-anchored\"\n",
        )
        .unwrap();

        let cfg_a = KhiveConfig::load_with_roots(cwd_a.path(), None, Some(&db_path))
            .expect("no error expected")
            .expect("db-anchored config must be found from cwd A");
        let cfg_b = KhiveConfig::load_with_roots(cwd_b.path(), None, Some(&db_path))
            .expect("no error expected")
            .expect("db-anchored config must be found from cwd B");

        assert_eq!(
            cfg_a.actor.id.as_deref(),
            Some("lambda:db-anchored"),
            "cwd A must resolve the db-anchored config, not its own decoy"
        );
        assert_eq!(
            cfg_b.actor.id.as_deref(),
            Some("lambda:db-anchored"),
            "cwd B must resolve the db-anchored config, not its own decoy"
        );
        assert_eq!(
            cfg_a.actor.id, cfg_b.actor.id,
            "two processes at different cwds targeting the same db must resolve \
             identical config, killing config_id drift between client and daemon"
        );
    }

    // Explicit `--config`/`KHIVE_CONFIG` (tier 1) must still win over the new
    // db-dir anchor (tier 3) — precedence is preserved, only the tier-3 anchor
    // moved.
    #[test]
    fn test_load_with_home_fallback_explicit_config_wins_over_db_anchor() {
        let explicit_dir = tempfile::tempdir().unwrap();
        let explicit_path = write_toml(&explicit_dir, "[actor]\nid = \"lambda:explicit-wins\"\n");

        let db_root = tempfile::tempdir().unwrap();
        let khive_dir = db_root.path().join(".khive");
        std::fs::create_dir_all(&khive_dir).unwrap();
        let db_path = khive_dir.join("khive.db");
        std::fs::write(&db_path, b"").unwrap();
        std::fs::write(
            khive_dir.join("config.toml"),
            "[actor]\nid = \"lambda:db-anchor-loses\"\n",
        )
        .unwrap();

        let cfg = KhiveConfig::load_with_home_fallback(Some(&explicit_path), Some(&db_path))
            .expect("no error expected")
            .expect("explicit path must be found");
        assert_eq!(
            cfg.actor.id.as_deref(),
            Some("lambda:explicit-wins"),
            "explicit --config/KHIVE_CONFIG must win over the db-dir anchor"
        );
    }

    // Tier 4 (`~/.khive/config.toml`) must still be reached when the db-anchored
    // tier-3 directory has no `config.toml` alongside it.
    #[test]
    fn test_load_with_roots_home_fallback_reached_when_db_anchor_has_no_config() {
        let cwd = tempfile::tempdir().unwrap();
        let home_dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
        std::fs::write(
            home_dir.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:home-fallback\"\n",
        )
        .unwrap();

        // A real db directory that exists but has no co-located config.toml.
        let db_root = tempfile::tempdir().unwrap();
        let khive_dir = db_root.path().join(".khive");
        std::fs::create_dir_all(&khive_dir).unwrap();
        let db_path = khive_dir.join("khive.db");
        std::fs::write(&db_path, b"").unwrap();

        let cfg = KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&db_path))
            .expect("no error expected")
            .expect("home-tier config must be found");
        assert_eq!(
            cfg.actor.id.as_deref(),
            Some("lambda:home-fallback"),
            "tier 4 (~/.khive/config.toml) must still be reached when the db-anchored \
             tier-3 directory has no config.toml"
        );
    }

    // Cold start: the database file does not exist yet (first run). Anchor
    // resolution must not panic and must fall through the remaining tiers.
    #[test]
    fn test_load_with_roots_nonexistent_db_path_does_not_panic_and_falls_through() {
        let cwd = tempfile::tempdir().unwrap();
        let home_dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
        std::fs::write(
            home_dir.path().join(".khive/config.toml"),
            "[actor]\nid = \"lambda:home-cold-start\"\n",
        )
        .unwrap();

        // Absolute path under a directory tree that was never created.
        let nonexistent_db = cwd.path().join("never-created/.khive/khive.db");

        let cfg =
            KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&nonexistent_db))
                .expect("cold-start db path must not error or panic")
                .expect("home-tier config must still be found");
        assert_eq!(
            cfg.actor.id.as_deref(),
            Some("lambda:home-cold-start"),
            "a nonexistent db path (cold start) must fall through to tier 4, not panic"
        );
    }

    // Cold start with a *relative* nonexistent db path exercises the
    // cwd-join fallback branch specifically (as opposed to the
    // already-absolute fallback branch above). Must not panic; no config
    // exists anywhere so the result is `Ok(None)`.
    #[test]
    fn test_load_with_roots_relative_nonexistent_db_path_does_not_panic() {
        let cwd = tempfile::tempdir().unwrap();
        let relative_db = PathBuf::from("never-created/.khive/khive.db");

        let result = KhiveConfig::load_with_roots(cwd.path(), None, Some(&relative_db));
        assert!(
            result.is_ok(),
            "relative cold-start db path must not error or panic: {result:?}"
        );
        assert!(
            result.unwrap().is_none(),
            "no config exists anywhere in this test; result must be None"
        );
    }

    // ── ADR-028 backend / pack config tests ─────────────────────────────────

    #[test]
    fn test_no_backends_section_is_valid() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[engines]]
name = "default"
model = "all-minilm-l6-v2"
default = true
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert!(cfg.backends.is_empty());
        assert!(cfg.packs.is_empty());
    }

    #[test]
    fn test_single_sqlite_backend_parses() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[backends]]
name = "knowledge"
kind = "sqlite"
path = "/tmp/knowledge.db"
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert_eq!(cfg.backends.len(), 1);
        let b = &cfg.backends[0];
        assert_eq!(b.name, "knowledge");
        assert!(matches!(b.kind, BackendKind::Sqlite));
        assert_eq!(
            b.path.as_ref().and_then(|p| p.to_str()),
            Some("/tmp/knowledge.db")
        );
    }

    #[test]
    fn test_memory_backend_parses() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[backends]]
name = "ephemeral"
kind = "memory"
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert_eq!(cfg.backends.len(), 1);
        assert!(matches!(cfg.backends[0].kind, BackendKind::Memory));
    }

    #[test]
    fn test_pack_backend_assignment_parses() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[backends]]
name = "knowledge"
kind = "memory"

[packs.knowledge]
backend = "knowledge"
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert_eq!(cfg.packs.len(), 1);
        let pc = cfg.packs.get("knowledge").expect("knowledge pack present");
        assert_eq!(pc.backend, "knowledge");
    }

    #[test]
    fn test_duplicate_backend_name_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[backends]]
name = "dup"
kind = "memory"

[[backends]]
name = "dup"
kind = "memory"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
        assert!(
            matches!(err, ConfigError::DuplicateBackendName { ref name } if name == "dup"),
            "expected DuplicateBackendName {{ name: \"dup\" }}, got {err:?}"
        );
    }

    #[test]
    fn test_pack_referencing_undefined_backend_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[backends]]
name = "knowledge"
kind = "memory"

[packs.kg]
backend = "nonexistent"
"#,
        );
        let err =
            KhiveConfig::load(Some(&path)).expect_err("should fail with unknown backend reference");
        assert!(
            matches!(err, ConfigError::UnknownPackBackend { ref pack, ref backend, .. }
                if pack == "kg" && backend == "nonexistent"),
            "expected UnknownPackBackend for kg→nonexistent, got {err:?}"
        );
    }

    #[test]
    fn test_pack_config_without_backends_section_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        // When [[backends]] is absent/empty, packs are not validated: all
        // packs fall through to the implicit main backend.
        let path = write_toml(
            &dir,
            r#"
[packs.kg]
backend = "main"
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error expected")
            .expect("file found");
        assert_eq!(cfg.backends.len(), 0);
        assert_eq!(cfg.packs.len(), 1);
    }

    #[test]
    fn test_backend_cache_mb_rejected_at_validate() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[backends]]
name = "main"
kind = "memory"
cache_mb = 128
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("cache_mb must be rejected");
        assert!(
            matches!(err, ConfigError::UnsupportedBackendField { ref name, field: "cache_mb" } if name == "main"),
            "expected UnsupportedBackendField {{ name: \"main\", field: \"cache_mb\" }}, got {err:?}"
        );
    }

    #[test]
    fn test_backend_journal_mode_rejected_at_validate() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[backends]]
name = "main"
kind = "memory"
journal_mode = "wal"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("journal_mode must be rejected");
        assert!(
            matches!(err, ConfigError::UnsupportedBackendField { ref name, field: "journal_mode" } if name == "main"),
            "expected UnsupportedBackendField {{ name: \"main\", field: \"journal_mode\" }}, got {err:?}"
        );
    }

    // A top-level `db` key must be rejected loudly instead of silently
    // ignored as an unknown key by serde's forward-compatible default.
    #[test]
    fn test_top_level_db_rejected_at_validate() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
db = "/tmp/scratch/demo.db"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("top-level db must be rejected");
        assert!(
            matches!(err, ConfigError::UnsupportedTopLevelDb { ref value } if value == "/tmp/scratch/demo.db"),
            "expected UnsupportedTopLevelDb {{ value: \"/tmp/scratch/demo.db\" }}, got {err:?}"
        );
    }

    // ── [git_write] section (ADR-108 Amendment) ─────────────────────────────

    // No [git_write] section at all -> empty allowlist, valid config.
    #[test]
    fn test_no_git_write_section_is_valid_and_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(&dir, "# no git_write section\n");
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert!(cfg.git_write.allowed.is_empty());
    }

    // A well-formed [[git_write.allowed]] entry parses correctly.
    #[test]
    fn test_git_write_entry_parses() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[git_write.allowed]]
repo = "/abs/path/repo"
branches = ["feat/*", "fix/*"]
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert_eq!(cfg.git_write.allowed.len(), 1);
        assert_eq!(cfg.git_write.allowed[0].repo, "/abs/path/repo");
        assert_eq!(
            cfg.git_write.allowed[0].branches,
            vec!["feat/*".to_string(), "fix/*".to_string()]
        );
    }

    // A relative repo path is rejected at validate() time.
    #[test]
    fn test_git_write_relative_repo_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[git_write.allowed]]
repo = "relative/path"
branches = ["main"]
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("relative repo must be rejected");
        assert!(
            matches!(err, ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "relative/path"),
            "expected InvalidGitWriteEntry, got {err:?}"
        );
    }

    // ADR-108: a branch pattern with more than one `*` is rejected at
    // validate() time -- the ADR authorizes exact-name or single-wildcard
    // patterns only.
    #[test]
    fn test_git_write_multi_star_branch_pattern_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[git_write.allowed]]
repo = "/abs/path"
branches = ["**"]
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("** must be rejected");
        assert!(
            matches!(err, ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
            "expected InvalidGitWriteEntry, got {err:?}"
        );

        let dir2 = tempfile::tempdir().unwrap();
        let path2 = write_toml(
            &dir2,
            r#"
[[git_write.allowed]]
repo = "/abs/path"
branches = ["rel-*-*-final"]
"#,
        );
        let err2 = KhiveConfig::load(Some(&path2)).expect_err("rel-*-*-final must be rejected");
        assert!(
            matches!(err2, ConfigError::InvalidGitWriteEntry { .. }),
            "expected InvalidGitWriteEntry, got {err2:?}"
        );
    }

    // Single-wildcard patterns remain accepted.
    #[test]
    fn test_git_write_single_star_branch_pattern_accepted() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[git_write.allowed]]
repo = "/abs/path"
branches = ["a*b", "main"]
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert_eq!(cfg.git_write.allowed[0].branches, vec!["a*b", "main"]);
    }

    // An entry with an empty branches list is rejected at validate() time --
    // it would otherwise silently allowlist a repo for no branch at all.
    #[test]
    fn test_git_write_empty_branches_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[[git_write.allowed]]
repo = "/abs/path"
branches = []
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("empty branches must be rejected");
        assert!(
            matches!(err, ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
            "expected InvalidGitWriteEntry, got {err:?}"
        );
    }

    // ── [storage.blob] section (ADR-111 Amendment 2) ─────────────────────────

    // No [storage] section at all -> fs default, existing configurations
    // keep behaving exactly as they did before this section existed.
    #[test]
    fn test_no_storage_section_defaults_to_fs() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(&dir, "# no storage section\n");
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        assert!(cfg.storage.blob.is_none());
    }

    #[test]
    fn test_storage_blob_fs_selection_parses() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[storage.blob]
backend = "fs"
root = "/var/lib/khive/blobs"
floor_bytes = 100000000000
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        match cfg.storage.blob {
            Some(BlobConfig::Fs { root, floor_bytes }) => {
                assert_eq!(root.as_deref(), Some("/var/lib/khive/blobs"));
                assert_eq!(floor_bytes, Some(100_000_000_000));
            }
            other => panic!("expected BlobConfig::Fs, got {other:?}"),
        }
    }

    #[test]
    fn test_storage_blob_s3_selection_parses() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[storage.blob]
backend = "s3"
bucket = "khive-blobs"
region = "us-east-1"
endpoint = "https://objects.example.invalid"
prefix = "blobs"
"#,
        );
        let cfg = KhiveConfig::load(Some(&path))
            .expect("no error")
            .expect("file found");
        match cfg.storage.blob {
            Some(BlobConfig::S3 {
                bucket,
                region,
                endpoint,
                prefix,
                allow_http,
            }) => {
                assert_eq!(bucket, "khive-blobs");
                assert_eq!(region, "us-east-1");
                assert_eq!(endpoint.as_deref(), Some("https://objects.example.invalid"));
                assert_eq!(prefix.as_deref(), Some("blobs"));
                assert_eq!(allow_http, None);
            }
            other => panic!("expected BlobConfig::S3, got {other:?}"),
        }
    }

    // An unknown field under [storage.blob] must be a startup error, not
    // silently ignored -- unlike the rest of KhiveConfig, this section is
    // strict (deny_unknown_fields).
    #[test]
    fn test_storage_blob_unknown_field_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[storage.blob]
backend = "fs"
made_up_field = "x"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("unknown field must be rejected");
        assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
    }

    // An s3-only field (bucket) under backend = "fs" must be rejected: the
    // internally tagged enum's Fs variant doesn't declare it, so it is an
    // unknown field for that variant.
    #[test]
    fn test_storage_blob_other_backend_field_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[storage.blob]
backend = "fs"
bucket = "khive-blobs"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("s3 field under fs must be rejected");
        assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
    }

    // Credentials are never accepted in TOML (ADR-111 Amendment 2): an
    // access-key field under backend = "s3" is unknown to that variant and
    // must be rejected, the same way an other-backend field is.
    #[test]
    fn test_storage_blob_credential_field_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[storage.blob]
backend = "s3"
bucket = "khive-blobs"
region = "us-east-1"
access_key_id = "AKIAEXAMPLE"
"#,
        );
        let err = KhiveConfig::load(Some(&path))
            .expect_err("a credential field in TOML must be rejected");
        assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
    }

    // An unrecognized backend value is rejected by the internally tagged
    // enum's own tag matching, same mechanism as an unknown field.
    #[test]
    fn test_storage_blob_unknown_backend_value_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[storage.blob]
backend = "gcs"
"#,
        );
        let err = KhiveConfig::load(Some(&path)).expect_err("unknown backend must be rejected");
        assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
    }
}