1use std::collections::{BTreeMap, BTreeSet};
8use std::path::{Path, PathBuf};
9
10use khive_types::{namespace::Namespace, SubstrateKind};
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13
14use crate::{config::BackendId, presentation::OutputFormat};
15
16#[path = "engine_config_backend_disk_guard.rs"]
17mod backend_disk_guard;
18
19#[path = "engine_config_embed_batch.rs"]
20mod embed_batch;
21pub use embed_batch::EmbedSectionConfig;
22
23#[path = "engine_config_peers.rs"]
24mod peers;
25pub use peers::EngineConfig;
26pub(crate) use peers::{canonical_engine_name, validate_peer_engines};
27
28#[derive(Debug, Error)]
32pub enum ConfigError {
33 #[error("[storage.blob] backend = \"s3\" requires the blob-s3 feature")]
34 BlobS3FeatureDisabled,
35
36 #[error(transparent)]
37 Credential(#[from] crate::credentials::CredentialError),
38
39 #[error("mount configuration: {reason}")]
40 InvalidMountConfig { reason: String },
41
42 #[error("channel.node: {reason}")]
43 InvalidNodeConfig { reason: String },
44
45 #[error("config file I/O: {0}")]
46 Io(#[from] std::io::Error),
47
48 #[error("config TOML parse error in {path}: {source}")]
49 Parse {
50 path: PathBuf,
51 #[source]
52 source: toml::de::Error,
53 },
54
55 #[error("config TOML policy error in {path}, key {key}: {source}")]
56 SchemaParse {
57 path: PathBuf,
58 key: &'static str,
59 #[source]
60 source: Box<toml::de::Error>,
61 },
62
63 #[error("exactly one engine must be marked `default = true`; found {found}")]
64 DefaultCount { found: usize },
65
66 #[error("duplicate engine name: {name:?}")]
67 DuplicateName { name: String },
68
69 #[error(
70 "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
71 )]
72 UnknownModel { name: String, model: String },
73
74 #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
75 InvalidFusionWeight { name: String, value: f64 },
76
77 #[error(
78 "engine {name:?}: fusion_weight is not applied by current retrieval; \
79 remove it until weighted multi-engine fusion is wired"
80 )]
81 UnsupportedFusionWeight { name: String },
82
83 #[error("engine name must not be empty: {name:?}")]
84 InvalidEngineName { name: String },
85
86 #[error("engine {name:?} collides with another engine after alias canonicalization to {canonical:?}; remove the duplicate declaration")]
87 AliasCollision { name: String, canonical: String },
88
89 #[error("engine {name:?}: weight must be finite and strictly positive, got {value}")]
90 InvalidEngineWeight { name: String, value: f64 },
91
92 #[error("engine {name:?}: non-unit weight is refused until configured weights reach every activated retrieval path")]
93 UnsupportedEngineWeight { name: String },
94
95 #[error("engine {name:?}: dims must be positive and at most 4294967295, got {value}")]
96 InvalidEngineDimensions { name: String, value: i64 },
97
98 #[error(
99 "engine {name:?}: configured dims {expected} do not match provider dimensions {actual}"
100 )]
101 EngineDimensionMismatch {
102 name: String,
103 expected: i64,
104 actual: usize,
105 },
106
107 #[error("engine {name:?}: cannot mix legacy model/default/fusion_weight entries with canonical name/weight entries")]
108 EngineKeyConflict { name: String },
109
110 #[error("engines {name:?} and {other:?} share the storage key {key:?}; distinct engine identities require distinct bindings")]
111 EngineKeyCollision {
112 name: String,
113 other: String,
114 key: String,
115 },
116
117 #[error("actor.id {id:?} is not a valid namespace: {reason}")]
118 InvalidActorId { id: String, reason: String },
119
120 #[error("[actor].mailbox_readers: {reason}")]
121 InvalidMailboxReaders { reason: String },
122
123 #[error("[gate].granted_actors entry {id:?} is not a valid actor id: {reason}")]
124 InvalidGrantedActorId { id: String, reason: String },
125 #[error("[gate].deny_writes_for is invalid: {reason}")]
126 InvalidWriteDenyPatterns { reason: String },
127
128 #[error("duplicate backend name: {name:?}")]
129 DuplicateBackendName { name: String },
130
131 #[error("invalid backend name {name:?}: {reason}")]
132 InvalidBackendName { name: String, reason: String },
133
134 #[error("backend {name:?}: `served_kinds` must not be empty when declared")]
135 EmptyBackendServedKinds { name: String },
136
137 #[error("backend {name:?}: invalid disk guard configuration: {reason}")]
138 InvalidBackendDiskGuard { name: String, reason: String },
139
140 #[error(
141 "backends {first_backend:?} and {second_backend:?} name the same database but resolve \
142 different disk reserve/deadline policies"
143 )]
144 DiskGuardAliasConflict {
145 first_backend: String,
146 second_backend: String,
147 },
148
149 #[error("KHIVE_SQLITE_WAL_CEILING_BYTES must be an unsigned decimal byte count")]
150 InvalidWalCeilingEnvironment { value: String },
151
152 #[error(
153 "backend {name:?}: wal_ceiling_bytes {value} exceeds supported SQLite offset arithmetic"
154 )]
155 WalCeilingOffsetOverflow { name: String, value: u64 },
156
157 #[error(
158 "backend {name:?}: nonzero wal_ceiling_bytes {value} requires a file-backed SQLite backend"
159 )]
160 WalCeilingMemoryBackend { name: String, value: u64 },
161
162 #[error("backend {name:?}: nonzero wal_ceiling_bytes {value} requires SQLite WAL mode")]
163 WalCeilingNonWalBackend { name: String, value: u64 },
164
165 #[error(
166 "backends {first_backend:?} and {second_backend:?} name the same database at {} \
167 but resolve different WAL ceilings ({first_bytes} and {second_bytes} bytes)",
168 crate::secret_gate::bounded_masked_log_text(&path.to_string_lossy())
169 )]
170 WalCeilingAliasConflict {
171 first_backend: String,
172 second_backend: String,
173 path: PathBuf,
174 first_bytes: u64,
175 second_bytes: u64,
176 },
177
178 #[error(
179 "backend configuration leaves searchable substrate kinds {kinds:?} unserved; \
180 defined backends: {defined}"
181 )]
182 MissingBackendSearchKinds {
183 kinds: Vec<SubstrateKind>,
184 defined: String,
185 },
186
187 #[error(
188 "[packs.{pack}].backend = {backend:?} references an unknown backend; \
189 defined backends: {defined}"
190 )]
191 UnknownPackBackend {
192 pack: String,
193 backend: String,
194 defined: String,
195 },
196
197 #[error(
198 "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
199 remove it from the config or wait for a future release that implements it"
200 )]
201 UnsupportedBackendField { name: String, field: &'static str },
202
203 #[error(
204 "top-level `db = {value:?}` is not a supported config-file key; \
205 use `--db` / `KHIVE_DB` to select a single-file database, or \
206 `[[backends]].path` to declare storage backend topology"
207 )]
208 UnsupportedTopLevelDb { value: String },
209
210 #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
211 InvalidGitWriteEntry { repo: String, reason: String },
212
213 #[error("[git_write] {key}: {reason}")]
214 InvalidGitWriteConfig { key: String, reason: String },
215
216 #[error("[exec] {key}: {reason}")]
217 InvalidExecConfig { key: String, reason: String },
218
219 #[error("{entry}: {reason}")]
220 InvalidTelemetryConfig { entry: String, reason: String },
221
222 #[error("[web] {key}: {reason}")]
223 InvalidWebConfig { key: String, reason: String },
224
225 #[error("[runtime] {key}: {reason}")]
226 InvalidRuntimeConfig { key: String, reason: String },
227
228 #[error(
229 "[runtime] blob_hydration_bytes must be between {min} and {max} bytes inclusive; got {value}"
230 )]
231 InvalidBlobHydrationBytes { value: u64, min: u64, max: u64 },
232
233 #[error("the explicitly selected config file does not exist: {path}")]
234 ExplicitConfigMissing { path: PathBuf },
235
236 #[error("[gate] configuration is not supported by this build")]
240 UnsupportedGateSection,
241
242 #[error(
243 "[display] timezone {timezone:?} is not a recognized IANA zone name (e.g. \"America/New_York\", \"UTC\")"
244 )]
245 InvalidDisplayTimezone { timezone: String },
246
247 #[error("{source} (config file: {})", path.display())]
257 InFile {
258 path: PathBuf,
259 #[source]
260 source: Box<ConfigError>,
261 },
262}
263
264impl ConfigError {
265 fn in_file(self, path: &Path) -> Self {
268 match self {
269 already @ (ConfigError::Parse { .. }
270 | ConfigError::SchemaParse { .. }
271 | ConfigError::ExplicitConfigMissing { .. }
272 | ConfigError::InFile { .. }) => already,
273 other => ConfigError::InFile {
274 path: path.to_path_buf(),
275 source: Box::new(other),
276 },
277 }
278 }
279}
280
281#[derive(Debug, Clone, Deserialize, Default)]
308#[serde(deny_unknown_fields)]
309pub struct ActorConfig {
310 #[serde(default)]
316 pub id: Option<String>,
317
318 #[serde(default)]
321 pub display_name: Option<String>,
322
323 #[serde(default)]
331 pub mailbox_readers: Vec<String>,
332
333 #[serde(default)]
339 pub visible_namespaces: Option<Vec<String>>,
340
341 #[serde(default)]
353 pub allowed_outbound_namespaces: Vec<String>,
354}
355
356#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
363#[serde(deny_unknown_fields)]
364pub struct GateSectionConfig {
365 #[serde(default)]
367 pub granted_actors: Vec<String>,
368
369 #[serde(default)]
371 pub grant_unattributed: bool,
372
373 #[serde(default)]
376 pub deny_writes_for: Vec<String>,
377}
378
379#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
383#[serde(rename_all = "lowercase")]
384pub enum BackendKind {
385 #[default]
387 Sqlite,
388 Memory,
390}
391
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub struct ResolvedWalCeiling {
398 pub configured_bytes: u64,
400 pub effective_bytes: u64,
402 pub source: khive_db::WalCeilingSource,
404}
405
406pub fn resolve_wal_ceiling(
412 backend_field: Option<u64>,
413 env_value: Option<&str>,
414 backend_name: &str,
415 kind: BackendKind,
416 wal_mode: bool,
417 read_only: bool,
418) -> Result<ResolvedWalCeiling, ConfigError> {
419 if kind == BackendKind::Memory && backend_field.is_none() {
420 return Ok(ResolvedWalCeiling {
421 configured_bytes: 0,
422 effective_bytes: 0,
423 source: khive_db::WalCeilingSource::Default,
424 });
425 }
426 let (configured_bytes, source) = if let Some(bytes) = backend_field {
427 (bytes, khive_db::WalCeilingSource::BackendField)
428 } else if let Some(raw) = env_value {
429 if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
430 return Err(ConfigError::InvalidWalCeilingEnvironment {
431 value: raw.to_owned(),
432 });
433 }
434 let bytes = raw
435 .parse::<u64>()
436 .map_err(|_| ConfigError::InvalidWalCeilingEnvironment {
437 value: raw.to_owned(),
438 })?;
439 (bytes, khive_db::WalCeilingSource::Environment)
440 } else {
441 (0, khive_db::WalCeilingSource::Default)
442 };
443
444 if configured_bytes != 0 {
445 if i64::try_from(configured_bytes).is_err() {
446 return Err(ConfigError::WalCeilingOffsetOverflow {
447 name: backend_name.to_owned(),
448 value: configured_bytes,
449 });
450 }
451 if kind == BackendKind::Memory {
452 return Err(ConfigError::WalCeilingMemoryBackend {
453 name: backend_name.to_owned(),
454 value: configured_bytes,
455 });
456 }
457 if !wal_mode {
458 return Err(ConfigError::WalCeilingNonWalBackend {
459 name: backend_name.to_owned(),
460 value: configured_bytes,
461 });
462 }
463 }
464
465 Ok(ResolvedWalCeiling {
466 configured_bytes,
467 effective_bytes: if read_only { 0 } else { configured_bytes },
468 source,
469 })
470}
471
472#[derive(Debug, Clone, Deserialize)]
489#[serde(deny_unknown_fields)]
490pub struct BackendConfig {
491 pub name: String,
493 #[serde(default)]
495 pub kind: BackendKind,
496 pub path: Option<std::path::PathBuf>,
499 pub cache_mb: Option<u32>,
501 pub journal_mode: Option<String>,
503 #[serde(default)]
509 pub served_kinds: Option<BTreeSet<SubstrateKind>>,
510 #[serde(default)]
512 pub read_only: bool,
513 pub wal_ceiling_bytes: Option<u64>,
517 #[serde(default)]
519 pub disk_reserve_bytes: Option<u64>,
520 #[serde(default)]
522 pub disk_guard_deadline_ms: Option<u64>,
523}
524
525#[derive(Debug, Clone, Deserialize, Default)]
532pub struct CodeMapConfig {
533 #[serde(default)]
535 pub name: Option<String>,
536 #[serde(default)]
538 pub path: Option<String>,
539 #[serde(default)]
541 pub source_root: Option<String>,
542 #[serde(default, flatten)]
544 pub unknown_fields: BTreeMap<String, toml::Value>,
545}
546
547#[derive(Debug, Clone, Deserialize)]
561pub struct PackConfig {
562 #[serde(default = "default_pack_backend")]
565 pub backend: String,
566 #[serde(default)]
568 pub verbs_disabled: Vec<String>,
569 #[serde(default)]
579 pub no_embed: bool,
580}
581
582fn default_pack_backend() -> String {
583 BackendId::MAIN.to_owned()
584}
585
586#[derive(Debug, Clone, Deserialize)]
614#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
615pub enum BlobConfig {
616 Fs {
620 #[serde(default)]
621 root: Option<String>,
622 #[serde(default)]
625 floor_bytes: Option<u64>,
626 },
627 S3 {
632 bucket: String,
633 region: String,
634 #[serde(default)]
635 endpoint: Option<String>,
636 #[serde(default)]
637 prefix: Option<String>,
638 #[serde(default)]
639 allow_http: Option<bool>,
640 },
641}
642
643#[derive(Debug, Clone, Deserialize, Default)]
645#[serde(deny_unknown_fields)]
646pub struct BlobSectionConfig {
647 #[serde(default)]
649 pub file_transfers: bool,
650}
651
652#[derive(Debug, Clone, Deserialize, Default)]
656#[serde(deny_unknown_fields)]
657pub struct StorageSectionConfig {
658 #[serde(default)]
663 pub blob: Option<BlobConfig>,
664}
665
666#[derive(Debug, Clone, Deserialize, Serialize, Default)]
668#[serde(deny_unknown_fields)]
669pub struct BrainSectionConfig {
670 #[serde(default)]
672 pub fleet_readers: Vec<String>,
673}
674
675#[derive(Debug, Clone, Deserialize, Serialize)]
687pub struct GitWriteEntryConfig {
688 pub repo: String,
690 pub branches: Vec<String>,
693}
694
695#[derive(Debug, Clone, Deserialize, Serialize)]
707pub struct GitWriteSectionConfig {
708 #[serde(default)]
710 pub program: Option<PathBuf>,
711 #[serde(default)]
712 pub allowed: Vec<GitWriteEntryConfig>,
713 #[serde(default)]
714 pub actors: BTreeMap<String, GitWriteActorConfig>,
715 #[serde(default)]
716 pub repositories: BTreeMap<String, GitWriteRepositoryConfig>,
717 #[serde(default = "default_git_credential_resolver")]
718 pub credential_resolver: Vec<String>,
719 #[serde(default)]
720 pub contract_faults: bool,
721 #[serde(default)]
722 pub fault: Option<String>,
723}
724
725#[derive(Debug, Clone, Deserialize, Serialize)]
726#[serde(deny_unknown_fields)]
727pub struct GitWriteRepositoryConfig {
728 pub remote: String,
730 pub slug: String,
732 pub visibility: String,
733 #[serde(default)]
739 pub merge_refusals: Vec<String>,
740}
741
742impl GitWriteRepositoryConfig {
743 pub const MERGE_REFUSALS: [&'static str; 2] = ["opener", "last_pusher"];
744
745 pub fn refuses_merge_by(&self, entry: &str) -> bool {
747 self.merge_refusals.iter().any(|listed| listed == entry)
748 }
749}
750
751#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
752#[serde(deny_unknown_fields)]
753pub struct GitWriteActorConfig {
754 pub name: String,
755 pub email: String,
756 pub credential_ref: String,
757 pub platform_identity: String,
758}
759
760fn default_git_credential_resolver() -> Vec<String> {
761 [
762 "/usr/bin/security",
763 "find-generic-password",
764 "-w",
765 "-s",
766 "{ref}",
767 ]
768 .into_iter()
769 .map(str::to_string)
770 .collect()
771}
772
773impl Default for GitWriteSectionConfig {
774 fn default() -> Self {
775 Self {
776 program: None,
777 allowed: Vec::new(),
778 actors: BTreeMap::new(),
779 repositories: BTreeMap::new(),
780 credential_resolver: default_git_credential_resolver(),
781 contract_faults: false,
782 fault: None,
783 }
784 }
785}
786
787impl GitWriteSectionConfig {
788 pub fn git_program(&self) -> &Path {
789 self.program.as_deref().unwrap_or_else(|| Path::new("git"))
790 }
791
792 pub fn validate_dev_loop(&self) -> Result<(), ConfigError> {
793 let invalid = |key: &str, reason: &str| ConfigError::InvalidGitWriteConfig {
794 key: key.to_string(),
795 reason: reason.to_string(),
796 };
797 if let Some(program) = &self.program {
798 if !program.is_absolute() {
799 return Err(invalid("git_write.program", "must be absolute"));
800 }
801 let metadata = std::fs::metadata(program).map_err(|error| {
802 if error.kind() == std::io::ErrorKind::NotFound {
803 invalid("git_write.program", "does not exist")
804 } else {
805 invalid("git_write.program", &format!("is not executable: {error}"))
806 }
807 })?;
808 #[cfg(unix)]
809 let executable = {
810 use std::os::unix::fs::PermissionsExt;
811 metadata.permissions().mode() & 0o111 != 0
812 };
813 #[cfg(windows)]
814 let executable = program
815 .extension()
816 .and_then(|extension| extension.to_str())
817 .is_some_and(|extension| {
818 extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
819 });
820 #[cfg(not(any(unix, windows)))]
821 let executable = false;
822 if !metadata.is_file() || !executable {
823 return Err(invalid("git_write.program", "is not executable"));
824 }
825 }
826 if self.contract_faults && !cfg!(feature = "contract-faults") {
827 tracing::error!(
828 target: "khive.boot",
829 "[git_write] contract_faults requires the test-only contract-faults build feature"
830 );
831 return Err(invalid(
832 "contract_faults",
833 "requires the test-only contract-faults build feature",
834 ));
835 }
836 if let Some(fault) = &self.fault {
837 if !self.contract_faults {
838 return Err(invalid("fault", "requires contract_faults = true"));
839 }
840 let valid = fault.split_once(':').is_some_and(|(verb, point)| {
841 matches!(verb, "git.push" | "git.pr_merge")
842 && matches!(
843 point,
844 "reply-lost-after-effect" | "audit-fails-after-effect"
845 )
846 });
847 if !valid {
848 return Err(invalid("fault", "unsupported contract fault selector"));
849 }
850 }
851 for (path, repository) in &self.repositories {
852 let key = format!("repositories.{path}.merge_refusals");
853 let mut seen: Vec<&str> = Vec::new();
854 for entry in &repository.merge_refusals {
855 if !GitWriteRepositoryConfig::MERGE_REFUSALS.contains(&entry.as_str()) {
856 return Err(invalid(&key, "entries must be opener or last_pusher"));
857 }
858 if seen.contains(&entry.as_str()) {
859 return Err(invalid(&key, "entries must not repeat"));
860 }
861 seen.push(entry);
862 }
863 }
864 if !cfg!(unix)
867 && self.actors.is_empty()
868 && self.credential_resolver == default_git_credential_resolver()
869 {
870 return Ok(());
871 }
872 let argv = &self.credential_resolver;
873 let Some(program) = argv.first() else {
874 return Err(invalid("credential_resolver", "argv must not be empty"));
875 };
876 let program_path = Path::new(program);
877 if !program_path.is_absolute() {
878 return Err(invalid(
879 "credential_resolver",
880 "argv[0] must be an absolute path",
881 ));
882 }
883 let program_name = program_path
884 .file_name()
885 .and_then(|name| name.to_str())
886 .unwrap_or_default()
887 .to_ascii_lowercase();
888 if matches!(
889 program_name.trim_end_matches(".exe"),
890 "sh" | "bash"
891 | "dash"
892 | "zsh"
893 | "ksh"
894 | "fish"
895 | "csh"
896 | "tcsh"
897 | "cmd"
898 | "powershell"
899 | "pwsh"
900 | "env"
901 ) {
902 return Err(invalid(
903 "credential_resolver",
904 "shell or env launcher is not allowed",
905 ));
906 }
907 if argv.iter().any(|arg| arg.chars().any(char::is_control)) {
908 return Err(invalid(
909 "credential_resolver",
910 "argv must not contain control characters",
911 ));
912 }
913 if program.contains(['{', '}'])
914 || argv[1..]
915 .iter()
916 .any(|arg| arg != "{ref}" && arg.contains(['{', '}']))
917 {
918 return Err(invalid(
919 "credential_resolver",
920 "{ref} must be a complete argument and is the only allowed template",
921 ));
922 }
923 if !argv[1..].iter().any(|arg| arg == "{ref}") {
924 return Err(invalid(
925 "credential_resolver",
926 "argv must contain a {ref} argument",
927 ));
928 }
929 for (actor, identity) in &self.actors {
930 if actor.trim().is_empty() || actor.chars().any(char::is_control) {
931 return Err(invalid(
932 "actors",
933 "actor labels must be nonempty and contain no control characters",
934 ));
935 }
936 for (field, value) in [
937 ("name", &identity.name),
938 ("email", &identity.email),
939 ("credential_ref", &identity.credential_ref),
940 ("platform_identity", &identity.platform_identity),
941 ] {
942 if value.trim().is_empty() || value.chars().any(char::is_control) {
943 return Err(invalid(
944 &format!("actors.{actor}.{field}"),
945 "must be nonempty and contain no control characters",
946 ));
947 }
948 }
949 if identity.name.contains(['<', '>']) || identity.email.contains(['<', '>']) {
950 return Err(invalid(
951 &format!("actors.{actor}"),
952 "name and email must not contain Git identity delimiters",
953 ));
954 }
955 }
956 Ok(())
957 }
958}
959
960#[derive(Debug, Clone, Deserialize, Default)]
965pub struct ExecLimitsConfig {
966 #[serde(default)]
967 pub cpu_seconds: Option<u64>,
968 #[serde(default)]
969 pub address_space: Option<u64>,
970 #[serde(default)]
971 pub file_size: Option<u64>,
972 #[serde(default)]
973 pub nproc: Option<u64>,
974}
975
976#[derive(Debug, Clone, Deserialize, Default)]
999#[serde(deny_unknown_fields)]
1000pub struct ExecSectionConfig {
1001 #[serde(default)]
1002 pub root: Option<String>,
1003 #[serde(default)]
1004 pub read_roots: Vec<String>,
1005 #[serde(default)]
1006 pub env: Vec<String>,
1007 #[serde(default)]
1008 pub never: Vec<String>,
1009 #[serde(default)]
1010 pub max_output_bytes: Option<u64>,
1011 #[serde(default)]
1012 pub timeout_default_s: Option<f64>,
1013 #[serde(default)]
1014 pub timeout_max_s: Option<f64>,
1015 #[serde(default)]
1017 pub binary_digest_timeout_s: Option<u64>,
1018 #[serde(default)]
1019 pub keep: bool,
1020 #[serde(default)]
1021 pub limits: ExecLimitsConfig,
1022}
1023
1024pub const DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 10;
1025pub const MAX_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 60;
1026
1027#[derive(Debug, Clone, Deserialize, Serialize)]
1036#[serde(deny_unknown_fields)]
1037pub struct WebAllowlistEntry {
1038 pub host: String,
1039}
1040
1041#[derive(Debug, Clone, Deserialize, Serialize)]
1048#[serde(deny_unknown_fields)]
1049pub struct WebCredentialConfig {
1050 pub name: String,
1052 pub env_var: String,
1054 pub hosts: Vec<String>,
1057}
1058
1059#[derive(Debug, Clone, Deserialize, Serialize)]
1063#[serde(deny_unknown_fields)]
1064pub struct WebFixtureResult {
1065 pub title: String,
1066 pub url: String,
1067 pub snippet: String,
1068}
1069
1070#[derive(Debug, Clone, Deserialize, Serialize)]
1074#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
1075pub enum WebSearchProviderConfig {
1076 Fixture {
1078 name: String,
1079 #[serde(default)]
1080 default: bool,
1081 results: Vec<WebFixtureResult>,
1082 },
1083 Http {
1090 name: String,
1091 #[serde(default)]
1092 default: bool,
1093 url_template: String,
1094 #[serde(default)]
1095 api_key_env: Option<String>,
1096 #[serde(default)]
1103 hosts: Vec<String>,
1104 },
1105}
1106
1107impl WebSearchProviderConfig {
1108 pub fn name(&self) -> &str {
1109 match self {
1110 WebSearchProviderConfig::Fixture { name, .. } => name,
1111 WebSearchProviderConfig::Http { name, .. } => name,
1112 }
1113 }
1114
1115 pub fn is_default(&self) -> bool {
1116 match self {
1117 WebSearchProviderConfig::Fixture { default, .. } => *default,
1118 WebSearchProviderConfig::Http { default, .. } => *default,
1119 }
1120 }
1121}
1122
1123#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1157#[serde(deny_unknown_fields)]
1158pub struct WebSectionConfig {
1159 #[serde(default)]
1160 pub timeout_default_s: Option<u64>,
1161 #[serde(default)]
1162 pub timeout_max_s: Option<u64>,
1163 #[serde(default)]
1164 pub max_bytes_default: Option<u64>,
1165 #[serde(default)]
1166 pub max_bytes_max: Option<u64>,
1167 #[serde(default)]
1168 pub search_limit_default: Option<u32>,
1169 #[serde(default)]
1170 pub search_limit_max: Option<u32>,
1171 #[serde(default)]
1172 pub allowlist: Vec<WebAllowlistEntry>,
1173 #[serde(default)]
1174 pub credentials: Vec<WebCredentialConfig>,
1175 #[serde(default)]
1176 pub search_providers: Vec<WebSearchProviderConfig>,
1177 #[serde(default)]
1181 pub read_roots: Vec<String>,
1182}
1183
1184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1186pub struct WebCeilings {
1187 pub timeout_default_s: u64,
1188 pub timeout_max_s: u64,
1189 pub max_bytes_default: u64,
1190 pub max_bytes_max: u64,
1191 pub search_limit_default: u32,
1192 pub search_limit_max: u32,
1193}
1194
1195impl Default for WebCeilings {
1196 fn default() -> Self {
1197 Self {
1198 timeout_default_s: 30,
1199 timeout_max_s: 120,
1200 max_bytes_default: 5 * 1024 * 1024,
1201 max_bytes_max: 50 * 1024 * 1024,
1202 search_limit_default: 10,
1203 search_limit_max: 50,
1204 }
1205 }
1206}
1207
1208impl WebSectionConfig {
1209 pub fn resolved_ceilings(&self) -> Result<WebCeilings, ConfigError> {
1210 let defaults = WebCeilings::default();
1211 let bounds = WebCeilings {
1212 timeout_default_s: self.timeout_default_s.unwrap_or(defaults.timeout_default_s),
1213 timeout_max_s: self.timeout_max_s.unwrap_or(defaults.timeout_max_s),
1214 max_bytes_default: self.max_bytes_default.unwrap_or(defaults.max_bytes_default),
1215 max_bytes_max: self.max_bytes_max.unwrap_or(defaults.max_bytes_max),
1216 search_limit_default: self
1217 .search_limit_default
1218 .unwrap_or(defaults.search_limit_default),
1219 search_limit_max: self.search_limit_max.unwrap_or(defaults.search_limit_max),
1220 };
1221 for (key, default, maximum, maximum_key) in [
1222 (
1223 "timeout_default_s",
1224 bounds.timeout_default_s,
1225 bounds.timeout_max_s,
1226 "timeout_max_s",
1227 ),
1228 (
1229 "max_bytes_default",
1230 bounds.max_bytes_default,
1231 bounds.max_bytes_max,
1232 "max_bytes_max",
1233 ),
1234 (
1235 "search_limit_default",
1236 u64::from(bounds.search_limit_default),
1237 u64::from(bounds.search_limit_max),
1238 "search_limit_max",
1239 ),
1240 ] {
1241 if default == 0 || default > maximum {
1242 return Err(ConfigError::InvalidWebConfig {
1243 key: key.into(),
1244 reason: format!(
1245 "resolved default must be positive and not exceed {maximum_key}={maximum}"
1246 ),
1247 });
1248 }
1249 }
1250 if std::time::Instant::now()
1251 .checked_add(std::time::Duration::from_secs(bounds.timeout_max_s))
1252 .is_none()
1253 {
1254 return Err(ConfigError::InvalidWebConfig {
1255 key: "timeout_max_s".into(),
1256 reason: "cannot be represented as a request deadline".into(),
1257 });
1258 }
1259 Ok(bounds)
1260 }
1261
1262 pub fn validate(&self) -> Result<(), ConfigError> {
1263 self.resolved_ceilings()?;
1264 let invalid = |key: &str, reason: &str| ConfigError::InvalidWebConfig {
1265 key: key.to_string(),
1266 reason: reason.to_string(),
1267 };
1268 let mut seen_hosts = std::collections::HashSet::new();
1269 for entry in &self.allowlist {
1270 let normalized = entry.host.trim().trim_end_matches('.').to_ascii_lowercase();
1271 if normalized.is_empty() {
1272 return Err(invalid("allowlist.host", "must not be empty"));
1273 }
1274 if !seen_hosts.insert(normalized) {
1275 return Err(invalid("allowlist.host", "duplicate host entry"));
1276 }
1277 }
1278 let mut seen_credentials = std::collections::HashSet::new();
1279 for credential in &self.credentials {
1280 if credential.name.trim().is_empty() {
1281 return Err(invalid("credentials.name", "must not be empty"));
1282 }
1283 if !seen_credentials.insert(credential.name.clone()) {
1284 return Err(invalid("credentials.name", "duplicate credential name"));
1285 }
1286 if credential.env_var.trim().is_empty() {
1287 return Err(invalid("credentials.env_var", "must not be empty"));
1288 }
1289 if credential.hosts.is_empty() {
1290 return Err(invalid(
1291 "credentials.hosts",
1292 "must name at least one host or suffix",
1293 ));
1294 }
1295 }
1296 let mut seen_providers = std::collections::HashSet::new();
1297 let mut default_count = 0;
1298 for provider in &self.search_providers {
1299 let name = provider.name();
1300 if name.trim().is_empty() {
1301 return Err(invalid("search_providers.name", "must not be empty"));
1302 }
1303 if !seen_providers.insert(name.to_string()) {
1304 return Err(invalid("search_providers.name", "duplicate provider name"));
1305 }
1306 if provider.is_default() {
1307 default_count += 1;
1308 }
1309 if let WebSearchProviderConfig::Http {
1310 url_template,
1311 api_key_env,
1312 hosts,
1313 ..
1314 } = provider
1315 {
1316 if !url_template.contains("{query}") {
1317 return Err(invalid(
1318 "search_providers.url_template",
1319 "must contain the literal substring {query}",
1320 ));
1321 }
1322 if api_key_env.is_some() && hosts.is_empty() {
1323 return Err(invalid(
1324 "search_providers.hosts",
1325 "an api_key_env-bearing provider must name at least one host or suffix",
1326 ));
1327 }
1328 }
1329 }
1330 if default_count > 1 {
1331 return Err(invalid(
1332 "search_providers",
1333 "at most one provider may set default = true",
1334 ));
1335 }
1336 Ok(())
1337 }
1338}
1339
1340#[derive(Debug, Clone, Deserialize, Serialize)]
1343pub struct SchemaSectionConfig {
1344 #[serde(default = "schema_strict_default")]
1345 pub strict: bool,
1346}
1347
1348fn schema_strict_default() -> bool {
1349 true
1350}
1351
1352impl Default for SchemaSectionConfig {
1353 fn default() -> Self {
1354 Self { strict: true }
1355 }
1356}
1357
1358#[derive(Deserialize)]
1361struct SchemaSyntaxProbe {
1362 #[serde(default, deserialize_with = "deserialize_schema_table")]
1363 schema: SchemaSectionConfig,
1364}
1365
1366fn deserialize_schema_table<'de, D>(deserializer: D) -> Result<SchemaSectionConfig, D::Error>
1367where
1368 D: serde::Deserializer<'de>,
1369{
1370 struct SchemaTableVisitor;
1371 impl<'de> serde::de::Visitor<'de> for SchemaTableVisitor {
1372 type Value = SchemaSectionConfig;
1373
1374 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1375 formatter.write_str("a schema configuration table")
1376 }
1377
1378 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1379 where
1380 A: serde::de::MapAccess<'de>,
1381 {
1382 SchemaSectionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
1383 }
1384 }
1385 deserializer.deserialize_map(SchemaTableVisitor)
1386}
1387
1388#[derive(Debug, Clone, Deserialize, Default)]
1411pub struct KhiveConfig {
1412 #[serde(default)]
1414 pub schema: SchemaSectionConfig,
1415
1416 #[serde(default, deserialize_with = "embed_batch::deserialize_table")]
1418 pub embed: EmbedSectionConfig,
1419
1420 #[serde(skip)]
1422 pub credentials: Vec<crate::credentials::CredentialConfig>,
1423
1424 #[serde(skip)]
1425 pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
1426
1427 #[serde(default)]
1430 pub channel: crate::node_config::ChannelSectionConfig,
1431
1432 #[serde(default)]
1433 pub mounts: Vec<crate::mount_config::MountConfig>,
1434
1435 #[serde(default)]
1441 pub db: Option<String>,
1442
1443 #[serde(default)]
1445 pub engines: Vec<EngineConfig>,
1446
1447 #[serde(skip)]
1451 pub engines_declared: bool,
1452
1453 #[serde(default)]
1461 pub actor: ActorConfig,
1462
1463 #[serde(default)]
1467 pub gate: Option<GateSectionConfig>,
1468
1469 #[serde(default)]
1471 pub runtime: RuntimeSectionConfig,
1472
1473 #[serde(default)]
1478 pub backends: Vec<BackendConfig>,
1479
1480 #[serde(default)]
1482 pub code_map_root: Option<String>,
1483
1484 #[serde(default)]
1486 pub code_maps: Vec<CodeMapConfig>,
1487
1488 #[serde(default)]
1494 pub packs: std::collections::HashMap<String, PackConfig>,
1495
1496 #[serde(default)]
1498 pub brain: BrainSectionConfig,
1499
1500 #[serde(default)]
1504 pub git_write: GitWriteSectionConfig,
1505
1506 #[serde(default)]
1508 pub blob: BlobSectionConfig,
1509
1510 #[serde(default)]
1513 pub storage: StorageSectionConfig,
1514
1515 #[serde(default)]
1518 pub exec: ExecSectionConfig,
1519
1520 #[serde(default)]
1522 pub telemetry: crate::telemetry_config::TelemetryConfig,
1523
1524 #[serde(default)]
1528 pub display: DisplaySectionConfig,
1529
1530 #[serde(default)]
1535 pub web: WebSectionConfig,
1536}
1537
1538#[derive(Debug, Clone, Deserialize, Default)]
1545pub struct RuntimeSectionConfig {
1546 #[serde(default)]
1549 pub warm_concurrency: Option<usize>,
1550
1551 #[serde(default)]
1554 pub maintenance_concurrency: Option<usize>,
1555
1556 #[serde(default)]
1559 pub packs: Option<Vec<String>>,
1560
1561 #[serde(default)]
1568 pub brain_profile: Option<String>,
1569
1570 #[serde(default)]
1577 pub default_output_format: Option<OutputFormat>,
1578
1579 #[serde(default)]
1586 pub blob_hydration_bytes: Option<u64>,
1587}
1588
1589#[derive(Debug, Clone, Deserialize, Default)]
1597pub struct DisplaySectionConfig {
1598 #[serde(default)]
1604 pub timezone: Option<String>,
1605}
1606
1607impl KhiveConfig {
1608 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
1624 let resolved = match path {
1625 Some(p) => p.to_path_buf(),
1626 None => PathBuf::from(".khive/config.toml"),
1627 };
1628
1629 if !resolved.exists() {
1630 return Ok(None);
1631 }
1632
1633 let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
1636 let raw = std::fs::read_to_string(&resolved)
1637 .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
1638 let mut document: toml::Value =
1639 toml::from_str(&raw).map_err(|source| ConfigError::Parse {
1640 path: diagnostic_path.clone(),
1641 source,
1642 })?;
1643 let schema_probe: SchemaSyntaxProbe =
1644 toml::from_str(&raw).map_err(|source| ConfigError::SchemaParse {
1645 path: diagnostic_path.clone(),
1646 key: if document
1647 .get("schema")
1648 .is_some_and(|value| !value.is_table())
1649 {
1650 "schema"
1651 } else {
1652 "schema.strict"
1653 },
1654 source: Box::new(source),
1655 })?;
1656 let unknown_schema_keys: Vec<String> = document
1657 .get("schema")
1658 .and_then(toml::Value::as_table)
1659 .map(|table| {
1660 table
1661 .keys()
1662 .filter(|key| key.as_str() != "strict")
1663 .cloned()
1664 .collect()
1665 })
1666 .unwrap_or_default();
1667 let (embed, unknown_embed_keys) = embed_batch::parse(&raw, &document, &diagnostic_path)?;
1668 let engines_declared = peers::normalize_engine_input(&mut document, &diagnostic_path)
1669 .map_err(|error| error.in_file(&diagnostic_path))?;
1670 let mut cfg: KhiveConfig = document.try_into().map_err(|source| ConfigError::Parse {
1671 path: diagnostic_path.clone(),
1672 source,
1673 })?;
1674 cfg.schema = schema_probe.schema;
1675 cfg.embed = embed;
1676 cfg.engines_declared = engines_declared;
1677 crate::credentials::read_tables(&raw, &mut cfg)
1678 .map_err(|error| ConfigError::from(error).in_file(&diagnostic_path))?;
1679 cfg.validate()
1680 .map_err(|error| error.in_file(&diagnostic_path))?;
1681 for engine in &mut cfg.engines {
1682 engine.name = canonical_engine_name(&engine.name);
1683 }
1684 for key in unknown_schema_keys {
1685 tracing::warn!(target: "khive.config.schema",
1686 key = %crate::secret_gate::bounded_masked_log_text(&key),
1687 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1688 "ignoring unknown schema configuration key");
1689 }
1690 for key in unknown_embed_keys {
1691 tracing::warn!(target: "khive.config.embed",
1692 key = %crate::secret_gate::bounded_masked_log_text(&key),
1693 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1694 "ignoring unknown embed configuration key");
1695 }
1696 Ok(Some(cfg))
1697 }
1698
1699 pub fn load_with_home_fallback(
1727 path: Option<&Path>,
1728 db_path: Option<&Path>,
1729 ) -> Result<Option<Self>, ConfigError> {
1730 Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
1731 }
1732
1733 pub fn load_with_home_fallback_and_source(
1741 path: Option<&Path>,
1742 db_path: Option<&Path>,
1743 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1744 if let Some(p) = path {
1752 if !p.exists() {
1753 return Err(ConfigError::ExplicitConfigMissing {
1754 path: p.to_path_buf(),
1755 });
1756 }
1757 return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
1758 }
1759
1760 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1762 let home_root = std::env::var_os("HOME").map(PathBuf::from);
1763 Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
1764 }
1765
1766 #[cfg(test)]
1775 pub(crate) fn load_with_roots(
1776 project_root: &Path,
1777 home_root: Option<&Path>,
1778 db_path: Option<&Path>,
1779 ) -> Result<Option<Self>, ConfigError> {
1780 Ok(
1781 Self::load_with_roots_and_source(project_root, home_root, db_path)?
1782 .map(|(config, _)| config),
1783 )
1784 }
1785
1786 fn load_with_roots_and_source(
1787 project_root: &Path,
1788 home_root: Option<&Path>,
1789 db_path: Option<&Path>,
1790 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1791 let tier2 = project_root.join("khive.toml");
1793 if tier2.exists() {
1794 return Ok(Self::load(Some(&tier2))?
1795 .map(|config| (config, Self::diagnostic_config_path(&tier2))));
1796 }
1797
1798 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
1801 if tier3.exists() {
1802 return Ok(Self::load(Some(&tier3))?
1803 .map(|config| (config, Self::diagnostic_config_path(&tier3))));
1804 }
1805
1806 if let Some(home) = home_root {
1808 let tier4 = home.join(".khive/config.toml");
1809 if tier4.exists() {
1810 return Ok(Self::load(Some(&tier4))?
1811 .map(|config| (config, Self::diagnostic_config_path(&tier4))));
1812 }
1813 }
1814
1815 Ok(None)
1816 }
1817
1818 fn diagnostic_config_path(path: &Path) -> PathBuf {
1819 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1820 }
1821
1822 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
1848 let Some(db_path) = db_path else {
1849 return project_root.join(".khive");
1850 };
1851
1852 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
1853 if db_path.is_absolute() {
1854 db_path.to_path_buf()
1855 } else {
1856 project_root.join(db_path)
1857 }
1858 });
1859
1860 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
1861
1862 if db_dir.file_name().is_some_and(|name| name == ".khive") {
1863 db_dir
1864 } else {
1865 db_dir.join(".khive")
1866 }
1867 }
1868
1869 pub fn validate(&self) -> Result<(), ConfigError> {
1875 #[cfg(not(feature = "blob-s3"))]
1876 if matches!(&self.storage.blob, Some(BlobConfig::S3 { .. })) {
1877 return Err(ConfigError::BlobS3FeatureDisabled);
1878 }
1879
1880 let warm = self
1881 .runtime
1882 .warm_concurrency
1883 .unwrap_or(crate::config::DEFAULT_WARM_CONCURRENCY);
1884 let maintenance = self
1885 .runtime
1886 .maintenance_concurrency
1887 .unwrap_or(crate::config::DEFAULT_MAINTENANCE_CONCURRENCY);
1888 crate::resource_admission::WorkClassLimits::validate(warm, maintenance).map_err(
1889 |error| {
1890 let key = match &error {
1891 crate::resource_admission::ResourceError::InvalidLimit {
1892 class: crate::resource_admission::WorkClass::Warm,
1893 ..
1894 } => "warm_concurrency",
1895 crate::resource_admission::ResourceError::InvalidLimit {
1896 class: crate::resource_admission::WorkClass::Maintenance,
1897 ..
1898 } => "maintenance_concurrency",
1899 _ => "background_concurrency",
1900 };
1901 ConfigError::InvalidRuntimeConfig {
1902 key: key.to_owned(),
1903 reason: error.to_string(),
1904 }
1905 },
1906 )?;
1907
1908 crate::mount_config::validate_mounts(&self.mounts)?;
1909 self.git_write.validate_dev_loop()?;
1910 self.telemetry.validate()?;
1911 self.web.validate()?;
1912 crate::credentials::CredentialConfig::validate_all(&self.credentials)?;
1913 if let Some(receipts) = &self.visibility_receipts {
1914 receipts.validate(&self.credentials)?;
1915 }
1916 self.channel.validate()?;
1917
1918 if let Some(value) = self.db.as_deref() {
1923 if !value.is_empty() {
1924 return Err(ConfigError::UnsupportedTopLevelDb {
1925 value: value.to_string(),
1926 });
1927 }
1928 }
1929
1930 if cfg!(target_os = "macos") {
1934 if self.exec.limits.address_space.is_some() {
1935 return Err(ConfigError::InvalidExecConfig {
1936 key: "limits.address_space".to_string(),
1937 reason: "unsupported_on_platform: macOS does not enforce an address-space rlimit per process".to_string(),
1938 });
1939 }
1940 if self.exec.limits.nproc.is_some() {
1941 return Err(ConfigError::InvalidExecConfig {
1942 key: "limits.nproc".to_string(),
1943 reason: "unsupported_on_platform: RLIMIT_NPROC counts every process of the uid, not one run".to_string(),
1944 });
1945 }
1946 }
1947 let default_timeout = self.exec.timeout_default_s.unwrap_or(30.0);
1951 let maximum_timeout = self.exec.timeout_max_s.unwrap_or(600.0);
1952 for (key, value) in [
1953 ("timeout_default_s", default_timeout),
1954 ("timeout_max_s", maximum_timeout),
1955 ] {
1956 let duration = value
1957 .is_finite()
1958 .then(|| std::time::Duration::try_from_secs_f64(value).ok())
1959 .flatten()
1960 .filter(|duration| !duration.is_zero());
1961 if duration
1962 .is_none_or(|duration| std::time::Instant::now().checked_add(duration).is_none())
1963 {
1964 return Err(ConfigError::InvalidExecConfig {
1965 key: key.to_string(),
1966 reason: "must be positive, finite, and representable as a deadline".to_string(),
1967 });
1968 }
1969 }
1970 if default_timeout > maximum_timeout {
1971 return Err(ConfigError::InvalidExecConfig {
1972 key: "timeout_default_s".to_string(),
1973 reason: format!(
1974 "default {default_timeout} exceeds timeout_max_s {maximum_timeout}"
1975 ),
1976 });
1977 }
1978 let binary_digest_timeout = self
1979 .exec
1980 .binary_digest_timeout_s
1981 .unwrap_or(DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S);
1982 if !(1..=MAX_EXEC_BINARY_DIGEST_TIMEOUT_S).contains(&binary_digest_timeout) {
1983 return Err(ConfigError::InvalidExecConfig {
1984 key: "binary_digest_timeout_s".to_string(),
1985 reason: format!("must be between 1 and {MAX_EXEC_BINARY_DIGEST_TIMEOUT_S} seconds"),
1986 });
1987 }
1988
1989 if let Some(value) = self.runtime.blob_hydration_bytes {
1990 let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
1991 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
1992 if value < min || value > max {
1993 return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
1994 }
1995 }
1996
1997 if let Some(id) = self.actor.id.as_deref() {
2000 if id.is_empty() {
2001 return Err(ConfigError::InvalidActorId {
2002 id: id.to_string(),
2003 reason: "actor.id must not be empty; remove the key or provide a value"
2004 .to_string(),
2005 });
2006 }
2007 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
2008 id: id.to_string(),
2009 reason: e.to_string(),
2010 })?;
2011 }
2012
2013 self.actor
2014 .mailbox_gate(std::sync::Arc::new(khive_gate::AllowAllGate))
2015 .map_err(|error| ConfigError::InvalidMailboxReaders {
2016 reason: error.to_string(),
2017 })?;
2018
2019 if let Some(ref vis) = self.actor.visible_namespaces {
2020 for ns_str in vis {
2021 if ns_str.is_empty() {
2022 return Err(ConfigError::InvalidActorId {
2023 id: ns_str.clone(),
2024 reason: "visible_namespaces entries must not be empty".to_string(),
2025 });
2026 }
2027 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2028 id: ns_str.clone(),
2029 reason: format!("invalid visible namespace: {e}"),
2030 })?;
2031 }
2032 }
2033
2034 if let Some(gate) = &self.gate {
2035 khive_gate::CallerEnrollmentGate::validate_write_denials(&gate.deny_writes_for)
2036 .map_err(|error| ConfigError::InvalidWriteDenyPatterns {
2037 reason: error.to_string(),
2038 })?;
2039 for id in &gate.granted_actors {
2040 if id.is_empty() {
2041 return Err(ConfigError::InvalidGrantedActorId {
2042 id: id.clone(),
2043 reason: "actor ids must not be empty".to_string(),
2044 });
2045 }
2046 Namespace::parse(id).map_err(|error| ConfigError::InvalidGrantedActorId {
2047 id: id.clone(),
2048 reason: error.to_string(),
2049 })?;
2050 }
2051 }
2052
2053 for ns_str in &self.actor.allowed_outbound_namespaces {
2055 if ns_str.is_empty() {
2056 return Err(ConfigError::InvalidActorId {
2057 id: ns_str.clone(),
2058 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
2059 });
2060 }
2061 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2062 id: ns_str.clone(),
2063 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
2064 })?;
2065 }
2066
2067 if !self.backends.is_empty() {
2069 let mut seen_backends = std::collections::HashSet::new();
2070 for backend in &self.backends {
2071 BackendId::parse(&backend.name).map_err(|error| {
2072 ConfigError::InvalidBackendName {
2073 name: backend.name.clone(),
2074 reason: error.to_string(),
2075 }
2076 })?;
2077 if backend
2078 .served_kinds
2079 .as_ref()
2080 .is_some_and(BTreeSet::is_empty)
2081 {
2082 return Err(ConfigError::EmptyBackendServedKinds {
2083 name: backend.name.clone(),
2084 });
2085 }
2086 if !seen_backends.insert(backend.name.clone()) {
2087 return Err(ConfigError::DuplicateBackendName {
2088 name: backend.name.clone(),
2089 });
2090 }
2091
2092 if backend.wal_ceiling_bytes.is_some() {
2096 resolve_wal_ceiling(
2097 backend.wal_ceiling_bytes,
2098 None,
2099 &backend.name,
2100 backend.kind.clone(),
2101 backend
2102 .journal_mode
2103 .as_deref()
2104 .is_none_or(|mode| mode.eq_ignore_ascii_case("wal")),
2105 backend.read_only,
2106 )?;
2107 }
2108
2109 backend.resolve_disk_guard(&khive_db::DiskGuardEnvironment::default())?;
2110
2111 if backend.cache_mb.is_some() {
2114 return Err(ConfigError::UnsupportedBackendField {
2115 name: backend.name.clone(),
2116 field: "cache_mb",
2117 });
2118 }
2119 if backend.journal_mode.is_some() {
2120 return Err(ConfigError::UnsupportedBackendField {
2121 name: backend.name.clone(),
2122 field: "journal_mode",
2123 });
2124 }
2125 }
2126 }
2127
2128 let defined: Vec<&str> = if self.backends.is_empty() {
2129 vec![BackendId::MAIN]
2130 } else {
2131 self.backends.iter().map(|b| b.name.as_str()).collect()
2132 };
2133 for (pack_name, pack_cfg) in &self.packs {
2134 if !defined.contains(&pack_cfg.backend.as_str()) {
2135 return Err(ConfigError::UnknownPackBackend {
2136 pack: pack_name.clone(),
2137 backend: pack_cfg.backend.clone(),
2138 defined: defined.join(", "),
2139 });
2140 }
2141 }
2142
2143 if !self.backends.is_empty() {
2144 let missing: Vec<_> = [SubstrateKind::Note, SubstrateKind::Entity]
2145 .into_iter()
2146 .filter(|kind| {
2147 !self.backends.iter().any(|backend| {
2148 backend
2149 .served_kinds
2150 .as_ref()
2151 .is_none_or(|served| served.contains(kind))
2152 })
2153 })
2154 .collect();
2155 if !missing.is_empty() {
2156 return Err(ConfigError::MissingBackendSearchKinds {
2157 kinds: missing,
2158 defined: defined.join(", "),
2159 });
2160 }
2161 }
2162
2163 if let Some(tz) = self.display.timezone.as_deref() {
2166 if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
2167 return Err(ConfigError::InvalidDisplayTimezone {
2168 timezone: tz.to_string(),
2169 });
2170 }
2171 }
2172
2173 for entry in &self.git_write.allowed {
2180 if entry.repo.trim().is_empty() {
2181 return Err(ConfigError::InvalidGitWriteEntry {
2182 repo: entry.repo.clone(),
2183 reason: "repo must not be empty".to_string(),
2184 });
2185 }
2186 if !Path::new(&entry.repo).is_absolute() {
2187 return Err(ConfigError::InvalidGitWriteEntry {
2188 repo: entry.repo.clone(),
2189 reason: "repo must be an absolute path".to_string(),
2190 });
2191 }
2192 if entry.branches.is_empty() {
2193 return Err(ConfigError::InvalidGitWriteEntry {
2194 repo: entry.repo.clone(),
2195 reason: "branches must not be empty".to_string(),
2196 });
2197 }
2198 if entry.branches.iter().any(|b| b.trim().is_empty()) {
2199 return Err(ConfigError::InvalidGitWriteEntry {
2200 repo: entry.repo.clone(),
2201 reason: "branches entries must not be empty".to_string(),
2202 });
2203 }
2204 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
2209 return Err(ConfigError::InvalidGitWriteEntry {
2210 repo: entry.repo.clone(),
2211 reason: format!(
2212 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
2213 ),
2214 });
2215 }
2216 }
2217
2218 validate_peer_engines(&self.engines)
2219 }
2220
2221 pub fn default_engine(&self) -> Option<&EngineConfig> {
2223 self.engines.first()
2224 }
2225}
2226
2227pub fn config_from_env() -> KhiveConfig {
2241 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
2242 .ok()
2243 .filter(|s| !s.trim().is_empty());
2244 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
2245 .ok()
2246 .unwrap_or_default();
2247 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
2248 .into_iter()
2249 .filter(|s| !s.is_empty())
2250 .collect();
2251
2252 if primary_model.is_none() && additional.is_empty() {
2253 return KhiveConfig::default();
2254 }
2255
2256 tracing::info!(
2257 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
2258 );
2259
2260 config_from_env_parts(primary_model, additional)
2261}
2262
2263fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
2266 let mut engines = Vec::new();
2267
2268 let primary =
2269 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
2270 for model in std::iter::once(primary).chain(additional) {
2271 let name = canonical_engine_name(&model);
2272 if engines
2273 .iter()
2274 .any(|engine: &EngineConfig| engine.name == name)
2275 {
2276 continue;
2277 }
2278 engines.push(EngineConfig {
2279 name,
2280 weight: 1.0,
2281 dims: None,
2282 });
2283 }
2284
2285 KhiveConfig {
2286 engines,
2287 ..KhiveConfig::default()
2288 }
2289}
2290
2291#[cfg(test)]
2292#[path = "engine_config_schema_tests.rs"]
2293mod schema_tests;
2294
2295#[cfg(test)]
2300#[path = "engine_config_tests.rs"]
2301mod tests;
2302
2303#[cfg(test)]
2304mod background_limit_tests {
2305 use super::*;
2306
2307 #[test]
2308 fn optional_background_limits_parse_and_validate() {
2309 let config: KhiveConfig =
2310 toml::from_str("[runtime]\nwarm_concurrency = 3\nmaintenance_concurrency = 2\n")
2311 .unwrap();
2312 config.validate().unwrap();
2313 assert_eq!(config.runtime.warm_concurrency, Some(3));
2314 assert_eq!(config.runtime.maintenance_concurrency, Some(2));
2315 }
2316
2317 #[test]
2318 fn zero_and_overflow_limits_report_the_actual_runtime_key() {
2319 for key in ["warm_concurrency", "maintenance_concurrency"] {
2320 for value in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] {
2321 let mut config: KhiveConfig = toml::from_str("").unwrap();
2322 if key == "warm_concurrency" {
2323 config.runtime.warm_concurrency = Some(value);
2324 } else {
2325 config.runtime.maintenance_concurrency = Some(value);
2326 }
2327 assert!(matches!(config.validate(),
2328 Err(ConfigError::InvalidRuntimeConfig { key: found, .. }) if found == key
2329 ));
2330 }
2331 }
2332 }
2333
2334 #[test]
2335 fn negative_toml_background_limits_are_not_deserialized() {
2336 for key in ["warm_concurrency", "maintenance_concurrency"] {
2337 let text = format!("[runtime]\n{key} = -1\n");
2338 assert!(toml::from_str::<KhiveConfig>(&text).is_err());
2339 }
2340 }
2341
2342 #[test]
2343 fn limits_keep_base_and_override_values_on_both_mapping_branches() {
2344 for engines_declared in [false, true] {
2345 let mut config: KhiveConfig =
2346 toml::from_str("[runtime]\nwarm_concurrency = 5\n").unwrap();
2347 config.engines_declared = engines_declared;
2348 let base = crate::RuntimeConfig {
2349 warm_concurrency: 3,
2350 maintenance_concurrency: 2,
2351 ..crate::RuntimeConfig::no_embeddings()
2352 };
2353 let mapped = crate::config::runtime_config_from_khive_config(&config, base);
2354 assert_eq!(mapped.warm_concurrency, 5);
2355 assert_eq!(mapped.maintenance_concurrency, 2);
2356 }
2357 }
2358
2359 #[test]
2360 fn defaults_use_the_named_validated_background_constants() {
2361 let config = crate::RuntimeConfig::default();
2362 assert_eq!(
2363 config.warm_concurrency,
2364 crate::config::DEFAULT_WARM_CONCURRENCY
2365 );
2366 assert_eq!(
2367 config.maintenance_concurrency,
2368 crate::config::DEFAULT_MAINTENANCE_CONCURRENCY
2369 );
2370 crate::resource_admission::WorkClassLimits::validate(
2371 config.warm_concurrency,
2372 config.maintenance_concurrency,
2373 )
2374 .unwrap();
2375 }
2376}