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 configuration: {reason}")]
43 InvalidChannelConfig { 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 #[error(
267 "config file {} is not the file in use (in use: {}); it was read only to look for \
268 `[actor] require_attributed`, which could not be read from it: {source}",
269 path.display(),
270 in_use.as_deref().map_or_else(|| "none".to_string(), |used| used.display().to_string())
271 )]
272 ShadowedTier {
273 path: PathBuf,
274 in_use: Option<PathBuf>,
276 #[source]
277 source: Box<ConfigError>,
278 },
279}
280
281impl ConfigError {
282 fn in_file(self, path: &Path) -> Self {
285 match self {
286 already @ (ConfigError::Parse { .. }
287 | ConfigError::SchemaParse { .. }
288 | ConfigError::ExplicitConfigMissing { .. }
289 | ConfigError::InFile { .. }) => already,
290 other => ConfigError::InFile {
291 path: path.to_path_buf(),
292 source: Box::new(other),
293 },
294 }
295 }
296}
297
298#[derive(Debug, Clone, Deserialize, Default)]
326#[serde(deny_unknown_fields)]
327pub struct ActorConfig {
328 #[serde(default)]
334 pub id: Option<String>,
335
336 #[serde(default)]
339 pub display_name: Option<String>,
340
341 #[serde(default)]
349 pub mailbox_readers: Vec<String>,
350
351 #[serde(default)]
357 pub visible_namespaces: Option<Vec<String>>,
358
359 #[serde(default)]
371 pub allowed_outbound_namespaces: Vec<String>,
372
373 #[serde(default)]
383 pub owned_namespaces: Vec<String>,
384
385 #[serde(default)]
398 pub require_attributed: bool,
399}
400
401#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
408#[serde(deny_unknown_fields)]
409pub struct GateSectionConfig {
410 #[serde(default)]
412 pub granted_actors: Vec<String>,
413
414 #[serde(default)]
416 pub grant_unattributed: bool,
417
418 #[serde(default)]
421 pub deny_writes_for: Vec<String>,
422}
423
424#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
428#[serde(rename_all = "lowercase")]
429pub enum BackendKind {
430 #[default]
432 Sqlite,
433 Memory,
435}
436
437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
442pub struct ResolvedWalCeiling {
443 pub configured_bytes: u64,
445 pub effective_bytes: u64,
447 pub source: khive_db::WalCeilingSource,
449}
450
451pub fn resolve_wal_ceiling(
457 backend_field: Option<u64>,
458 env_value: Option<&str>,
459 backend_name: &str,
460 kind: BackendKind,
461 wal_mode: bool,
462 read_only: bool,
463) -> Result<ResolvedWalCeiling, ConfigError> {
464 if kind == BackendKind::Memory && backend_field.is_none() {
465 return Ok(ResolvedWalCeiling {
466 configured_bytes: 0,
467 effective_bytes: 0,
468 source: khive_db::WalCeilingSource::Default,
469 });
470 }
471 let (configured_bytes, source) = if let Some(bytes) = backend_field {
472 (bytes, khive_db::WalCeilingSource::BackendField)
473 } else if let Some(raw) = env_value {
474 if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
475 return Err(ConfigError::InvalidWalCeilingEnvironment {
476 value: raw.to_owned(),
477 });
478 }
479 let bytes = raw
480 .parse::<u64>()
481 .map_err(|_| ConfigError::InvalidWalCeilingEnvironment {
482 value: raw.to_owned(),
483 })?;
484 (bytes, khive_db::WalCeilingSource::Environment)
485 } else {
486 (0, khive_db::WalCeilingSource::Default)
487 };
488
489 if configured_bytes != 0 {
490 if i64::try_from(configured_bytes).is_err() {
491 return Err(ConfigError::WalCeilingOffsetOverflow {
492 name: backend_name.to_owned(),
493 value: configured_bytes,
494 });
495 }
496 if kind == BackendKind::Memory {
497 return Err(ConfigError::WalCeilingMemoryBackend {
498 name: backend_name.to_owned(),
499 value: configured_bytes,
500 });
501 }
502 if !wal_mode {
503 return Err(ConfigError::WalCeilingNonWalBackend {
504 name: backend_name.to_owned(),
505 value: configured_bytes,
506 });
507 }
508 }
509
510 Ok(ResolvedWalCeiling {
511 configured_bytes,
512 effective_bytes: if read_only { 0 } else { configured_bytes },
513 source,
514 })
515}
516
517#[derive(Debug, Clone, Deserialize)]
534#[serde(deny_unknown_fields)]
535pub struct BackendConfig {
536 pub name: String,
538 #[serde(default)]
540 pub kind: BackendKind,
541 pub path: Option<std::path::PathBuf>,
544 pub cache_mb: Option<u32>,
546 pub journal_mode: Option<String>,
548 #[serde(default)]
554 pub served_kinds: Option<BTreeSet<SubstrateKind>>,
555 #[serde(default)]
557 pub read_only: bool,
558 pub wal_ceiling_bytes: Option<u64>,
562 #[serde(default)]
564 pub disk_reserve_bytes: Option<u64>,
565 #[serde(default)]
567 pub disk_guard_deadline_ms: Option<u64>,
568}
569
570#[derive(Debug, Clone, Deserialize, Default)]
577pub struct CodeMapConfig {
578 #[serde(default)]
580 pub name: Option<String>,
581 #[serde(default)]
583 pub path: Option<String>,
584 #[serde(default)]
586 pub source_root: Option<String>,
587 #[serde(default, flatten)]
589 pub unknown_fields: BTreeMap<String, toml::Value>,
590}
591
592#[derive(Debug, Clone, Deserialize)]
606pub struct PackConfig {
607 #[serde(default = "default_pack_backend")]
610 pub backend: String,
611 #[serde(default)]
613 pub verbs_disabled: Vec<String>,
614 #[serde(default)]
624 pub no_embed: bool,
625}
626
627fn default_pack_backend() -> String {
628 BackendId::MAIN.to_owned()
629}
630
631#[derive(Debug, Clone, Deserialize)]
659#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
660pub enum BlobConfig {
661 Fs {
665 #[serde(default)]
666 root: Option<String>,
667 #[serde(default)]
670 floor_bytes: Option<u64>,
671 },
672 S3 {
677 bucket: String,
678 region: String,
679 #[serde(default)]
680 endpoint: Option<String>,
681 #[serde(default)]
682 prefix: Option<String>,
683 #[serde(default)]
684 allow_http: Option<bool>,
685 },
686}
687
688#[derive(Debug, Clone, Deserialize, Default)]
690#[serde(deny_unknown_fields)]
691pub struct BlobSectionConfig {
692 #[serde(default)]
694 pub file_transfers: bool,
695}
696
697#[derive(Debug, Clone, Deserialize, Default)]
701#[serde(deny_unknown_fields)]
702pub struct StorageSectionConfig {
703 #[serde(default)]
708 pub blob: Option<BlobConfig>,
709}
710
711#[derive(Debug, Clone, Deserialize, Serialize, Default)]
713#[serde(deny_unknown_fields)]
714pub struct BrainSectionConfig {
715 #[serde(default)]
717 pub fleet_readers: Vec<String>,
718}
719
720#[derive(Debug, Clone, Deserialize, Serialize)]
732pub struct GitWriteEntryConfig {
733 pub repo: String,
735 pub branches: Vec<String>,
738}
739
740#[derive(Debug, Clone, Deserialize, Serialize)]
752pub struct GitWriteSectionConfig {
753 #[serde(default)]
755 pub program: Option<PathBuf>,
756 #[serde(default)]
757 pub allowed: Vec<GitWriteEntryConfig>,
758 #[serde(default)]
759 pub actors: BTreeMap<String, GitWriteActorConfig>,
760 #[serde(default)]
761 pub repositories: BTreeMap<String, GitWriteRepositoryConfig>,
762 #[serde(default = "default_git_credential_resolver")]
763 pub credential_resolver: Vec<String>,
764 #[serde(default)]
765 pub contract_faults: bool,
766 #[serde(default)]
767 pub fault: Option<String>,
768}
769
770#[derive(Debug, Clone, Deserialize, Serialize)]
771#[serde(deny_unknown_fields)]
772pub struct GitWriteRepositoryConfig {
773 pub remote: String,
775 pub slug: String,
777 pub visibility: String,
778 #[serde(default)]
784 pub merge_refusals: Vec<String>,
785}
786
787impl GitWriteRepositoryConfig {
788 pub const MERGE_REFUSALS: [&'static str; 2] = ["opener", "last_pusher"];
789
790 pub fn refuses_merge_by(&self, entry: &str) -> bool {
792 self.merge_refusals.iter().any(|listed| listed == entry)
793 }
794}
795
796#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
797#[serde(deny_unknown_fields)]
798pub struct GitWriteActorConfig {
799 pub name: String,
800 pub email: String,
801 pub credential_ref: String,
802 pub platform_identity: String,
803}
804
805fn default_git_credential_resolver() -> Vec<String> {
806 [
807 "/usr/bin/security",
808 "find-generic-password",
809 "-w",
810 "-s",
811 "{ref}",
812 ]
813 .into_iter()
814 .map(str::to_string)
815 .collect()
816}
817
818impl Default for GitWriteSectionConfig {
819 fn default() -> Self {
820 Self {
821 program: None,
822 allowed: Vec::new(),
823 actors: BTreeMap::new(),
824 repositories: BTreeMap::new(),
825 credential_resolver: default_git_credential_resolver(),
826 contract_faults: false,
827 fault: None,
828 }
829 }
830}
831
832impl GitWriteSectionConfig {
833 pub fn git_program(&self) -> &Path {
834 self.program.as_deref().unwrap_or_else(|| Path::new("git"))
835 }
836
837 pub fn validate_dev_loop(&self) -> Result<(), ConfigError> {
838 let invalid = |key: &str, reason: &str| ConfigError::InvalidGitWriteConfig {
839 key: key.to_string(),
840 reason: reason.to_string(),
841 };
842 if let Some(program) = &self.program {
843 if !program.is_absolute() {
844 return Err(invalid("git_write.program", "must be absolute"));
845 }
846 let metadata = std::fs::metadata(program).map_err(|error| {
847 if error.kind() == std::io::ErrorKind::NotFound {
848 invalid("git_write.program", "does not exist")
849 } else {
850 invalid("git_write.program", &format!("is not executable: {error}"))
851 }
852 })?;
853 #[cfg(unix)]
854 let executable = {
855 use std::os::unix::fs::PermissionsExt;
856 metadata.permissions().mode() & 0o111 != 0
857 };
858 #[cfg(windows)]
859 let executable = program
860 .extension()
861 .and_then(|extension| extension.to_str())
862 .is_some_and(|extension| {
863 extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
864 });
865 #[cfg(not(any(unix, windows)))]
866 let executable = false;
867 if !metadata.is_file() || !executable {
868 return Err(invalid("git_write.program", "is not executable"));
869 }
870 }
871 if self.contract_faults && !cfg!(feature = "contract-faults") {
872 tracing::error!(
873 target: "khive.boot",
874 "[git_write] contract_faults requires the test-only contract-faults build feature"
875 );
876 return Err(invalid(
877 "contract_faults",
878 "requires the test-only contract-faults build feature",
879 ));
880 }
881 if let Some(fault) = &self.fault {
882 if !self.contract_faults {
883 return Err(invalid("fault", "requires contract_faults = true"));
884 }
885 let valid = fault.split_once(':').is_some_and(|(verb, point)| {
886 matches!(verb, "git.push" | "git.pr_merge")
887 && matches!(
888 point,
889 "reply-lost-after-effect" | "audit-fails-after-effect"
890 )
891 });
892 if !valid {
893 return Err(invalid("fault", "unsupported contract fault selector"));
894 }
895 }
896 for (path, repository) in &self.repositories {
897 let key = format!("repositories.{path}.merge_refusals");
898 let mut seen: Vec<&str> = Vec::new();
899 for entry in &repository.merge_refusals {
900 if !GitWriteRepositoryConfig::MERGE_REFUSALS.contains(&entry.as_str()) {
901 return Err(invalid(&key, "entries must be opener or last_pusher"));
902 }
903 if seen.contains(&entry.as_str()) {
904 return Err(invalid(&key, "entries must not repeat"));
905 }
906 seen.push(entry);
907 }
908 }
909 if !cfg!(unix)
912 && self.actors.is_empty()
913 && self.credential_resolver == default_git_credential_resolver()
914 {
915 return Ok(());
916 }
917 let argv = &self.credential_resolver;
918 let Some(program) = argv.first() else {
919 return Err(invalid("credential_resolver", "argv must not be empty"));
920 };
921 let program_path = Path::new(program);
922 if !program_path.is_absolute() {
923 return Err(invalid(
924 "credential_resolver",
925 "argv[0] must be an absolute path",
926 ));
927 }
928 let program_name = program_path
929 .file_name()
930 .and_then(|name| name.to_str())
931 .unwrap_or_default()
932 .to_ascii_lowercase();
933 if matches!(
934 program_name.trim_end_matches(".exe"),
935 "sh" | "bash"
936 | "dash"
937 | "zsh"
938 | "ksh"
939 | "fish"
940 | "csh"
941 | "tcsh"
942 | "cmd"
943 | "powershell"
944 | "pwsh"
945 | "env"
946 ) {
947 return Err(invalid(
948 "credential_resolver",
949 "shell or env launcher is not allowed",
950 ));
951 }
952 if argv.iter().any(|arg| arg.chars().any(char::is_control)) {
953 return Err(invalid(
954 "credential_resolver",
955 "argv must not contain control characters",
956 ));
957 }
958 if program.contains(['{', '}'])
959 || argv[1..]
960 .iter()
961 .any(|arg| arg != "{ref}" && arg.contains(['{', '}']))
962 {
963 return Err(invalid(
964 "credential_resolver",
965 "{ref} must be a complete argument and is the only allowed template",
966 ));
967 }
968 if !argv[1..].iter().any(|arg| arg == "{ref}") {
969 return Err(invalid(
970 "credential_resolver",
971 "argv must contain a {ref} argument",
972 ));
973 }
974 for (actor, identity) in &self.actors {
975 if actor.trim().is_empty() || actor.chars().any(char::is_control) {
976 return Err(invalid(
977 "actors",
978 "actor labels must be nonempty and contain no control characters",
979 ));
980 }
981 for (field, value) in [
982 ("name", &identity.name),
983 ("email", &identity.email),
984 ("credential_ref", &identity.credential_ref),
985 ("platform_identity", &identity.platform_identity),
986 ] {
987 if value.trim().is_empty() || value.chars().any(char::is_control) {
988 return Err(invalid(
989 &format!("actors.{actor}.{field}"),
990 "must be nonempty and contain no control characters",
991 ));
992 }
993 }
994 if identity.name.contains(['<', '>']) || identity.email.contains(['<', '>']) {
995 return Err(invalid(
996 &format!("actors.{actor}"),
997 "name and email must not contain Git identity delimiters",
998 ));
999 }
1000 }
1001 Ok(())
1002 }
1003}
1004
1005#[derive(Debug, Clone, Deserialize, Default)]
1010pub struct ExecLimitsConfig {
1011 #[serde(default)]
1012 pub cpu_seconds: Option<u64>,
1013 #[serde(default)]
1014 pub address_space: Option<u64>,
1015 #[serde(default)]
1016 pub file_size: Option<u64>,
1017 #[serde(default)]
1018 pub nproc: Option<u64>,
1019}
1020
1021#[derive(Debug, Clone, Deserialize, Default)]
1044#[serde(deny_unknown_fields)]
1045pub struct ExecSectionConfig {
1046 #[serde(default)]
1047 pub root: Option<String>,
1048 #[serde(default)]
1049 pub read_roots: Vec<String>,
1050 #[serde(default)]
1051 pub env: Vec<String>,
1052 #[serde(default)]
1053 pub never: Vec<String>,
1054 #[serde(default)]
1055 pub max_output_bytes: Option<u64>,
1056 #[serde(default)]
1057 pub timeout_default_s: Option<f64>,
1058 #[serde(default)]
1059 pub timeout_max_s: Option<f64>,
1060 #[serde(default)]
1062 pub binary_digest_timeout_s: Option<u64>,
1063 #[serde(default)]
1064 pub keep: bool,
1065 #[serde(default)]
1066 pub limits: ExecLimitsConfig,
1067}
1068
1069pub const DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 10;
1070pub const MAX_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 60;
1071
1072#[derive(Debug, Clone, Deserialize, Serialize)]
1081#[serde(deny_unknown_fields)]
1082pub struct WebAllowlistEntry {
1083 pub host: String,
1084}
1085
1086#[derive(Debug, Clone, Deserialize, Serialize)]
1093#[serde(deny_unknown_fields)]
1094pub struct WebCredentialConfig {
1095 pub name: String,
1097 pub env_var: String,
1099 pub hosts: Vec<String>,
1102}
1103
1104#[derive(Debug, Clone, Deserialize, Serialize)]
1108#[serde(deny_unknown_fields)]
1109pub struct WebFixtureResult {
1110 pub title: String,
1111 pub url: String,
1112 pub snippet: String,
1113}
1114
1115#[derive(Debug, Clone, Deserialize, Serialize)]
1119#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
1120pub enum WebSearchProviderConfig {
1121 Fixture {
1123 name: String,
1124 #[serde(default)]
1125 default: bool,
1126 results: Vec<WebFixtureResult>,
1127 },
1128 Http {
1135 name: String,
1136 #[serde(default)]
1137 default: bool,
1138 url_template: String,
1139 #[serde(default)]
1140 api_key_env: Option<String>,
1141 #[serde(default)]
1148 hosts: Vec<String>,
1149 },
1150}
1151
1152impl WebSearchProviderConfig {
1153 pub fn name(&self) -> &str {
1154 match self {
1155 WebSearchProviderConfig::Fixture { name, .. } => name,
1156 WebSearchProviderConfig::Http { name, .. } => name,
1157 }
1158 }
1159
1160 pub fn is_default(&self) -> bool {
1161 match self {
1162 WebSearchProviderConfig::Fixture { default, .. } => *default,
1163 WebSearchProviderConfig::Http { default, .. } => *default,
1164 }
1165 }
1166}
1167
1168#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1202#[serde(deny_unknown_fields)]
1203pub struct WebSectionConfig {
1204 #[serde(default)]
1205 pub timeout_default_s: Option<u64>,
1206 #[serde(default)]
1207 pub timeout_max_s: Option<u64>,
1208 #[serde(default)]
1209 pub max_bytes_default: Option<u64>,
1210 #[serde(default)]
1211 pub max_bytes_max: Option<u64>,
1212 #[serde(default)]
1213 pub search_limit_default: Option<u32>,
1214 #[serde(default)]
1215 pub search_limit_max: Option<u32>,
1216 #[serde(default)]
1217 pub allowlist: Vec<WebAllowlistEntry>,
1218 #[serde(default)]
1219 pub credentials: Vec<WebCredentialConfig>,
1220 #[serde(default)]
1221 pub search_providers: Vec<WebSearchProviderConfig>,
1222 #[serde(default)]
1226 pub read_roots: Vec<String>,
1227}
1228
1229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1231pub struct WebCeilings {
1232 pub timeout_default_s: u64,
1233 pub timeout_max_s: u64,
1234 pub max_bytes_default: u64,
1235 pub max_bytes_max: u64,
1236 pub search_limit_default: u32,
1237 pub search_limit_max: u32,
1238}
1239
1240impl Default for WebCeilings {
1241 fn default() -> Self {
1242 Self {
1243 timeout_default_s: 30,
1244 timeout_max_s: 120,
1245 max_bytes_default: 5 * 1024 * 1024,
1246 max_bytes_max: 50 * 1024 * 1024,
1247 search_limit_default: 10,
1248 search_limit_max: 50,
1249 }
1250 }
1251}
1252
1253impl WebSectionConfig {
1254 pub fn resolved_ceilings(&self) -> Result<WebCeilings, ConfigError> {
1255 let defaults = WebCeilings::default();
1256 let bounds = WebCeilings {
1257 timeout_default_s: self.timeout_default_s.unwrap_or(defaults.timeout_default_s),
1258 timeout_max_s: self.timeout_max_s.unwrap_or(defaults.timeout_max_s),
1259 max_bytes_default: self.max_bytes_default.unwrap_or(defaults.max_bytes_default),
1260 max_bytes_max: self.max_bytes_max.unwrap_or(defaults.max_bytes_max),
1261 search_limit_default: self
1262 .search_limit_default
1263 .unwrap_or(defaults.search_limit_default),
1264 search_limit_max: self.search_limit_max.unwrap_or(defaults.search_limit_max),
1265 };
1266 for (key, default, maximum, maximum_key) in [
1267 (
1268 "timeout_default_s",
1269 bounds.timeout_default_s,
1270 bounds.timeout_max_s,
1271 "timeout_max_s",
1272 ),
1273 (
1274 "max_bytes_default",
1275 bounds.max_bytes_default,
1276 bounds.max_bytes_max,
1277 "max_bytes_max",
1278 ),
1279 (
1280 "search_limit_default",
1281 u64::from(bounds.search_limit_default),
1282 u64::from(bounds.search_limit_max),
1283 "search_limit_max",
1284 ),
1285 ] {
1286 if default == 0 || default > maximum {
1287 return Err(ConfigError::InvalidWebConfig {
1288 key: key.into(),
1289 reason: format!(
1290 "resolved default must be positive and not exceed {maximum_key}={maximum}"
1291 ),
1292 });
1293 }
1294 }
1295 if std::time::Instant::now()
1296 .checked_add(std::time::Duration::from_secs(bounds.timeout_max_s))
1297 .is_none()
1298 {
1299 return Err(ConfigError::InvalidWebConfig {
1300 key: "timeout_max_s".into(),
1301 reason: "cannot be represented as a request deadline".into(),
1302 });
1303 }
1304 Ok(bounds)
1305 }
1306
1307 pub fn validate(&self) -> Result<(), ConfigError> {
1308 self.resolved_ceilings()?;
1309 let invalid = |key: &str, reason: &str| ConfigError::InvalidWebConfig {
1310 key: key.to_string(),
1311 reason: reason.to_string(),
1312 };
1313 let mut seen_hosts = std::collections::HashSet::new();
1314 for entry in &self.allowlist {
1315 let normalized = entry.host.trim().trim_end_matches('.').to_ascii_lowercase();
1316 if normalized.is_empty() {
1317 return Err(invalid("allowlist.host", "must not be empty"));
1318 }
1319 if !seen_hosts.insert(normalized) {
1320 return Err(invalid("allowlist.host", "duplicate host entry"));
1321 }
1322 }
1323 let mut seen_credentials = std::collections::HashSet::new();
1324 for credential in &self.credentials {
1325 if credential.name.trim().is_empty() {
1326 return Err(invalid("credentials.name", "must not be empty"));
1327 }
1328 if !seen_credentials.insert(credential.name.clone()) {
1329 return Err(invalid("credentials.name", "duplicate credential name"));
1330 }
1331 if credential.env_var.trim().is_empty() {
1332 return Err(invalid("credentials.env_var", "must not be empty"));
1333 }
1334 if credential.hosts.is_empty() {
1335 return Err(invalid(
1336 "credentials.hosts",
1337 "must name at least one host or suffix",
1338 ));
1339 }
1340 }
1341 let mut seen_providers = std::collections::HashSet::new();
1342 let mut default_count = 0;
1343 for provider in &self.search_providers {
1344 let name = provider.name();
1345 if name.trim().is_empty() {
1346 return Err(invalid("search_providers.name", "must not be empty"));
1347 }
1348 if !seen_providers.insert(name.to_string()) {
1349 return Err(invalid("search_providers.name", "duplicate provider name"));
1350 }
1351 if provider.is_default() {
1352 default_count += 1;
1353 }
1354 if let WebSearchProviderConfig::Http {
1355 url_template,
1356 api_key_env,
1357 hosts,
1358 ..
1359 } = provider
1360 {
1361 if !url_template.contains("{query}") {
1362 return Err(invalid(
1363 "search_providers.url_template",
1364 "must contain the literal substring {query}",
1365 ));
1366 }
1367 if api_key_env.is_some() && hosts.is_empty() {
1368 return Err(invalid(
1369 "search_providers.hosts",
1370 "an api_key_env-bearing provider must name at least one host or suffix",
1371 ));
1372 }
1373 }
1374 }
1375 if default_count > 1 {
1376 return Err(invalid(
1377 "search_providers",
1378 "at most one provider may set default = true",
1379 ));
1380 }
1381 Ok(())
1382 }
1383}
1384
1385#[derive(Debug, Clone, Deserialize, Serialize)]
1388pub struct SchemaSectionConfig {
1389 #[serde(default = "schema_strict_default")]
1390 pub strict: bool,
1391}
1392
1393fn schema_strict_default() -> bool {
1394 true
1395}
1396
1397impl Default for SchemaSectionConfig {
1398 fn default() -> Self {
1399 Self { strict: true }
1400 }
1401}
1402
1403#[derive(Deserialize)]
1406struct SchemaSyntaxProbe {
1407 #[serde(default, deserialize_with = "deserialize_schema_table")]
1408 schema: SchemaSectionConfig,
1409}
1410
1411fn deserialize_schema_table<'de, D>(deserializer: D) -> Result<SchemaSectionConfig, D::Error>
1412where
1413 D: serde::Deserializer<'de>,
1414{
1415 struct SchemaTableVisitor;
1416 impl<'de> serde::de::Visitor<'de> for SchemaTableVisitor {
1417 type Value = SchemaSectionConfig;
1418
1419 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1420 formatter.write_str("a schema configuration table")
1421 }
1422
1423 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1424 where
1425 A: serde::de::MapAccess<'de>,
1426 {
1427 SchemaSectionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
1428 }
1429 }
1430 deserializer.deserialize_map(SchemaTableVisitor)
1431}
1432
1433#[derive(Debug, Clone, Deserialize, Default)]
1456pub struct KhiveConfig {
1457 #[serde(default)]
1459 pub schema: SchemaSectionConfig,
1460
1461 #[serde(default, deserialize_with = "embed_batch::deserialize_table")]
1463 pub embed: EmbedSectionConfig,
1464
1465 #[serde(skip)]
1467 pub credentials: Vec<crate::credentials::CredentialConfig>,
1468
1469 #[serde(skip)]
1470 pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
1471
1472 #[serde(default)]
1475 pub channel: crate::channel_section::ChannelSectionConfig,
1476
1477 #[serde(default)]
1478 pub mounts: Vec<crate::mount_config::MountConfig>,
1479
1480 #[serde(default)]
1486 pub db: Option<String>,
1487
1488 #[serde(default)]
1490 pub engines: Vec<EngineConfig>,
1491
1492 #[serde(skip)]
1496 pub engines_declared: bool,
1497
1498 #[serde(default)]
1506 pub actor: ActorConfig,
1507
1508 #[serde(default)]
1512 pub gate: Option<GateSectionConfig>,
1513
1514 #[serde(default)]
1516 pub runtime: RuntimeSectionConfig,
1517
1518 #[serde(default)]
1523 pub backends: Vec<BackendConfig>,
1524
1525 #[serde(default)]
1527 pub code_map_root: Option<String>,
1528
1529 #[serde(default)]
1531 pub code_maps: Vec<CodeMapConfig>,
1532
1533 #[serde(default)]
1539 pub packs: std::collections::HashMap<String, PackConfig>,
1540
1541 #[serde(default)]
1543 pub brain: BrainSectionConfig,
1544
1545 #[serde(default)]
1549 pub git_write: GitWriteSectionConfig,
1550
1551 #[serde(default)]
1553 pub blob: BlobSectionConfig,
1554
1555 #[serde(default)]
1558 pub storage: StorageSectionConfig,
1559
1560 #[serde(default)]
1563 pub exec: ExecSectionConfig,
1564
1565 #[serde(default)]
1567 pub telemetry: crate::telemetry_config::TelemetryConfig,
1568
1569 #[serde(default)]
1573 pub display: DisplaySectionConfig,
1574
1575 #[serde(default)]
1580 pub web: WebSectionConfig,
1581}
1582
1583#[derive(Debug, Clone, Deserialize, Default)]
1590pub struct RuntimeSectionConfig {
1591 #[serde(default)]
1594 pub warm_concurrency: Option<usize>,
1595
1596 #[serde(default)]
1599 pub maintenance_concurrency: Option<usize>,
1600
1601 #[serde(default)]
1604 pub packs: Option<Vec<String>>,
1605
1606 #[serde(default)]
1613 pub brain_profile: Option<String>,
1614
1615 #[serde(default)]
1622 pub default_output_format: Option<OutputFormat>,
1623
1624 #[serde(default)]
1631 pub blob_hydration_bytes: Option<u64>,
1632}
1633
1634#[derive(Debug, Clone, Deserialize, Default)]
1642pub struct DisplaySectionConfig {
1643 #[serde(default)]
1649 pub timezone: Option<String>,
1650}
1651
1652impl KhiveConfig {
1653 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
1669 let resolved = match path {
1670 Some(p) => p.to_path_buf(),
1671 None => PathBuf::from(".khive/config.toml"),
1672 };
1673
1674 if !resolved.exists() {
1675 return Ok(None);
1676 }
1677
1678 let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
1681 let raw = std::fs::read_to_string(&resolved)
1682 .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
1683 let mut document: toml::Value =
1684 toml::from_str(&raw).map_err(|source| ConfigError::Parse {
1685 path: diagnostic_path.clone(),
1686 source,
1687 })?;
1688 let schema_probe: SchemaSyntaxProbe =
1689 toml::from_str(&raw).map_err(|source| ConfigError::SchemaParse {
1690 path: diagnostic_path.clone(),
1691 key: if document
1692 .get("schema")
1693 .is_some_and(|value| !value.is_table())
1694 {
1695 "schema"
1696 } else {
1697 "schema.strict"
1698 },
1699 source: Box::new(source),
1700 })?;
1701 let unknown_schema_keys: Vec<String> = document
1702 .get("schema")
1703 .and_then(toml::Value::as_table)
1704 .map(|table| {
1705 table
1706 .keys()
1707 .filter(|key| key.as_str() != "strict")
1708 .cloned()
1709 .collect()
1710 })
1711 .unwrap_or_default();
1712 let (embed, unknown_embed_keys) = embed_batch::parse(&raw, &document, &diagnostic_path)?;
1713 let engines_declared = peers::normalize_engine_input(&mut document, &diagnostic_path)
1714 .map_err(|error| error.in_file(&diagnostic_path))?;
1715 let mut cfg: KhiveConfig = document.try_into().map_err(|source| ConfigError::Parse {
1716 path: diagnostic_path.clone(),
1717 source,
1718 })?;
1719 cfg.schema = schema_probe.schema;
1720 cfg.embed = embed;
1721 cfg.engines_declared = engines_declared;
1722 crate::credentials::read_tables(&raw, &mut cfg)
1723 .map_err(|error| ConfigError::from(error).in_file(&diagnostic_path))?;
1724 cfg.validate()
1725 .map_err(|error| error.in_file(&diagnostic_path))?;
1726 for engine in &mut cfg.engines {
1727 engine.name = canonical_engine_name(&engine.name);
1728 }
1729 for key in unknown_schema_keys {
1730 tracing::warn!(target: "khive.config.schema",
1731 key = %crate::secret_gate::bounded_masked_log_text(&key),
1732 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1733 "ignoring unknown schema configuration key");
1734 }
1735 for key in unknown_embed_keys {
1736 tracing::warn!(target: "khive.config.embed",
1737 key = %crate::secret_gate::bounded_masked_log_text(&key),
1738 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1739 "ignoring unknown embed configuration key");
1740 }
1741 Ok(Some(cfg))
1742 }
1743
1744 pub fn load_with_home_fallback(
1772 path: Option<&Path>,
1773 db_path: Option<&Path>,
1774 ) -> Result<Option<Self>, ConfigError> {
1775 Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
1776 }
1777
1778 pub fn load_with_home_fallback_and_source(
1786 path: Option<&Path>,
1787 db_path: Option<&Path>,
1788 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1789 if let Some(p) = path {
1797 if !p.exists() {
1798 return Err(ConfigError::ExplicitConfigMissing {
1799 path: p.to_path_buf(),
1800 });
1801 }
1802 return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
1803 }
1804
1805 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1807 let home_root = std::env::var_os("HOME").map(PathBuf::from);
1808 Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
1809 }
1810
1811 #[cfg(test)]
1820 pub(crate) fn load_with_roots(
1821 project_root: &Path,
1822 home_root: Option<&Path>,
1823 db_path: Option<&Path>,
1824 ) -> Result<Option<Self>, ConfigError> {
1825 Ok(
1826 Self::load_with_roots_and_source(project_root, home_root, db_path)?
1827 .map(|(config, _)| config),
1828 )
1829 }
1830
1831 fn load_with_roots_and_source(
1832 project_root: &Path,
1833 home_root: Option<&Path>,
1834 db_path: Option<&Path>,
1835 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1836 let tier2 = project_root.join("khive.toml");
1838 if tier2.exists() {
1839 return Ok(Self::load(Some(&tier2))?
1840 .map(|config| (config, Self::diagnostic_config_path(&tier2))));
1841 }
1842
1843 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
1846 if tier3.exists() {
1847 return Ok(Self::load(Some(&tier3))?
1848 .map(|config| (config, Self::diagnostic_config_path(&tier3))));
1849 }
1850
1851 if let Some(home) = home_root {
1853 let tier4 = home.join(".khive/config.toml");
1854 if tier4.exists() {
1855 return Ok(Self::load(Some(&tier4))?
1856 .map(|config| (config, Self::diagnostic_config_path(&tier4))));
1857 }
1858 }
1859
1860 Ok(None)
1861 }
1862
1863 pub fn require_attributed_in_any_tier(
1867 path: Option<&Path>,
1868 db_path: Option<&Path>,
1869 ) -> Result<bool, ConfigError> {
1870 if let Some(p) = path {
1871 if !p.exists() {
1872 return Err(ConfigError::ExplicitConfigMissing {
1873 path: p.to_path_buf(),
1874 });
1875 }
1876 return Ok(Self::load(Some(p))?.is_some_and(|cfg| cfg.actor.require_attributed));
1877 }
1878 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1879 let home_root = std::env::var_os("HOME").map(PathBuf::from);
1880 Self::require_attributed_in_tiers(&project_root, home_root.as_deref(), db_path)
1881 }
1882
1883 pub(crate) fn require_attributed_in_tiers(
1886 project_root: &Path,
1887 home_root: Option<&Path>,
1888 db_path: Option<&Path>,
1889 ) -> Result<bool, ConfigError> {
1890 let mut files = vec![
1891 project_root.join("khive.toml"),
1892 Self::project_config_anchor_dir(db_path, project_root).join("config.toml"),
1893 project_root.join(".khive/config.toml"),
1894 ];
1895 let home_file = home_root.map(|home| home.join(".khive/config.toml"));
1896 let in_use = [Some(&files[0]), Some(&files[1]), home_file.as_ref()]
1898 .into_iter()
1899 .flatten()
1900 .find(|file| file.exists())
1901 .cloned();
1902 files.extend(home_file);
1903 files.dedup();
1904 for file in files.iter().filter(|file| file.exists()) {
1905 let loaded = Self::load(Some(file)).map_err(|source| match &in_use {
1906 Some(used) if used == file => source,
1907 _ => ConfigError::ShadowedTier {
1908 path: Self::diagnostic_config_path(file),
1909 in_use: in_use.as_deref().map(Self::diagnostic_config_path),
1910 source: Box::new(source),
1911 },
1912 })?;
1913 if loaded.is_some_and(|cfg| cfg.actor.require_attributed) {
1914 return Ok(true);
1915 }
1916 }
1917 Ok(false)
1918 }
1919
1920 fn diagnostic_config_path(path: &Path) -> PathBuf {
1921 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1922 }
1923
1924 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
1950 let Some(db_path) = db_path else {
1951 return project_root.join(".khive");
1952 };
1953
1954 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
1955 if db_path.is_absolute() {
1956 db_path.to_path_buf()
1957 } else {
1958 project_root.join(db_path)
1959 }
1960 });
1961
1962 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
1963
1964 if db_dir.file_name().is_some_and(|name| name == ".khive") {
1965 db_dir
1966 } else {
1967 db_dir.join(".khive")
1968 }
1969 }
1970
1971 pub fn validate(&self) -> Result<(), ConfigError> {
1977 #[cfg(not(feature = "blob-s3"))]
1978 if matches!(&self.storage.blob, Some(BlobConfig::S3 { .. })) {
1979 return Err(ConfigError::BlobS3FeatureDisabled);
1980 }
1981
1982 let warm = self
1983 .runtime
1984 .warm_concurrency
1985 .unwrap_or(crate::config::DEFAULT_WARM_CONCURRENCY);
1986 let maintenance = self
1987 .runtime
1988 .maintenance_concurrency
1989 .unwrap_or(crate::config::DEFAULT_MAINTENANCE_CONCURRENCY);
1990 crate::resource_admission::WorkClassLimits::validate(warm, maintenance).map_err(
1991 |error| {
1992 let key = match &error {
1993 crate::resource_admission::ResourceError::InvalidLimit {
1994 class: crate::resource_admission::WorkClass::Warm,
1995 ..
1996 } => "warm_concurrency",
1997 crate::resource_admission::ResourceError::InvalidLimit {
1998 class: crate::resource_admission::WorkClass::Maintenance,
1999 ..
2000 } => "maintenance_concurrency",
2001 _ => "background_concurrency",
2002 };
2003 ConfigError::InvalidRuntimeConfig {
2004 key: key.to_owned(),
2005 reason: error.to_string(),
2006 }
2007 },
2008 )?;
2009
2010 crate::mount_config::validate_mounts(&self.mounts)?;
2011 self.git_write.validate_dev_loop()?;
2012 self.telemetry.validate()?;
2013 self.web.validate()?;
2014 crate::credentials::CredentialConfig::validate_all(&self.credentials)?;
2015 if let Some(receipts) = &self.visibility_receipts {
2016 receipts.validate(&self.credentials)?;
2017 }
2018 self.channel.validate()?;
2019
2020 if let Some(value) = self.db.as_deref() {
2025 if !value.is_empty() {
2026 return Err(ConfigError::UnsupportedTopLevelDb {
2027 value: value.to_string(),
2028 });
2029 }
2030 }
2031
2032 if cfg!(target_os = "macos") {
2036 if self.exec.limits.address_space.is_some() {
2037 return Err(ConfigError::InvalidExecConfig {
2038 key: "limits.address_space".to_string(),
2039 reason: "unsupported_on_platform: macOS does not enforce an address-space rlimit per process".to_string(),
2040 });
2041 }
2042 if self.exec.limits.nproc.is_some() {
2043 return Err(ConfigError::InvalidExecConfig {
2044 key: "limits.nproc".to_string(),
2045 reason: "unsupported_on_platform: RLIMIT_NPROC counts every process of the uid, not one run".to_string(),
2046 });
2047 }
2048 }
2049 let default_timeout = self.exec.timeout_default_s.unwrap_or(30.0);
2053 let maximum_timeout = self.exec.timeout_max_s.unwrap_or(600.0);
2054 for (key, value) in [
2055 ("timeout_default_s", default_timeout),
2056 ("timeout_max_s", maximum_timeout),
2057 ] {
2058 let duration = value
2059 .is_finite()
2060 .then(|| std::time::Duration::try_from_secs_f64(value).ok())
2061 .flatten()
2062 .filter(|duration| !duration.is_zero());
2063 if duration
2064 .is_none_or(|duration| std::time::Instant::now().checked_add(duration).is_none())
2065 {
2066 return Err(ConfigError::InvalidExecConfig {
2067 key: key.to_string(),
2068 reason: "must be positive, finite, and representable as a deadline".to_string(),
2069 });
2070 }
2071 }
2072 if default_timeout > maximum_timeout {
2073 return Err(ConfigError::InvalidExecConfig {
2074 key: "timeout_default_s".to_string(),
2075 reason: format!(
2076 "default {default_timeout} exceeds timeout_max_s {maximum_timeout}"
2077 ),
2078 });
2079 }
2080 let binary_digest_timeout = self
2081 .exec
2082 .binary_digest_timeout_s
2083 .unwrap_or(DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S);
2084 if !(1..=MAX_EXEC_BINARY_DIGEST_TIMEOUT_S).contains(&binary_digest_timeout) {
2085 return Err(ConfigError::InvalidExecConfig {
2086 key: "binary_digest_timeout_s".to_string(),
2087 reason: format!("must be between 1 and {MAX_EXEC_BINARY_DIGEST_TIMEOUT_S} seconds"),
2088 });
2089 }
2090
2091 if let Some(value) = self.runtime.blob_hydration_bytes {
2092 let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
2093 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
2094 if value < min || value > max {
2095 return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
2096 }
2097 }
2098
2099 if let Some(id) = self.actor.id.as_deref() {
2102 if id.is_empty() {
2103 return Err(ConfigError::InvalidActorId {
2104 id: id.to_string(),
2105 reason: "actor.id must not be empty; remove the key or provide a value"
2106 .to_string(),
2107 });
2108 }
2109 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
2110 id: id.to_string(),
2111 reason: e.to_string(),
2112 })?;
2113 }
2114
2115 self.actor
2116 .mailbox_gate(std::sync::Arc::new(khive_gate::AllowAllGate))
2117 .map_err(|error| ConfigError::InvalidMailboxReaders {
2118 reason: error.to_string(),
2119 })?;
2120
2121 if let Some(ref vis) = self.actor.visible_namespaces {
2122 for ns_str in vis {
2123 if ns_str.is_empty() {
2124 return Err(ConfigError::InvalidActorId {
2125 id: ns_str.clone(),
2126 reason: "visible_namespaces entries must not be empty".to_string(),
2127 });
2128 }
2129 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2130 id: ns_str.clone(),
2131 reason: format!("invalid visible namespace: {e}"),
2132 })?;
2133 }
2134 }
2135
2136 if !self.actor.owned_namespaces.is_empty() {
2140 let Some(actor_id) = self.actor.id.as_deref() else {
2141 return Err(ConfigError::InvalidActorId {
2142 id: String::new(),
2143 reason: "owned_namespaces requires an explicit [actor] id".to_string(),
2144 });
2145 };
2146 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2147 for ns_str in &self.actor.owned_namespaces {
2148 if ns_str.is_empty() {
2149 return Err(ConfigError::InvalidActorId {
2150 id: ns_str.clone(),
2151 reason: "owned_namespaces entries must not be empty".to_string(),
2152 });
2153 }
2154 let parsed = Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2155 id: ns_str.clone(),
2156 reason: format!("invalid owned namespace: {e}"),
2157 })?;
2158 if parsed.as_str() == Namespace::LOCAL {
2159 return Err(ConfigError::InvalidActorId {
2160 id: ns_str.clone(),
2161 reason: "owned_namespaces must not list the shared namespace `local`"
2162 .to_string(),
2163 });
2164 }
2165 if parsed.as_str() == actor_id {
2166 return Err(ConfigError::InvalidActorId {
2167 id: ns_str.clone(),
2168 reason: "owned_namespaces must not list the actor's own id".to_string(),
2169 });
2170 }
2171 if !seen.insert(parsed.as_str().to_string()) {
2172 return Err(ConfigError::InvalidActorId {
2173 id: ns_str.clone(),
2174 reason: "owned_namespaces entries must be unique".to_string(),
2175 });
2176 }
2177 }
2178 }
2179
2180 if let Some(gate) = &self.gate {
2181 khive_gate::CallerEnrollmentGate::validate_write_denials(&gate.deny_writes_for)
2182 .map_err(|error| ConfigError::InvalidWriteDenyPatterns {
2183 reason: error.to_string(),
2184 })?;
2185 for id in &gate.granted_actors {
2186 if id.is_empty() {
2187 return Err(ConfigError::InvalidGrantedActorId {
2188 id: id.clone(),
2189 reason: "actor ids must not be empty".to_string(),
2190 });
2191 }
2192 Namespace::parse(id).map_err(|error| ConfigError::InvalidGrantedActorId {
2193 id: id.clone(),
2194 reason: error.to_string(),
2195 })?;
2196 }
2197 }
2198
2199 for ns_str in &self.actor.allowed_outbound_namespaces {
2201 if ns_str.is_empty() {
2202 return Err(ConfigError::InvalidActorId {
2203 id: ns_str.clone(),
2204 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
2205 });
2206 }
2207 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2208 id: ns_str.clone(),
2209 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
2210 })?;
2211 }
2212
2213 if !self.backends.is_empty() {
2215 let mut seen_backends = std::collections::HashSet::new();
2216 for backend in &self.backends {
2217 BackendId::parse(&backend.name).map_err(|error| {
2218 ConfigError::InvalidBackendName {
2219 name: backend.name.clone(),
2220 reason: error.to_string(),
2221 }
2222 })?;
2223 if backend
2224 .served_kinds
2225 .as_ref()
2226 .is_some_and(BTreeSet::is_empty)
2227 {
2228 return Err(ConfigError::EmptyBackendServedKinds {
2229 name: backend.name.clone(),
2230 });
2231 }
2232 if !seen_backends.insert(backend.name.clone()) {
2233 return Err(ConfigError::DuplicateBackendName {
2234 name: backend.name.clone(),
2235 });
2236 }
2237
2238 if backend.wal_ceiling_bytes.is_some() {
2242 resolve_wal_ceiling(
2243 backend.wal_ceiling_bytes,
2244 None,
2245 &backend.name,
2246 backend.kind.clone(),
2247 backend
2248 .journal_mode
2249 .as_deref()
2250 .is_none_or(|mode| mode.eq_ignore_ascii_case("wal")),
2251 backend.read_only,
2252 )?;
2253 }
2254
2255 backend.resolve_disk_guard(&khive_db::DiskGuardEnvironment::default())?;
2256
2257 if backend.cache_mb.is_some() {
2260 return Err(ConfigError::UnsupportedBackendField {
2261 name: backend.name.clone(),
2262 field: "cache_mb",
2263 });
2264 }
2265 if backend.journal_mode.is_some() {
2266 return Err(ConfigError::UnsupportedBackendField {
2267 name: backend.name.clone(),
2268 field: "journal_mode",
2269 });
2270 }
2271 }
2272 }
2273
2274 let defined: Vec<&str> = if self.backends.is_empty() {
2275 vec![BackendId::MAIN]
2276 } else {
2277 self.backends.iter().map(|b| b.name.as_str()).collect()
2278 };
2279 for (pack_name, pack_cfg) in &self.packs {
2280 if !defined.contains(&pack_cfg.backend.as_str()) {
2281 return Err(ConfigError::UnknownPackBackend {
2282 pack: pack_name.clone(),
2283 backend: pack_cfg.backend.clone(),
2284 defined: defined.join(", "),
2285 });
2286 }
2287 }
2288
2289 if !self.backends.is_empty() {
2290 let missing: Vec<_> = [SubstrateKind::Note, SubstrateKind::Entity]
2291 .into_iter()
2292 .filter(|kind| {
2293 !self.backends.iter().any(|backend| {
2294 backend
2295 .served_kinds
2296 .as_ref()
2297 .is_none_or(|served| served.contains(kind))
2298 })
2299 })
2300 .collect();
2301 if !missing.is_empty() {
2302 return Err(ConfigError::MissingBackendSearchKinds {
2303 kinds: missing,
2304 defined: defined.join(", "),
2305 });
2306 }
2307 }
2308
2309 if let Some(tz) = self.display.timezone.as_deref() {
2312 if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
2313 return Err(ConfigError::InvalidDisplayTimezone {
2314 timezone: tz.to_string(),
2315 });
2316 }
2317 }
2318
2319 for entry in &self.git_write.allowed {
2326 if entry.repo.trim().is_empty() {
2327 return Err(ConfigError::InvalidGitWriteEntry {
2328 repo: entry.repo.clone(),
2329 reason: "repo must not be empty".to_string(),
2330 });
2331 }
2332 if !Path::new(&entry.repo).is_absolute() {
2333 return Err(ConfigError::InvalidGitWriteEntry {
2334 repo: entry.repo.clone(),
2335 reason: "repo must be an absolute path".to_string(),
2336 });
2337 }
2338 if entry.branches.is_empty() {
2339 return Err(ConfigError::InvalidGitWriteEntry {
2340 repo: entry.repo.clone(),
2341 reason: "branches must not be empty".to_string(),
2342 });
2343 }
2344 if entry.branches.iter().any(|b| b.trim().is_empty()) {
2345 return Err(ConfigError::InvalidGitWriteEntry {
2346 repo: entry.repo.clone(),
2347 reason: "branches entries must not be empty".to_string(),
2348 });
2349 }
2350 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
2355 return Err(ConfigError::InvalidGitWriteEntry {
2356 repo: entry.repo.clone(),
2357 reason: format!(
2358 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
2359 ),
2360 });
2361 }
2362 }
2363
2364 validate_peer_engines(&self.engines)
2365 }
2366
2367 pub fn default_engine(&self) -> Option<&EngineConfig> {
2369 self.engines.first()
2370 }
2371}
2372
2373pub fn config_from_env() -> KhiveConfig {
2387 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
2388 .ok()
2389 .filter(|s| !s.trim().is_empty());
2390 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
2391 .ok()
2392 .unwrap_or_default();
2393 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
2394 .into_iter()
2395 .filter(|s| !s.is_empty())
2396 .collect();
2397
2398 if primary_model.is_none() && additional.is_empty() {
2399 return KhiveConfig::default();
2400 }
2401
2402 tracing::info!(
2403 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
2404 );
2405
2406 config_from_env_parts(primary_model, additional)
2407}
2408
2409fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
2412 let mut engines = Vec::new();
2413
2414 let primary =
2415 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
2416 for model in std::iter::once(primary).chain(additional) {
2417 let name = canonical_engine_name(&model);
2418 if engines
2419 .iter()
2420 .any(|engine: &EngineConfig| engine.name == name)
2421 {
2422 continue;
2423 }
2424 engines.push(EngineConfig {
2425 name,
2426 weight: 1.0,
2427 dims: None,
2428 });
2429 }
2430
2431 KhiveConfig {
2432 engines,
2433 ..KhiveConfig::default()
2434 }
2435}
2436
2437#[cfg(test)]
2438#[path = "engine_config_schema_tests.rs"]
2439mod schema_tests;
2440
2441#[cfg(test)]
2446#[path = "engine_config_tests.rs"]
2447mod tests;
2448
2449#[cfg(test)]
2450mod background_limit_tests {
2451 use super::*;
2452
2453 #[test]
2454 fn optional_background_limits_parse_and_validate() {
2455 let config: KhiveConfig =
2456 toml::from_str("[runtime]\nwarm_concurrency = 3\nmaintenance_concurrency = 2\n")
2457 .unwrap();
2458 config.validate().unwrap();
2459 assert_eq!(config.runtime.warm_concurrency, Some(3));
2460 assert_eq!(config.runtime.maintenance_concurrency, Some(2));
2461 }
2462
2463 #[test]
2464 fn zero_and_overflow_limits_report_the_actual_runtime_key() {
2465 for key in ["warm_concurrency", "maintenance_concurrency"] {
2466 for value in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] {
2467 let mut config: KhiveConfig = toml::from_str("").unwrap();
2468 if key == "warm_concurrency" {
2469 config.runtime.warm_concurrency = Some(value);
2470 } else {
2471 config.runtime.maintenance_concurrency = Some(value);
2472 }
2473 assert!(matches!(config.validate(),
2474 Err(ConfigError::InvalidRuntimeConfig { key: found, .. }) if found == key
2475 ));
2476 }
2477 }
2478 }
2479
2480 #[test]
2481 fn negative_toml_background_limits_are_not_deserialized() {
2482 for key in ["warm_concurrency", "maintenance_concurrency"] {
2483 let text = format!("[runtime]\n{key} = -1\n");
2484 assert!(toml::from_str::<KhiveConfig>(&text).is_err());
2485 }
2486 }
2487
2488 #[test]
2489 fn limits_keep_base_and_override_values_on_both_mapping_branches() {
2490 for engines_declared in [false, true] {
2491 let mut config: KhiveConfig =
2492 toml::from_str("[runtime]\nwarm_concurrency = 5\n").unwrap();
2493 config.engines_declared = engines_declared;
2494 let base = crate::RuntimeConfig {
2495 warm_concurrency: 3,
2496 maintenance_concurrency: 2,
2497 ..crate::RuntimeConfig::no_embeddings()
2498 };
2499 let mapped = crate::config::runtime_config_from_khive_config(&config, base);
2500 assert_eq!(mapped.warm_concurrency, 5);
2501 assert_eq!(mapped.maintenance_concurrency, 2);
2502 }
2503 }
2504
2505 #[test]
2506 fn defaults_use_the_named_validated_background_constants() {
2507 let config = crate::RuntimeConfig::default();
2508 assert_eq!(
2509 config.warm_concurrency,
2510 crate::config::DEFAULT_WARM_CONCURRENCY
2511 );
2512 assert_eq!(
2513 config.maintenance_concurrency,
2514 crate::config::DEFAULT_MAINTENANCE_CONCURRENCY
2515 );
2516 crate::resource_admission::WorkClassLimits::validate(
2517 config.warm_concurrency,
2518 config.maintenance_concurrency,
2519 )
2520 .unwrap();
2521 }
2522}