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 #[serde(default)]
365 pub owned_namespaces: Vec<String>,
366}
367
368#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
375#[serde(deny_unknown_fields)]
376pub struct GateSectionConfig {
377 #[serde(default)]
379 pub granted_actors: Vec<String>,
380
381 #[serde(default)]
383 pub grant_unattributed: bool,
384
385 #[serde(default)]
388 pub deny_writes_for: Vec<String>,
389}
390
391#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
395#[serde(rename_all = "lowercase")]
396pub enum BackendKind {
397 #[default]
399 Sqlite,
400 Memory,
402}
403
404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
409pub struct ResolvedWalCeiling {
410 pub configured_bytes: u64,
412 pub effective_bytes: u64,
414 pub source: khive_db::WalCeilingSource,
416}
417
418pub fn resolve_wal_ceiling(
424 backend_field: Option<u64>,
425 env_value: Option<&str>,
426 backend_name: &str,
427 kind: BackendKind,
428 wal_mode: bool,
429 read_only: bool,
430) -> Result<ResolvedWalCeiling, ConfigError> {
431 if kind == BackendKind::Memory && backend_field.is_none() {
432 return Ok(ResolvedWalCeiling {
433 configured_bytes: 0,
434 effective_bytes: 0,
435 source: khive_db::WalCeilingSource::Default,
436 });
437 }
438 let (configured_bytes, source) = if let Some(bytes) = backend_field {
439 (bytes, khive_db::WalCeilingSource::BackendField)
440 } else if let Some(raw) = env_value {
441 if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
442 return Err(ConfigError::InvalidWalCeilingEnvironment {
443 value: raw.to_owned(),
444 });
445 }
446 let bytes = raw
447 .parse::<u64>()
448 .map_err(|_| ConfigError::InvalidWalCeilingEnvironment {
449 value: raw.to_owned(),
450 })?;
451 (bytes, khive_db::WalCeilingSource::Environment)
452 } else {
453 (0, khive_db::WalCeilingSource::Default)
454 };
455
456 if configured_bytes != 0 {
457 if i64::try_from(configured_bytes).is_err() {
458 return Err(ConfigError::WalCeilingOffsetOverflow {
459 name: backend_name.to_owned(),
460 value: configured_bytes,
461 });
462 }
463 if kind == BackendKind::Memory {
464 return Err(ConfigError::WalCeilingMemoryBackend {
465 name: backend_name.to_owned(),
466 value: configured_bytes,
467 });
468 }
469 if !wal_mode {
470 return Err(ConfigError::WalCeilingNonWalBackend {
471 name: backend_name.to_owned(),
472 value: configured_bytes,
473 });
474 }
475 }
476
477 Ok(ResolvedWalCeiling {
478 configured_bytes,
479 effective_bytes: if read_only { 0 } else { configured_bytes },
480 source,
481 })
482}
483
484#[derive(Debug, Clone, Deserialize)]
501#[serde(deny_unknown_fields)]
502pub struct BackendConfig {
503 pub name: String,
505 #[serde(default)]
507 pub kind: BackendKind,
508 pub path: Option<std::path::PathBuf>,
511 pub cache_mb: Option<u32>,
513 pub journal_mode: Option<String>,
515 #[serde(default)]
521 pub served_kinds: Option<BTreeSet<SubstrateKind>>,
522 #[serde(default)]
524 pub read_only: bool,
525 pub wal_ceiling_bytes: Option<u64>,
529 #[serde(default)]
531 pub disk_reserve_bytes: Option<u64>,
532 #[serde(default)]
534 pub disk_guard_deadline_ms: Option<u64>,
535}
536
537#[derive(Debug, Clone, Deserialize, Default)]
544pub struct CodeMapConfig {
545 #[serde(default)]
547 pub name: Option<String>,
548 #[serde(default)]
550 pub path: Option<String>,
551 #[serde(default)]
553 pub source_root: Option<String>,
554 #[serde(default, flatten)]
556 pub unknown_fields: BTreeMap<String, toml::Value>,
557}
558
559#[derive(Debug, Clone, Deserialize)]
573pub struct PackConfig {
574 #[serde(default = "default_pack_backend")]
577 pub backend: String,
578 #[serde(default)]
580 pub verbs_disabled: Vec<String>,
581 #[serde(default)]
591 pub no_embed: bool,
592}
593
594fn default_pack_backend() -> String {
595 BackendId::MAIN.to_owned()
596}
597
598#[derive(Debug, Clone, Deserialize)]
626#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
627pub enum BlobConfig {
628 Fs {
632 #[serde(default)]
633 root: Option<String>,
634 #[serde(default)]
637 floor_bytes: Option<u64>,
638 },
639 S3 {
644 bucket: String,
645 region: String,
646 #[serde(default)]
647 endpoint: Option<String>,
648 #[serde(default)]
649 prefix: Option<String>,
650 #[serde(default)]
651 allow_http: Option<bool>,
652 },
653}
654
655#[derive(Debug, Clone, Deserialize, Default)]
657#[serde(deny_unknown_fields)]
658pub struct BlobSectionConfig {
659 #[serde(default)]
661 pub file_transfers: bool,
662}
663
664#[derive(Debug, Clone, Deserialize, Default)]
668#[serde(deny_unknown_fields)]
669pub struct StorageSectionConfig {
670 #[serde(default)]
675 pub blob: Option<BlobConfig>,
676}
677
678#[derive(Debug, Clone, Deserialize, Serialize, Default)]
680#[serde(deny_unknown_fields)]
681pub struct BrainSectionConfig {
682 #[serde(default)]
684 pub fleet_readers: Vec<String>,
685}
686
687#[derive(Debug, Clone, Deserialize, Serialize)]
699pub struct GitWriteEntryConfig {
700 pub repo: String,
702 pub branches: Vec<String>,
705}
706
707#[derive(Debug, Clone, Deserialize, Serialize)]
719pub struct GitWriteSectionConfig {
720 #[serde(default)]
722 pub program: Option<PathBuf>,
723 #[serde(default)]
724 pub allowed: Vec<GitWriteEntryConfig>,
725 #[serde(default)]
726 pub actors: BTreeMap<String, GitWriteActorConfig>,
727 #[serde(default)]
728 pub repositories: BTreeMap<String, GitWriteRepositoryConfig>,
729 #[serde(default = "default_git_credential_resolver")]
730 pub credential_resolver: Vec<String>,
731 #[serde(default)]
732 pub contract_faults: bool,
733 #[serde(default)]
734 pub fault: Option<String>,
735}
736
737#[derive(Debug, Clone, Deserialize, Serialize)]
738#[serde(deny_unknown_fields)]
739pub struct GitWriteRepositoryConfig {
740 pub remote: String,
742 pub slug: String,
744 pub visibility: String,
745 #[serde(default)]
751 pub merge_refusals: Vec<String>,
752}
753
754impl GitWriteRepositoryConfig {
755 pub const MERGE_REFUSALS: [&'static str; 2] = ["opener", "last_pusher"];
756
757 pub fn refuses_merge_by(&self, entry: &str) -> bool {
759 self.merge_refusals.iter().any(|listed| listed == entry)
760 }
761}
762
763#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
764#[serde(deny_unknown_fields)]
765pub struct GitWriteActorConfig {
766 pub name: String,
767 pub email: String,
768 pub credential_ref: String,
769 pub platform_identity: String,
770}
771
772fn default_git_credential_resolver() -> Vec<String> {
773 [
774 "/usr/bin/security",
775 "find-generic-password",
776 "-w",
777 "-s",
778 "{ref}",
779 ]
780 .into_iter()
781 .map(str::to_string)
782 .collect()
783}
784
785impl Default for GitWriteSectionConfig {
786 fn default() -> Self {
787 Self {
788 program: None,
789 allowed: Vec::new(),
790 actors: BTreeMap::new(),
791 repositories: BTreeMap::new(),
792 credential_resolver: default_git_credential_resolver(),
793 contract_faults: false,
794 fault: None,
795 }
796 }
797}
798
799impl GitWriteSectionConfig {
800 pub fn git_program(&self) -> &Path {
801 self.program.as_deref().unwrap_or_else(|| Path::new("git"))
802 }
803
804 pub fn validate_dev_loop(&self) -> Result<(), ConfigError> {
805 let invalid = |key: &str, reason: &str| ConfigError::InvalidGitWriteConfig {
806 key: key.to_string(),
807 reason: reason.to_string(),
808 };
809 if let Some(program) = &self.program {
810 if !program.is_absolute() {
811 return Err(invalid("git_write.program", "must be absolute"));
812 }
813 let metadata = std::fs::metadata(program).map_err(|error| {
814 if error.kind() == std::io::ErrorKind::NotFound {
815 invalid("git_write.program", "does not exist")
816 } else {
817 invalid("git_write.program", &format!("is not executable: {error}"))
818 }
819 })?;
820 #[cfg(unix)]
821 let executable = {
822 use std::os::unix::fs::PermissionsExt;
823 metadata.permissions().mode() & 0o111 != 0
824 };
825 #[cfg(windows)]
826 let executable = program
827 .extension()
828 .and_then(|extension| extension.to_str())
829 .is_some_and(|extension| {
830 extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
831 });
832 #[cfg(not(any(unix, windows)))]
833 let executable = false;
834 if !metadata.is_file() || !executable {
835 return Err(invalid("git_write.program", "is not executable"));
836 }
837 }
838 if self.contract_faults && !cfg!(feature = "contract-faults") {
839 tracing::error!(
840 target: "khive.boot",
841 "[git_write] contract_faults requires the test-only contract-faults build feature"
842 );
843 return Err(invalid(
844 "contract_faults",
845 "requires the test-only contract-faults build feature",
846 ));
847 }
848 if let Some(fault) = &self.fault {
849 if !self.contract_faults {
850 return Err(invalid("fault", "requires contract_faults = true"));
851 }
852 let valid = fault.split_once(':').is_some_and(|(verb, point)| {
853 matches!(verb, "git.push" | "git.pr_merge")
854 && matches!(
855 point,
856 "reply-lost-after-effect" | "audit-fails-after-effect"
857 )
858 });
859 if !valid {
860 return Err(invalid("fault", "unsupported contract fault selector"));
861 }
862 }
863 for (path, repository) in &self.repositories {
864 let key = format!("repositories.{path}.merge_refusals");
865 let mut seen: Vec<&str> = Vec::new();
866 for entry in &repository.merge_refusals {
867 if !GitWriteRepositoryConfig::MERGE_REFUSALS.contains(&entry.as_str()) {
868 return Err(invalid(&key, "entries must be opener or last_pusher"));
869 }
870 if seen.contains(&entry.as_str()) {
871 return Err(invalid(&key, "entries must not repeat"));
872 }
873 seen.push(entry);
874 }
875 }
876 if !cfg!(unix)
879 && self.actors.is_empty()
880 && self.credential_resolver == default_git_credential_resolver()
881 {
882 return Ok(());
883 }
884 let argv = &self.credential_resolver;
885 let Some(program) = argv.first() else {
886 return Err(invalid("credential_resolver", "argv must not be empty"));
887 };
888 let program_path = Path::new(program);
889 if !program_path.is_absolute() {
890 return Err(invalid(
891 "credential_resolver",
892 "argv[0] must be an absolute path",
893 ));
894 }
895 let program_name = program_path
896 .file_name()
897 .and_then(|name| name.to_str())
898 .unwrap_or_default()
899 .to_ascii_lowercase();
900 if matches!(
901 program_name.trim_end_matches(".exe"),
902 "sh" | "bash"
903 | "dash"
904 | "zsh"
905 | "ksh"
906 | "fish"
907 | "csh"
908 | "tcsh"
909 | "cmd"
910 | "powershell"
911 | "pwsh"
912 | "env"
913 ) {
914 return Err(invalid(
915 "credential_resolver",
916 "shell or env launcher is not allowed",
917 ));
918 }
919 if argv.iter().any(|arg| arg.chars().any(char::is_control)) {
920 return Err(invalid(
921 "credential_resolver",
922 "argv must not contain control characters",
923 ));
924 }
925 if program.contains(['{', '}'])
926 || argv[1..]
927 .iter()
928 .any(|arg| arg != "{ref}" && arg.contains(['{', '}']))
929 {
930 return Err(invalid(
931 "credential_resolver",
932 "{ref} must be a complete argument and is the only allowed template",
933 ));
934 }
935 if !argv[1..].iter().any(|arg| arg == "{ref}") {
936 return Err(invalid(
937 "credential_resolver",
938 "argv must contain a {ref} argument",
939 ));
940 }
941 for (actor, identity) in &self.actors {
942 if actor.trim().is_empty() || actor.chars().any(char::is_control) {
943 return Err(invalid(
944 "actors",
945 "actor labels must be nonempty and contain no control characters",
946 ));
947 }
948 for (field, value) in [
949 ("name", &identity.name),
950 ("email", &identity.email),
951 ("credential_ref", &identity.credential_ref),
952 ("platform_identity", &identity.platform_identity),
953 ] {
954 if value.trim().is_empty() || value.chars().any(char::is_control) {
955 return Err(invalid(
956 &format!("actors.{actor}.{field}"),
957 "must be nonempty and contain no control characters",
958 ));
959 }
960 }
961 if identity.name.contains(['<', '>']) || identity.email.contains(['<', '>']) {
962 return Err(invalid(
963 &format!("actors.{actor}"),
964 "name and email must not contain Git identity delimiters",
965 ));
966 }
967 }
968 Ok(())
969 }
970}
971
972#[derive(Debug, Clone, Deserialize, Default)]
977pub struct ExecLimitsConfig {
978 #[serde(default)]
979 pub cpu_seconds: Option<u64>,
980 #[serde(default)]
981 pub address_space: Option<u64>,
982 #[serde(default)]
983 pub file_size: Option<u64>,
984 #[serde(default)]
985 pub nproc: Option<u64>,
986}
987
988#[derive(Debug, Clone, Deserialize, Default)]
1011#[serde(deny_unknown_fields)]
1012pub struct ExecSectionConfig {
1013 #[serde(default)]
1014 pub root: Option<String>,
1015 #[serde(default)]
1016 pub read_roots: Vec<String>,
1017 #[serde(default)]
1018 pub env: Vec<String>,
1019 #[serde(default)]
1020 pub never: Vec<String>,
1021 #[serde(default)]
1022 pub max_output_bytes: Option<u64>,
1023 #[serde(default)]
1024 pub timeout_default_s: Option<f64>,
1025 #[serde(default)]
1026 pub timeout_max_s: Option<f64>,
1027 #[serde(default)]
1029 pub binary_digest_timeout_s: Option<u64>,
1030 #[serde(default)]
1031 pub keep: bool,
1032 #[serde(default)]
1033 pub limits: ExecLimitsConfig,
1034}
1035
1036pub const DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 10;
1037pub const MAX_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 60;
1038
1039#[derive(Debug, Clone, Deserialize, Serialize)]
1048#[serde(deny_unknown_fields)]
1049pub struct WebAllowlistEntry {
1050 pub host: String,
1051}
1052
1053#[derive(Debug, Clone, Deserialize, Serialize)]
1060#[serde(deny_unknown_fields)]
1061pub struct WebCredentialConfig {
1062 pub name: String,
1064 pub env_var: String,
1066 pub hosts: Vec<String>,
1069}
1070
1071#[derive(Debug, Clone, Deserialize, Serialize)]
1075#[serde(deny_unknown_fields)]
1076pub struct WebFixtureResult {
1077 pub title: String,
1078 pub url: String,
1079 pub snippet: String,
1080}
1081
1082#[derive(Debug, Clone, Deserialize, Serialize)]
1086#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
1087pub enum WebSearchProviderConfig {
1088 Fixture {
1090 name: String,
1091 #[serde(default)]
1092 default: bool,
1093 results: Vec<WebFixtureResult>,
1094 },
1095 Http {
1102 name: String,
1103 #[serde(default)]
1104 default: bool,
1105 url_template: String,
1106 #[serde(default)]
1107 api_key_env: Option<String>,
1108 #[serde(default)]
1115 hosts: Vec<String>,
1116 },
1117}
1118
1119impl WebSearchProviderConfig {
1120 pub fn name(&self) -> &str {
1121 match self {
1122 WebSearchProviderConfig::Fixture { name, .. } => name,
1123 WebSearchProviderConfig::Http { name, .. } => name,
1124 }
1125 }
1126
1127 pub fn is_default(&self) -> bool {
1128 match self {
1129 WebSearchProviderConfig::Fixture { default, .. } => *default,
1130 WebSearchProviderConfig::Http { default, .. } => *default,
1131 }
1132 }
1133}
1134
1135#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1169#[serde(deny_unknown_fields)]
1170pub struct WebSectionConfig {
1171 #[serde(default)]
1172 pub timeout_default_s: Option<u64>,
1173 #[serde(default)]
1174 pub timeout_max_s: Option<u64>,
1175 #[serde(default)]
1176 pub max_bytes_default: Option<u64>,
1177 #[serde(default)]
1178 pub max_bytes_max: Option<u64>,
1179 #[serde(default)]
1180 pub search_limit_default: Option<u32>,
1181 #[serde(default)]
1182 pub search_limit_max: Option<u32>,
1183 #[serde(default)]
1184 pub allowlist: Vec<WebAllowlistEntry>,
1185 #[serde(default)]
1186 pub credentials: Vec<WebCredentialConfig>,
1187 #[serde(default)]
1188 pub search_providers: Vec<WebSearchProviderConfig>,
1189 #[serde(default)]
1193 pub read_roots: Vec<String>,
1194}
1195
1196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1198pub struct WebCeilings {
1199 pub timeout_default_s: u64,
1200 pub timeout_max_s: u64,
1201 pub max_bytes_default: u64,
1202 pub max_bytes_max: u64,
1203 pub search_limit_default: u32,
1204 pub search_limit_max: u32,
1205}
1206
1207impl Default for WebCeilings {
1208 fn default() -> Self {
1209 Self {
1210 timeout_default_s: 30,
1211 timeout_max_s: 120,
1212 max_bytes_default: 5 * 1024 * 1024,
1213 max_bytes_max: 50 * 1024 * 1024,
1214 search_limit_default: 10,
1215 search_limit_max: 50,
1216 }
1217 }
1218}
1219
1220impl WebSectionConfig {
1221 pub fn resolved_ceilings(&self) -> Result<WebCeilings, ConfigError> {
1222 let defaults = WebCeilings::default();
1223 let bounds = WebCeilings {
1224 timeout_default_s: self.timeout_default_s.unwrap_or(defaults.timeout_default_s),
1225 timeout_max_s: self.timeout_max_s.unwrap_or(defaults.timeout_max_s),
1226 max_bytes_default: self.max_bytes_default.unwrap_or(defaults.max_bytes_default),
1227 max_bytes_max: self.max_bytes_max.unwrap_or(defaults.max_bytes_max),
1228 search_limit_default: self
1229 .search_limit_default
1230 .unwrap_or(defaults.search_limit_default),
1231 search_limit_max: self.search_limit_max.unwrap_or(defaults.search_limit_max),
1232 };
1233 for (key, default, maximum, maximum_key) in [
1234 (
1235 "timeout_default_s",
1236 bounds.timeout_default_s,
1237 bounds.timeout_max_s,
1238 "timeout_max_s",
1239 ),
1240 (
1241 "max_bytes_default",
1242 bounds.max_bytes_default,
1243 bounds.max_bytes_max,
1244 "max_bytes_max",
1245 ),
1246 (
1247 "search_limit_default",
1248 u64::from(bounds.search_limit_default),
1249 u64::from(bounds.search_limit_max),
1250 "search_limit_max",
1251 ),
1252 ] {
1253 if default == 0 || default > maximum {
1254 return Err(ConfigError::InvalidWebConfig {
1255 key: key.into(),
1256 reason: format!(
1257 "resolved default must be positive and not exceed {maximum_key}={maximum}"
1258 ),
1259 });
1260 }
1261 }
1262 if std::time::Instant::now()
1263 .checked_add(std::time::Duration::from_secs(bounds.timeout_max_s))
1264 .is_none()
1265 {
1266 return Err(ConfigError::InvalidWebConfig {
1267 key: "timeout_max_s".into(),
1268 reason: "cannot be represented as a request deadline".into(),
1269 });
1270 }
1271 Ok(bounds)
1272 }
1273
1274 pub fn validate(&self) -> Result<(), ConfigError> {
1275 self.resolved_ceilings()?;
1276 let invalid = |key: &str, reason: &str| ConfigError::InvalidWebConfig {
1277 key: key.to_string(),
1278 reason: reason.to_string(),
1279 };
1280 let mut seen_hosts = std::collections::HashSet::new();
1281 for entry in &self.allowlist {
1282 let normalized = entry.host.trim().trim_end_matches('.').to_ascii_lowercase();
1283 if normalized.is_empty() {
1284 return Err(invalid("allowlist.host", "must not be empty"));
1285 }
1286 if !seen_hosts.insert(normalized) {
1287 return Err(invalid("allowlist.host", "duplicate host entry"));
1288 }
1289 }
1290 let mut seen_credentials = std::collections::HashSet::new();
1291 for credential in &self.credentials {
1292 if credential.name.trim().is_empty() {
1293 return Err(invalid("credentials.name", "must not be empty"));
1294 }
1295 if !seen_credentials.insert(credential.name.clone()) {
1296 return Err(invalid("credentials.name", "duplicate credential name"));
1297 }
1298 if credential.env_var.trim().is_empty() {
1299 return Err(invalid("credentials.env_var", "must not be empty"));
1300 }
1301 if credential.hosts.is_empty() {
1302 return Err(invalid(
1303 "credentials.hosts",
1304 "must name at least one host or suffix",
1305 ));
1306 }
1307 }
1308 let mut seen_providers = std::collections::HashSet::new();
1309 let mut default_count = 0;
1310 for provider in &self.search_providers {
1311 let name = provider.name();
1312 if name.trim().is_empty() {
1313 return Err(invalid("search_providers.name", "must not be empty"));
1314 }
1315 if !seen_providers.insert(name.to_string()) {
1316 return Err(invalid("search_providers.name", "duplicate provider name"));
1317 }
1318 if provider.is_default() {
1319 default_count += 1;
1320 }
1321 if let WebSearchProviderConfig::Http {
1322 url_template,
1323 api_key_env,
1324 hosts,
1325 ..
1326 } = provider
1327 {
1328 if !url_template.contains("{query}") {
1329 return Err(invalid(
1330 "search_providers.url_template",
1331 "must contain the literal substring {query}",
1332 ));
1333 }
1334 if api_key_env.is_some() && hosts.is_empty() {
1335 return Err(invalid(
1336 "search_providers.hosts",
1337 "an api_key_env-bearing provider must name at least one host or suffix",
1338 ));
1339 }
1340 }
1341 }
1342 if default_count > 1 {
1343 return Err(invalid(
1344 "search_providers",
1345 "at most one provider may set default = true",
1346 ));
1347 }
1348 Ok(())
1349 }
1350}
1351
1352#[derive(Debug, Clone, Deserialize, Serialize)]
1355pub struct SchemaSectionConfig {
1356 #[serde(default = "schema_strict_default")]
1357 pub strict: bool,
1358}
1359
1360fn schema_strict_default() -> bool {
1361 true
1362}
1363
1364impl Default for SchemaSectionConfig {
1365 fn default() -> Self {
1366 Self { strict: true }
1367 }
1368}
1369
1370#[derive(Deserialize)]
1373struct SchemaSyntaxProbe {
1374 #[serde(default, deserialize_with = "deserialize_schema_table")]
1375 schema: SchemaSectionConfig,
1376}
1377
1378fn deserialize_schema_table<'de, D>(deserializer: D) -> Result<SchemaSectionConfig, D::Error>
1379where
1380 D: serde::Deserializer<'de>,
1381{
1382 struct SchemaTableVisitor;
1383 impl<'de> serde::de::Visitor<'de> for SchemaTableVisitor {
1384 type Value = SchemaSectionConfig;
1385
1386 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1387 formatter.write_str("a schema configuration table")
1388 }
1389
1390 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1391 where
1392 A: serde::de::MapAccess<'de>,
1393 {
1394 SchemaSectionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
1395 }
1396 }
1397 deserializer.deserialize_map(SchemaTableVisitor)
1398}
1399
1400#[derive(Debug, Clone, Deserialize, Default)]
1423pub struct KhiveConfig {
1424 #[serde(default)]
1426 pub schema: SchemaSectionConfig,
1427
1428 #[serde(default, deserialize_with = "embed_batch::deserialize_table")]
1430 pub embed: EmbedSectionConfig,
1431
1432 #[serde(skip)]
1434 pub credentials: Vec<crate::credentials::CredentialConfig>,
1435
1436 #[serde(skip)]
1437 pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
1438
1439 #[serde(default)]
1442 pub channel: crate::node_config::ChannelSectionConfig,
1443
1444 #[serde(default)]
1445 pub mounts: Vec<crate::mount_config::MountConfig>,
1446
1447 #[serde(default)]
1453 pub db: Option<String>,
1454
1455 #[serde(default)]
1457 pub engines: Vec<EngineConfig>,
1458
1459 #[serde(skip)]
1463 pub engines_declared: bool,
1464
1465 #[serde(default)]
1473 pub actor: ActorConfig,
1474
1475 #[serde(default)]
1479 pub gate: Option<GateSectionConfig>,
1480
1481 #[serde(default)]
1483 pub runtime: RuntimeSectionConfig,
1484
1485 #[serde(default)]
1490 pub backends: Vec<BackendConfig>,
1491
1492 #[serde(default)]
1494 pub code_map_root: Option<String>,
1495
1496 #[serde(default)]
1498 pub code_maps: Vec<CodeMapConfig>,
1499
1500 #[serde(default)]
1506 pub packs: std::collections::HashMap<String, PackConfig>,
1507
1508 #[serde(default)]
1510 pub brain: BrainSectionConfig,
1511
1512 #[serde(default)]
1516 pub git_write: GitWriteSectionConfig,
1517
1518 #[serde(default)]
1520 pub blob: BlobSectionConfig,
1521
1522 #[serde(default)]
1525 pub storage: StorageSectionConfig,
1526
1527 #[serde(default)]
1530 pub exec: ExecSectionConfig,
1531
1532 #[serde(default)]
1534 pub telemetry: crate::telemetry_config::TelemetryConfig,
1535
1536 #[serde(default)]
1540 pub display: DisplaySectionConfig,
1541
1542 #[serde(default)]
1547 pub web: WebSectionConfig,
1548}
1549
1550#[derive(Debug, Clone, Deserialize, Default)]
1557pub struct RuntimeSectionConfig {
1558 #[serde(default)]
1561 pub warm_concurrency: Option<usize>,
1562
1563 #[serde(default)]
1566 pub maintenance_concurrency: Option<usize>,
1567
1568 #[serde(default)]
1571 pub packs: Option<Vec<String>>,
1572
1573 #[serde(default)]
1580 pub brain_profile: Option<String>,
1581
1582 #[serde(default)]
1589 pub default_output_format: Option<OutputFormat>,
1590
1591 #[serde(default)]
1598 pub blob_hydration_bytes: Option<u64>,
1599}
1600
1601#[derive(Debug, Clone, Deserialize, Default)]
1609pub struct DisplaySectionConfig {
1610 #[serde(default)]
1616 pub timezone: Option<String>,
1617}
1618
1619impl KhiveConfig {
1620 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
1636 let resolved = match path {
1637 Some(p) => p.to_path_buf(),
1638 None => PathBuf::from(".khive/config.toml"),
1639 };
1640
1641 if !resolved.exists() {
1642 return Ok(None);
1643 }
1644
1645 let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
1648 let raw = std::fs::read_to_string(&resolved)
1649 .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
1650 let mut document: toml::Value =
1651 toml::from_str(&raw).map_err(|source| ConfigError::Parse {
1652 path: diagnostic_path.clone(),
1653 source,
1654 })?;
1655 let schema_probe: SchemaSyntaxProbe =
1656 toml::from_str(&raw).map_err(|source| ConfigError::SchemaParse {
1657 path: diagnostic_path.clone(),
1658 key: if document
1659 .get("schema")
1660 .is_some_and(|value| !value.is_table())
1661 {
1662 "schema"
1663 } else {
1664 "schema.strict"
1665 },
1666 source: Box::new(source),
1667 })?;
1668 let unknown_schema_keys: Vec<String> = document
1669 .get("schema")
1670 .and_then(toml::Value::as_table)
1671 .map(|table| {
1672 table
1673 .keys()
1674 .filter(|key| key.as_str() != "strict")
1675 .cloned()
1676 .collect()
1677 })
1678 .unwrap_or_default();
1679 let (embed, unknown_embed_keys) = embed_batch::parse(&raw, &document, &diagnostic_path)?;
1680 let engines_declared = peers::normalize_engine_input(&mut document, &diagnostic_path)
1681 .map_err(|error| error.in_file(&diagnostic_path))?;
1682 let mut cfg: KhiveConfig = document.try_into().map_err(|source| ConfigError::Parse {
1683 path: diagnostic_path.clone(),
1684 source,
1685 })?;
1686 cfg.schema = schema_probe.schema;
1687 cfg.embed = embed;
1688 cfg.engines_declared = engines_declared;
1689 crate::credentials::read_tables(&raw, &mut cfg)
1690 .map_err(|error| ConfigError::from(error).in_file(&diagnostic_path))?;
1691 cfg.validate()
1692 .map_err(|error| error.in_file(&diagnostic_path))?;
1693 for engine in &mut cfg.engines {
1694 engine.name = canonical_engine_name(&engine.name);
1695 }
1696 for key in unknown_schema_keys {
1697 tracing::warn!(target: "khive.config.schema",
1698 key = %crate::secret_gate::bounded_masked_log_text(&key),
1699 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1700 "ignoring unknown schema configuration key");
1701 }
1702 for key in unknown_embed_keys {
1703 tracing::warn!(target: "khive.config.embed",
1704 key = %crate::secret_gate::bounded_masked_log_text(&key),
1705 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1706 "ignoring unknown embed configuration key");
1707 }
1708 Ok(Some(cfg))
1709 }
1710
1711 pub fn load_with_home_fallback(
1739 path: Option<&Path>,
1740 db_path: Option<&Path>,
1741 ) -> Result<Option<Self>, ConfigError> {
1742 Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
1743 }
1744
1745 pub fn load_with_home_fallback_and_source(
1753 path: Option<&Path>,
1754 db_path: Option<&Path>,
1755 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1756 if let Some(p) = path {
1764 if !p.exists() {
1765 return Err(ConfigError::ExplicitConfigMissing {
1766 path: p.to_path_buf(),
1767 });
1768 }
1769 return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
1770 }
1771
1772 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1774 let home_root = std::env::var_os("HOME").map(PathBuf::from);
1775 Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
1776 }
1777
1778 #[cfg(test)]
1787 pub(crate) fn load_with_roots(
1788 project_root: &Path,
1789 home_root: Option<&Path>,
1790 db_path: Option<&Path>,
1791 ) -> Result<Option<Self>, ConfigError> {
1792 Ok(
1793 Self::load_with_roots_and_source(project_root, home_root, db_path)?
1794 .map(|(config, _)| config),
1795 )
1796 }
1797
1798 fn load_with_roots_and_source(
1799 project_root: &Path,
1800 home_root: Option<&Path>,
1801 db_path: Option<&Path>,
1802 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1803 let tier2 = project_root.join("khive.toml");
1805 if tier2.exists() {
1806 return Ok(Self::load(Some(&tier2))?
1807 .map(|config| (config, Self::diagnostic_config_path(&tier2))));
1808 }
1809
1810 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
1813 if tier3.exists() {
1814 return Ok(Self::load(Some(&tier3))?
1815 .map(|config| (config, Self::diagnostic_config_path(&tier3))));
1816 }
1817
1818 if let Some(home) = home_root {
1820 let tier4 = home.join(".khive/config.toml");
1821 if tier4.exists() {
1822 return Ok(Self::load(Some(&tier4))?
1823 .map(|config| (config, Self::diagnostic_config_path(&tier4))));
1824 }
1825 }
1826
1827 Ok(None)
1828 }
1829
1830 fn diagnostic_config_path(path: &Path) -> PathBuf {
1831 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1832 }
1833
1834 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
1860 let Some(db_path) = db_path else {
1861 return project_root.join(".khive");
1862 };
1863
1864 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
1865 if db_path.is_absolute() {
1866 db_path.to_path_buf()
1867 } else {
1868 project_root.join(db_path)
1869 }
1870 });
1871
1872 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
1873
1874 if db_dir.file_name().is_some_and(|name| name == ".khive") {
1875 db_dir
1876 } else {
1877 db_dir.join(".khive")
1878 }
1879 }
1880
1881 pub fn validate(&self) -> Result<(), ConfigError> {
1887 #[cfg(not(feature = "blob-s3"))]
1888 if matches!(&self.storage.blob, Some(BlobConfig::S3 { .. })) {
1889 return Err(ConfigError::BlobS3FeatureDisabled);
1890 }
1891
1892 let warm = self
1893 .runtime
1894 .warm_concurrency
1895 .unwrap_or(crate::config::DEFAULT_WARM_CONCURRENCY);
1896 let maintenance = self
1897 .runtime
1898 .maintenance_concurrency
1899 .unwrap_or(crate::config::DEFAULT_MAINTENANCE_CONCURRENCY);
1900 crate::resource_admission::WorkClassLimits::validate(warm, maintenance).map_err(
1901 |error| {
1902 let key = match &error {
1903 crate::resource_admission::ResourceError::InvalidLimit {
1904 class: crate::resource_admission::WorkClass::Warm,
1905 ..
1906 } => "warm_concurrency",
1907 crate::resource_admission::ResourceError::InvalidLimit {
1908 class: crate::resource_admission::WorkClass::Maintenance,
1909 ..
1910 } => "maintenance_concurrency",
1911 _ => "background_concurrency",
1912 };
1913 ConfigError::InvalidRuntimeConfig {
1914 key: key.to_owned(),
1915 reason: error.to_string(),
1916 }
1917 },
1918 )?;
1919
1920 crate::mount_config::validate_mounts(&self.mounts)?;
1921 self.git_write.validate_dev_loop()?;
1922 self.telemetry.validate()?;
1923 self.web.validate()?;
1924 crate::credentials::CredentialConfig::validate_all(&self.credentials)?;
1925 if let Some(receipts) = &self.visibility_receipts {
1926 receipts.validate(&self.credentials)?;
1927 }
1928 self.channel.validate()?;
1929
1930 if let Some(value) = self.db.as_deref() {
1935 if !value.is_empty() {
1936 return Err(ConfigError::UnsupportedTopLevelDb {
1937 value: value.to_string(),
1938 });
1939 }
1940 }
1941
1942 if cfg!(target_os = "macos") {
1946 if self.exec.limits.address_space.is_some() {
1947 return Err(ConfigError::InvalidExecConfig {
1948 key: "limits.address_space".to_string(),
1949 reason: "unsupported_on_platform: macOS does not enforce an address-space rlimit per process".to_string(),
1950 });
1951 }
1952 if self.exec.limits.nproc.is_some() {
1953 return Err(ConfigError::InvalidExecConfig {
1954 key: "limits.nproc".to_string(),
1955 reason: "unsupported_on_platform: RLIMIT_NPROC counts every process of the uid, not one run".to_string(),
1956 });
1957 }
1958 }
1959 let default_timeout = self.exec.timeout_default_s.unwrap_or(30.0);
1963 let maximum_timeout = self.exec.timeout_max_s.unwrap_or(600.0);
1964 for (key, value) in [
1965 ("timeout_default_s", default_timeout),
1966 ("timeout_max_s", maximum_timeout),
1967 ] {
1968 let duration = value
1969 .is_finite()
1970 .then(|| std::time::Duration::try_from_secs_f64(value).ok())
1971 .flatten()
1972 .filter(|duration| !duration.is_zero());
1973 if duration
1974 .is_none_or(|duration| std::time::Instant::now().checked_add(duration).is_none())
1975 {
1976 return Err(ConfigError::InvalidExecConfig {
1977 key: key.to_string(),
1978 reason: "must be positive, finite, and representable as a deadline".to_string(),
1979 });
1980 }
1981 }
1982 if default_timeout > maximum_timeout {
1983 return Err(ConfigError::InvalidExecConfig {
1984 key: "timeout_default_s".to_string(),
1985 reason: format!(
1986 "default {default_timeout} exceeds timeout_max_s {maximum_timeout}"
1987 ),
1988 });
1989 }
1990 let binary_digest_timeout = self
1991 .exec
1992 .binary_digest_timeout_s
1993 .unwrap_or(DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S);
1994 if !(1..=MAX_EXEC_BINARY_DIGEST_TIMEOUT_S).contains(&binary_digest_timeout) {
1995 return Err(ConfigError::InvalidExecConfig {
1996 key: "binary_digest_timeout_s".to_string(),
1997 reason: format!("must be between 1 and {MAX_EXEC_BINARY_DIGEST_TIMEOUT_S} seconds"),
1998 });
1999 }
2000
2001 if let Some(value) = self.runtime.blob_hydration_bytes {
2002 let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
2003 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
2004 if value < min || value > max {
2005 return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
2006 }
2007 }
2008
2009 if let Some(id) = self.actor.id.as_deref() {
2012 if id.is_empty() {
2013 return Err(ConfigError::InvalidActorId {
2014 id: id.to_string(),
2015 reason: "actor.id must not be empty; remove the key or provide a value"
2016 .to_string(),
2017 });
2018 }
2019 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
2020 id: id.to_string(),
2021 reason: e.to_string(),
2022 })?;
2023 }
2024
2025 self.actor
2026 .mailbox_gate(std::sync::Arc::new(khive_gate::AllowAllGate))
2027 .map_err(|error| ConfigError::InvalidMailboxReaders {
2028 reason: error.to_string(),
2029 })?;
2030
2031 if let Some(ref vis) = self.actor.visible_namespaces {
2032 for ns_str in vis {
2033 if ns_str.is_empty() {
2034 return Err(ConfigError::InvalidActorId {
2035 id: ns_str.clone(),
2036 reason: "visible_namespaces entries must not be empty".to_string(),
2037 });
2038 }
2039 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2040 id: ns_str.clone(),
2041 reason: format!("invalid visible namespace: {e}"),
2042 })?;
2043 }
2044 }
2045
2046 if !self.actor.owned_namespaces.is_empty() {
2050 let Some(actor_id) = self.actor.id.as_deref() else {
2051 return Err(ConfigError::InvalidActorId {
2052 id: String::new(),
2053 reason: "owned_namespaces requires an explicit [actor] id".to_string(),
2054 });
2055 };
2056 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2057 for ns_str in &self.actor.owned_namespaces {
2058 if ns_str.is_empty() {
2059 return Err(ConfigError::InvalidActorId {
2060 id: ns_str.clone(),
2061 reason: "owned_namespaces entries must not be empty".to_string(),
2062 });
2063 }
2064 let parsed = Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2065 id: ns_str.clone(),
2066 reason: format!("invalid owned namespace: {e}"),
2067 })?;
2068 if parsed.as_str() == Namespace::LOCAL {
2069 return Err(ConfigError::InvalidActorId {
2070 id: ns_str.clone(),
2071 reason: "owned_namespaces must not list the shared namespace `local`"
2072 .to_string(),
2073 });
2074 }
2075 if parsed.as_str() == actor_id {
2076 return Err(ConfigError::InvalidActorId {
2077 id: ns_str.clone(),
2078 reason: "owned_namespaces must not list the actor's own id".to_string(),
2079 });
2080 }
2081 if !seen.insert(parsed.as_str().to_string()) {
2082 return Err(ConfigError::InvalidActorId {
2083 id: ns_str.clone(),
2084 reason: "owned_namespaces entries must be unique".to_string(),
2085 });
2086 }
2087 }
2088 }
2089
2090 if let Some(gate) = &self.gate {
2091 khive_gate::CallerEnrollmentGate::validate_write_denials(&gate.deny_writes_for)
2092 .map_err(|error| ConfigError::InvalidWriteDenyPatterns {
2093 reason: error.to_string(),
2094 })?;
2095 for id in &gate.granted_actors {
2096 if id.is_empty() {
2097 return Err(ConfigError::InvalidGrantedActorId {
2098 id: id.clone(),
2099 reason: "actor ids must not be empty".to_string(),
2100 });
2101 }
2102 Namespace::parse(id).map_err(|error| ConfigError::InvalidGrantedActorId {
2103 id: id.clone(),
2104 reason: error.to_string(),
2105 })?;
2106 }
2107 }
2108
2109 for ns_str in &self.actor.allowed_outbound_namespaces {
2111 if ns_str.is_empty() {
2112 return Err(ConfigError::InvalidActorId {
2113 id: ns_str.clone(),
2114 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
2115 });
2116 }
2117 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2118 id: ns_str.clone(),
2119 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
2120 })?;
2121 }
2122
2123 if !self.backends.is_empty() {
2125 let mut seen_backends = std::collections::HashSet::new();
2126 for backend in &self.backends {
2127 BackendId::parse(&backend.name).map_err(|error| {
2128 ConfigError::InvalidBackendName {
2129 name: backend.name.clone(),
2130 reason: error.to_string(),
2131 }
2132 })?;
2133 if backend
2134 .served_kinds
2135 .as_ref()
2136 .is_some_and(BTreeSet::is_empty)
2137 {
2138 return Err(ConfigError::EmptyBackendServedKinds {
2139 name: backend.name.clone(),
2140 });
2141 }
2142 if !seen_backends.insert(backend.name.clone()) {
2143 return Err(ConfigError::DuplicateBackendName {
2144 name: backend.name.clone(),
2145 });
2146 }
2147
2148 if backend.wal_ceiling_bytes.is_some() {
2152 resolve_wal_ceiling(
2153 backend.wal_ceiling_bytes,
2154 None,
2155 &backend.name,
2156 backend.kind.clone(),
2157 backend
2158 .journal_mode
2159 .as_deref()
2160 .is_none_or(|mode| mode.eq_ignore_ascii_case("wal")),
2161 backend.read_only,
2162 )?;
2163 }
2164
2165 backend.resolve_disk_guard(&khive_db::DiskGuardEnvironment::default())?;
2166
2167 if backend.cache_mb.is_some() {
2170 return Err(ConfigError::UnsupportedBackendField {
2171 name: backend.name.clone(),
2172 field: "cache_mb",
2173 });
2174 }
2175 if backend.journal_mode.is_some() {
2176 return Err(ConfigError::UnsupportedBackendField {
2177 name: backend.name.clone(),
2178 field: "journal_mode",
2179 });
2180 }
2181 }
2182 }
2183
2184 let defined: Vec<&str> = if self.backends.is_empty() {
2185 vec![BackendId::MAIN]
2186 } else {
2187 self.backends.iter().map(|b| b.name.as_str()).collect()
2188 };
2189 for (pack_name, pack_cfg) in &self.packs {
2190 if !defined.contains(&pack_cfg.backend.as_str()) {
2191 return Err(ConfigError::UnknownPackBackend {
2192 pack: pack_name.clone(),
2193 backend: pack_cfg.backend.clone(),
2194 defined: defined.join(", "),
2195 });
2196 }
2197 }
2198
2199 if !self.backends.is_empty() {
2200 let missing: Vec<_> = [SubstrateKind::Note, SubstrateKind::Entity]
2201 .into_iter()
2202 .filter(|kind| {
2203 !self.backends.iter().any(|backend| {
2204 backend
2205 .served_kinds
2206 .as_ref()
2207 .is_none_or(|served| served.contains(kind))
2208 })
2209 })
2210 .collect();
2211 if !missing.is_empty() {
2212 return Err(ConfigError::MissingBackendSearchKinds {
2213 kinds: missing,
2214 defined: defined.join(", "),
2215 });
2216 }
2217 }
2218
2219 if let Some(tz) = self.display.timezone.as_deref() {
2222 if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
2223 return Err(ConfigError::InvalidDisplayTimezone {
2224 timezone: tz.to_string(),
2225 });
2226 }
2227 }
2228
2229 for entry in &self.git_write.allowed {
2236 if entry.repo.trim().is_empty() {
2237 return Err(ConfigError::InvalidGitWriteEntry {
2238 repo: entry.repo.clone(),
2239 reason: "repo must not be empty".to_string(),
2240 });
2241 }
2242 if !Path::new(&entry.repo).is_absolute() {
2243 return Err(ConfigError::InvalidGitWriteEntry {
2244 repo: entry.repo.clone(),
2245 reason: "repo must be an absolute path".to_string(),
2246 });
2247 }
2248 if entry.branches.is_empty() {
2249 return Err(ConfigError::InvalidGitWriteEntry {
2250 repo: entry.repo.clone(),
2251 reason: "branches must not be empty".to_string(),
2252 });
2253 }
2254 if entry.branches.iter().any(|b| b.trim().is_empty()) {
2255 return Err(ConfigError::InvalidGitWriteEntry {
2256 repo: entry.repo.clone(),
2257 reason: "branches entries must not be empty".to_string(),
2258 });
2259 }
2260 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
2265 return Err(ConfigError::InvalidGitWriteEntry {
2266 repo: entry.repo.clone(),
2267 reason: format!(
2268 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
2269 ),
2270 });
2271 }
2272 }
2273
2274 validate_peer_engines(&self.engines)
2275 }
2276
2277 pub fn default_engine(&self) -> Option<&EngineConfig> {
2279 self.engines.first()
2280 }
2281}
2282
2283pub fn config_from_env() -> KhiveConfig {
2297 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
2298 .ok()
2299 .filter(|s| !s.trim().is_empty());
2300 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
2301 .ok()
2302 .unwrap_or_default();
2303 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
2304 .into_iter()
2305 .filter(|s| !s.is_empty())
2306 .collect();
2307
2308 if primary_model.is_none() && additional.is_empty() {
2309 return KhiveConfig::default();
2310 }
2311
2312 tracing::info!(
2313 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
2314 );
2315
2316 config_from_env_parts(primary_model, additional)
2317}
2318
2319fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
2322 let mut engines = Vec::new();
2323
2324 let primary =
2325 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
2326 for model in std::iter::once(primary).chain(additional) {
2327 let name = canonical_engine_name(&model);
2328 if engines
2329 .iter()
2330 .any(|engine: &EngineConfig| engine.name == name)
2331 {
2332 continue;
2333 }
2334 engines.push(EngineConfig {
2335 name,
2336 weight: 1.0,
2337 dims: None,
2338 });
2339 }
2340
2341 KhiveConfig {
2342 engines,
2343 ..KhiveConfig::default()
2344 }
2345}
2346
2347#[cfg(test)]
2348#[path = "engine_config_schema_tests.rs"]
2349mod schema_tests;
2350
2351#[cfg(test)]
2356#[path = "engine_config_tests.rs"]
2357mod tests;
2358
2359#[cfg(test)]
2360mod background_limit_tests {
2361 use super::*;
2362
2363 #[test]
2364 fn optional_background_limits_parse_and_validate() {
2365 let config: KhiveConfig =
2366 toml::from_str("[runtime]\nwarm_concurrency = 3\nmaintenance_concurrency = 2\n")
2367 .unwrap();
2368 config.validate().unwrap();
2369 assert_eq!(config.runtime.warm_concurrency, Some(3));
2370 assert_eq!(config.runtime.maintenance_concurrency, Some(2));
2371 }
2372
2373 #[test]
2374 fn zero_and_overflow_limits_report_the_actual_runtime_key() {
2375 for key in ["warm_concurrency", "maintenance_concurrency"] {
2376 for value in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] {
2377 let mut config: KhiveConfig = toml::from_str("").unwrap();
2378 if key == "warm_concurrency" {
2379 config.runtime.warm_concurrency = Some(value);
2380 } else {
2381 config.runtime.maintenance_concurrency = Some(value);
2382 }
2383 assert!(matches!(config.validate(),
2384 Err(ConfigError::InvalidRuntimeConfig { key: found, .. }) if found == key
2385 ));
2386 }
2387 }
2388 }
2389
2390 #[test]
2391 fn negative_toml_background_limits_are_not_deserialized() {
2392 for key in ["warm_concurrency", "maintenance_concurrency"] {
2393 let text = format!("[runtime]\n{key} = -1\n");
2394 assert!(toml::from_str::<KhiveConfig>(&text).is_err());
2395 }
2396 }
2397
2398 #[test]
2399 fn limits_keep_base_and_override_values_on_both_mapping_branches() {
2400 for engines_declared in [false, true] {
2401 let mut config: KhiveConfig =
2402 toml::from_str("[runtime]\nwarm_concurrency = 5\n").unwrap();
2403 config.engines_declared = engines_declared;
2404 let base = crate::RuntimeConfig {
2405 warm_concurrency: 3,
2406 maintenance_concurrency: 2,
2407 ..crate::RuntimeConfig::no_embeddings()
2408 };
2409 let mapped = crate::config::runtime_config_from_khive_config(&config, base);
2410 assert_eq!(mapped.warm_concurrency, 5);
2411 assert_eq!(mapped.maintenance_concurrency, 2);
2412 }
2413 }
2414
2415 #[test]
2416 fn defaults_use_the_named_validated_background_constants() {
2417 let config = crate::RuntimeConfig::default();
2418 assert_eq!(
2419 config.warm_concurrency,
2420 crate::config::DEFAULT_WARM_CONCURRENCY
2421 );
2422 assert_eq!(
2423 config.maintenance_concurrency,
2424 crate::config::DEFAULT_MAINTENANCE_CONCURRENCY
2425 );
2426 crate::resource_admission::WorkClassLimits::validate(
2427 config.warm_concurrency,
2428 config.maintenance_concurrency,
2429 )
2430 .unwrap();
2431 }
2432}