khive-runtime 0.2.4

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
//! TOML-based embedding engine configuration for khive.
//!
//! Loads `./.khive/config.toml` (or a path from `--config` / `KHIVE_CONFIG`)
//! and exposes an `[[engines]]` array that drives arbitrary-N embedding engine
//! registration per ADR-031 §D3.
//!
//! # Config file format
//!
//! ```toml
//! [[engines]]
//! name = "default"
//! model = "all-minilm-l6-v2"
//! default = true
//! fusion_weight = 0.5
//!
//! [[engines]]
//! name = "paraphrase"
//! model = "paraphrase-multilingual-minilm-l12-v2"
//! fusion_weight = 0.5
//! ```
//!
//! # Resolution order
//!
//! 1. Config file (from `--config` / `KHIVE_CONFIG` / `./.khive/config.toml`)
//! 2. Env-var fallback (`KHIVE_EMBEDDING_MODEL` + `KHIVE_ADDITIONAL_EMBEDDING_MODELS`)
//!    when no config file is present
//!
//! If both file and env vars are present, the file wins and a warning is emitted.

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

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

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

// ---- 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. In OSS mode the runtime uses
/// `id` as the `default_namespace` stamped on every write operation. Cloud
/// deployments derive the namespace from an authenticated `NamespaceToken`
/// instead; the `[actor]` section is ignored there.
///
/// ```toml
/// [actor]
/// id = "lambda:khive"          # default namespace (required)
/// display_name = "Ocean's khive lambda"  # human label (optional)
/// ```
#[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>,
}

/// Top-level khive configuration loaded from `khive.toml` or `config.toml`.
///
/// Sections consumed today:
/// - `[[engines]]`: embedding engine declarations (ADR-031 §D3)
/// - `[actor]`: default namespace / identity (OSS actor model)
///
/// Unknown keys are silently ignored by serde — forward-compatible.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct KhiveConfig {
    /// Embedding engine declarations (ADR-031 §D3).
    #[serde(default)]
    pub engines: Vec<EngineConfig>,

    /// Default actor (namespace) for this khive instance.
    ///
    /// When present, `actor.id` becomes the `default_namespace` used by the
    /// runtime when no per-operation `namespace` argument is supplied. OSS
    /// model: no enforcement — any operation may still pass `namespace=` to
    /// use a different namespace. Cloud model derives namespace from an
    /// authenticated token and ignores this field.
    #[serde(default)]
    pub actor: ActorConfig,
}

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 (ADR-007 §NamespaceToken minting).
        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 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 fusion_weight when present
        for engine in &self.engines {
            if let Some(w) = engine.fusion_weight {
                if 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,
        actor: ActorConfig::default(),
    }
}

// ---- Tests ----

#[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,
            actor: ActorConfig::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. runtime_config_from_khive_config applies valid actor.id to default_namespace.
    #[test]
    fn test_runtime_config_actor_id_applied() {
        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,
            },
        };
        cfg.validate().expect("valid config");

        let base = RuntimeConfig::default();
        let result = runtime_config_from_khive_config(&cfg, base);
        assert_eq!(
            result.default_namespace,
            Namespace::parse("lambda:test-actor").unwrap(),
            "actor.id must become default_namespace"
        );
    }

    // 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,
            },
        };
        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)"
        );
    }
}