khive-runtime 0.3.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
//! 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 },
}

// ---- 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 = "Leo global orchestrator"   # 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,
}

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

/// `[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. `./.khive/config.toml` (project-local, hidden 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.
    pub fn load_with_home_fallback(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, 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())
    }

    /// Testable inner search: tiers 2-4, given explicit roots instead of
    /// reading `cwd` and `HOME` from process state.
    ///
    /// - Tier 2: `<project_root>/khive.toml`
    /// - Tier 3: `<project_root>/.khive/config.toml`
    /// - Tier 4: `<home_root>/.khive/config.toml` (skipped when `None`)
    pub(crate) fn load_with_roots(
        project_root: &Path,
        home_root: 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.
        let tier3 = project_root.join(".khive/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)
    }

    /// 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> {
        // 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(),
            })?;
        }

        // Validate actor.visible_namespaces when present.
        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}"),
            })?;
        }

        // Validate [[backends]]: unique names (ADR-028).
        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 supported (ADR-028 §1).
                // An operator setting cache_mb or journal_mode would get silently
                // ignored — reject loudly so misconfiguration is caught at 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",
                    });
                }
            }

            // Validate [packs.<name>].backend references (ADR-028).
            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(", "),
                    });
                }
            }
        }

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

        // Unique names
        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(),
                });
            }
        }

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

        // Positive, finite fusion_weight when present.
        // NaN does not satisfy `w <= 0.0`, and positive infinity is unbounded,
        // so reject all non-finite values explicitly before the range check.
        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 ----

// INLINE TEST JUSTIFICATION: tests here cover config validation error paths that
// rely on private ConfigError variants and temp-file helpers shared with the
// config loader. Moving them to tests/ would require pub-exporting ConfigError
// internals that are not part of the stable public API.
#[cfg(test)]
mod tests {
    use super::*;

    // Helper: write a temp file and return the path.
    fn write_toml(dir: &tempfile::TempDir, content: &str) -> PathBuf {
        let path = dir.path().join("config.toml");
        std::fs::write(&path, content).unwrap();
        path
    }

    // 1. Minimal config parses successfully.
    #[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);
    }

    // 2. Zero default-flagged engines -> error.
    #[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:?}"
        );
    }

    // 3. Two engines both flagged default -> error.
    #[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:?}"
        );
    }

    // 4. Negative or zero fusion_weight -> error.
    #[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:?}"
        );
    }

    // 5. File absent + env vars set -> constructs equivalent KhiveConfig.
    #[test]
    fn test_env_var_fallback() {
        let dir = tempfile::tempdir().unwrap();
        let absent = dir.path().join("missing.toml");

        // File does not exist -> KhiveConfig::load returns None.
        let loaded = KhiveConfig::load(Some(&absent)).unwrap();
        assert!(loaded.is_none());

        // With env vars set, config_from_env builds a synthetic config.
        // We can't set env vars safely in a parallel test suite, so test via
        // 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");
    }

    // 6. File present + env vars set -> file wins; test via RuntimeConfig.
    #[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
"#,
        );

        // File load succeeds even if env vars would provide a different model.
        // The caller (RuntimeConfig::from_khive_config) is responsible for
        // checking whether env vars are also present and emitting the warning.
        // Here we verify that KhiveConfig::load returns the file config.
        let cfg = KhiveConfig::load(Some(&path))
            .expect("load should succeed")
            .expect("file should be present");
        assert_eq!(cfg.engines[0].name, "file-engine");
    }

    // 7. Duplicate engine names -> error.
    #[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:?}"
        );
    }

    // 8. Empty config file -> no engines; validate succeeds.
    #[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");
    }

    // 9. Multi-engine config with valid positive fusion_weight -> succeeds.
    #[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));
    }

    // 10. [actor] section with id -> parsed correctly.
    #[test]
    fn test_actor_id_parsed() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_toml(
            &dir,
            r#"
[actor]
id = "lambda:khive"
display_name = "Ocean's khive lambda"
"#,
        );
        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("Ocean's khive lambda")
        );
        assert!(cfg.engines.is_empty());
    }

    // 11. [actor] section with engines -> both parsed.
    #[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);
    }

    // 12. Missing [actor] section -> defaults to None id (backward compat).
    #[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"
        );
    }

    // 13. load_with_roots returns None when no files exist in the given roots.
    #[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()));
        assert!(
            result.expect("no error expected").is_none(),
            "should return None when no config files exist in the given roots"
        );
    }

    // 14. load_with_home_fallback explicit path overrides search.
    #[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))
            .expect("no error expected")
            .expect("file found");
        assert_eq!(cfg.actor.id.as_deref(), Some("lambda:explicit"));
    }

    // 15. actor.id with an invalid namespace string -> ConfigError::InvalidActorId at load time.
    #[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:?}"
        );
    }

    // 16. actor.id = "" (empty string) -> ConfigError::InvalidActorId.
    #[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:?}"
        );
    }

    // 17. actor.id = "lambda:" (structurally invalid — no slug) -> ConfigError::InvalidActorId.
    #[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:?}"
        );
    }

    // 18. ADR-007 Rev 4 Rule 0: actor.id must NOT become default_namespace — writes
    //     stay pinned to `local`. A non-`'local'` actor.id IS folded into the
    //     default READ visible-set (ADR-007 Rev 4 Rule 3b), but that does not affect
    //     default_namespace. This test asserts the write-routing invariant only.
    #[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"
        );
        // Also assert the fold-in: actor.id MUST appear in visible_namespaces so that
        // default reads widen to {local} ∪ {actor namespace} (ADR-007 Rev 4 Rule 3b,
        // config.rs:~444). This is the load-bearing side-effect of the actor id config.
        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
        );
    }

    // 19. runtime_config_from_khive_config with no actor preserves base namespace.
    #[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"
        );
    }

    // 20. load_with_roots: khive.toml (tier 2) wins over .khive/config.toml (tier 3).
    #[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)
            .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)"
        );
    }

    // 21. load_with_roots: .khive/config.toml (tier 3) wins when khive.toml absent.
    #[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)
            .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"
        );
    }

    // 22. load_with_roots: ~/.khive/config.toml (tier 4) found when project files 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()))
            .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"
        );
    }

    // 23. load_with_roots: project tier wins over home tier.
    #[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()))
            .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)"
        );
    }

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

    // 22. No [[backends]] → empty vecs, no validation error.
    #[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());
    }

    // 23. Single Sqlite backend deserializes correctly.
    #[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")
        );
    }

    // 24. Memory backend parses correctly.
    #[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));
    }

    // 25. Pack config backend assignment parses correctly.
    #[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");
    }

    // 26. Duplicate backend names → DuplicateBackendName error.
    #[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:?}"
        );
    }

    // 27. Pack referencing undefined backend → UnknownPackBackend error.
    #[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:?}"
        );
    }

    // 28. Pack config with no [[backends]] → packs section validated only when backends present.
    #[test]
    fn test_pack_config_without_backends_section_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        // Per the spec: 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"
"#,
        );
        // This should succeed: no backends declared → no validation of packs.
        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);
    }

    // B-SHOULD-FIX-1: cache_mb in [[backends]] must be rejected at validate() with a clear error.
    #[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:?}"
        );
    }

    // B-SHOULD-FIX-1: journal_mode in [[backends]] must be rejected at validate() with a clear error.
    #[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:?}"
        );
    }
}