1use std::path::{Path, PathBuf};
8
9use khive_types::namespace::Namespace;
10use serde::Deserialize;
11use thiserror::Error;
12
13use crate::presentation::OutputFormat;
14
15#[derive(Debug, Error)]
19pub enum ConfigError {
20 #[error("config file I/O: {0}")]
21 Io(#[from] std::io::Error),
22
23 #[error("config TOML parse error in {path}: {source}")]
24 Parse {
25 path: PathBuf,
26 #[source]
27 source: toml::de::Error,
28 },
29
30 #[error("exactly one engine must be marked `default = true`; found {found}")]
31 DefaultCount { found: usize },
32
33 #[error("duplicate engine name: {name:?}")]
34 DuplicateName { name: String },
35
36 #[error(
37 "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
38 )]
39 UnknownModel { name: String, model: String },
40
41 #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
42 InvalidFusionWeight { name: String, value: f64 },
43
44 #[error("actor.id {id:?} is not a valid namespace: {reason}")]
45 InvalidActorId { id: String, reason: String },
46
47 #[error("duplicate backend name: {name:?}")]
48 DuplicateBackendName { name: String },
49
50 #[error(
51 "[packs.{pack}].backend = {backend:?} references an unknown backend; \
52 defined backends: {defined}"
53 )]
54 UnknownPackBackend {
55 pack: String,
56 backend: String,
57 defined: String,
58 },
59
60 #[error(
61 "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
62 remove it from the config or wait for a future release that implements it"
63 )]
64 UnsupportedBackendField { name: String, field: &'static str },
65
66 #[error(
67 "top-level `db = {value:?}` is not a supported config-file key; \
68 use `--db` / `KHIVE_DB` to select a single-file database, or \
69 `[[backends]].path` to declare storage backend topology"
70 )]
71 UnsupportedTopLevelDb { value: String },
72
73 #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
74 InvalidGitWriteEntry { repo: String, reason: String },
75}
76
77#[derive(Debug, Clone, Deserialize)]
81pub struct EngineConfig {
82 pub name: String,
84
85 pub model: String,
90
91 #[serde(default)]
94 pub default: bool,
95
96 pub fusion_weight: Option<f64>,
106
107 pub dims: Option<u32>,
113}
114
115#[derive(Debug, Clone, Deserialize, Default)]
136pub struct ActorConfig {
137 #[serde(default)]
143 pub id: Option<String>,
144
145 #[serde(default)]
148 pub display_name: Option<String>,
149
150 #[serde(default)]
156 pub visible_namespaces: Option<Vec<String>>,
157
158 #[serde(default)]
170 pub allowed_outbound_namespaces: Vec<String>,
171}
172
173#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
177#[serde(rename_all = "lowercase")]
178pub enum BackendKind {
179 #[default]
181 Sqlite,
182 Memory,
184}
185
186#[derive(Debug, Clone, Deserialize)]
203pub struct BackendConfig {
204 pub name: String,
206 #[serde(default)]
208 pub kind: BackendKind,
209 pub path: Option<std::path::PathBuf>,
212 pub cache_mb: Option<u32>,
214 pub journal_mode: Option<String>,
216 #[serde(default)]
218 pub read_only: bool,
219}
220
221#[derive(Debug, Clone, Deserialize)]
231pub struct PackConfig {
232 pub backend: String,
234}
235
236#[derive(Debug, Clone, Deserialize)]
263#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
264pub enum BlobConfig {
265 Fs {
269 #[serde(default)]
270 root: Option<String>,
271 #[serde(default)]
272 floor_bytes: Option<u64>,
273 },
274 S3 {
279 bucket: String,
280 region: String,
281 #[serde(default)]
282 endpoint: Option<String>,
283 #[serde(default)]
284 prefix: Option<String>,
285 #[serde(default)]
286 allow_http: Option<bool>,
287 },
288}
289
290#[derive(Debug, Clone, Deserialize, Default)]
293pub struct StorageSectionConfig {
294 #[serde(default)]
299 pub blob: Option<BlobConfig>,
300}
301
302#[derive(Debug, Clone, Deserialize)]
314pub struct GitWriteEntryConfig {
315 pub repo: String,
317 pub branches: Vec<String>,
320}
321
322#[derive(Debug, Clone, Deserialize, Default)]
334pub struct GitWriteSectionConfig {
335 #[serde(default)]
336 pub allowed: Vec<GitWriteEntryConfig>,
337}
338
339#[derive(Debug, Clone, Deserialize, Default)]
350pub struct KhiveConfig {
351 #[serde(default)]
357 pub db: Option<String>,
358
359 #[serde(default)]
361 pub engines: Vec<EngineConfig>,
362
363 #[serde(default)]
371 pub actor: ActorConfig,
372
373 #[serde(default)]
375 pub runtime: RuntimeSectionConfig,
376
377 #[serde(default)]
382 pub backends: Vec<BackendConfig>,
383
384 #[serde(default)]
390 pub packs: std::collections::HashMap<String, PackConfig>,
391
392 #[serde(default)]
396 pub git_write: GitWriteSectionConfig,
397
398 #[serde(default)]
401 pub storage: StorageSectionConfig,
402}
403
404#[derive(Debug, Clone, Deserialize, Default)]
410pub struct RuntimeSectionConfig {
411 #[serde(default)]
414 pub packs: Option<Vec<String>>,
415
416 #[serde(default)]
423 pub brain_profile: Option<String>,
424
425 #[serde(default)]
432 pub default_output_format: Option<OutputFormat>,
433}
434
435impl KhiveConfig {
436 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
452 let resolved = match path {
453 Some(p) => p.to_path_buf(),
454 None => PathBuf::from(".khive/config.toml"),
455 };
456
457 if !resolved.exists() {
458 return Ok(None);
459 }
460
461 let raw = std::fs::read_to_string(&resolved)?;
462 let cfg: KhiveConfig = toml::from_str(&raw).map_err(|source| ConfigError::Parse {
463 path: resolved,
464 source,
465 })?;
466 cfg.validate()?;
467 Ok(Some(cfg))
468 }
469
470 pub fn load_with_home_fallback(
490 path: Option<&Path>,
491 db_path: Option<&Path>,
492 ) -> Result<Option<Self>, ConfigError> {
493 if let Some(p) = path {
495 return Self::load(Some(p));
496 }
497
498 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
500 let home_root = std::env::var_os("HOME").map(PathBuf::from);
501 Self::load_with_roots(&project_root, home_root.as_deref(), db_path)
502 }
503
504 pub(crate) fn load_with_roots(
513 project_root: &Path,
514 home_root: Option<&Path>,
515 db_path: Option<&Path>,
516 ) -> Result<Option<Self>, ConfigError> {
517 let tier2 = project_root.join("khive.toml");
519 if tier2.exists() {
520 return Self::load(Some(&tier2));
521 }
522
523 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
526 if tier3.exists() {
527 return Self::load(Some(&tier3));
528 }
529
530 if let Some(home) = home_root {
532 let tier4 = home.join(".khive/config.toml");
533 if tier4.exists() {
534 return Self::load(Some(&tier4));
535 }
536 }
537
538 Ok(None)
539 }
540
541 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
567 let Some(db_path) = db_path else {
568 return project_root.join(".khive");
569 };
570
571 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
572 if db_path.is_absolute() {
573 db_path.to_path_buf()
574 } else {
575 project_root.join(db_path)
576 }
577 });
578
579 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
580
581 if db_dir.file_name().is_some_and(|name| name == ".khive") {
582 db_dir
583 } else {
584 db_dir.join(".khive")
585 }
586 }
587
588 pub fn validate(&self) -> Result<(), ConfigError> {
598 if let Some(value) = self.db.as_deref() {
603 if !value.is_empty() {
604 return Err(ConfigError::UnsupportedTopLevelDb {
605 value: value.to_string(),
606 });
607 }
608 }
609
610 if let Some(id) = self.actor.id.as_deref() {
613 if id.is_empty() {
614 return Err(ConfigError::InvalidActorId {
615 id: id.to_string(),
616 reason: "actor.id must not be empty; remove the key or provide a value"
617 .to_string(),
618 });
619 }
620 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
621 id: id.to_string(),
622 reason: e.to_string(),
623 })?;
624 }
625
626 if let Some(ref vis) = self.actor.visible_namespaces {
627 for ns_str in vis {
628 if ns_str.is_empty() {
629 return Err(ConfigError::InvalidActorId {
630 id: ns_str.clone(),
631 reason: "visible_namespaces entries must not be empty".to_string(),
632 });
633 }
634 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
635 id: ns_str.clone(),
636 reason: format!("invalid visible namespace: {e}"),
637 })?;
638 }
639 }
640
641 for ns_str in &self.actor.allowed_outbound_namespaces {
643 if ns_str.is_empty() {
644 return Err(ConfigError::InvalidActorId {
645 id: ns_str.clone(),
646 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
647 });
648 }
649 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
650 id: ns_str.clone(),
651 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
652 })?;
653 }
654
655 if !self.backends.is_empty() {
657 let mut seen_backends = std::collections::HashSet::new();
658 for backend in &self.backends {
659 if !seen_backends.insert(backend.name.clone()) {
660 return Err(ConfigError::DuplicateBackendName {
661 name: backend.name.clone(),
662 });
663 }
664
665 if backend.cache_mb.is_some() {
668 return Err(ConfigError::UnsupportedBackendField {
669 name: backend.name.clone(),
670 field: "cache_mb",
671 });
672 }
673 if backend.journal_mode.is_some() {
674 return Err(ConfigError::UnsupportedBackendField {
675 name: backend.name.clone(),
676 field: "journal_mode",
677 });
678 }
679 }
680
681 let defined: Vec<&str> = self.backends.iter().map(|b| b.name.as_str()).collect();
683 for (pack_name, pack_cfg) in &self.packs {
684 if !defined.contains(&pack_cfg.backend.as_str()) {
685 return Err(ConfigError::UnknownPackBackend {
686 pack: pack_name.clone(),
687 backend: pack_cfg.backend.clone(),
688 defined: defined.join(", "),
689 });
690 }
691 }
692 }
693
694 for entry in &self.git_write.allowed {
701 if entry.repo.trim().is_empty() {
702 return Err(ConfigError::InvalidGitWriteEntry {
703 repo: entry.repo.clone(),
704 reason: "repo must not be empty".to_string(),
705 });
706 }
707 if !Path::new(&entry.repo).is_absolute() {
708 return Err(ConfigError::InvalidGitWriteEntry {
709 repo: entry.repo.clone(),
710 reason: "repo must be an absolute path".to_string(),
711 });
712 }
713 if entry.branches.is_empty() {
714 return Err(ConfigError::InvalidGitWriteEntry {
715 repo: entry.repo.clone(),
716 reason: "branches must not be empty".to_string(),
717 });
718 }
719 if entry.branches.iter().any(|b| b.trim().is_empty()) {
720 return Err(ConfigError::InvalidGitWriteEntry {
721 repo: entry.repo.clone(),
722 reason: "branches entries must not be empty".to_string(),
723 });
724 }
725 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
730 return Err(ConfigError::InvalidGitWriteEntry {
731 repo: entry.repo.clone(),
732 reason: format!(
733 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
734 ),
735 });
736 }
737 }
738
739 if self.engines.is_empty() {
740 return Ok(());
741 }
742
743 let mut seen_names = std::collections::HashSet::new();
744 for engine in &self.engines {
745 if !seen_names.insert(engine.name.clone()) {
746 return Err(ConfigError::DuplicateName {
747 name: engine.name.clone(),
748 });
749 }
750 }
751
752 let default_count = self.engines.iter().filter(|e| e.default).count();
753 if default_count != 1 {
754 return Err(ConfigError::DefaultCount {
755 found: default_count,
756 });
757 }
758
759 for engine in &self.engines {
762 if let Some(w) = engine.fusion_weight {
763 if !w.is_finite() || w <= 0.0 {
764 return Err(ConfigError::InvalidFusionWeight {
765 name: engine.name.clone(),
766 value: w,
767 });
768 }
769 }
770 }
771
772 Ok(())
773 }
774
775 pub fn default_engine(&self) -> Option<&EngineConfig> {
777 self.engines.iter().find(|e| e.default)
778 }
779}
780
781pub fn config_from_env() -> KhiveConfig {
795 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
796 .ok()
797 .filter(|s| !s.trim().is_empty());
798 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
799 .ok()
800 .unwrap_or_default();
801 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
802 .into_iter()
803 .filter(|s| !s.is_empty())
804 .collect();
805
806 if primary_model.is_none() && additional.is_empty() {
807 return KhiveConfig::default();
808 }
809
810 tracing::info!(
811 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
812 );
813
814 config_from_env_parts(primary_model, additional)
815}
816
817fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
820 let mut engines = Vec::new();
821
822 let primary =
823 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
824 engines.push(EngineConfig {
825 name: "default".to_string(),
826 model: primary.clone(),
827 default: true,
828 fusion_weight: None,
829 dims: None,
830 });
831
832 for (i, model) in additional.into_iter().enumerate() {
833 if model.eq_ignore_ascii_case(&primary) {
835 continue;
836 }
837 engines.push(EngineConfig {
838 name: format!("engine-{}", i + 1),
839 model,
840 default: false,
841 fusion_weight: None,
842 dims: None,
843 });
844 }
845
846 KhiveConfig {
847 engines,
848 ..KhiveConfig::default()
849 }
850}
851
852#[cfg(test)]
857mod tests {
858 use super::*;
859
860 fn write_toml(dir: &tempfile::TempDir, content: &str) -> PathBuf {
861 let path = dir.path().join("config.toml");
862 std::fs::write(&path, content).unwrap();
863 path
864 }
865
866 #[test]
869 fn env_additional_only_keeps_builtin_primary() {
870 let cfg = super::config_from_env_parts(
871 None,
872 vec!["paraphrase-multilingual-minilm-l12-v2".to_string()],
873 );
874 assert_eq!(cfg.engines.len(), 2);
875 let default_engine = cfg.default_engine().expect("a default engine");
876 assert_eq!(default_engine.model, "all-minilm-l6-v2");
877 assert!(
878 cfg.engines
879 .iter()
880 .any(|e| !e.default && e.model == "paraphrase-multilingual-minilm-l12-v2"),
881 "additional model must be a non-default secondary engine"
882 );
883 }
884
885 #[test]
886 fn env_explicit_primary_stays_primary() {
887 let cfg = super::config_from_env_parts(
888 Some("paraphrase-multilingual-minilm-l12-v2".to_string()),
889 vec![],
890 );
891 assert_eq!(cfg.engines.len(), 1);
892 assert_eq!(
893 cfg.default_engine().expect("default").model,
894 "paraphrase-multilingual-minilm-l12-v2"
895 );
896 }
897
898 #[test]
899 fn env_additional_restating_primary_is_deduped() {
900 let cfg = super::config_from_env_parts(None, vec!["all-minilm-l6-v2".to_string()]);
901 assert_eq!(cfg.engines.len(), 1);
902 assert!(cfg.engines[0].default);
903 }
904
905 #[test]
906 fn test_load_minimal_config() {
907 let dir = tempfile::tempdir().unwrap();
908 let path = write_toml(
909 &dir,
910 r#"
911[[engines]]
912name = "x"
913model = "all-minilm-l6-v2"
914default = true
915"#,
916 );
917 let cfg = KhiveConfig::load(Some(&path))
918 .expect("load should succeed")
919 .expect("file should be found");
920 assert_eq!(cfg.engines.len(), 1);
921 assert_eq!(cfg.engines[0].name, "x");
922 assert_eq!(cfg.engines[0].model, "all-minilm-l6-v2");
923 assert!(cfg.engines[0].default);
924 }
925
926 #[test]
927 fn test_default_engine_required_when_engines_present() {
928 let dir = tempfile::tempdir().unwrap();
929 let path = write_toml(
930 &dir,
931 r#"
932[[engines]]
933name = "a"
934model = "all-minilm-l6-v2"
935"#,
936 );
937 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with no default flagged");
938 assert!(
939 matches!(err, ConfigError::DefaultCount { found: 0 }),
940 "expected DefaultCount {{ found: 0 }}, got {err:?}"
941 );
942 }
943
944 #[test]
945 fn test_multiple_default_rejected() {
946 let dir = tempfile::tempdir().unwrap();
947 let path = write_toml(
948 &dir,
949 r#"
950[[engines]]
951name = "a"
952model = "all-minilm-l6-v2"
953default = true
954
955[[engines]]
956name = "b"
957model = "paraphrase-multilingual-minilm-l12-v2"
958default = true
959"#,
960 );
961 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with two defaults");
962 assert!(
963 matches!(err, ConfigError::DefaultCount { found: 2 }),
964 "expected DefaultCount {{ found: 2 }}, got {err:?}"
965 );
966 }
967
968 #[test]
969 fn test_fusion_weight_validation() {
970 let dir = tempfile::tempdir().unwrap();
971 let path = write_toml(
972 &dir,
973 r#"
974[[engines]]
975name = "a"
976model = "all-minilm-l6-v2"
977default = true
978fusion_weight = -0.5
979"#,
980 );
981 let err =
982 KhiveConfig::load(Some(&path)).expect_err("should fail with negative fusion_weight");
983 assert!(
984 matches!(err, ConfigError::InvalidFusionWeight { .. }),
985 "expected InvalidFusionWeight, got {err:?}"
986 );
987
988 let path2 = write_toml(
989 &dir,
990 r#"
991[[engines]]
992name = "a"
993model = "all-minilm-l6-v2"
994default = true
995fusion_weight = 0.0
996"#,
997 );
998 let err2 =
999 KhiveConfig::load(Some(&path2)).expect_err("should fail with zero fusion_weight");
1000 assert!(
1001 matches!(err2, ConfigError::InvalidFusionWeight { .. }),
1002 "expected InvalidFusionWeight, got {err2:?}"
1003 );
1004 }
1005
1006 #[test]
1007 fn test_env_var_fallback() {
1008 let dir = tempfile::tempdir().unwrap();
1009 let absent = dir.path().join("missing.toml");
1010
1011 let loaded = KhiveConfig::load(Some(&absent)).unwrap();
1012 assert!(loaded.is_none());
1013
1014 let primary = "all-minilm-l6-v2".to_string();
1017 let additional = vec!["paraphrase-multilingual-minilm-l12-v2".to_string()];
1018
1019 let mut engines = vec![EngineConfig {
1020 name: "default".to_string(),
1021 model: primary,
1022 default: true,
1023 fusion_weight: None,
1024 dims: None,
1025 }];
1026 for (i, model) in additional.into_iter().enumerate() {
1027 engines.push(EngineConfig {
1028 name: format!("engine-{}", i + 1),
1029 model,
1030 default: false,
1031 fusion_weight: None,
1032 dims: None,
1033 });
1034 }
1035 let cfg = KhiveConfig {
1036 engines,
1037 ..KhiveConfig::default()
1038 };
1039 cfg.validate().expect("env-derived config should be valid");
1040 assert_eq!(cfg.engines.len(), 2);
1041 assert!(cfg.default_engine().is_some());
1042 assert_eq!(cfg.default_engine().unwrap().name, "default");
1043 }
1044
1045 #[test]
1046 fn test_file_overrides_env() {
1047 let dir = tempfile::tempdir().unwrap();
1048 let path = write_toml(
1049 &dir,
1050 r#"
1051[[engines]]
1052name = "file-engine"
1053model = "all-minilm-l6-v2"
1054default = true
1055"#,
1056 );
1057
1058 let cfg = KhiveConfig::load(Some(&path))
1061 .expect("load should succeed")
1062 .expect("file should be present");
1063 assert_eq!(cfg.engines[0].name, "file-engine");
1064 }
1065
1066 #[test]
1067 fn test_duplicate_engine_names_rejected() {
1068 let dir = tempfile::tempdir().unwrap();
1069 let path = write_toml(
1070 &dir,
1071 r#"
1072[[engines]]
1073name = "shared"
1074model = "all-minilm-l6-v2"
1075default = true
1076
1077[[engines]]
1078name = "shared"
1079model = "paraphrase-multilingual-minilm-l12-v2"
1080"#,
1081 );
1082 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
1083 assert!(
1084 matches!(err, ConfigError::DuplicateName { .. }),
1085 "expected DuplicateName, got {err:?}"
1086 );
1087 }
1088
1089 #[test]
1090 fn test_empty_config_is_valid() {
1091 let dir = tempfile::tempdir().unwrap();
1092 let path = write_toml(&dir, "# no engines\n");
1093 let cfg = KhiveConfig::load(Some(&path))
1094 .expect("load should succeed")
1095 .expect("file should be found");
1096 assert!(cfg.engines.is_empty());
1097 cfg.validate().expect("empty config should be valid");
1098 }
1099
1100 #[test]
1101 fn test_multi_engine_positive_fusion_weight() {
1102 let dir = tempfile::tempdir().unwrap();
1103 let path = write_toml(
1104 &dir,
1105 r#"
1106[[engines]]
1107name = "primary"
1108model = "all-minilm-l6-v2"
1109default = true
1110fusion_weight = 0.7
1111
1112[[engines]]
1113name = "secondary"
1114model = "paraphrase-multilingual-minilm-l12-v2"
1115fusion_weight = 0.3
1116"#,
1117 );
1118 let cfg = KhiveConfig::load(Some(&path))
1119 .expect("load should succeed")
1120 .expect("file should be found");
1121 assert_eq!(cfg.engines.len(), 2);
1122 assert_eq!(cfg.engines[0].fusion_weight, Some(0.7));
1123 assert_eq!(cfg.engines[1].fusion_weight, Some(0.3));
1124 }
1125
1126 #[test]
1127 fn test_actor_id_parsed() {
1128 let dir = tempfile::tempdir().unwrap();
1129 let path = write_toml(
1130 &dir,
1131 r#"
1132[actor]
1133id = "lambda:khive"
1134display_name = "example actor"
1135"#,
1136 );
1137 let cfg = KhiveConfig::load(Some(&path))
1138 .expect("load should succeed")
1139 .expect("file should be found");
1140 assert_eq!(cfg.actor.id.as_deref(), Some("lambda:khive"));
1141 assert_eq!(cfg.actor.display_name.as_deref(), Some("example actor"));
1142 assert!(cfg.engines.is_empty());
1143 }
1144
1145 #[test]
1146 fn test_actor_and_engines_together() {
1147 let dir = tempfile::tempdir().unwrap();
1148 let path = write_toml(
1149 &dir,
1150 r#"
1151[actor]
1152id = "lambda:test"
1153
1154[[engines]]
1155name = "default"
1156model = "all-minilm-l6-v2"
1157default = true
1158"#,
1159 );
1160 let cfg = KhiveConfig::load(Some(&path))
1161 .expect("load should succeed")
1162 .expect("file should be found");
1163 assert_eq!(cfg.actor.id.as_deref(), Some("lambda:test"));
1164 assert_eq!(cfg.engines.len(), 1);
1165 }
1166
1167 #[test]
1168 fn test_actor_absent_defaults_to_none() {
1169 let dir = tempfile::tempdir().unwrap();
1170 let path = write_toml(
1171 &dir,
1172 r#"
1173[[engines]]
1174name = "x"
1175model = "all-minilm-l6-v2"
1176default = true
1177"#,
1178 );
1179 let cfg = KhiveConfig::load(Some(&path))
1180 .expect("load should succeed")
1181 .expect("file should be found");
1182 assert!(
1183 cfg.actor.id.is_none(),
1184 "actor.id must be None when [actor] section is absent"
1185 );
1186 }
1187
1188 #[test]
1189 fn test_load_with_home_fallback_no_files() {
1190 let project_dir = tempfile::tempdir().unwrap();
1191 let home_dir = tempfile::tempdir().unwrap();
1192 let result = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None);
1193 assert!(
1194 result.expect("no error expected").is_none(),
1195 "should return None when no config files exist in the given roots"
1196 );
1197 }
1198
1199 #[test]
1200 fn test_load_with_home_fallback_explicit_path() {
1201 let dir = tempfile::tempdir().unwrap();
1202 let path = write_toml(
1203 &dir,
1204 r#"
1205[actor]
1206id = "lambda:explicit"
1207"#,
1208 );
1209 let cfg = KhiveConfig::load_with_home_fallback(Some(&path), None)
1210 .expect("no error expected")
1211 .expect("file found");
1212 assert_eq!(cfg.actor.id.as_deref(), Some("lambda:explicit"));
1213 }
1214
1215 #[test]
1216 fn test_invalid_actor_id_rejected_at_load() {
1217 let dir = tempfile::tempdir().unwrap();
1218 let path = write_toml(
1219 &dir,
1220 r#"
1221[actor]
1222id = "bad namespace"
1223"#,
1224 );
1225 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with invalid actor.id");
1226 assert!(
1227 matches!(err, ConfigError::InvalidActorId { .. }),
1228 "expected InvalidActorId, got {err:?}"
1229 );
1230 }
1231
1232 #[test]
1233 fn test_empty_actor_id_rejected() {
1234 let dir = tempfile::tempdir().unwrap();
1235 let path = write_toml(
1236 &dir,
1237 r#"
1238[actor]
1239id = ""
1240"#,
1241 );
1242 let err = KhiveConfig::load(Some(&path)).expect_err("empty actor.id should be rejected");
1243 assert!(
1244 matches!(err, ConfigError::InvalidActorId { .. }),
1245 "expected InvalidActorId for empty string, got {err:?}"
1246 );
1247 }
1248
1249 #[test]
1250 fn test_malformed_actor_id_lambda_colon_only() {
1251 let dir = tempfile::tempdir().unwrap();
1252 let path = write_toml(
1253 &dir,
1254 r#"
1255[actor]
1256id = "lambda:"
1257"#,
1258 );
1259 let err =
1260 KhiveConfig::load(Some(&path)).expect_err("lambda: with no slug should be rejected");
1261 assert!(
1262 matches!(err, ConfigError::InvalidActorId { .. }),
1263 "expected InvalidActorId for 'lambda:', got {err:?}"
1264 );
1265 }
1266
1267 #[test]
1270 fn test_runtime_config_actor_id_does_not_override_namespace() {
1271 use crate::runtime::runtime_config_from_khive_config;
1272 use crate::RuntimeConfig;
1273 use khive_types::namespace::Namespace;
1274
1275 let cfg = KhiveConfig {
1276 engines: vec![],
1277 actor: ActorConfig {
1278 id: Some("lambda:test-actor".to_string()),
1279 display_name: None,
1280 ..Default::default()
1281 },
1282 ..KhiveConfig::default()
1283 };
1284 cfg.validate().expect("valid config");
1285
1286 let base = RuntimeConfig::default();
1287 let result = runtime_config_from_khive_config(&cfg, base);
1288 assert_eq!(
1289 result.default_namespace,
1290 Namespace::local(),
1291 "actor.id must NOT become default_namespace (ADR-007 Rev 4 Rule 0); \
1292 writes stay pinned to local"
1293 );
1294 assert!(
1297 result
1298 .visible_namespaces
1299 .contains(&Namespace::parse("lambda:test-actor").unwrap()),
1300 "actor.id must be folded into visible_namespaces (ADR-007 Rev 4 Rule 3b fold-in); \
1301 got: {:?}",
1302 result.visible_namespaces
1303 );
1304 }
1305
1306 #[test]
1307 fn test_runtime_config_no_actor_preserves_base() {
1308 use crate::runtime::runtime_config_from_khive_config;
1309 use crate::RuntimeConfig;
1310 use khive_types::namespace::Namespace;
1311
1312 let cfg = KhiveConfig {
1313 engines: vec![],
1314 actor: ActorConfig {
1315 id: None,
1316 display_name: None,
1317 ..Default::default()
1318 },
1319 ..KhiveConfig::default()
1320 };
1321 cfg.validate().expect("valid config");
1322
1323 let base_ns = Namespace::parse("lambda:base").unwrap();
1324 let base = RuntimeConfig {
1325 default_namespace: base_ns.clone(),
1326 ..RuntimeConfig::default()
1327 };
1328 let result = runtime_config_from_khive_config(&cfg, base);
1329 assert_eq!(
1330 result.default_namespace, base_ns,
1331 "no actor.id must leave base namespace unchanged"
1332 );
1333 }
1334
1335 #[test]
1336 fn test_load_with_home_fallback_project_root_over_hidden() {
1337 let dir = tempfile::tempdir().unwrap();
1338
1339 std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
1341 std::fs::write(
1342 dir.path().join(".khive/config.toml"),
1343 "[actor]\nid = \"lambda:hidden\"\n",
1344 )
1345 .unwrap();
1346
1347 std::fs::write(
1349 dir.path().join("khive.toml"),
1350 "[actor]\nid = \"lambda:project-root\"\n",
1351 )
1352 .unwrap();
1353
1354 let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
1355 .expect("no error expected")
1356 .expect("file should be found");
1357 assert_eq!(
1358 cfg.actor.id.as_deref(),
1359 Some("lambda:project-root"),
1360 "khive.toml (tier 2) must win over .khive/config.toml (tier 3)"
1361 );
1362 }
1363
1364 #[test]
1365 fn test_load_with_home_fallback_hidden_over_absent_root() {
1366 let dir = tempfile::tempdir().unwrap();
1367
1368 std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
1369 std::fs::write(
1370 dir.path().join(".khive/config.toml"),
1371 "[actor]\nid = \"lambda:hidden-config\"\n",
1372 )
1373 .unwrap();
1374 let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
1377 .expect("no error expected")
1378 .expect("file should be found");
1379 assert_eq!(
1380 cfg.actor.id.as_deref(),
1381 Some("lambda:hidden-config"),
1382 ".khive/config.toml (tier 3) must be found when khive.toml is absent"
1383 );
1384 }
1385
1386 #[test]
1387 fn test_load_with_roots_home_tier_found() {
1388 let project_dir = tempfile::tempdir().unwrap();
1389 let home_dir = tempfile::tempdir().unwrap();
1390
1391 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1392 std::fs::write(
1393 home_dir.path().join(".khive/config.toml"),
1394 "[actor]\nid = \"lambda:user-global\"\n",
1395 )
1396 .unwrap();
1397 let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1400 .expect("no error expected")
1401 .expect("file should be found");
1402 assert_eq!(
1403 cfg.actor.id.as_deref(),
1404 Some("lambda:user-global"),
1405 "~/.khive/config.toml (tier 4) must be found when project files absent"
1406 );
1407 }
1408
1409 #[test]
1410 fn test_load_with_roots_project_wins_over_home() {
1411 let project_dir = tempfile::tempdir().unwrap();
1412 let home_dir = tempfile::tempdir().unwrap();
1413
1414 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1416 std::fs::write(
1417 home_dir.path().join(".khive/config.toml"),
1418 "[actor]\nid = \"lambda:user-global\"\n",
1419 )
1420 .unwrap();
1421
1422 std::fs::create_dir_all(project_dir.path().join(".khive")).unwrap();
1424 std::fs::write(
1425 project_dir.path().join(".khive/config.toml"),
1426 "[actor]\nid = \"lambda:project-wins\"\n",
1427 )
1428 .unwrap();
1429
1430 let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1431 .expect("no error expected")
1432 .expect("file should be found");
1433 assert_eq!(
1434 cfg.actor.id.as_deref(),
1435 Some("lambda:project-wins"),
1436 "project .khive/config.toml (tier 3) must win over ~/.khive/config.toml (tier 4)"
1437 );
1438 }
1439
1440 #[test]
1448 fn test_load_with_roots_same_db_different_cwd_resolves_identical_config() {
1449 let cwd_a = tempfile::tempdir().unwrap();
1450 let cwd_b = tempfile::tempdir().unwrap();
1451
1452 std::fs::create_dir_all(cwd_a.path().join(".khive")).unwrap();
1455 std::fs::write(
1456 cwd_a.path().join(".khive/config.toml"),
1457 "[actor]\nid = \"lambda:wrong-cwd-a\"\n",
1458 )
1459 .unwrap();
1460 std::fs::create_dir_all(cwd_b.path().join(".khive")).unwrap();
1461 std::fs::write(
1462 cwd_b.path().join(".khive/config.toml"),
1463 "[actor]\nid = \"lambda:wrong-cwd-b\"\n",
1464 )
1465 .unwrap();
1466
1467 let db_root = tempfile::tempdir().unwrap();
1470 let khive_dir = db_root.path().join(".khive");
1471 std::fs::create_dir_all(&khive_dir).unwrap();
1472 let db_path = khive_dir.join("khive.db");
1473 std::fs::write(&db_path, b"").unwrap(); std::fs::write(
1475 khive_dir.join("config.toml"),
1476 "[actor]\nid = \"lambda:db-anchored\"\n",
1477 )
1478 .unwrap();
1479
1480 let cfg_a = KhiveConfig::load_with_roots(cwd_a.path(), None, Some(&db_path))
1481 .expect("no error expected")
1482 .expect("db-anchored config must be found from cwd A");
1483 let cfg_b = KhiveConfig::load_with_roots(cwd_b.path(), None, Some(&db_path))
1484 .expect("no error expected")
1485 .expect("db-anchored config must be found from cwd B");
1486
1487 assert_eq!(
1488 cfg_a.actor.id.as_deref(),
1489 Some("lambda:db-anchored"),
1490 "cwd A must resolve the db-anchored config, not its own decoy"
1491 );
1492 assert_eq!(
1493 cfg_b.actor.id.as_deref(),
1494 Some("lambda:db-anchored"),
1495 "cwd B must resolve the db-anchored config, not its own decoy"
1496 );
1497 assert_eq!(
1498 cfg_a.actor.id, cfg_b.actor.id,
1499 "two processes at different cwds targeting the same db must resolve \
1500 identical config, killing config_id drift between client and daemon"
1501 );
1502 }
1503
1504 #[test]
1508 fn test_load_with_home_fallback_explicit_config_wins_over_db_anchor() {
1509 let explicit_dir = tempfile::tempdir().unwrap();
1510 let explicit_path = write_toml(&explicit_dir, "[actor]\nid = \"lambda:explicit-wins\"\n");
1511
1512 let db_root = tempfile::tempdir().unwrap();
1513 let khive_dir = db_root.path().join(".khive");
1514 std::fs::create_dir_all(&khive_dir).unwrap();
1515 let db_path = khive_dir.join("khive.db");
1516 std::fs::write(&db_path, b"").unwrap();
1517 std::fs::write(
1518 khive_dir.join("config.toml"),
1519 "[actor]\nid = \"lambda:db-anchor-loses\"\n",
1520 )
1521 .unwrap();
1522
1523 let cfg = KhiveConfig::load_with_home_fallback(Some(&explicit_path), Some(&db_path))
1524 .expect("no error expected")
1525 .expect("explicit path must be found");
1526 assert_eq!(
1527 cfg.actor.id.as_deref(),
1528 Some("lambda:explicit-wins"),
1529 "explicit --config/KHIVE_CONFIG must win over the db-dir anchor"
1530 );
1531 }
1532
1533 #[test]
1536 fn test_load_with_roots_home_fallback_reached_when_db_anchor_has_no_config() {
1537 let cwd = tempfile::tempdir().unwrap();
1538 let home_dir = tempfile::tempdir().unwrap();
1539 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1540 std::fs::write(
1541 home_dir.path().join(".khive/config.toml"),
1542 "[actor]\nid = \"lambda:home-fallback\"\n",
1543 )
1544 .unwrap();
1545
1546 let db_root = tempfile::tempdir().unwrap();
1548 let khive_dir = db_root.path().join(".khive");
1549 std::fs::create_dir_all(&khive_dir).unwrap();
1550 let db_path = khive_dir.join("khive.db");
1551 std::fs::write(&db_path, b"").unwrap();
1552
1553 let cfg = KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&db_path))
1554 .expect("no error expected")
1555 .expect("home-tier config must be found");
1556 assert_eq!(
1557 cfg.actor.id.as_deref(),
1558 Some("lambda:home-fallback"),
1559 "tier 4 (~/.khive/config.toml) must still be reached when the db-anchored \
1560 tier-3 directory has no config.toml"
1561 );
1562 }
1563
1564 #[test]
1567 fn test_load_with_roots_nonexistent_db_path_does_not_panic_and_falls_through() {
1568 let cwd = tempfile::tempdir().unwrap();
1569 let home_dir = tempfile::tempdir().unwrap();
1570 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1571 std::fs::write(
1572 home_dir.path().join(".khive/config.toml"),
1573 "[actor]\nid = \"lambda:home-cold-start\"\n",
1574 )
1575 .unwrap();
1576
1577 let nonexistent_db = cwd.path().join("never-created/.khive/khive.db");
1579
1580 let cfg =
1581 KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&nonexistent_db))
1582 .expect("cold-start db path must not error or panic")
1583 .expect("home-tier config must still be found");
1584 assert_eq!(
1585 cfg.actor.id.as_deref(),
1586 Some("lambda:home-cold-start"),
1587 "a nonexistent db path (cold start) must fall through to tier 4, not panic"
1588 );
1589 }
1590
1591 #[test]
1596 fn test_load_with_roots_relative_nonexistent_db_path_does_not_panic() {
1597 let cwd = tempfile::tempdir().unwrap();
1598 let relative_db = PathBuf::from("never-created/.khive/khive.db");
1599
1600 let result = KhiveConfig::load_with_roots(cwd.path(), None, Some(&relative_db));
1601 assert!(
1602 result.is_ok(),
1603 "relative cold-start db path must not error or panic: {result:?}"
1604 );
1605 assert!(
1606 result.unwrap().is_none(),
1607 "no config exists anywhere in this test; result must be None"
1608 );
1609 }
1610
1611 #[test]
1614 fn test_no_backends_section_is_valid() {
1615 let dir = tempfile::tempdir().unwrap();
1616 let path = write_toml(
1617 &dir,
1618 r#"
1619[[engines]]
1620name = "default"
1621model = "all-minilm-l6-v2"
1622default = true
1623"#,
1624 );
1625 let cfg = KhiveConfig::load(Some(&path))
1626 .expect("no error")
1627 .expect("file found");
1628 assert!(cfg.backends.is_empty());
1629 assert!(cfg.packs.is_empty());
1630 }
1631
1632 #[test]
1633 fn test_single_sqlite_backend_parses() {
1634 let dir = tempfile::tempdir().unwrap();
1635 let path = write_toml(
1636 &dir,
1637 r#"
1638[[backends]]
1639name = "knowledge"
1640kind = "sqlite"
1641path = "/tmp/knowledge.db"
1642"#,
1643 );
1644 let cfg = KhiveConfig::load(Some(&path))
1645 .expect("no error")
1646 .expect("file found");
1647 assert_eq!(cfg.backends.len(), 1);
1648 let b = &cfg.backends[0];
1649 assert_eq!(b.name, "knowledge");
1650 assert!(matches!(b.kind, BackendKind::Sqlite));
1651 assert_eq!(
1652 b.path.as_ref().and_then(|p| p.to_str()),
1653 Some("/tmp/knowledge.db")
1654 );
1655 }
1656
1657 #[test]
1658 fn test_memory_backend_parses() {
1659 let dir = tempfile::tempdir().unwrap();
1660 let path = write_toml(
1661 &dir,
1662 r#"
1663[[backends]]
1664name = "ephemeral"
1665kind = "memory"
1666"#,
1667 );
1668 let cfg = KhiveConfig::load(Some(&path))
1669 .expect("no error")
1670 .expect("file found");
1671 assert_eq!(cfg.backends.len(), 1);
1672 assert!(matches!(cfg.backends[0].kind, BackendKind::Memory));
1673 }
1674
1675 #[test]
1676 fn test_pack_backend_assignment_parses() {
1677 let dir = tempfile::tempdir().unwrap();
1678 let path = write_toml(
1679 &dir,
1680 r#"
1681[[backends]]
1682name = "knowledge"
1683kind = "memory"
1684
1685[packs.knowledge]
1686backend = "knowledge"
1687"#,
1688 );
1689 let cfg = KhiveConfig::load(Some(&path))
1690 .expect("no error")
1691 .expect("file found");
1692 assert_eq!(cfg.packs.len(), 1);
1693 let pc = cfg.packs.get("knowledge").expect("knowledge pack present");
1694 assert_eq!(pc.backend, "knowledge");
1695 }
1696
1697 #[test]
1698 fn test_duplicate_backend_name_rejected() {
1699 let dir = tempfile::tempdir().unwrap();
1700 let path = write_toml(
1701 &dir,
1702 r#"
1703[[backends]]
1704name = "dup"
1705kind = "memory"
1706
1707[[backends]]
1708name = "dup"
1709kind = "memory"
1710"#,
1711 );
1712 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
1713 assert!(
1714 matches!(err, ConfigError::DuplicateBackendName { ref name } if name == "dup"),
1715 "expected DuplicateBackendName {{ name: \"dup\" }}, got {err:?}"
1716 );
1717 }
1718
1719 #[test]
1720 fn test_pack_referencing_undefined_backend_rejected() {
1721 let dir = tempfile::tempdir().unwrap();
1722 let path = write_toml(
1723 &dir,
1724 r#"
1725[[backends]]
1726name = "knowledge"
1727kind = "memory"
1728
1729[packs.kg]
1730backend = "nonexistent"
1731"#,
1732 );
1733 let err =
1734 KhiveConfig::load(Some(&path)).expect_err("should fail with unknown backend reference");
1735 assert!(
1736 matches!(err, ConfigError::UnknownPackBackend { ref pack, ref backend, .. }
1737 if pack == "kg" && backend == "nonexistent"),
1738 "expected UnknownPackBackend for kg→nonexistent, got {err:?}"
1739 );
1740 }
1741
1742 #[test]
1743 fn test_pack_config_without_backends_section_is_allowed() {
1744 let dir = tempfile::tempdir().unwrap();
1745 let path = write_toml(
1748 &dir,
1749 r#"
1750[packs.kg]
1751backend = "main"
1752"#,
1753 );
1754 let cfg = KhiveConfig::load(Some(&path))
1755 .expect("no error expected")
1756 .expect("file found");
1757 assert_eq!(cfg.backends.len(), 0);
1758 assert_eq!(cfg.packs.len(), 1);
1759 }
1760
1761 #[test]
1762 fn test_backend_cache_mb_rejected_at_validate() {
1763 let dir = tempfile::tempdir().unwrap();
1764 let path = write_toml(
1765 &dir,
1766 r#"
1767[[backends]]
1768name = "main"
1769kind = "memory"
1770cache_mb = 128
1771"#,
1772 );
1773 let err = KhiveConfig::load(Some(&path)).expect_err("cache_mb must be rejected");
1774 assert!(
1775 matches!(err, ConfigError::UnsupportedBackendField { ref name, field: "cache_mb" } if name == "main"),
1776 "expected UnsupportedBackendField {{ name: \"main\", field: \"cache_mb\" }}, got {err:?}"
1777 );
1778 }
1779
1780 #[test]
1781 fn test_backend_journal_mode_rejected_at_validate() {
1782 let dir = tempfile::tempdir().unwrap();
1783 let path = write_toml(
1784 &dir,
1785 r#"
1786[[backends]]
1787name = "main"
1788kind = "memory"
1789journal_mode = "wal"
1790"#,
1791 );
1792 let err = KhiveConfig::load(Some(&path)).expect_err("journal_mode must be rejected");
1793 assert!(
1794 matches!(err, ConfigError::UnsupportedBackendField { ref name, field: "journal_mode" } if name == "main"),
1795 "expected UnsupportedBackendField {{ name: \"main\", field: \"journal_mode\" }}, got {err:?}"
1796 );
1797 }
1798
1799 #[test]
1802 fn test_top_level_db_rejected_at_validate() {
1803 let dir = tempfile::tempdir().unwrap();
1804 let path = write_toml(
1805 &dir,
1806 r#"
1807db = "/tmp/scratch/demo.db"
1808"#,
1809 );
1810 let err = KhiveConfig::load(Some(&path)).expect_err("top-level db must be rejected");
1811 assert!(
1812 matches!(err, ConfigError::UnsupportedTopLevelDb { ref value } if value == "/tmp/scratch/demo.db"),
1813 "expected UnsupportedTopLevelDb {{ value: \"/tmp/scratch/demo.db\" }}, got {err:?}"
1814 );
1815 }
1816
1817 #[test]
1821 fn test_no_git_write_section_is_valid_and_empty() {
1822 let dir = tempfile::tempdir().unwrap();
1823 let path = write_toml(&dir, "# no git_write section\n");
1824 let cfg = KhiveConfig::load(Some(&path))
1825 .expect("no error")
1826 .expect("file found");
1827 assert!(cfg.git_write.allowed.is_empty());
1828 }
1829
1830 #[test]
1832 fn test_git_write_entry_parses() {
1833 let dir = tempfile::tempdir().unwrap();
1834 let path = write_toml(
1835 &dir,
1836 r#"
1837[[git_write.allowed]]
1838repo = "/abs/path/repo"
1839branches = ["feat/*", "fix/*"]
1840"#,
1841 );
1842 let cfg = KhiveConfig::load(Some(&path))
1843 .expect("no error")
1844 .expect("file found");
1845 assert_eq!(cfg.git_write.allowed.len(), 1);
1846 assert_eq!(cfg.git_write.allowed[0].repo, "/abs/path/repo");
1847 assert_eq!(
1848 cfg.git_write.allowed[0].branches,
1849 vec!["feat/*".to_string(), "fix/*".to_string()]
1850 );
1851 }
1852
1853 #[test]
1855 fn test_git_write_relative_repo_rejected() {
1856 let dir = tempfile::tempdir().unwrap();
1857 let path = write_toml(
1858 &dir,
1859 r#"
1860[[git_write.allowed]]
1861repo = "relative/path"
1862branches = ["main"]
1863"#,
1864 );
1865 let err = KhiveConfig::load(Some(&path)).expect_err("relative repo must be rejected");
1866 assert!(
1867 matches!(err, ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "relative/path"),
1868 "expected InvalidGitWriteEntry, got {err:?}"
1869 );
1870 }
1871
1872 #[test]
1876 fn test_git_write_multi_star_branch_pattern_rejected() {
1877 let dir = tempfile::tempdir().unwrap();
1878 let path = write_toml(
1879 &dir,
1880 r#"
1881[[git_write.allowed]]
1882repo = "/abs/path"
1883branches = ["**"]
1884"#,
1885 );
1886 let err = KhiveConfig::load(Some(&path)).expect_err("** must be rejected");
1887 assert!(
1888 matches!(err, ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
1889 "expected InvalidGitWriteEntry, got {err:?}"
1890 );
1891
1892 let dir2 = tempfile::tempdir().unwrap();
1893 let path2 = write_toml(
1894 &dir2,
1895 r#"
1896[[git_write.allowed]]
1897repo = "/abs/path"
1898branches = ["rel-*-*-final"]
1899"#,
1900 );
1901 let err2 = KhiveConfig::load(Some(&path2)).expect_err("rel-*-*-final must be rejected");
1902 assert!(
1903 matches!(err2, ConfigError::InvalidGitWriteEntry { .. }),
1904 "expected InvalidGitWriteEntry, got {err2:?}"
1905 );
1906 }
1907
1908 #[test]
1910 fn test_git_write_single_star_branch_pattern_accepted() {
1911 let dir = tempfile::tempdir().unwrap();
1912 let path = write_toml(
1913 &dir,
1914 r#"
1915[[git_write.allowed]]
1916repo = "/abs/path"
1917branches = ["a*b", "main"]
1918"#,
1919 );
1920 let cfg = KhiveConfig::load(Some(&path))
1921 .expect("no error")
1922 .expect("file found");
1923 assert_eq!(cfg.git_write.allowed[0].branches, vec!["a*b", "main"]);
1924 }
1925
1926 #[test]
1929 fn test_git_write_empty_branches_rejected() {
1930 let dir = tempfile::tempdir().unwrap();
1931 let path = write_toml(
1932 &dir,
1933 r#"
1934[[git_write.allowed]]
1935repo = "/abs/path"
1936branches = []
1937"#,
1938 );
1939 let err = KhiveConfig::load(Some(&path)).expect_err("empty branches must be rejected");
1940 assert!(
1941 matches!(err, ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
1942 "expected InvalidGitWriteEntry, got {err:?}"
1943 );
1944 }
1945
1946 #[test]
1951 fn test_no_storage_section_defaults_to_fs() {
1952 let dir = tempfile::tempdir().unwrap();
1953 let path = write_toml(&dir, "# no storage section\n");
1954 let cfg = KhiveConfig::load(Some(&path))
1955 .expect("no error")
1956 .expect("file found");
1957 assert!(cfg.storage.blob.is_none());
1958 }
1959
1960 #[test]
1961 fn test_storage_blob_fs_selection_parses() {
1962 let dir = tempfile::tempdir().unwrap();
1963 let path = write_toml(
1964 &dir,
1965 r#"
1966[storage.blob]
1967backend = "fs"
1968root = "/var/lib/khive/blobs"
1969floor_bytes = 100000000000
1970"#,
1971 );
1972 let cfg = KhiveConfig::load(Some(&path))
1973 .expect("no error")
1974 .expect("file found");
1975 match cfg.storage.blob {
1976 Some(BlobConfig::Fs { root, floor_bytes }) => {
1977 assert_eq!(root.as_deref(), Some("/var/lib/khive/blobs"));
1978 assert_eq!(floor_bytes, Some(100_000_000_000));
1979 }
1980 other => panic!("expected BlobConfig::Fs, got {other:?}"),
1981 }
1982 }
1983
1984 #[test]
1985 fn test_storage_blob_s3_selection_parses() {
1986 let dir = tempfile::tempdir().unwrap();
1987 let path = write_toml(
1988 &dir,
1989 r#"
1990[storage.blob]
1991backend = "s3"
1992bucket = "khive-blobs"
1993region = "us-east-1"
1994endpoint = "https://objects.example.invalid"
1995prefix = "blobs"
1996"#,
1997 );
1998 let cfg = KhiveConfig::load(Some(&path))
1999 .expect("no error")
2000 .expect("file found");
2001 match cfg.storage.blob {
2002 Some(BlobConfig::S3 {
2003 bucket,
2004 region,
2005 endpoint,
2006 prefix,
2007 allow_http,
2008 }) => {
2009 assert_eq!(bucket, "khive-blobs");
2010 assert_eq!(region, "us-east-1");
2011 assert_eq!(endpoint.as_deref(), Some("https://objects.example.invalid"));
2012 assert_eq!(prefix.as_deref(), Some("blobs"));
2013 assert_eq!(allow_http, None);
2014 }
2015 other => panic!("expected BlobConfig::S3, got {other:?}"),
2016 }
2017 }
2018
2019 #[test]
2023 fn test_storage_blob_unknown_field_rejected() {
2024 let dir = tempfile::tempdir().unwrap();
2025 let path = write_toml(
2026 &dir,
2027 r#"
2028[storage.blob]
2029backend = "fs"
2030made_up_field = "x"
2031"#,
2032 );
2033 let err = KhiveConfig::load(Some(&path)).expect_err("unknown field must be rejected");
2034 assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
2035 }
2036
2037 #[test]
2041 fn test_storage_blob_other_backend_field_rejected() {
2042 let dir = tempfile::tempdir().unwrap();
2043 let path = write_toml(
2044 &dir,
2045 r#"
2046[storage.blob]
2047backend = "fs"
2048bucket = "khive-blobs"
2049"#,
2050 );
2051 let err = KhiveConfig::load(Some(&path)).expect_err("s3 field under fs must be rejected");
2052 assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
2053 }
2054
2055 #[test]
2059 fn test_storage_blob_credential_field_rejected() {
2060 let dir = tempfile::tempdir().unwrap();
2061 let path = write_toml(
2062 &dir,
2063 r#"
2064[storage.blob]
2065backend = "s3"
2066bucket = "khive-blobs"
2067region = "us-east-1"
2068access_key_id = "AKIAEXAMPLE"
2069"#,
2070 );
2071 let err = KhiveConfig::load(Some(&path))
2072 .expect_err("a credential field in TOML must be rejected");
2073 assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
2074 }
2075
2076 #[test]
2079 fn test_storage_blob_unknown_backend_value_rejected() {
2080 let dir = tempfile::tempdir().unwrap();
2081 let path = write_toml(
2082 &dir,
2083 r#"
2084[storage.blob]
2085backend = "gcs"
2086"#,
2087 );
2088 let err = KhiveConfig::load(Some(&path)).expect_err("unknown backend must be rejected");
2089 assert!(matches!(err, ConfigError::Parse { .. }), "got {err:?}");
2090 }
2091}