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 #[error(
77 "[runtime] blob_hydration_bytes must be between {min} and {max} bytes inclusive; got {value}"
78 )]
79 InvalidBlobHydrationBytes { value: u64, min: u64, max: u64 },
80
81 #[error("the explicitly selected config file does not exist: {path}")]
82 ExplicitConfigMissing { path: PathBuf },
83
84 #[error(
85 "[gate] configuration is not supported by this build; refusing to start because the requested caller-enrollment policy would not be enforced"
86 )]
87 UnsupportedGateSection,
88
89 #[error(
90 "[display] timezone {timezone:?} is not a recognized IANA zone name (e.g. \"America/New_York\", \"UTC\")"
91 )]
92 InvalidDisplayTimezone { timezone: String },
93
94 #[error("{source} (config file: {})", path.display())]
104 InFile {
105 path: PathBuf,
106 #[source]
107 source: Box<ConfigError>,
108 },
109}
110
111impl ConfigError {
112 fn in_file(self, path: &Path) -> Self {
115 match self {
116 already @ (ConfigError::Parse { .. }
117 | ConfigError::ExplicitConfigMissing { .. }
118 | ConfigError::InFile { .. }) => already,
119 other => ConfigError::InFile {
120 path: path.to_path_buf(),
121 source: Box::new(other),
122 },
123 }
124 }
125}
126
127#[derive(Debug, Clone, Deserialize)]
131pub struct EngineConfig {
132 pub name: String,
134
135 pub model: String,
140
141 #[serde(default)]
144 pub default: bool,
145
146 pub fusion_weight: Option<f64>,
156
157 pub dims: Option<u32>,
163}
164
165#[derive(Debug, Clone, Deserialize, Default)]
186pub struct ActorConfig {
187 #[serde(default)]
193 pub id: Option<String>,
194
195 #[serde(default)]
198 pub display_name: Option<String>,
199
200 #[serde(default)]
206 pub visible_namespaces: Option<Vec<String>>,
207
208 #[serde(default)]
220 pub allowed_outbound_namespaces: Vec<String>,
221}
222
223#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
227#[serde(rename_all = "lowercase")]
228pub enum BackendKind {
229 #[default]
231 Sqlite,
232 Memory,
234}
235
236#[derive(Debug, Clone, Deserialize)]
253pub struct BackendConfig {
254 pub name: String,
256 #[serde(default)]
258 pub kind: BackendKind,
259 pub path: Option<std::path::PathBuf>,
262 pub cache_mb: Option<u32>,
264 pub journal_mode: Option<String>,
266 #[serde(default)]
268 pub read_only: bool,
269}
270
271#[derive(Debug, Clone, Deserialize)]
281pub struct PackConfig {
282 pub backend: String,
284}
285
286#[derive(Debug, Clone, Deserialize)]
313#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
314pub enum BlobConfig {
315 Fs {
319 #[serde(default)]
320 root: Option<String>,
321 #[serde(default)]
322 floor_bytes: Option<u64>,
323 },
324 S3 {
329 bucket: String,
330 region: String,
331 #[serde(default)]
332 endpoint: Option<String>,
333 #[serde(default)]
334 prefix: Option<String>,
335 #[serde(default)]
336 allow_http: Option<bool>,
337 },
338}
339
340#[derive(Debug, Clone, Deserialize, Default)]
343pub struct StorageSectionConfig {
344 #[serde(default)]
349 pub blob: Option<BlobConfig>,
350}
351
352#[derive(Debug, Clone, Deserialize)]
364pub struct GitWriteEntryConfig {
365 pub repo: String,
367 pub branches: Vec<String>,
370}
371
372#[derive(Debug, Clone, Deserialize, Default)]
384pub struct GitWriteSectionConfig {
385 #[serde(default)]
386 pub allowed: Vec<GitWriteEntryConfig>,
387}
388
389#[derive(Debug, Clone, Deserialize, Default)]
404pub struct KhiveConfig {
405 #[serde(default)]
411 pub db: Option<String>,
412
413 #[serde(default)]
415 pub engines: Vec<EngineConfig>,
416
417 #[serde(default)]
425 pub actor: ActorConfig,
426
427 #[serde(default)]
429 pub runtime: RuntimeSectionConfig,
430
431 #[serde(default)]
436 pub backends: Vec<BackendConfig>,
437
438 #[serde(default)]
444 pub packs: std::collections::HashMap<String, PackConfig>,
445
446 #[serde(default)]
450 pub git_write: GitWriteSectionConfig,
451
452 #[serde(default)]
455 pub storage: StorageSectionConfig,
456
457 #[serde(default)]
461 pub display: DisplaySectionConfig,
462}
463
464#[derive(Debug, Clone, Deserialize, Default)]
471pub struct RuntimeSectionConfig {
472 #[serde(default)]
475 pub packs: Option<Vec<String>>,
476
477 #[serde(default)]
484 pub brain_profile: Option<String>,
485
486 #[serde(default)]
493 pub default_output_format: Option<OutputFormat>,
494
495 #[serde(default)]
502 pub blob_hydration_bytes: Option<u64>,
503}
504
505#[derive(Debug, Clone, Deserialize, Default)]
513pub struct DisplaySectionConfig {
514 #[serde(default)]
520 pub timezone: Option<String>,
521}
522
523impl KhiveConfig {
524 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
540 let resolved = match path {
541 Some(p) => p.to_path_buf(),
542 None => PathBuf::from(".khive/config.toml"),
543 };
544
545 if !resolved.exists() {
546 return Ok(None);
547 }
548
549 let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
552 let raw = std::fs::read_to_string(&resolved)
553 .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
554 let parsed: toml::Value = toml::from_str(&raw).map_err(|source| ConfigError::Parse {
555 path: diagnostic_path.clone(),
556 source,
557 })?;
558 if parsed
559 .as_table()
560 .is_some_and(|table| table.contains_key("gate"))
561 {
562 return Err(ConfigError::UnsupportedGateSection.in_file(&diagnostic_path));
563 }
564 let cfg: KhiveConfig = parsed.try_into().map_err(|source| ConfigError::Parse {
565 path: diagnostic_path.clone(),
566 source,
567 })?;
568 cfg.validate()
569 .map_err(|error| error.in_file(&diagnostic_path))?;
570 Ok(Some(cfg))
571 }
572
573 pub fn load_with_home_fallback(
601 path: Option<&Path>,
602 db_path: Option<&Path>,
603 ) -> Result<Option<Self>, ConfigError> {
604 Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
605 }
606
607 pub fn load_with_home_fallback_and_source(
615 path: Option<&Path>,
616 db_path: Option<&Path>,
617 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
618 if let Some(p) = path {
626 if !p.exists() {
627 return Err(ConfigError::ExplicitConfigMissing {
628 path: p.to_path_buf(),
629 });
630 }
631 return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
632 }
633
634 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
636 let home_root = std::env::var_os("HOME").map(PathBuf::from);
637 Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
638 }
639
640 #[cfg(test)]
649 pub(crate) fn load_with_roots(
650 project_root: &Path,
651 home_root: Option<&Path>,
652 db_path: Option<&Path>,
653 ) -> Result<Option<Self>, ConfigError> {
654 Ok(
655 Self::load_with_roots_and_source(project_root, home_root, db_path)?
656 .map(|(config, _)| config),
657 )
658 }
659
660 fn load_with_roots_and_source(
661 project_root: &Path,
662 home_root: Option<&Path>,
663 db_path: Option<&Path>,
664 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
665 let tier2 = project_root.join("khive.toml");
667 if tier2.exists() {
668 return Ok(Self::load(Some(&tier2))?
669 .map(|config| (config, Self::diagnostic_config_path(&tier2))));
670 }
671
672 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
675 if tier3.exists() {
676 return Ok(Self::load(Some(&tier3))?
677 .map(|config| (config, Self::diagnostic_config_path(&tier3))));
678 }
679
680 if let Some(home) = home_root {
682 let tier4 = home.join(".khive/config.toml");
683 if tier4.exists() {
684 return Ok(Self::load(Some(&tier4))?
685 .map(|config| (config, Self::diagnostic_config_path(&tier4))));
686 }
687 }
688
689 Ok(None)
690 }
691
692 fn diagnostic_config_path(path: &Path) -> PathBuf {
693 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
694 }
695
696 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
722 let Some(db_path) = db_path else {
723 return project_root.join(".khive");
724 };
725
726 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
727 if db_path.is_absolute() {
728 db_path.to_path_buf()
729 } else {
730 project_root.join(db_path)
731 }
732 });
733
734 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
735
736 if db_dir.file_name().is_some_and(|name| name == ".khive") {
737 db_dir
738 } else {
739 db_dir.join(".khive")
740 }
741 }
742
743 pub fn validate(&self) -> Result<(), ConfigError> {
753 if let Some(value) = self.db.as_deref() {
758 if !value.is_empty() {
759 return Err(ConfigError::UnsupportedTopLevelDb {
760 value: value.to_string(),
761 });
762 }
763 }
764
765 if let Some(value) = self.runtime.blob_hydration_bytes {
766 let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
767 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
768 if value < min || value > max {
769 return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
770 }
771 }
772
773 if let Some(id) = self.actor.id.as_deref() {
776 if id.is_empty() {
777 return Err(ConfigError::InvalidActorId {
778 id: id.to_string(),
779 reason: "actor.id must not be empty; remove the key or provide a value"
780 .to_string(),
781 });
782 }
783 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
784 id: id.to_string(),
785 reason: e.to_string(),
786 })?;
787 }
788
789 if let Some(ref vis) = self.actor.visible_namespaces {
790 for ns_str in vis {
791 if ns_str.is_empty() {
792 return Err(ConfigError::InvalidActorId {
793 id: ns_str.clone(),
794 reason: "visible_namespaces entries must not be empty".to_string(),
795 });
796 }
797 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
798 id: ns_str.clone(),
799 reason: format!("invalid visible namespace: {e}"),
800 })?;
801 }
802 }
803
804 for ns_str in &self.actor.allowed_outbound_namespaces {
806 if ns_str.is_empty() {
807 return Err(ConfigError::InvalidActorId {
808 id: ns_str.clone(),
809 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
810 });
811 }
812 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
813 id: ns_str.clone(),
814 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
815 })?;
816 }
817
818 if !self.backends.is_empty() {
820 let mut seen_backends = std::collections::HashSet::new();
821 for backend in &self.backends {
822 if !seen_backends.insert(backend.name.clone()) {
823 return Err(ConfigError::DuplicateBackendName {
824 name: backend.name.clone(),
825 });
826 }
827
828 if backend.cache_mb.is_some() {
831 return Err(ConfigError::UnsupportedBackendField {
832 name: backend.name.clone(),
833 field: "cache_mb",
834 });
835 }
836 if backend.journal_mode.is_some() {
837 return Err(ConfigError::UnsupportedBackendField {
838 name: backend.name.clone(),
839 field: "journal_mode",
840 });
841 }
842 }
843
844 let defined: Vec<&str> = self.backends.iter().map(|b| b.name.as_str()).collect();
846 for (pack_name, pack_cfg) in &self.packs {
847 if !defined.contains(&pack_cfg.backend.as_str()) {
848 return Err(ConfigError::UnknownPackBackend {
849 pack: pack_name.clone(),
850 backend: pack_cfg.backend.clone(),
851 defined: defined.join(", "),
852 });
853 }
854 }
855 }
856
857 if let Some(tz) = self.display.timezone.as_deref() {
860 if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
861 return Err(ConfigError::InvalidDisplayTimezone {
862 timezone: tz.to_string(),
863 });
864 }
865 }
866
867 for entry in &self.git_write.allowed {
874 if entry.repo.trim().is_empty() {
875 return Err(ConfigError::InvalidGitWriteEntry {
876 repo: entry.repo.clone(),
877 reason: "repo must not be empty".to_string(),
878 });
879 }
880 if !Path::new(&entry.repo).is_absolute() {
881 return Err(ConfigError::InvalidGitWriteEntry {
882 repo: entry.repo.clone(),
883 reason: "repo must be an absolute path".to_string(),
884 });
885 }
886 if entry.branches.is_empty() {
887 return Err(ConfigError::InvalidGitWriteEntry {
888 repo: entry.repo.clone(),
889 reason: "branches must not be empty".to_string(),
890 });
891 }
892 if entry.branches.iter().any(|b| b.trim().is_empty()) {
893 return Err(ConfigError::InvalidGitWriteEntry {
894 repo: entry.repo.clone(),
895 reason: "branches entries must not be empty".to_string(),
896 });
897 }
898 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
903 return Err(ConfigError::InvalidGitWriteEntry {
904 repo: entry.repo.clone(),
905 reason: format!(
906 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
907 ),
908 });
909 }
910 }
911
912 if self.engines.is_empty() {
913 return Ok(());
914 }
915
916 let mut seen_names = std::collections::HashSet::new();
917 for engine in &self.engines {
918 if !seen_names.insert(engine.name.clone()) {
919 return Err(ConfigError::DuplicateName {
920 name: engine.name.clone(),
921 });
922 }
923 }
924
925 let default_count = self.engines.iter().filter(|e| e.default).count();
926 if default_count != 1 {
927 return Err(ConfigError::DefaultCount {
928 found: default_count,
929 });
930 }
931
932 for engine in &self.engines {
935 if let Some(w) = engine.fusion_weight {
936 if !w.is_finite() || w <= 0.0 {
937 return Err(ConfigError::InvalidFusionWeight {
938 name: engine.name.clone(),
939 value: w,
940 });
941 }
942 }
943 }
944
945 Ok(())
946 }
947
948 pub fn default_engine(&self) -> Option<&EngineConfig> {
950 self.engines.iter().find(|e| e.default)
951 }
952}
953
954pub fn config_from_env() -> KhiveConfig {
968 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
969 .ok()
970 .filter(|s| !s.trim().is_empty());
971 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
972 .ok()
973 .unwrap_or_default();
974 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
975 .into_iter()
976 .filter(|s| !s.is_empty())
977 .collect();
978
979 if primary_model.is_none() && additional.is_empty() {
980 return KhiveConfig::default();
981 }
982
983 tracing::info!(
984 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
985 );
986
987 config_from_env_parts(primary_model, additional)
988}
989
990fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
993 let mut engines = Vec::new();
994
995 let primary =
996 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
997 engines.push(EngineConfig {
998 name: "default".to_string(),
999 model: primary.clone(),
1000 default: true,
1001 fusion_weight: None,
1002 dims: None,
1003 });
1004
1005 for (i, model) in additional.into_iter().enumerate() {
1006 if model.eq_ignore_ascii_case(&primary) {
1008 continue;
1009 }
1010 engines.push(EngineConfig {
1011 name: format!("engine-{}", i + 1),
1012 model,
1013 default: false,
1014 fusion_weight: None,
1015 dims: None,
1016 });
1017 }
1018
1019 KhiveConfig {
1020 engines,
1021 ..KhiveConfig::default()
1022 }
1023}
1024
1025#[cfg(test)]
1030mod tests {
1031 use super::*;
1032
1033 fn write_toml(dir: &tempfile::TempDir, content: &str) -> PathBuf {
1034 let path = dir.path().join("config.toml");
1035 std::fs::write(&path, content).unwrap();
1036 path
1037 }
1038
1039 #[test]
1044 fn load_errors_name_the_config_file() {
1045 let dir = tempfile::tempdir().unwrap();
1046
1047 let gate = write_toml(&dir, "[gate]\nmode = \"x\"\n");
1048 let err = KhiveConfig::load(Some(&gate)).expect_err("gate section must fail");
1049 assert!(
1050 err.to_string().contains("(config file: ") && err.to_string().contains("config.toml"),
1051 "gate error must name the file, got: {err}"
1052 );
1053
1054 let invalid = write_toml(
1055 &dir,
1056 "[[engines]]\nname = \"a\"\nmodel = \"all-minilm-l6-v2\"\n",
1057 );
1058 let err = KhiveConfig::load(Some(&invalid)).expect_err("validation must fail");
1059 assert!(
1060 err.to_string().contains("(config file: "),
1061 "validation error must name the file, got: {err}"
1062 );
1063
1064 let parse = write_toml(&dir, "not = = toml");
1065 let err = KhiveConfig::load(Some(&parse)).expect_err("parse must fail");
1066 assert!(
1067 err.to_string().contains("config.toml"),
1068 "parse error must name the file, got: {err}"
1069 );
1070 assert!(
1071 matches!(err, ConfigError::Parse { .. }),
1072 "parse errors keep their own variant unwrapped, got: {err:?}"
1073 );
1074 }
1075
1076 fn config_error_root(err: &ConfigError) -> &ConfigError {
1079 match err {
1080 ConfigError::InFile { path, source } => {
1081 assert!(
1082 !path.as_os_str().is_empty(),
1083 "InFile must carry the config path"
1084 );
1085 source
1086 }
1087 other => other,
1088 }
1089 }
1090
1091 #[test]
1094 fn env_additional_only_keeps_builtin_primary() {
1095 let cfg = super::config_from_env_parts(
1096 None,
1097 vec!["paraphrase-multilingual-minilm-l12-v2".to_string()],
1098 );
1099 assert_eq!(cfg.engines.len(), 2);
1100 let default_engine = cfg.default_engine().expect("a default engine");
1101 assert_eq!(default_engine.model, "all-minilm-l6-v2");
1102 assert!(
1103 cfg.engines
1104 .iter()
1105 .any(|e| !e.default && e.model == "paraphrase-multilingual-minilm-l12-v2"),
1106 "additional model must be a non-default secondary engine"
1107 );
1108 }
1109
1110 #[test]
1111 fn env_explicit_primary_stays_primary() {
1112 let cfg = super::config_from_env_parts(
1113 Some("paraphrase-multilingual-minilm-l12-v2".to_string()),
1114 vec![],
1115 );
1116 assert_eq!(cfg.engines.len(), 1);
1117 assert_eq!(
1118 cfg.default_engine().expect("default").model,
1119 "paraphrase-multilingual-minilm-l12-v2"
1120 );
1121 }
1122
1123 #[test]
1124 fn env_additional_restating_primary_is_deduped() {
1125 let cfg = super::config_from_env_parts(None, vec!["all-minilm-l6-v2".to_string()]);
1126 assert_eq!(cfg.engines.len(), 1);
1127 assert!(cfg.engines[0].default);
1128 }
1129
1130 #[test]
1131 fn test_load_minimal_config() {
1132 let dir = tempfile::tempdir().unwrap();
1133 let path = write_toml(
1134 &dir,
1135 r#"
1136[[engines]]
1137name = "x"
1138model = "all-minilm-l6-v2"
1139default = true
1140"#,
1141 );
1142 let cfg = KhiveConfig::load(Some(&path))
1143 .expect("load should succeed")
1144 .expect("file should be found");
1145 assert_eq!(cfg.engines.len(), 1);
1146 assert_eq!(cfg.engines[0].name, "x");
1147 assert_eq!(cfg.engines[0].model, "all-minilm-l6-v2");
1148 assert!(cfg.engines[0].default);
1149 }
1150
1151 #[test]
1152 fn test_default_engine_required_when_engines_present() {
1153 let dir = tempfile::tempdir().unwrap();
1154 let path = write_toml(
1155 &dir,
1156 r#"
1157[[engines]]
1158name = "a"
1159model = "all-minilm-l6-v2"
1160"#,
1161 );
1162 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with no default flagged");
1163 assert!(
1164 matches!(
1165 config_error_root(&err),
1166 ConfigError::DefaultCount { found: 0 }
1167 ),
1168 "expected DefaultCount {{ found: 0 }}, got {err:?}"
1169 );
1170 }
1171
1172 #[test]
1173 fn test_multiple_default_rejected() {
1174 let dir = tempfile::tempdir().unwrap();
1175 let path = write_toml(
1176 &dir,
1177 r#"
1178[[engines]]
1179name = "a"
1180model = "all-minilm-l6-v2"
1181default = true
1182
1183[[engines]]
1184name = "b"
1185model = "paraphrase-multilingual-minilm-l12-v2"
1186default = true
1187"#,
1188 );
1189 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with two defaults");
1190 assert!(
1191 matches!(
1192 config_error_root(&err),
1193 ConfigError::DefaultCount { found: 2 }
1194 ),
1195 "expected DefaultCount {{ found: 2 }}, got {err:?}"
1196 );
1197 }
1198
1199 #[test]
1200 fn test_fusion_weight_validation() {
1201 let dir = tempfile::tempdir().unwrap();
1202 let path = write_toml(
1203 &dir,
1204 r#"
1205[[engines]]
1206name = "a"
1207model = "all-minilm-l6-v2"
1208default = true
1209fusion_weight = -0.5
1210"#,
1211 );
1212 let err =
1213 KhiveConfig::load(Some(&path)).expect_err("should fail with negative fusion_weight");
1214 assert!(
1215 matches!(
1216 config_error_root(&err),
1217 ConfigError::InvalidFusionWeight { .. }
1218 ),
1219 "expected InvalidFusionWeight, got {err:?}"
1220 );
1221
1222 let path2 = write_toml(
1223 &dir,
1224 r#"
1225[[engines]]
1226name = "a"
1227model = "all-minilm-l6-v2"
1228default = true
1229fusion_weight = 0.0
1230"#,
1231 );
1232 let err2 =
1233 KhiveConfig::load(Some(&path2)).expect_err("should fail with zero fusion_weight");
1234 assert!(
1235 matches!(
1236 config_error_root(&err2),
1237 ConfigError::InvalidFusionWeight { .. }
1238 ),
1239 "expected InvalidFusionWeight, got {err2:?}"
1240 );
1241 }
1242
1243 #[test]
1244 fn test_env_var_fallback() {
1245 let dir = tempfile::tempdir().unwrap();
1246 let absent = dir.path().join("missing.toml");
1247
1248 let loaded = KhiveConfig::load(Some(&absent)).unwrap();
1249 assert!(loaded.is_none());
1250
1251 let primary = "all-minilm-l6-v2".to_string();
1254 let additional = vec!["paraphrase-multilingual-minilm-l12-v2".to_string()];
1255
1256 let mut engines = vec![EngineConfig {
1257 name: "default".to_string(),
1258 model: primary,
1259 default: true,
1260 fusion_weight: None,
1261 dims: None,
1262 }];
1263 for (i, model) in additional.into_iter().enumerate() {
1264 engines.push(EngineConfig {
1265 name: format!("engine-{}", i + 1),
1266 model,
1267 default: false,
1268 fusion_weight: None,
1269 dims: None,
1270 });
1271 }
1272 let cfg = KhiveConfig {
1273 engines,
1274 ..KhiveConfig::default()
1275 };
1276 cfg.validate().expect("env-derived config should be valid");
1277 assert_eq!(cfg.engines.len(), 2);
1278 assert!(cfg.default_engine().is_some());
1279 assert_eq!(cfg.default_engine().unwrap().name, "default");
1280 }
1281
1282 #[test]
1283 fn test_file_overrides_env() {
1284 let dir = tempfile::tempdir().unwrap();
1285 let path = write_toml(
1286 &dir,
1287 r#"
1288[[engines]]
1289name = "file-engine"
1290model = "all-minilm-l6-v2"
1291default = true
1292"#,
1293 );
1294
1295 let cfg = KhiveConfig::load(Some(&path))
1298 .expect("load should succeed")
1299 .expect("file should be present");
1300 assert_eq!(cfg.engines[0].name, "file-engine");
1301 }
1302
1303 #[test]
1304 fn test_duplicate_engine_names_rejected() {
1305 let dir = tempfile::tempdir().unwrap();
1306 let path = write_toml(
1307 &dir,
1308 r#"
1309[[engines]]
1310name = "shared"
1311model = "all-minilm-l6-v2"
1312default = true
1313
1314[[engines]]
1315name = "shared"
1316model = "paraphrase-multilingual-minilm-l12-v2"
1317"#,
1318 );
1319 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
1320 assert!(
1321 matches!(config_error_root(&err), ConfigError::DuplicateName { .. }),
1322 "expected DuplicateName, got {err:?}"
1323 );
1324 }
1325
1326 #[test]
1327 fn test_empty_config_is_valid() {
1328 let dir = tempfile::tempdir().unwrap();
1329 let path = write_toml(&dir, "# no engines\n");
1330 let cfg = KhiveConfig::load(Some(&path))
1331 .expect("load should succeed")
1332 .expect("file should be found");
1333 assert!(cfg.engines.is_empty());
1334 cfg.validate().expect("empty config should be valid");
1335 }
1336
1337 #[test]
1338 fn runtime_blob_hydration_budget_parses_and_resolves_before_engine_early_return() {
1339 use crate::runtime::runtime_config_from_khive_config;
1340 use crate::RuntimeConfig;
1341
1342 let dir = tempfile::tempdir().unwrap();
1343 let path = write_toml(
1344 &dir,
1345 r#"
1346[runtime]
1347blob_hydration_bytes = 134217728
1348"#,
1349 );
1350 let cfg = KhiveConfig::load(Some(&path))
1351 .expect("load should succeed")
1352 .expect("file should be found");
1353
1354 assert_eq!(cfg.runtime.blob_hydration_bytes, Some(134_217_728));
1355 let resolved = runtime_config_from_khive_config(&cfg, RuntimeConfig::default());
1356 assert_eq!(resolved.blob_hydration_bytes, 134_217_728);
1357 }
1358
1359 #[test]
1360 fn runtime_blob_hydration_budget_below_one_whole_blob_is_rejected() {
1361 let dir = tempfile::tempdir().unwrap();
1362 let value = khive_storage::MAX_BLOB_WHOLE_BYTES - 1;
1363 let path = write_toml(
1364 &dir,
1365 &format!("[runtime]\nblob_hydration_bytes = {value}\n"),
1366 );
1367
1368 let err = KhiveConfig::load(Some(&path)).expect_err("undersized budget must fail closed");
1369 assert!(
1370 matches!(
1371 config_error_root(&err),
1372 ConfigError::InvalidBlobHydrationBytes {
1373 value: actual,
1374 min,
1375 ..
1376 } if *actual == value && *min == khive_storage::MAX_BLOB_WHOLE_BYTES
1377 ),
1378 "got {err:?}"
1379 );
1380 }
1381
1382 #[test]
1383 fn runtime_blob_hydration_budget_accepts_the_inclusive_portable_minimum() {
1384 let dir = tempfile::tempdir().unwrap();
1385 let value = khive_storage::MAX_BLOB_WHOLE_BYTES;
1386 let path = write_toml(
1387 &dir,
1388 &format!("[runtime]\nblob_hydration_bytes = {value}\n"),
1389 );
1390
1391 let cfg = KhiveConfig::load(Some(&path))
1392 .expect("the inclusive minimum must be valid")
1393 .expect("config should exist");
1394 assert_eq!(cfg.runtime.blob_hydration_bytes, Some(value));
1395 }
1396
1397 #[test]
1398 fn runtime_blob_hydration_budget_above_semaphore_capacity_is_rejected() {
1399 let dir = tempfile::tempdir().unwrap();
1400 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
1401 let value = max
1402 .checked_add(1)
1403 .expect("tokio maximum fits below u64::MAX");
1404 let path = write_toml(
1405 &dir,
1406 &format!("[runtime]\nblob_hydration_bytes = {value}\n"),
1407 );
1408
1409 let err = KhiveConfig::load(Some(&path)).expect_err("oversized budget must fail closed");
1410 assert!(
1411 matches!(
1412 config_error_root(&err),
1413 ConfigError::InvalidBlobHydrationBytes {
1414 value: actual,
1415 max: actual_max,
1416 ..
1417 } if *actual == value && *actual_max == max
1418 ),
1419 "got {err:?}"
1420 );
1421 }
1422
1423 #[test]
1424 fn test_multi_engine_positive_fusion_weight() {
1425 let dir = tempfile::tempdir().unwrap();
1426 let path = write_toml(
1427 &dir,
1428 r#"
1429[[engines]]
1430name = "primary"
1431model = "all-minilm-l6-v2"
1432default = true
1433fusion_weight = 0.7
1434
1435[[engines]]
1436name = "secondary"
1437model = "paraphrase-multilingual-minilm-l12-v2"
1438fusion_weight = 0.3
1439"#,
1440 );
1441 let cfg = KhiveConfig::load(Some(&path))
1442 .expect("load should succeed")
1443 .expect("file should be found");
1444 assert_eq!(cfg.engines.len(), 2);
1445 assert_eq!(cfg.engines[0].fusion_weight, Some(0.7));
1446 assert_eq!(cfg.engines[1].fusion_weight, Some(0.3));
1447 }
1448
1449 #[test]
1450 fn test_actor_id_parsed() {
1451 let dir = tempfile::tempdir().unwrap();
1452 let path = write_toml(
1453 &dir,
1454 r#"
1455[actor]
1456id = "lambda:khive"
1457display_name = "example actor"
1458"#,
1459 );
1460 let cfg = KhiveConfig::load(Some(&path))
1461 .expect("load should succeed")
1462 .expect("file should be found");
1463 assert_eq!(cfg.actor.id.as_deref(), Some("lambda:khive"));
1464 assert_eq!(cfg.actor.display_name.as_deref(), Some("example actor"));
1465 assert!(cfg.engines.is_empty());
1466 }
1467
1468 #[test]
1469 fn test_actor_and_engines_together() {
1470 let dir = tempfile::tempdir().unwrap();
1471 let path = write_toml(
1472 &dir,
1473 r#"
1474[actor]
1475id = "lambda:test"
1476
1477[[engines]]
1478name = "default"
1479model = "all-minilm-l6-v2"
1480default = true
1481"#,
1482 );
1483 let cfg = KhiveConfig::load(Some(&path))
1484 .expect("load should succeed")
1485 .expect("file should be found");
1486 assert_eq!(cfg.actor.id.as_deref(), Some("lambda:test"));
1487 assert_eq!(cfg.engines.len(), 1);
1488 }
1489
1490 #[test]
1491 fn test_actor_absent_defaults_to_none() {
1492 let dir = tempfile::tempdir().unwrap();
1493 let path = write_toml(
1494 &dir,
1495 r#"
1496[[engines]]
1497name = "x"
1498model = "all-minilm-l6-v2"
1499default = true
1500"#,
1501 );
1502 let cfg = KhiveConfig::load(Some(&path))
1503 .expect("load should succeed")
1504 .expect("file should be found");
1505 assert!(
1506 cfg.actor.id.is_none(),
1507 "actor.id must be None when [actor] section is absent"
1508 );
1509 }
1510
1511 #[test]
1512 fn test_load_with_home_fallback_no_files() {
1513 let project_dir = tempfile::tempdir().unwrap();
1514 let home_dir = tempfile::tempdir().unwrap();
1515 let result = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None);
1516 assert!(
1517 result.expect("no error expected").is_none(),
1518 "should return None when no config files exist in the given roots"
1519 );
1520 }
1521
1522 #[test]
1523 fn home_gate_config_is_rejected_while_explicit_empty_config_is_hermetic() {
1524 let project_dir = tempfile::tempdir().unwrap();
1525 let home_dir = tempfile::tempdir().unwrap();
1526 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1527 std::fs::write(
1528 home_dir.path().join(".khive/config.toml"),
1529 "[gate]\ngranted_actors = [\"lambda:enrolled\"]\n",
1530 )
1531 .unwrap();
1532
1533 let err = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1534 .expect_err("an unsupported home gate policy must still fail loud");
1535 assert!(matches!(
1536 config_error_root(&err),
1537 ConfigError::UnsupportedGateSection
1538 ));
1539
1540 let empty = project_dir.path().join("empty-khive-config.toml");
1541 std::fs::write(&empty, "").unwrap();
1542 let isolated = KhiveConfig::load_with_home_fallback(Some(&empty), None)
1543 .expect("an explicit empty fixture must isolate config discovery")
1544 .expect("the explicit config exists");
1545 assert!(isolated.engines.is_empty());
1546 assert!(isolated.actor.id.is_none());
1547 }
1548
1549 #[test]
1550 fn test_load_with_home_fallback_explicit_path() {
1551 let dir = tempfile::tempdir().unwrap();
1552 let path = write_toml(
1553 &dir,
1554 r#"
1555[actor]
1556id = "lambda:explicit"
1557"#,
1558 );
1559 let cfg = KhiveConfig::load_with_home_fallback(Some(&path), None)
1560 .expect("no error expected")
1561 .expect("file found");
1562 assert_eq!(cfg.actor.id.as_deref(), Some("lambda:explicit"));
1563 }
1564
1565 #[test]
1566 fn load_with_home_fallback_and_source_names_selected_file() {
1567 let project_dir = tempfile::tempdir().unwrap();
1568 let home_dir = tempfile::tempdir().unwrap();
1569 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1570 let selected = home_dir.path().join(".khive/config.toml");
1571 std::fs::write(&selected, "[actor]\nid = \"lambda:home\"\n").unwrap();
1572
1573 let (config, source) = KhiveConfig::load_with_roots_and_source(
1574 project_dir.path(),
1575 Some(home_dir.path()),
1576 None,
1577 )
1578 .expect("load should succeed")
1579 .expect("home fallback should be selected");
1580
1581 assert_eq!(config.actor.id.as_deref(), Some("lambda:home"));
1582 assert_eq!(
1583 source,
1584 std::fs::canonicalize(selected).expect("canonical selected config path")
1585 );
1586 }
1587
1588 #[test]
1589 fn test_invalid_actor_id_rejected_at_load() {
1590 let dir = tempfile::tempdir().unwrap();
1591 let path = write_toml(
1592 &dir,
1593 r#"
1594[actor]
1595id = "bad namespace"
1596"#,
1597 );
1598 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with invalid actor.id");
1599 assert!(
1600 matches!(config_error_root(&err), ConfigError::InvalidActorId { .. }),
1601 "expected InvalidActorId, got {err:?}"
1602 );
1603 }
1604
1605 #[test]
1606 fn test_empty_actor_id_rejected() {
1607 let dir = tempfile::tempdir().unwrap();
1608 let path = write_toml(
1609 &dir,
1610 r#"
1611[actor]
1612id = ""
1613"#,
1614 );
1615 let err = KhiveConfig::load(Some(&path)).expect_err("empty actor.id should be rejected");
1616 assert!(
1617 matches!(config_error_root(&err), ConfigError::InvalidActorId { .. }),
1618 "expected InvalidActorId for empty string, got {err:?}"
1619 );
1620 }
1621
1622 #[test]
1623 fn test_malformed_actor_id_lambda_colon_only() {
1624 let dir = tempfile::tempdir().unwrap();
1625 let path = write_toml(
1626 &dir,
1627 r#"
1628[actor]
1629id = "lambda:"
1630"#,
1631 );
1632 let err =
1633 KhiveConfig::load(Some(&path)).expect_err("lambda: with no slug should be rejected");
1634 assert!(
1635 matches!(config_error_root(&err), ConfigError::InvalidActorId { .. }),
1636 "expected InvalidActorId for 'lambda:', got {err:?}"
1637 );
1638 }
1639
1640 #[test]
1643 fn test_runtime_config_actor_id_does_not_override_namespace() {
1644 use crate::runtime::runtime_config_from_khive_config;
1645 use crate::RuntimeConfig;
1646 use khive_types::namespace::Namespace;
1647
1648 let cfg = KhiveConfig {
1649 engines: vec![],
1650 actor: ActorConfig {
1651 id: Some("lambda:test-actor".to_string()),
1652 display_name: None,
1653 ..Default::default()
1654 },
1655 ..KhiveConfig::default()
1656 };
1657 cfg.validate().expect("valid config");
1658
1659 let base = RuntimeConfig::default();
1660 let result = runtime_config_from_khive_config(&cfg, base);
1661 assert_eq!(
1662 result.default_namespace,
1663 Namespace::local(),
1664 "actor.id must NOT become default_namespace (ADR-007 Rev 4 Rule 0); \
1665 writes stay pinned to local"
1666 );
1667 assert!(
1670 result
1671 .visible_namespaces
1672 .contains(&Namespace::parse("lambda:test-actor").unwrap()),
1673 "actor.id must be folded into visible_namespaces (ADR-007 Rev 4 Rule 3b fold-in); \
1674 got: {:?}",
1675 result.visible_namespaces
1676 );
1677 }
1678
1679 #[test]
1680 fn test_runtime_config_no_actor_preserves_base() {
1681 use crate::runtime::runtime_config_from_khive_config;
1682 use crate::RuntimeConfig;
1683 use khive_types::namespace::Namespace;
1684
1685 let cfg = KhiveConfig {
1686 engines: vec![],
1687 actor: ActorConfig {
1688 id: None,
1689 display_name: None,
1690 ..Default::default()
1691 },
1692 ..KhiveConfig::default()
1693 };
1694 cfg.validate().expect("valid config");
1695
1696 let base_ns = Namespace::parse("lambda:base").unwrap();
1697 let base = RuntimeConfig {
1698 default_namespace: base_ns.clone(),
1699 ..RuntimeConfig::default()
1700 };
1701 let result = runtime_config_from_khive_config(&cfg, base);
1702 assert_eq!(
1703 result.default_namespace, base_ns,
1704 "no actor.id must leave base namespace unchanged"
1705 );
1706 }
1707
1708 #[test]
1709 fn test_load_with_home_fallback_project_root_over_hidden() {
1710 let dir = tempfile::tempdir().unwrap();
1711
1712 std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
1714 std::fs::write(
1715 dir.path().join(".khive/config.toml"),
1716 "[actor]\nid = \"lambda:hidden\"\n",
1717 )
1718 .unwrap();
1719
1720 std::fs::write(
1722 dir.path().join("khive.toml"),
1723 "[actor]\nid = \"lambda:project-root\"\n",
1724 )
1725 .unwrap();
1726
1727 let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
1728 .expect("no error expected")
1729 .expect("file should be found");
1730 assert_eq!(
1731 cfg.actor.id.as_deref(),
1732 Some("lambda:project-root"),
1733 "khive.toml (tier 2) must win over .khive/config.toml (tier 3)"
1734 );
1735 }
1736
1737 #[test]
1738 fn test_load_with_home_fallback_hidden_over_absent_root() {
1739 let dir = tempfile::tempdir().unwrap();
1740
1741 std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
1742 std::fs::write(
1743 dir.path().join(".khive/config.toml"),
1744 "[actor]\nid = \"lambda:hidden-config\"\n",
1745 )
1746 .unwrap();
1747 let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
1750 .expect("no error expected")
1751 .expect("file should be found");
1752 assert_eq!(
1753 cfg.actor.id.as_deref(),
1754 Some("lambda:hidden-config"),
1755 ".khive/config.toml (tier 3) must be found when khive.toml is absent"
1756 );
1757 }
1758
1759 #[test]
1760 fn test_load_with_roots_home_tier_found() {
1761 let project_dir = tempfile::tempdir().unwrap();
1762 let home_dir = tempfile::tempdir().unwrap();
1763
1764 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1765 std::fs::write(
1766 home_dir.path().join(".khive/config.toml"),
1767 "[actor]\nid = \"lambda:user-global\"\n",
1768 )
1769 .unwrap();
1770 let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1773 .expect("no error expected")
1774 .expect("file should be found");
1775 assert_eq!(
1776 cfg.actor.id.as_deref(),
1777 Some("lambda:user-global"),
1778 "~/.khive/config.toml (tier 4) must be found when project files absent"
1779 );
1780 }
1781
1782 #[test]
1783 fn test_load_with_roots_project_wins_over_home() {
1784 let project_dir = tempfile::tempdir().unwrap();
1785 let home_dir = tempfile::tempdir().unwrap();
1786
1787 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1789 std::fs::write(
1790 home_dir.path().join(".khive/config.toml"),
1791 "[actor]\nid = \"lambda:user-global\"\n",
1792 )
1793 .unwrap();
1794
1795 std::fs::create_dir_all(project_dir.path().join(".khive")).unwrap();
1797 std::fs::write(
1798 project_dir.path().join(".khive/config.toml"),
1799 "[actor]\nid = \"lambda:project-wins\"\n",
1800 )
1801 .unwrap();
1802
1803 let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1804 .expect("no error expected")
1805 .expect("file should be found");
1806 assert_eq!(
1807 cfg.actor.id.as_deref(),
1808 Some("lambda:project-wins"),
1809 "project .khive/config.toml (tier 3) must win over ~/.khive/config.toml (tier 4)"
1810 );
1811 }
1812
1813 #[test]
1821 fn test_load_with_roots_same_db_different_cwd_resolves_identical_config() {
1822 let cwd_a = tempfile::tempdir().unwrap();
1823 let cwd_b = tempfile::tempdir().unwrap();
1824
1825 std::fs::create_dir_all(cwd_a.path().join(".khive")).unwrap();
1828 std::fs::write(
1829 cwd_a.path().join(".khive/config.toml"),
1830 "[actor]\nid = \"lambda:wrong-cwd-a\"\n",
1831 )
1832 .unwrap();
1833 std::fs::create_dir_all(cwd_b.path().join(".khive")).unwrap();
1834 std::fs::write(
1835 cwd_b.path().join(".khive/config.toml"),
1836 "[actor]\nid = \"lambda:wrong-cwd-b\"\n",
1837 )
1838 .unwrap();
1839
1840 let db_root = tempfile::tempdir().unwrap();
1843 let khive_dir = db_root.path().join(".khive");
1844 std::fs::create_dir_all(&khive_dir).unwrap();
1845 let db_path = khive_dir.join("khive.db");
1846 std::fs::write(&db_path, b"").unwrap(); std::fs::write(
1848 khive_dir.join("config.toml"),
1849 "[actor]\nid = \"lambda:db-anchored\"\n",
1850 )
1851 .unwrap();
1852
1853 let cfg_a = KhiveConfig::load_with_roots(cwd_a.path(), None, Some(&db_path))
1854 .expect("no error expected")
1855 .expect("db-anchored config must be found from cwd A");
1856 let cfg_b = KhiveConfig::load_with_roots(cwd_b.path(), None, Some(&db_path))
1857 .expect("no error expected")
1858 .expect("db-anchored config must be found from cwd B");
1859
1860 assert_eq!(
1861 cfg_a.actor.id.as_deref(),
1862 Some("lambda:db-anchored"),
1863 "cwd A must resolve the db-anchored config, not its own decoy"
1864 );
1865 assert_eq!(
1866 cfg_b.actor.id.as_deref(),
1867 Some("lambda:db-anchored"),
1868 "cwd B must resolve the db-anchored config, not its own decoy"
1869 );
1870 assert_eq!(
1871 cfg_a.actor.id, cfg_b.actor.id,
1872 "two processes at different cwds targeting the same db must resolve \
1873 identical config, killing config_id drift between client and daemon"
1874 );
1875 }
1876
1877 #[test]
1881 fn test_load_with_home_fallback_explicit_config_wins_over_db_anchor() {
1882 let explicit_dir = tempfile::tempdir().unwrap();
1883 let explicit_path = write_toml(&explicit_dir, "[actor]\nid = \"lambda:explicit-wins\"\n");
1884
1885 let db_root = tempfile::tempdir().unwrap();
1886 let khive_dir = db_root.path().join(".khive");
1887 std::fs::create_dir_all(&khive_dir).unwrap();
1888 let db_path = khive_dir.join("khive.db");
1889 std::fs::write(&db_path, b"").unwrap();
1890 std::fs::write(
1891 khive_dir.join("config.toml"),
1892 "[actor]\nid = \"lambda:db-anchor-loses\"\n",
1893 )
1894 .unwrap();
1895
1896 let cfg = KhiveConfig::load_with_home_fallback(Some(&explicit_path), Some(&db_path))
1897 .expect("no error expected")
1898 .expect("explicit path must be found");
1899 assert_eq!(
1900 cfg.actor.id.as_deref(),
1901 Some("lambda:explicit-wins"),
1902 "explicit --config/KHIVE_CONFIG must win over the db-dir anchor"
1903 );
1904 }
1905
1906 #[test]
1909 fn test_load_with_roots_home_fallback_reached_when_db_anchor_has_no_config() {
1910 let cwd = tempfile::tempdir().unwrap();
1911 let home_dir = tempfile::tempdir().unwrap();
1912 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1913 std::fs::write(
1914 home_dir.path().join(".khive/config.toml"),
1915 "[actor]\nid = \"lambda:home-fallback\"\n",
1916 )
1917 .unwrap();
1918
1919 let db_root = tempfile::tempdir().unwrap();
1921 let khive_dir = db_root.path().join(".khive");
1922 std::fs::create_dir_all(&khive_dir).unwrap();
1923 let db_path = khive_dir.join("khive.db");
1924 std::fs::write(&db_path, b"").unwrap();
1925
1926 let cfg = KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&db_path))
1927 .expect("no error expected")
1928 .expect("home-tier config must be found");
1929 assert_eq!(
1930 cfg.actor.id.as_deref(),
1931 Some("lambda:home-fallback"),
1932 "tier 4 (~/.khive/config.toml) must still be reached when the db-anchored \
1933 tier-3 directory has no config.toml"
1934 );
1935 }
1936
1937 #[test]
1940 fn test_load_with_roots_nonexistent_db_path_does_not_panic_and_falls_through() {
1941 let cwd = tempfile::tempdir().unwrap();
1942 let home_dir = tempfile::tempdir().unwrap();
1943 std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1944 std::fs::write(
1945 home_dir.path().join(".khive/config.toml"),
1946 "[actor]\nid = \"lambda:home-cold-start\"\n",
1947 )
1948 .unwrap();
1949
1950 let nonexistent_db = cwd.path().join("never-created/.khive/khive.db");
1952
1953 let cfg =
1954 KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&nonexistent_db))
1955 .expect("cold-start db path must not error or panic")
1956 .expect("home-tier config must still be found");
1957 assert_eq!(
1958 cfg.actor.id.as_deref(),
1959 Some("lambda:home-cold-start"),
1960 "a nonexistent db path (cold start) must fall through to tier 4, not panic"
1961 );
1962 }
1963
1964 #[test]
1969 fn test_load_with_roots_relative_nonexistent_db_path_does_not_panic() {
1970 let cwd = tempfile::tempdir().unwrap();
1971 let relative_db = PathBuf::from("never-created/.khive/khive.db");
1972
1973 let result = KhiveConfig::load_with_roots(cwd.path(), None, Some(&relative_db));
1974 assert!(
1975 result.is_ok(),
1976 "relative cold-start db path must not error or panic: {result:?}"
1977 );
1978 assert!(
1979 result.unwrap().is_none(),
1980 "no config exists anywhere in this test; result must be None"
1981 );
1982 }
1983
1984 #[test]
1987 fn test_no_backends_section_is_valid() {
1988 let dir = tempfile::tempdir().unwrap();
1989 let path = write_toml(
1990 &dir,
1991 r#"
1992[[engines]]
1993name = "default"
1994model = "all-minilm-l6-v2"
1995default = true
1996"#,
1997 );
1998 let cfg = KhiveConfig::load(Some(&path))
1999 .expect("no error")
2000 .expect("file found");
2001 assert!(cfg.backends.is_empty());
2002 assert!(cfg.packs.is_empty());
2003 }
2004
2005 #[test]
2006 fn test_single_sqlite_backend_parses() {
2007 let dir = tempfile::tempdir().unwrap();
2008 let path = write_toml(
2009 &dir,
2010 r#"
2011[[backends]]
2012name = "knowledge"
2013kind = "sqlite"
2014path = "/tmp/knowledge.db"
2015"#,
2016 );
2017 let cfg = KhiveConfig::load(Some(&path))
2018 .expect("no error")
2019 .expect("file found");
2020 assert_eq!(cfg.backends.len(), 1);
2021 let b = &cfg.backends[0];
2022 assert_eq!(b.name, "knowledge");
2023 assert!(matches!(b.kind, BackendKind::Sqlite));
2024 assert_eq!(
2025 b.path.as_ref().and_then(|p| p.to_str()),
2026 Some("/tmp/knowledge.db")
2027 );
2028 }
2029
2030 #[test]
2031 fn test_memory_backend_parses() {
2032 let dir = tempfile::tempdir().unwrap();
2033 let path = write_toml(
2034 &dir,
2035 r#"
2036[[backends]]
2037name = "ephemeral"
2038kind = "memory"
2039"#,
2040 );
2041 let cfg = KhiveConfig::load(Some(&path))
2042 .expect("no error")
2043 .expect("file found");
2044 assert_eq!(cfg.backends.len(), 1);
2045 assert!(matches!(cfg.backends[0].kind, BackendKind::Memory));
2046 }
2047
2048 #[test]
2049 fn test_pack_backend_assignment_parses() {
2050 let dir = tempfile::tempdir().unwrap();
2051 let path = write_toml(
2052 &dir,
2053 r#"
2054[[backends]]
2055name = "knowledge"
2056kind = "memory"
2057
2058[packs.knowledge]
2059backend = "knowledge"
2060"#,
2061 );
2062 let cfg = KhiveConfig::load(Some(&path))
2063 .expect("no error")
2064 .expect("file found");
2065 assert_eq!(cfg.packs.len(), 1);
2066 let pc = cfg.packs.get("knowledge").expect("knowledge pack present");
2067 assert_eq!(pc.backend, "knowledge");
2068 }
2069
2070 #[test]
2071 fn test_duplicate_backend_name_rejected() {
2072 let dir = tempfile::tempdir().unwrap();
2073 let path = write_toml(
2074 &dir,
2075 r#"
2076[[backends]]
2077name = "dup"
2078kind = "memory"
2079
2080[[backends]]
2081name = "dup"
2082kind = "memory"
2083"#,
2084 );
2085 let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
2086 assert!(
2087 matches!(config_error_root(&err), ConfigError::DuplicateBackendName { ref name } if name == "dup"),
2088 "expected DuplicateBackendName {{ name: \"dup\" }}, got {err:?}"
2089 );
2090 }
2091
2092 #[test]
2093 fn test_pack_referencing_undefined_backend_rejected() {
2094 let dir = tempfile::tempdir().unwrap();
2095 let path = write_toml(
2096 &dir,
2097 r#"
2098[[backends]]
2099name = "knowledge"
2100kind = "memory"
2101
2102[packs.kg]
2103backend = "nonexistent"
2104"#,
2105 );
2106 let err =
2107 KhiveConfig::load(Some(&path)).expect_err("should fail with unknown backend reference");
2108 assert!(
2109 matches!(config_error_root(&err), ConfigError::UnknownPackBackend { ref pack, ref backend, .. }
2110 if pack == "kg" && backend == "nonexistent"),
2111 "expected UnknownPackBackend for kg→nonexistent, got {err:?}"
2112 );
2113 }
2114
2115 #[test]
2116 fn test_pack_config_without_backends_section_is_allowed() {
2117 let dir = tempfile::tempdir().unwrap();
2118 let path = write_toml(
2121 &dir,
2122 r#"
2123[packs.kg]
2124backend = "main"
2125"#,
2126 );
2127 let cfg = KhiveConfig::load(Some(&path))
2128 .expect("no error expected")
2129 .expect("file found");
2130 assert_eq!(cfg.backends.len(), 0);
2131 assert_eq!(cfg.packs.len(), 1);
2132 }
2133
2134 #[test]
2135 fn test_backend_cache_mb_rejected_at_validate() {
2136 let dir = tempfile::tempdir().unwrap();
2137 let path = write_toml(
2138 &dir,
2139 r#"
2140[[backends]]
2141name = "main"
2142kind = "memory"
2143cache_mb = 128
2144"#,
2145 );
2146 let err = KhiveConfig::load(Some(&path)).expect_err("cache_mb must be rejected");
2147 assert!(
2148 matches!(config_error_root(&err), ConfigError::UnsupportedBackendField { ref name, field: "cache_mb" } if name == "main"),
2149 "expected UnsupportedBackendField {{ name: \"main\", field: \"cache_mb\" }}, got {err:?}"
2150 );
2151 }
2152
2153 #[test]
2154 fn test_backend_journal_mode_rejected_at_validate() {
2155 let dir = tempfile::tempdir().unwrap();
2156 let path = write_toml(
2157 &dir,
2158 r#"
2159[[backends]]
2160name = "main"
2161kind = "memory"
2162journal_mode = "wal"
2163"#,
2164 );
2165 let err = KhiveConfig::load(Some(&path)).expect_err("journal_mode must be rejected");
2166 assert!(
2167 matches!(config_error_root(&err), ConfigError::UnsupportedBackendField { ref name, field: "journal_mode" } if name == "main"),
2168 "expected UnsupportedBackendField {{ name: \"main\", field: \"journal_mode\" }}, got {err:?}"
2169 );
2170 }
2171
2172 #[test]
2175 fn test_top_level_db_rejected_at_validate() {
2176 let dir = tempfile::tempdir().unwrap();
2177 let path = write_toml(
2178 &dir,
2179 r#"
2180db = "/tmp/scratch/demo.db"
2181"#,
2182 );
2183 let err = KhiveConfig::load(Some(&path)).expect_err("top-level db must be rejected");
2184 assert!(
2185 matches!(config_error_root(&err), ConfigError::UnsupportedTopLevelDb { ref value } if value == "/tmp/scratch/demo.db"),
2186 "expected UnsupportedTopLevelDb {{ value: \"/tmp/scratch/demo.db\" }}, got {err:?}"
2187 );
2188 }
2189
2190 #[test]
2191 fn gate_caller_enrollment_is_rejected_instead_of_ignored() {
2192 let dir = tempfile::tempdir().unwrap();
2193 let path = write_toml(
2194 &dir,
2195 r#"
2196[gate]
2197granted_actors = ["lambda:enrolled"]
2198grant_unattributed = false
2199"#,
2200 );
2201
2202 let err = KhiveConfig::load(Some(&path))
2203 .expect_err("an unenforced caller-enrollment policy must abort startup");
2204 assert!(
2205 matches!(config_error_root(&err), ConfigError::UnsupportedGateSection),
2206 "expected UnsupportedGateSection, got {err:?}"
2207 );
2208 assert!(
2209 err.to_string().contains("would not be enforced"),
2210 "operator-facing error must explain the fail-loud reason: {err}"
2211 );
2212 }
2213
2214 #[test]
2215 fn empty_gate_table_is_still_rejected() {
2216 let dir = tempfile::tempdir().unwrap();
2217 let path = write_toml(&dir, "[gate]\n");
2218 let err = KhiveConfig::load(Some(&path))
2219 .expect_err("a present gate table must never disappear through serde defaults");
2220 assert!(matches!(
2221 config_error_root(&err),
2222 ConfigError::UnsupportedGateSection
2223 ));
2224 }
2225
2226 #[test]
2227 fn unrelated_unknown_top_level_sections_remain_forward_compatible() {
2228 let dir = tempfile::tempdir().unwrap();
2229 let path = write_toml(&dir, "[future_feature]\nenabled = true\n");
2230 KhiveConfig::load(Some(&path))
2231 .expect("unrelated future config stays forward compatible")
2232 .expect("config exists");
2233 }
2234
2235 #[test]
2239 fn test_no_git_write_section_is_valid_and_empty() {
2240 let dir = tempfile::tempdir().unwrap();
2241 let path = write_toml(&dir, "# no git_write section\n");
2242 let cfg = KhiveConfig::load(Some(&path))
2243 .expect("no error")
2244 .expect("file found");
2245 assert!(cfg.git_write.allowed.is_empty());
2246 }
2247
2248 #[test]
2250 fn test_git_write_entry_parses() {
2251 let dir = tempfile::tempdir().unwrap();
2252 let path = write_toml(
2253 &dir,
2254 r#"
2255[[git_write.allowed]]
2256repo = "/abs/path/repo"
2257branches = ["feat/*", "fix/*"]
2258"#,
2259 );
2260 let cfg = KhiveConfig::load(Some(&path))
2261 .expect("no error")
2262 .expect("file found");
2263 assert_eq!(cfg.git_write.allowed.len(), 1);
2264 assert_eq!(cfg.git_write.allowed[0].repo, "/abs/path/repo");
2265 assert_eq!(
2266 cfg.git_write.allowed[0].branches,
2267 vec!["feat/*".to_string(), "fix/*".to_string()]
2268 );
2269 }
2270
2271 #[test]
2273 fn test_git_write_relative_repo_rejected() {
2274 let dir = tempfile::tempdir().unwrap();
2275 let path = write_toml(
2276 &dir,
2277 r#"
2278[[git_write.allowed]]
2279repo = "relative/path"
2280branches = ["main"]
2281"#,
2282 );
2283 let err = KhiveConfig::load(Some(&path)).expect_err("relative repo must be rejected");
2284 assert!(
2285 matches!(config_error_root(&err), ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "relative/path"),
2286 "expected InvalidGitWriteEntry, got {err:?}"
2287 );
2288 }
2289
2290 #[test]
2294 fn test_git_write_multi_star_branch_pattern_rejected() {
2295 let dir = tempfile::tempdir().unwrap();
2296 let path = write_toml(
2297 &dir,
2298 r#"
2299[[git_write.allowed]]
2300repo = "/abs/path"
2301branches = ["**"]
2302"#,
2303 );
2304 let err = KhiveConfig::load(Some(&path)).expect_err("** must be rejected");
2305 assert!(
2306 matches!(config_error_root(&err), ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
2307 "expected InvalidGitWriteEntry, got {err:?}"
2308 );
2309
2310 let dir2 = tempfile::tempdir().unwrap();
2311 let path2 = write_toml(
2312 &dir2,
2313 r#"
2314[[git_write.allowed]]
2315repo = "/abs/path"
2316branches = ["rel-*-*-final"]
2317"#,
2318 );
2319 let err2 = KhiveConfig::load(Some(&path2)).expect_err("rel-*-*-final must be rejected");
2320 assert!(
2321 matches!(
2322 config_error_root(&err2),
2323 ConfigError::InvalidGitWriteEntry { .. }
2324 ),
2325 "expected InvalidGitWriteEntry, got {err2:?}"
2326 );
2327 }
2328
2329 #[test]
2331 fn test_git_write_single_star_branch_pattern_accepted() {
2332 let dir = tempfile::tempdir().unwrap();
2333 let path = write_toml(
2334 &dir,
2335 r#"
2336[[git_write.allowed]]
2337repo = "/abs/path"
2338branches = ["a*b", "main"]
2339"#,
2340 );
2341 let cfg = KhiveConfig::load(Some(&path))
2342 .expect("no error")
2343 .expect("file found");
2344 assert_eq!(cfg.git_write.allowed[0].branches, vec!["a*b", "main"]);
2345 }
2346
2347 #[test]
2350 fn test_git_write_empty_branches_rejected() {
2351 let dir = tempfile::tempdir().unwrap();
2352 let path = write_toml(
2353 &dir,
2354 r#"
2355[[git_write.allowed]]
2356repo = "/abs/path"
2357branches = []
2358"#,
2359 );
2360 let err = KhiveConfig::load(Some(&path)).expect_err("empty branches must be rejected");
2361 assert!(
2362 matches!(config_error_root(&err), ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
2363 "expected InvalidGitWriteEntry, got {err:?}"
2364 );
2365 }
2366
2367 #[test]
2372 fn test_no_storage_section_defaults_to_fs() {
2373 let dir = tempfile::tempdir().unwrap();
2374 let path = write_toml(&dir, "# no storage section\n");
2375 let cfg = KhiveConfig::load(Some(&path))
2376 .expect("no error")
2377 .expect("file found");
2378 assert!(cfg.storage.blob.is_none());
2379 }
2380
2381 #[test]
2382 fn test_storage_blob_fs_selection_parses() {
2383 let dir = tempfile::tempdir().unwrap();
2384 let path = write_toml(
2385 &dir,
2386 r#"
2387[storage.blob]
2388backend = "fs"
2389root = "/var/lib/khive/blobs"
2390floor_bytes = 100000000000
2391"#,
2392 );
2393 let cfg = KhiveConfig::load(Some(&path))
2394 .expect("no error")
2395 .expect("file found");
2396 match cfg.storage.blob {
2397 Some(BlobConfig::Fs { root, floor_bytes }) => {
2398 assert_eq!(root.as_deref(), Some("/var/lib/khive/blobs"));
2399 assert_eq!(floor_bytes, Some(100_000_000_000));
2400 }
2401 other => panic!("expected BlobConfig::Fs, got {other:?}"),
2402 }
2403 }
2404
2405 #[test]
2406 fn test_storage_blob_s3_selection_parses() {
2407 let dir = tempfile::tempdir().unwrap();
2408 let path = write_toml(
2409 &dir,
2410 r#"
2411[storage.blob]
2412backend = "s3"
2413bucket = "khive-blobs"
2414region = "us-east-1"
2415endpoint = "https://objects.example.invalid"
2416prefix = "blobs"
2417"#,
2418 );
2419 let cfg = KhiveConfig::load(Some(&path))
2420 .expect("no error")
2421 .expect("file found");
2422 match cfg.storage.blob {
2423 Some(BlobConfig::S3 {
2424 bucket,
2425 region,
2426 endpoint,
2427 prefix,
2428 allow_http,
2429 }) => {
2430 assert_eq!(bucket, "khive-blobs");
2431 assert_eq!(region, "us-east-1");
2432 assert_eq!(endpoint.as_deref(), Some("https://objects.example.invalid"));
2433 assert_eq!(prefix.as_deref(), Some("blobs"));
2434 assert_eq!(allow_http, None);
2435 }
2436 other => panic!("expected BlobConfig::S3, got {other:?}"),
2437 }
2438 }
2439
2440 #[test]
2444 fn test_storage_blob_unknown_field_rejected() {
2445 let dir = tempfile::tempdir().unwrap();
2446 let path = write_toml(
2447 &dir,
2448 r#"
2449[storage.blob]
2450backend = "fs"
2451made_up_field = "x"
2452"#,
2453 );
2454 let err = KhiveConfig::load(Some(&path)).expect_err("unknown field must be rejected");
2455 assert!(
2456 matches!(config_error_root(&err), ConfigError::Parse { .. }),
2457 "got {err:?}"
2458 );
2459 }
2460
2461 #[test]
2465 fn test_storage_blob_other_backend_field_rejected() {
2466 let dir = tempfile::tempdir().unwrap();
2467 let path = write_toml(
2468 &dir,
2469 r#"
2470[storage.blob]
2471backend = "fs"
2472bucket = "khive-blobs"
2473"#,
2474 );
2475 let err = KhiveConfig::load(Some(&path)).expect_err("s3 field under fs must be rejected");
2476 assert!(
2477 matches!(config_error_root(&err), ConfigError::Parse { .. }),
2478 "got {err:?}"
2479 );
2480 }
2481
2482 #[test]
2486 fn test_storage_blob_credential_field_rejected() {
2487 let dir = tempfile::tempdir().unwrap();
2488 let path = write_toml(
2489 &dir,
2490 r#"
2491[storage.blob]
2492backend = "s3"
2493bucket = "khive-blobs"
2494region = "us-east-1"
2495access_key_id = "AKIAEXAMPLE"
2496"#,
2497 );
2498 let err = KhiveConfig::load(Some(&path))
2499 .expect_err("a credential field in TOML must be rejected");
2500 assert!(
2501 matches!(config_error_root(&err), ConfigError::Parse { .. }),
2502 "got {err:?}"
2503 );
2504 }
2505
2506 #[test]
2509 fn test_storage_blob_unknown_backend_value_rejected() {
2510 let dir = tempfile::tempdir().unwrap();
2511 let path = write_toml(
2512 &dir,
2513 r#"
2514[storage.blob]
2515backend = "gcs"
2516"#,
2517 );
2518 let err = KhiveConfig::load(Some(&path)).expect_err("unknown backend must be rejected");
2519 assert!(
2520 matches!(config_error_root(&err), ConfigError::Parse { .. }),
2521 "got {err:?}"
2522 );
2523 }
2524
2525 #[test]
2529 fn test_no_display_section_defaults_to_none() {
2530 let dir = tempfile::tempdir().unwrap();
2531 let path = write_toml(&dir, "# no display section\n");
2532 let cfg = KhiveConfig::load(Some(&path))
2533 .expect("no error")
2534 .expect("file found");
2535 assert!(cfg.display.timezone.is_none());
2536 }
2537
2538 #[test]
2539 fn test_display_timezone_valid_iana_name_parses() {
2540 let dir = tempfile::tempdir().unwrap();
2541 let path = write_toml(
2542 &dir,
2543 r#"
2544[display]
2545timezone = "America/New_York"
2546"#,
2547 );
2548 let cfg = KhiveConfig::load(Some(&path))
2549 .expect("no error")
2550 .expect("file found");
2551 assert_eq!(cfg.display.timezone.as_deref(), Some("America/New_York"));
2552 }
2553
2554 #[test]
2555 fn test_display_timezone_unrecognized_name_rejected() {
2556 let dir = tempfile::tempdir().unwrap();
2557 let path = write_toml(
2558 &dir,
2559 r#"
2560[display]
2561timezone = "Mars/Olympus_Mons"
2562"#,
2563 );
2564 let err = KhiveConfig::load(Some(&path))
2565 .expect_err("an unrecognized IANA zone name must fail at load, not silently fall back");
2566 assert!(
2567 matches!(config_error_root(&err), ConfigError::InvalidDisplayTimezone { ref timezone } if timezone == "Mars/Olympus_Mons"),
2568 "expected InvalidDisplayTimezone, got {err:?}"
2569 );
2570 }
2571
2572 #[test]
2573 fn test_display_timezone_empty_string_rejected() {
2574 let dir = tempfile::tempdir().unwrap();
2575 let path = write_toml(
2576 &dir,
2577 r#"
2578[display]
2579timezone = ""
2580"#,
2581 );
2582 let err =
2583 KhiveConfig::load(Some(&path)).expect_err("an empty timezone string must be rejected");
2584 assert!(
2585 matches!(
2586 config_error_root(&err),
2587 ConfigError::InvalidDisplayTimezone { .. }
2588 ),
2589 "expected InvalidDisplayTimezone, got {err:?}"
2590 );
2591 }
2592}