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, EntityEmbeddingFields, LegacyEmbedDevice};
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#[path = "engine_config_computer.rs"]
29mod computer;
30pub use computer::{
31 read_computer_key, ComputerEndpoint, ComputerKey, ComputerKeyError, ComputerKeyRefusal,
32 ComputerSectionConfig, COMMAND_RUNNING_PACKS, COMPUTER_ROUTABLE_PACKS,
33 DEFAULT_COMPUTER_CALL_TIMEOUT_S, MAX_COMPUTER_CALL_TIMEOUT_S, MAX_COMPUTER_KEY_BYTES,
34};
35
36#[path = "engine_config_share.rs"]
37mod share;
38pub use share::{
39 ShareSectionConfig, ShareTargetConfig, DEFAULT_SHARE_FILES, DEFAULT_SHARE_TOTAL_BYTES,
40 MAX_SHARE_FILES, MAX_SHARE_FILE_BYTES, MAX_SHARE_TOTAL_BYTES,
41};
42
43#[derive(Debug, Error)]
47pub enum ConfigError {
48 #[error("[storage.blob] backend = \"s3\" requires the blob-s3 feature")]
49 BlobS3FeatureDisabled,
50
51 #[error(transparent)]
52 Credential(#[from] crate::credentials::CredentialError),
53
54 #[error("mount configuration: {reason}")]
55 InvalidMountConfig { reason: String },
56
57 #[error("channel configuration: {reason}")]
58 InvalidChannelConfig { reason: String },
59
60 #[error("config file I/O: {0}")]
61 Io(#[from] std::io::Error),
62
63 #[error("config TOML parse error in {path}: {source}")]
64 Parse {
65 path: PathBuf,
66 #[source]
67 source: toml::de::Error,
68 },
69
70 #[error("config TOML policy error in {path}, key {key}: {source}")]
71 SchemaParse {
72 path: PathBuf,
73 key: &'static str,
74 #[source]
75 source: Box<toml::de::Error>,
76 },
77
78 #[error("exactly one engine must be marked `default = true`; found {found}")]
79 DefaultCount { found: usize },
80
81 #[error("duplicate engine name: {name:?}")]
82 DuplicateName { name: String },
83
84 #[error(
85 "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
86 )]
87 UnknownModel { name: String, model: String },
88
89 #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
90 InvalidFusionWeight { name: String, value: f64 },
91
92 #[error(
93 "engine {name:?}: fusion_weight is not applied by current retrieval; \
94 remove it until weighted multi-engine fusion is wired"
95 )]
96 UnsupportedFusionWeight { name: String },
97
98 #[error("engine name must not be empty: {name:?}")]
99 InvalidEngineName { name: String },
100
101 #[error("engine {name:?} collides with another engine after alias canonicalization to {canonical:?}; remove the duplicate declaration")]
102 AliasCollision { name: String, canonical: String },
103
104 #[error("engine {name:?}: weight must be finite and strictly positive, got {value}")]
105 InvalidEngineWeight { name: String, value: f64 },
106
107 #[error("engine {name:?}: non-unit weight is refused until configured weights reach every activated retrieval path")]
108 UnsupportedEngineWeight { name: String },
109
110 #[error("engine {name:?}: dims must be positive and at most 4294967295, got {value}")]
111 InvalidEngineDimensions { name: String, value: i64 },
112
113 #[error(
114 "engine {name:?}: configured dims {expected} do not match provider dimensions {actual}"
115 )]
116 EngineDimensionMismatch {
117 name: String,
118 expected: i64,
119 actual: usize,
120 },
121
122 #[error("engine {name:?}: cannot mix legacy model/default/fusion_weight entries with canonical name/weight entries")]
123 EngineKeyConflict { name: String },
124
125 #[error("engines {name:?} and {other:?} share the storage key {key:?}; distinct engine identities require distinct bindings")]
126 EngineKeyCollision {
127 name: String,
128 other: String,
129 key: String,
130 },
131
132 #[error("actor.id {id:?} is not a valid namespace: {reason}")]
133 InvalidActorId { id: String, reason: String },
134
135 #[error("[actor].mailbox_readers: {reason}")]
136 InvalidMailboxReaders { reason: String },
137
138 #[error("[gate].granted_actors entry {id:?} is not a valid actor id: {reason}")]
139 InvalidGrantedActorId { id: String, reason: String },
140 #[error("[gate].deny_writes_for is invalid: {reason}")]
141 InvalidWriteDenyPatterns { reason: String },
142
143 #[error("duplicate backend name: {name:?}")]
144 DuplicateBackendName { name: String },
145
146 #[error("invalid backend name {name:?}: {reason}")]
147 InvalidBackendName { name: String, reason: String },
148
149 #[error("backend {name:?}: `served_kinds` must not be empty when declared")]
150 EmptyBackendServedKinds { name: String },
151
152 #[error("backend {name:?}: invalid disk guard configuration: {reason}")]
153 InvalidBackendDiskGuard { name: String, reason: String },
154
155 #[error(
156 "backends {first_backend:?} and {second_backend:?} name the same database but resolve \
157 different disk reserve/deadline policies"
158 )]
159 DiskGuardAliasConflict {
160 first_backend: String,
161 second_backend: String,
162 },
163
164 #[error("KHIVE_SQLITE_WAL_CEILING_BYTES must be an unsigned decimal byte count")]
165 InvalidWalCeilingEnvironment { value: String },
166
167 #[error(
168 "backend {name:?}: wal_ceiling_bytes {value} exceeds supported SQLite offset arithmetic"
169 )]
170 WalCeilingOffsetOverflow { name: String, value: u64 },
171
172 #[error(
173 "backend {name:?}: nonzero wal_ceiling_bytes {value} requires a file-backed SQLite backend"
174 )]
175 WalCeilingMemoryBackend { name: String, value: u64 },
176
177 #[error("backend {name:?}: nonzero wal_ceiling_bytes {value} requires SQLite WAL mode")]
178 WalCeilingNonWalBackend { name: String, value: u64 },
179
180 #[error(
181 "backends {first_backend:?} and {second_backend:?} name the same database at {} \
182 but resolve different WAL ceilings ({first_bytes} and {second_bytes} bytes)",
183 crate::secret_gate::bounded_masked_log_text(&path.to_string_lossy())
184 )]
185 WalCeilingAliasConflict {
186 first_backend: String,
187 second_backend: String,
188 path: PathBuf,
189 first_bytes: u64,
190 second_bytes: u64,
191 },
192
193 #[error(
194 "backend configuration leaves searchable substrate kinds {kinds:?} unserved; \
195 defined backends: {defined}"
196 )]
197 MissingBackendSearchKinds {
198 kinds: Vec<SubstrateKind>,
199 defined: String,
200 },
201
202 #[error(
203 "[packs.{pack}].backend = {backend:?} references an unknown backend; \
204 defined backends: {defined}"
205 )]
206 UnknownPackBackend {
207 pack: String,
208 backend: String,
209 defined: String,
210 },
211
212 #[error(
213 "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
214 remove it from the config or wait for a future release that implements it"
215 )]
216 UnsupportedBackendField { name: String, field: &'static str },
217
218 #[error(
219 "top-level `db = {value:?}` is not a supported config-file key; \
220 use `--db` / `KHIVE_DB` to select a single-file database, or \
221 `[[backends]].path` to declare storage backend topology"
222 )]
223 UnsupportedTopLevelDb { value: String },
224
225 #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
226 InvalidGitWriteEntry { repo: String, reason: String },
227
228 #[error("[git_write] {key}: {reason}")]
229 InvalidGitWriteConfig { key: String, reason: String },
230
231 #[error("[exec] {key}: {reason}")]
232 InvalidExecConfig { key: String, reason: String },
233
234 #[error("{entry}: {reason}")]
235 InvalidTelemetryConfig { entry: String, reason: String },
236
237 #[error("[web] {key}: {reason}")]
238 InvalidWebConfig { key: String, reason: String },
239
240 #[error("[computer].{key}: {reason}")]
241 InvalidComputerConfig { key: String, reason: String },
242
243 #[error("[actor].computer {reason}")]
244 InvalidActorComputer { reason: String },
245
246 #[error("[share].{key}: {reason}")]
247 InvalidShareConfig { key: String, reason: String },
248
249 #[error("[runtime] {key}: {reason}")]
250 InvalidRuntimeConfig { key: String, reason: String },
251
252 #[error(
253 "[runtime] blob_hydration_bytes must be between {min} and {max} bytes inclusive; got {value}"
254 )]
255 InvalidBlobHydrationBytes { value: u64, min: u64, max: u64 },
256
257 #[error("the explicitly selected config file does not exist: {path}")]
258 ExplicitConfigMissing { path: PathBuf },
259
260 #[error("[gate] configuration is not supported by this build")]
264 UnsupportedGateSection,
265
266 #[error(
267 "[display] timezone {timezone:?} is not a recognized IANA zone name (e.g. \"America/New_York\", \"UTC\")"
268 )]
269 InvalidDisplayTimezone { timezone: String },
270
271 #[error("{source} (config file: {})", path.display())]
281 InFile {
282 path: PathBuf,
283 #[source]
284 source: Box<ConfigError>,
285 },
286
287 #[error(
291 "config file {} is not the file in use (in use: {}); it was read only to look for \
292 `[actor] require_attributed`, which could not be read from it: {source}",
293 path.display(),
294 in_use.as_deref().map_or_else(|| "none".to_string(), |used| used.display().to_string())
295 )]
296 ShadowedTier {
297 path: PathBuf,
298 in_use: Option<PathBuf>,
300 #[source]
301 source: Box<ConfigError>,
302 },
303}
304
305impl ConfigError {
306 fn in_file(self, path: &Path) -> Self {
309 match self {
310 already @ (ConfigError::Parse { .. }
311 | ConfigError::SchemaParse { .. }
312 | ConfigError::ExplicitConfigMissing { .. }
313 | ConfigError::InFile { .. }) => already,
314 other => ConfigError::InFile {
315 path: path.to_path_buf(),
316 source: Box::new(other),
317 },
318 }
319 }
320}
321
322#[derive(Debug, Clone, Deserialize, Default)]
351#[serde(deny_unknown_fields)]
352pub struct ActorConfig {
353 #[serde(default)]
359 pub id: Option<String>,
360
361 #[serde(default)]
364 pub display_name: Option<String>,
365
366 #[serde(default)]
374 pub mailbox_readers: Vec<String>,
375
376 #[serde(default)]
382 pub visible_namespaces: Option<Vec<String>>,
383
384 #[serde(default)]
396 pub allowed_outbound_namespaces: Vec<String>,
397
398 #[serde(default)]
408 pub owned_namespaces: Vec<String>,
409
410 #[serde(default)]
423 pub require_attributed: bool,
424
425 #[serde(default)]
432 pub computer: Option<String>,
433}
434
435#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
442#[serde(deny_unknown_fields)]
443pub struct GateSectionConfig {
444 #[serde(default)]
446 pub granted_actors: Vec<String>,
447
448 #[serde(default)]
450 pub grant_unattributed: bool,
451
452 #[serde(default)]
455 pub deny_writes_for: Vec<String>,
456}
457
458#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
462#[serde(rename_all = "lowercase")]
463pub enum BackendKind {
464 #[default]
466 Sqlite,
467 Memory,
469}
470
471#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476pub struct ResolvedWalCeiling {
477 pub configured_bytes: u64,
479 pub effective_bytes: u64,
481 pub source: khive_db::WalCeilingSource,
483}
484
485pub fn resolve_wal_ceiling(
491 backend_field: Option<u64>,
492 env_value: Option<&str>,
493 backend_name: &str,
494 kind: BackendKind,
495 wal_mode: bool,
496 read_only: bool,
497) -> Result<ResolvedWalCeiling, ConfigError> {
498 if kind == BackendKind::Memory && backend_field.is_none() {
499 return Ok(ResolvedWalCeiling {
500 configured_bytes: 0,
501 effective_bytes: 0,
502 source: khive_db::WalCeilingSource::Default,
503 });
504 }
505 let (configured_bytes, source) = if let Some(bytes) = backend_field {
506 (bytes, khive_db::WalCeilingSource::BackendField)
507 } else if let Some(raw) = env_value {
508 if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
509 return Err(ConfigError::InvalidWalCeilingEnvironment {
510 value: raw.to_owned(),
511 });
512 }
513 let bytes = raw
514 .parse::<u64>()
515 .map_err(|_| ConfigError::InvalidWalCeilingEnvironment {
516 value: raw.to_owned(),
517 })?;
518 (bytes, khive_db::WalCeilingSource::Environment)
519 } else {
520 (0, khive_db::WalCeilingSource::Default)
521 };
522
523 if configured_bytes != 0 {
524 if i64::try_from(configured_bytes).is_err() {
525 return Err(ConfigError::WalCeilingOffsetOverflow {
526 name: backend_name.to_owned(),
527 value: configured_bytes,
528 });
529 }
530 if kind == BackendKind::Memory {
531 return Err(ConfigError::WalCeilingMemoryBackend {
532 name: backend_name.to_owned(),
533 value: configured_bytes,
534 });
535 }
536 if !wal_mode {
537 return Err(ConfigError::WalCeilingNonWalBackend {
538 name: backend_name.to_owned(),
539 value: configured_bytes,
540 });
541 }
542 }
543
544 Ok(ResolvedWalCeiling {
545 configured_bytes,
546 effective_bytes: if read_only { 0 } else { configured_bytes },
547 source,
548 })
549}
550
551#[derive(Debug, Clone, Deserialize)]
568#[serde(deny_unknown_fields)]
569pub struct BackendConfig {
570 pub name: String,
572 #[serde(default)]
574 pub kind: BackendKind,
575 pub path: Option<std::path::PathBuf>,
578 pub cache_mb: Option<u32>,
580 pub journal_mode: Option<String>,
582 #[serde(default)]
588 pub served_kinds: Option<BTreeSet<SubstrateKind>>,
589 #[serde(default)]
591 pub read_only: bool,
592 pub wal_ceiling_bytes: Option<u64>,
596 #[serde(default)]
598 pub disk_reserve_bytes: Option<u64>,
599 #[serde(default)]
601 pub disk_guard_deadline_ms: Option<u64>,
602}
603
604#[derive(Debug, Clone, Deserialize, Default)]
611pub struct CodeMapConfig {
612 #[serde(default)]
614 pub name: Option<String>,
615 #[serde(default)]
617 pub path: Option<String>,
618 #[serde(default)]
620 pub source_root: Option<String>,
621 #[serde(default, flatten)]
623 pub unknown_fields: BTreeMap<String, toml::Value>,
624}
625
626#[derive(Debug, Clone, Deserialize)]
640pub struct PackConfig {
641 #[serde(default = "default_pack_backend")]
644 pub backend: String,
645 #[serde(default)]
647 pub verbs_disabled: Vec<String>,
648 #[serde(default)]
658 pub no_embed: bool,
659}
660
661fn default_pack_backend() -> String {
662 BackendId::MAIN.to_owned()
663}
664
665#[derive(Debug, Clone, Deserialize)]
693#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
694pub enum BlobConfig {
695 Fs {
699 #[serde(default)]
700 root: Option<String>,
701 #[serde(default)]
704 floor_bytes: Option<u64>,
705 },
706 S3 {
711 bucket: String,
712 region: String,
713 #[serde(default)]
714 endpoint: Option<String>,
715 #[serde(default)]
716 prefix: Option<String>,
717 #[serde(default)]
718 allow_http: Option<bool>,
719 },
720}
721
722#[derive(Debug, Clone, Deserialize, Default)]
724#[serde(deny_unknown_fields)]
725pub struct BlobSectionConfig {
726 #[serde(default)]
728 pub file_transfers: bool,
729}
730
731#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
733#[serde(deny_unknown_fields)]
734pub struct KnowledgeSectionConfig {
735 #[serde(default)]
739 pub import_roots: Vec<std::path::PathBuf>,
740}
741
742fn names_one_repository(remote: &str) -> bool {
747 let Some(rest) = remote.strip_prefix("https://") else {
748 return false;
749 };
750 if rest.contains(['*', '?', '#', '[', ']']) {
751 return false;
752 }
753 let rest = rest.trim_end_matches('/');
754 let rest = rest.strip_suffix(".git").unwrap_or(rest);
755 let mut segments = rest.split('/');
756 let host = segments.next().unwrap_or("");
757 let path: Vec<&str> = segments.collect();
758 !host.is_empty() && path.len() >= 2 && path.iter().all(|segment| !segment.is_empty())
759}
760
761fn authority_carries_userinfo(remote: &str) -> bool {
768 let rest = match remote.split_once(':') {
769 Some((scheme, rest)) if !scheme.contains(['@', '/']) => rest,
770 _ => remote,
771 };
772 rest.trim_start_matches(['/', '\\'])
773 .split('/')
774 .next()
775 .is_some_and(|authority| authority.contains('@'))
776}
777
778fn quoted_remote(remote: &str) -> String {
782 if remote.contains('@') {
783 "an entry holding '@'".to_owned()
784 } else {
785 format!("{remote:?}")
786 }
787}
788
789#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
798#[serde(deny_unknown_fields)]
799pub struct GitDigestSectionConfig {
800 #[serde(default)]
802 pub local_roots: Vec<std::path::PathBuf>,
803 #[serde(default)]
806 pub remotes: Vec<String>,
807}
808
809#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
812#[serde(deny_unknown_fields)]
813pub struct CodeIngestSectionConfig {
814 #[serde(default)]
817 pub roots: Vec<std::path::PathBuf>,
818}
819
820impl KnowledgeSectionConfig {
821 pub fn resolved_import_roots(&self) -> Vec<std::path::PathBuf> {
824 self.import_roots
825 .iter()
826 .filter_map(|root| std::fs::canonicalize(root).ok())
827 .filter(|root| root.is_dir())
828 .collect()
829 }
830}
831
832#[derive(Debug, Clone, Deserialize, Default)]
836#[serde(deny_unknown_fields)]
837pub struct StorageSectionConfig {
838 #[serde(default)]
843 pub blob: Option<BlobConfig>,
844}
845
846#[derive(Debug, Clone, Deserialize, Serialize, Default)]
848#[serde(deny_unknown_fields)]
849pub struct BrainSectionConfig {
850 #[serde(default)]
852 pub fleet_readers: Vec<String>,
853}
854
855#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
859#[serde(rename_all = "lowercase")]
860pub enum GitRepoAccess {
861 Read,
863 #[default]
866 Write,
867}
868
869#[derive(Debug, Clone, Deserialize, Serialize)]
885pub struct GitWriteEntryConfig {
886 pub repo: String,
888 #[serde(default)]
891 pub branches: Vec<String>,
892 #[serde(default)]
894 pub access: GitRepoAccess,
895}
896
897#[derive(Debug, Clone, Deserialize, Serialize)]
909pub struct GitWriteSectionConfig {
910 #[serde(default)]
912 pub program: Option<PathBuf>,
913 #[serde(default)]
914 pub allowed: Vec<GitWriteEntryConfig>,
915 #[serde(default)]
916 pub actors: BTreeMap<String, GitWriteActorConfig>,
917 #[serde(default)]
918 pub repositories: BTreeMap<String, GitWriteRepositoryConfig>,
919 #[serde(default = "default_git_credential_resolver")]
920 pub credential_resolver: Vec<String>,
921 #[serde(default)]
922 pub contract_faults: bool,
923 #[serde(default)]
924 pub fault: Option<String>,
925}
926
927#[derive(Debug, Clone, Deserialize, Serialize)]
928#[serde(deny_unknown_fields)]
929pub struct GitWriteRepositoryConfig {
930 pub remote: String,
932 pub slug: String,
934 pub visibility: String,
935 #[serde(default)]
941 pub merge_refusals: Vec<String>,
942 #[serde(default, skip_serializing_if = "Option::is_none")]
946 pub author: Option<GitWriteAuthorConfig>,
947}
948
949#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
951#[serde(deny_unknown_fields)]
952pub struct GitWriteAuthorConfig {
953 pub name: String,
954 pub email: String,
955}
956
957impl GitWriteRepositoryConfig {
958 pub const MERGE_REFUSALS: [&'static str; 2] = ["opener", "last_pusher"];
959
960 pub fn refuses_merge_by(&self, entry: &str) -> bool {
962 self.merge_refusals.iter().any(|listed| listed == entry)
963 }
964}
965
966#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
967#[serde(deny_unknown_fields)]
968pub struct GitWriteActorConfig {
969 pub name: String,
970 pub email: String,
971 pub credential_ref: String,
972 pub platform_identity: String,
973}
974
975fn default_git_credential_resolver() -> Vec<String> {
976 [
977 "/usr/bin/security",
978 "find-generic-password",
979 "-w",
980 "-s",
981 "{ref}",
982 ]
983 .into_iter()
984 .map(str::to_string)
985 .collect()
986}
987
988impl Default for GitWriteSectionConfig {
989 fn default() -> Self {
990 Self {
991 program: None,
992 allowed: Vec::new(),
993 actors: BTreeMap::new(),
994 repositories: BTreeMap::new(),
995 credential_resolver: default_git_credential_resolver(),
996 contract_faults: false,
997 fault: None,
998 }
999 }
1000}
1001
1002impl GitWriteSectionConfig {
1003 pub fn git_program(&self) -> &Path {
1004 self.program.as_deref().unwrap_or_else(|| Path::new("git"))
1005 }
1006
1007 pub fn validate_dev_loop(&self) -> Result<(), ConfigError> {
1008 let invalid = |key: &str, reason: &str| ConfigError::InvalidGitWriteConfig {
1009 key: key.to_string(),
1010 reason: reason.to_string(),
1011 };
1012 if let Some(program) = &self.program {
1013 if !program.is_absolute() {
1014 return Err(invalid("git_write.program", "must be absolute"));
1015 }
1016 let metadata = std::fs::metadata(program).map_err(|error| {
1017 if error.kind() == std::io::ErrorKind::NotFound {
1018 invalid("git_write.program", "does not exist")
1019 } else {
1020 invalid("git_write.program", &format!("is not executable: {error}"))
1021 }
1022 })?;
1023 #[cfg(unix)]
1024 let executable = {
1025 use std::os::unix::fs::PermissionsExt;
1026 metadata.permissions().mode() & 0o111 != 0
1027 };
1028 #[cfg(windows)]
1029 let executable = program
1030 .extension()
1031 .and_then(|extension| extension.to_str())
1032 .is_some_and(|extension| {
1033 extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
1034 });
1035 #[cfg(not(any(unix, windows)))]
1036 let executable = false;
1037 if !metadata.is_file() || !executable {
1038 return Err(invalid("git_write.program", "is not executable"));
1039 }
1040 }
1041 if self.contract_faults && !cfg!(feature = "contract-faults") {
1042 tracing::error!(
1043 target: "khive.boot",
1044 "[git_write] contract_faults requires the test-only contract-faults build feature"
1045 );
1046 return Err(invalid(
1047 "contract_faults",
1048 "requires the test-only contract-faults build feature",
1049 ));
1050 }
1051 if let Some(fault) = &self.fault {
1052 if !self.contract_faults {
1053 return Err(invalid("fault", "requires contract_faults = true"));
1054 }
1055 let valid = fault.split_once(':').is_some_and(|(verb, point)| {
1056 matches!(verb, "git.push" | "git.pr_merge")
1057 && matches!(
1058 point,
1059 "reply-lost-after-effect" | "audit-fails-after-effect"
1060 )
1061 });
1062 if !valid {
1063 return Err(invalid("fault", "unsupported contract fault selector"));
1064 }
1065 }
1066 for (path, repository) in &self.repositories {
1067 let key = format!("repositories.{path}.merge_refusals");
1068 let mut seen: Vec<&str> = Vec::new();
1069 for entry in &repository.merge_refusals {
1070 if !GitWriteRepositoryConfig::MERGE_REFUSALS.contains(&entry.as_str()) {
1071 return Err(invalid(&key, "entries must be opener or last_pusher"));
1072 }
1073 if seen.contains(&entry.as_str()) {
1074 return Err(invalid(&key, "entries must not repeat"));
1075 }
1076 seen.push(entry);
1077 }
1078 if let Some(author) = &repository.author {
1079 let invalid_value = |value: &str| {
1082 value.trim().is_empty()
1083 || value
1084 .chars()
1085 .any(|c| c.is_control() || matches!(c, '<' | '>'))
1086 };
1087 if invalid_value(&author.name) || invalid_value(&author.email) {
1088 return Err(invalid(
1089 &format!("repositories.{path}.author"),
1090 "name and email must be non-empty and hold no control character or angle bracket",
1091 ));
1092 }
1093 }
1094 }
1095 if !cfg!(unix)
1098 && self.actors.is_empty()
1099 && self.credential_resolver == default_git_credential_resolver()
1100 {
1101 return Ok(());
1102 }
1103 let argv = &self.credential_resolver;
1104 let Some(program) = argv.first() else {
1105 return Err(invalid("credential_resolver", "argv must not be empty"));
1106 };
1107 let program_path = Path::new(program);
1108 if !program_path.is_absolute() {
1109 return Err(invalid(
1110 "credential_resolver",
1111 "argv[0] must be an absolute path",
1112 ));
1113 }
1114 let program_name = program_path
1115 .file_name()
1116 .and_then(|name| name.to_str())
1117 .unwrap_or_default()
1118 .to_ascii_lowercase();
1119 if matches!(
1120 program_name.trim_end_matches(".exe"),
1121 "sh" | "bash"
1122 | "dash"
1123 | "zsh"
1124 | "ksh"
1125 | "fish"
1126 | "csh"
1127 | "tcsh"
1128 | "cmd"
1129 | "powershell"
1130 | "pwsh"
1131 | "env"
1132 ) {
1133 return Err(invalid(
1134 "credential_resolver",
1135 "shell or env launcher is not allowed",
1136 ));
1137 }
1138 if argv.iter().any(|arg| arg.chars().any(char::is_control)) {
1139 return Err(invalid(
1140 "credential_resolver",
1141 "argv must not contain control characters",
1142 ));
1143 }
1144 if program.contains(['{', '}'])
1145 || argv[1..]
1146 .iter()
1147 .any(|arg| arg != "{ref}" && arg.contains(['{', '}']))
1148 {
1149 return Err(invalid(
1150 "credential_resolver",
1151 "{ref} must be a complete argument and is the only allowed template",
1152 ));
1153 }
1154 if !argv[1..].iter().any(|arg| arg == "{ref}") {
1155 return Err(invalid(
1156 "credential_resolver",
1157 "argv must contain a {ref} argument",
1158 ));
1159 }
1160 for (actor, identity) in &self.actors {
1161 if actor.trim().is_empty() || actor.chars().any(char::is_control) {
1162 return Err(invalid(
1163 "actors",
1164 "actor labels must be nonempty and contain no control characters",
1165 ));
1166 }
1167 for (field, value) in [
1168 ("name", &identity.name),
1169 ("email", &identity.email),
1170 ("credential_ref", &identity.credential_ref),
1171 ("platform_identity", &identity.platform_identity),
1172 ] {
1173 if value.trim().is_empty() || value.chars().any(char::is_control) {
1174 return Err(invalid(
1175 &format!("actors.{actor}.{field}"),
1176 "must be nonempty and contain no control characters",
1177 ));
1178 }
1179 }
1180 if identity.name.contains(['<', '>']) || identity.email.contains(['<', '>']) {
1181 return Err(invalid(
1182 &format!("actors.{actor}"),
1183 "name and email must not contain Git identity delimiters",
1184 ));
1185 }
1186 }
1187 Ok(())
1188 }
1189}
1190
1191#[derive(Debug, Clone, Deserialize, Default)]
1196pub struct ExecLimitsConfig {
1197 #[serde(default)]
1198 pub cpu_seconds: Option<u64>,
1199 #[serde(default)]
1200 pub address_space: Option<u64>,
1201 #[serde(default)]
1202 pub file_size: Option<u64>,
1203 #[serde(default)]
1204 pub nproc: Option<u64>,
1205}
1206
1207#[derive(Debug, Clone, Deserialize, Default)]
1230#[serde(deny_unknown_fields)]
1231pub struct ExecSectionConfig {
1232 #[serde(default)]
1233 pub root: Option<String>,
1234 #[serde(default)]
1235 pub read_roots: Vec<String>,
1236 #[serde(default)]
1240 pub cache_roots: Vec<String>,
1241 #[serde(default)]
1242 pub env: Vec<String>,
1243 #[serde(default)]
1244 pub never: Vec<String>,
1245 #[serde(default)]
1246 pub max_output_bytes: Option<u64>,
1247 #[serde(default)]
1248 pub timeout_default_s: Option<f64>,
1249 #[serde(default)]
1250 pub timeout_max_s: Option<f64>,
1251 #[serde(default)]
1253 pub binary_digest_timeout_s: Option<u64>,
1254 #[serde(default)]
1255 pub keep: bool,
1256 #[serde(default)]
1257 pub limits: ExecLimitsConfig,
1258 #[serde(default)]
1261 pub tool_profiles: Vec<ExecToolProfileConfig>,
1262}
1263
1264#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
1276#[serde(deny_unknown_fields)]
1277pub struct ExecToolProfileConfig {
1278 pub tool: String,
1280 #[serde(default)]
1283 pub metal: bool,
1284 #[serde(default)]
1290 pub unix_sockets: bool,
1291 #[serde(default)]
1293 pub files: Vec<String>,
1294 #[serde(default)]
1297 pub list_dirs: Vec<String>,
1298}
1299
1300pub const DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 10;
1301pub const MAX_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 60;
1302
1303#[derive(Debug, Clone, Deserialize, Serialize)]
1312#[serde(deny_unknown_fields)]
1313pub struct WebAllowlistEntry {
1314 pub host: String,
1315}
1316
1317#[derive(Debug, Clone, Deserialize, Serialize)]
1324#[serde(deny_unknown_fields)]
1325pub struct WebCredentialConfig {
1326 pub name: String,
1328 pub env_var: String,
1330 pub hosts: Vec<String>,
1333}
1334
1335#[derive(Debug, Clone, Deserialize, Serialize)]
1339#[serde(deny_unknown_fields)]
1340pub struct WebFixtureResult {
1341 pub title: String,
1342 pub url: String,
1343 pub snippet: String,
1344}
1345
1346#[derive(Debug, Clone, Deserialize, Serialize)]
1350#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
1351pub enum WebSearchProviderConfig {
1352 Fixture {
1354 name: String,
1355 #[serde(default)]
1356 default: bool,
1357 results: Vec<WebFixtureResult>,
1358 },
1359 Http {
1366 name: String,
1367 #[serde(default)]
1368 default: bool,
1369 url_template: String,
1370 #[serde(default)]
1371 api_key_env: Option<String>,
1372 #[serde(default)]
1379 hosts: Vec<String>,
1380 },
1381}
1382
1383impl WebSearchProviderConfig {
1384 pub fn name(&self) -> &str {
1385 match self {
1386 WebSearchProviderConfig::Fixture { name, .. } => name,
1387 WebSearchProviderConfig::Http { name, .. } => name,
1388 }
1389 }
1390
1391 pub fn is_default(&self) -> bool {
1392 match self {
1393 WebSearchProviderConfig::Fixture { default, .. } => *default,
1394 WebSearchProviderConfig::Http { default, .. } => *default,
1395 }
1396 }
1397}
1398
1399#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1433#[serde(deny_unknown_fields)]
1434pub struct WebSectionConfig {
1435 #[serde(default)]
1436 pub timeout_default_s: Option<u64>,
1437 #[serde(default)]
1438 pub timeout_max_s: Option<u64>,
1439 #[serde(default)]
1440 pub max_bytes_default: Option<u64>,
1441 #[serde(default)]
1442 pub max_bytes_max: Option<u64>,
1443 #[serde(default)]
1444 pub search_limit_default: Option<u32>,
1445 #[serde(default)]
1446 pub search_limit_max: Option<u32>,
1447 #[serde(default)]
1448 pub allowlist: Vec<WebAllowlistEntry>,
1449 #[serde(default)]
1450 pub credentials: Vec<WebCredentialConfig>,
1451 #[serde(default)]
1452 pub search_providers: Vec<WebSearchProviderConfig>,
1453 #[serde(default)]
1457 pub read_roots: Vec<String>,
1458}
1459
1460#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1462pub struct WebCeilings {
1463 pub timeout_default_s: u64,
1464 pub timeout_max_s: u64,
1465 pub max_bytes_default: u64,
1466 pub max_bytes_max: u64,
1467 pub search_limit_default: u32,
1468 pub search_limit_max: u32,
1469}
1470
1471impl Default for WebCeilings {
1472 fn default() -> Self {
1473 Self {
1474 timeout_default_s: 30,
1475 timeout_max_s: 120,
1476 max_bytes_default: 5 * 1024 * 1024,
1477 max_bytes_max: 50 * 1024 * 1024,
1478 search_limit_default: 10,
1479 search_limit_max: 50,
1480 }
1481 }
1482}
1483
1484impl WebSectionConfig {
1485 pub fn resolved_ceilings(&self) -> Result<WebCeilings, ConfigError> {
1486 let defaults = WebCeilings::default();
1487 let bounds = WebCeilings {
1488 timeout_default_s: self.timeout_default_s.unwrap_or(defaults.timeout_default_s),
1489 timeout_max_s: self.timeout_max_s.unwrap_or(defaults.timeout_max_s),
1490 max_bytes_default: self.max_bytes_default.unwrap_or(defaults.max_bytes_default),
1491 max_bytes_max: self.max_bytes_max.unwrap_or(defaults.max_bytes_max),
1492 search_limit_default: self
1493 .search_limit_default
1494 .unwrap_or(defaults.search_limit_default),
1495 search_limit_max: self.search_limit_max.unwrap_or(defaults.search_limit_max),
1496 };
1497 for (key, default, maximum, maximum_key) in [
1498 (
1499 "timeout_default_s",
1500 bounds.timeout_default_s,
1501 bounds.timeout_max_s,
1502 "timeout_max_s",
1503 ),
1504 (
1505 "max_bytes_default",
1506 bounds.max_bytes_default,
1507 bounds.max_bytes_max,
1508 "max_bytes_max",
1509 ),
1510 (
1511 "search_limit_default",
1512 u64::from(bounds.search_limit_default),
1513 u64::from(bounds.search_limit_max),
1514 "search_limit_max",
1515 ),
1516 ] {
1517 if default == 0 || default > maximum {
1518 return Err(ConfigError::InvalidWebConfig {
1519 key: key.into(),
1520 reason: format!(
1521 "resolved default must be positive and not exceed {maximum_key}={maximum}"
1522 ),
1523 });
1524 }
1525 }
1526 if std::time::Instant::now()
1527 .checked_add(std::time::Duration::from_secs(bounds.timeout_max_s))
1528 .is_none()
1529 {
1530 return Err(ConfigError::InvalidWebConfig {
1531 key: "timeout_max_s".into(),
1532 reason: "cannot be represented as a request deadline".into(),
1533 });
1534 }
1535 Ok(bounds)
1536 }
1537
1538 pub fn validate(&self) -> Result<(), ConfigError> {
1539 self.resolved_ceilings()?;
1540 let invalid = |key: &str, reason: &str| ConfigError::InvalidWebConfig {
1541 key: key.to_string(),
1542 reason: reason.to_string(),
1543 };
1544 let mut seen_hosts = std::collections::HashSet::new();
1545 for entry in &self.allowlist {
1546 let normalized = entry.host.trim().trim_end_matches('.').to_ascii_lowercase();
1547 if normalized.is_empty() {
1548 return Err(invalid("allowlist.host", "must not be empty"));
1549 }
1550 if !seen_hosts.insert(normalized) {
1551 return Err(invalid("allowlist.host", "duplicate host entry"));
1552 }
1553 }
1554 let mut seen_credentials = std::collections::HashSet::new();
1555 for credential in &self.credentials {
1556 if credential.name.trim().is_empty() {
1557 return Err(invalid("credentials.name", "must not be empty"));
1558 }
1559 if !seen_credentials.insert(credential.name.clone()) {
1560 return Err(invalid("credentials.name", "duplicate credential name"));
1561 }
1562 if credential.env_var.trim().is_empty() {
1563 return Err(invalid("credentials.env_var", "must not be empty"));
1564 }
1565 if credential.hosts.is_empty() {
1566 return Err(invalid(
1567 "credentials.hosts",
1568 "must name at least one host or suffix",
1569 ));
1570 }
1571 }
1572 let mut seen_providers = std::collections::HashSet::new();
1573 let mut default_count = 0;
1574 for provider in &self.search_providers {
1575 let name = provider.name();
1576 if name.trim().is_empty() {
1577 return Err(invalid("search_providers.name", "must not be empty"));
1578 }
1579 if !seen_providers.insert(name.to_string()) {
1580 return Err(invalid("search_providers.name", "duplicate provider name"));
1581 }
1582 if provider.is_default() {
1583 default_count += 1;
1584 }
1585 if let WebSearchProviderConfig::Http {
1586 url_template,
1587 api_key_env,
1588 hosts,
1589 ..
1590 } = provider
1591 {
1592 if !url_template.contains("{query}") {
1593 return Err(invalid(
1594 "search_providers.url_template",
1595 "must contain the literal substring {query}",
1596 ));
1597 }
1598 if api_key_env.is_some() && hosts.is_empty() {
1599 return Err(invalid(
1600 "search_providers.hosts",
1601 "an api_key_env-bearing provider must name at least one host or suffix",
1602 ));
1603 }
1604 }
1605 }
1606 if default_count > 1 {
1607 return Err(invalid(
1608 "search_providers",
1609 "at most one provider may set default = true",
1610 ));
1611 }
1612 Ok(())
1613 }
1614}
1615
1616#[derive(Debug, Clone, Deserialize, Serialize)]
1619pub struct SchemaSectionConfig {
1620 #[serde(default = "schema_strict_default")]
1621 pub strict: bool,
1622}
1623
1624fn schema_strict_default() -> bool {
1625 true
1626}
1627
1628impl Default for SchemaSectionConfig {
1629 fn default() -> Self {
1630 Self { strict: true }
1631 }
1632}
1633
1634#[derive(Deserialize)]
1637struct SchemaSyntaxProbe {
1638 #[serde(default, deserialize_with = "deserialize_schema_table")]
1639 schema: SchemaSectionConfig,
1640}
1641
1642fn deserialize_schema_table<'de, D>(deserializer: D) -> Result<SchemaSectionConfig, D::Error>
1643where
1644 D: serde::Deserializer<'de>,
1645{
1646 struct SchemaTableVisitor;
1647 impl<'de> serde::de::Visitor<'de> for SchemaTableVisitor {
1648 type Value = SchemaSectionConfig;
1649
1650 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1651 formatter.write_str("a schema configuration table")
1652 }
1653
1654 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1655 where
1656 A: serde::de::MapAccess<'de>,
1657 {
1658 SchemaSectionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
1659 }
1660 }
1661 deserializer.deserialize_map(SchemaTableVisitor)
1662}
1663
1664#[derive(Debug, Clone, Deserialize, Default)]
1690pub struct KhiveConfig {
1691 #[serde(default)]
1693 pub schema: SchemaSectionConfig,
1694
1695 #[serde(default, deserialize_with = "embed_batch::deserialize_table")]
1697 pub embed: EmbedSectionConfig,
1698
1699 #[serde(skip)]
1701 pub credentials: Vec<crate::credentials::CredentialConfig>,
1702
1703 #[serde(skip)]
1704 pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
1705
1706 #[serde(default)]
1709 pub channel: crate::channel_section::ChannelSectionConfig,
1710
1711 #[serde(default)]
1712 pub mounts: Vec<crate::mount_config::MountConfig>,
1713
1714 #[serde(default)]
1720 pub db: Option<String>,
1721
1722 #[serde(default)]
1724 pub engines: Vec<EngineConfig>,
1725
1726 #[serde(skip)]
1730 pub engines_declared: bool,
1731
1732 #[serde(default)]
1740 pub actor: ActorConfig,
1741
1742 #[serde(default)]
1746 pub gate: Option<GateSectionConfig>,
1747
1748 #[serde(default)]
1750 pub runtime: RuntimeSectionConfig,
1751
1752 #[serde(default)]
1757 pub backends: Vec<BackendConfig>,
1758
1759 #[serde(default)]
1761 pub code_map_root: Option<String>,
1762
1763 #[serde(default)]
1765 pub code_maps: Vec<CodeMapConfig>,
1766
1767 #[serde(default)]
1773 pub packs: std::collections::HashMap<String, PackConfig>,
1774
1775 #[serde(default)]
1777 pub brain: BrainSectionConfig,
1778
1779 #[serde(default)]
1783 pub git_write: GitWriteSectionConfig,
1784
1785 #[serde(default)]
1787 pub blob: BlobSectionConfig,
1788
1789 #[serde(default)]
1791 pub knowledge: KnowledgeSectionConfig,
1792
1793 #[serde(default)]
1795 pub git_digest: GitDigestSectionConfig,
1796
1797 #[serde(default)]
1799 pub code_ingest: CodeIngestSectionConfig,
1800
1801 #[serde(default)]
1804 pub storage: StorageSectionConfig,
1805
1806 #[serde(default)]
1809 pub exec: ExecSectionConfig,
1810
1811 #[serde(default)]
1813 pub telemetry: crate::telemetry_config::TelemetryConfig,
1814
1815 #[serde(default)]
1819 pub display: DisplaySectionConfig,
1820
1821 #[serde(default)]
1826 pub web: WebSectionConfig,
1827
1828 #[serde(default)]
1833 pub computer: Option<ComputerSectionConfig>,
1834
1835 #[serde(default)]
1839 pub share: Option<ShareSectionConfig>,
1840}
1841
1842#[derive(Debug, Clone, Deserialize, Default)]
1849pub struct RuntimeSectionConfig {
1850 #[serde(default)]
1853 pub warm_concurrency: Option<usize>,
1854
1855 #[serde(default)]
1858 pub maintenance_concurrency: Option<usize>,
1859
1860 #[serde(default)]
1863 pub packs: Option<Vec<String>>,
1864
1865 #[serde(default)]
1872 pub brain_profile: Option<String>,
1873
1874 #[serde(default)]
1881 pub default_output_format: Option<OutputFormat>,
1882
1883 #[serde(default)]
1890 pub blob_hydration_bytes: Option<u64>,
1891}
1892
1893#[derive(Debug, Clone, Deserialize, Default)]
1901pub struct DisplaySectionConfig {
1902 #[serde(default)]
1908 pub timezone: Option<String>,
1909}
1910
1911impl KhiveConfig {
1912 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
1928 let resolved = match path {
1929 Some(p) => p.to_path_buf(),
1930 None => PathBuf::from(".khive/config.toml"),
1931 };
1932
1933 if !resolved.exists() {
1934 return Ok(None);
1935 }
1936
1937 let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
1940 let raw = std::fs::read_to_string(&resolved)
1941 .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
1942 let mut document: toml::Value =
1943 toml::from_str(&raw).map_err(|source| ConfigError::Parse {
1944 path: diagnostic_path.clone(),
1945 source,
1946 })?;
1947 let schema_probe: SchemaSyntaxProbe =
1948 toml::from_str(&raw).map_err(|source| ConfigError::SchemaParse {
1949 path: diagnostic_path.clone(),
1950 key: if document
1951 .get("schema")
1952 .is_some_and(|value| !value.is_table())
1953 {
1954 "schema"
1955 } else {
1956 "schema.strict"
1957 },
1958 source: Box::new(source),
1959 })?;
1960 let unknown_schema_keys: Vec<String> = document
1961 .get("schema")
1962 .and_then(toml::Value::as_table)
1963 .map(|table| {
1964 table
1965 .keys()
1966 .filter(|key| key.as_str() != "strict")
1967 .cloned()
1968 .collect()
1969 })
1970 .unwrap_or_default();
1971 let (embed, unknown_embed_keys) = embed_batch::parse(&raw, &document, &diagnostic_path)?;
1972 let engines_declared = peers::normalize_engine_input(&mut document, &diagnostic_path)
1973 .map_err(|error| error.in_file(&diagnostic_path))?;
1974 if let Some(table) = document.as_table_mut() {
1977 table.remove("embed");
1978 }
1979 let mut cfg: KhiveConfig = document.try_into().map_err(|source| ConfigError::Parse {
1980 path: diagnostic_path.clone(),
1981 source,
1982 })?;
1983 cfg.schema = schema_probe.schema;
1984 cfg.embed = embed;
1985 cfg.engines_declared = engines_declared;
1986 crate::credentials::read_tables(&raw, &mut cfg)
1987 .map_err(|error| ConfigError::from(error).in_file(&diagnostic_path))?;
1988 cfg.validate()
1989 .map_err(|error| error.in_file(&diagnostic_path))?;
1990 for engine in &mut cfg.engines {
1991 engine.name = canonical_engine_name(&engine.name);
1992 }
1993 for key in unknown_schema_keys {
1994 tracing::warn!(target: "khive.config.schema",
1995 key = %crate::secret_gate::bounded_masked_log_text(&key),
1996 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1997 "ignoring unknown schema configuration key");
1998 }
1999 for key in unknown_embed_keys {
2000 tracing::warn!(target: "khive.config.embed",
2001 key = %crate::secret_gate::bounded_masked_log_text(&key),
2002 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
2003 "ignoring unknown embed configuration key");
2004 }
2005 Ok(Some(cfg))
2006 }
2007
2008 pub fn load_with_home_fallback(
2036 path: Option<&Path>,
2037 db_path: Option<&Path>,
2038 ) -> Result<Option<Self>, ConfigError> {
2039 Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
2040 }
2041
2042 pub fn load_with_home_fallback_and_source(
2050 path: Option<&Path>,
2051 db_path: Option<&Path>,
2052 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
2053 if let Some(p) = path {
2061 if !p.exists() {
2062 return Err(ConfigError::ExplicitConfigMissing {
2063 path: p.to_path_buf(),
2064 });
2065 }
2066 return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
2067 }
2068
2069 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
2071 let home_root = std::env::var_os("HOME").map(PathBuf::from);
2072 Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
2073 }
2074
2075 #[cfg(test)]
2084 pub(crate) fn load_with_roots(
2085 project_root: &Path,
2086 home_root: Option<&Path>,
2087 db_path: Option<&Path>,
2088 ) -> Result<Option<Self>, ConfigError> {
2089 Ok(
2090 Self::load_with_roots_and_source(project_root, home_root, db_path)?
2091 .map(|(config, _)| config),
2092 )
2093 }
2094
2095 fn load_with_roots_and_source(
2096 project_root: &Path,
2097 home_root: Option<&Path>,
2098 db_path: Option<&Path>,
2099 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
2100 let tier2 = project_root.join("khive.toml");
2102 if tier2.exists() {
2103 return Ok(Self::load(Some(&tier2))?
2104 .map(|config| (config, Self::diagnostic_config_path(&tier2))));
2105 }
2106
2107 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
2110 if tier3.exists() {
2111 return Ok(Self::load(Some(&tier3))?
2112 .map(|config| (config, Self::diagnostic_config_path(&tier3))));
2113 }
2114
2115 if let Some(home) = home_root {
2117 let tier4 = home.join(".khive/config.toml");
2118 if tier4.exists() {
2119 return Ok(Self::load(Some(&tier4))?
2120 .map(|config| (config, Self::diagnostic_config_path(&tier4))));
2121 }
2122 }
2123
2124 Ok(None)
2125 }
2126
2127 pub fn require_attributed_in_any_tier(
2131 path: Option<&Path>,
2132 db_path: Option<&Path>,
2133 ) -> Result<bool, ConfigError> {
2134 if let Some(p) = path {
2135 if !p.exists() {
2136 return Err(ConfigError::ExplicitConfigMissing {
2137 path: p.to_path_buf(),
2138 });
2139 }
2140 return Ok(Self::load(Some(p))?.is_some_and(|cfg| cfg.actor.require_attributed));
2141 }
2142 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
2143 let home_root = std::env::var_os("HOME").map(PathBuf::from);
2144 Self::require_attributed_in_tiers(&project_root, home_root.as_deref(), db_path)
2145 }
2146
2147 pub(crate) fn require_attributed_in_tiers(
2150 project_root: &Path,
2151 home_root: Option<&Path>,
2152 db_path: Option<&Path>,
2153 ) -> Result<bool, ConfigError> {
2154 let mut files = vec![
2155 project_root.join("khive.toml"),
2156 Self::project_config_anchor_dir(db_path, project_root).join("config.toml"),
2157 project_root.join(".khive/config.toml"),
2158 ];
2159 let home_file = home_root.map(|home| home.join(".khive/config.toml"));
2160 let in_use = [Some(&files[0]), Some(&files[1]), home_file.as_ref()]
2162 .into_iter()
2163 .flatten()
2164 .find(|file| file.exists())
2165 .cloned();
2166 files.extend(home_file);
2167 files.dedup();
2168 for file in files.iter().filter(|file| file.exists()) {
2169 let loaded = Self::load(Some(file)).map_err(|source| match &in_use {
2170 Some(used) if used == file => source,
2171 _ => ConfigError::ShadowedTier {
2172 path: Self::diagnostic_config_path(file),
2173 in_use: in_use.as_deref().map(Self::diagnostic_config_path),
2174 source: Box::new(source),
2175 },
2176 })?;
2177 if loaded.is_some_and(|cfg| cfg.actor.require_attributed) {
2178 return Ok(true);
2179 }
2180 }
2181 Ok(false)
2182 }
2183
2184 fn diagnostic_config_path(path: &Path) -> PathBuf {
2185 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
2186 }
2187
2188 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
2214 let Some(db_path) = db_path else {
2215 return project_root.join(".khive");
2216 };
2217
2218 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
2219 if db_path.is_absolute() {
2220 db_path.to_path_buf()
2221 } else {
2222 project_root.join(db_path)
2223 }
2224 });
2225
2226 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
2227
2228 if db_dir.file_name().is_some_and(|name| name == ".khive") {
2229 db_dir
2230 } else {
2231 db_dir.join(".khive")
2232 }
2233 }
2234
2235 pub fn validate(&self) -> Result<(), ConfigError> {
2241 #[cfg(not(feature = "blob-s3"))]
2242 if matches!(&self.storage.blob, Some(BlobConfig::S3 { .. })) {
2243 return Err(ConfigError::BlobS3FeatureDisabled);
2244 }
2245
2246 if let Some(root) = self
2247 .knowledge
2248 .import_roots
2249 .iter()
2250 .find(|root| !root.is_absolute())
2251 {
2252 return Err(ConfigError::InvalidRuntimeConfig {
2253 key: "knowledge.import_roots".to_owned(),
2254 reason: format!("{root:?} is not an absolute path"),
2255 });
2256 }
2257 if let Some(root) = self
2258 .git_digest
2259 .local_roots
2260 .iter()
2261 .find(|root| !root.is_absolute())
2262 {
2263 return Err(ConfigError::InvalidRuntimeConfig {
2264 key: "git_digest.local_roots".to_owned(),
2265 reason: format!("{root:?} is not an absolute path"),
2266 });
2267 }
2268 if let Some(root) = self
2269 .code_ingest
2270 .roots
2271 .iter()
2272 .find(|root| !root.is_absolute())
2273 {
2274 return Err(ConfigError::InvalidRuntimeConfig {
2275 key: "code_ingest.roots".to_owned(),
2276 reason: format!("{root:?} is not an absolute path"),
2277 });
2278 }
2279 if self
2283 .git_digest
2284 .remotes
2285 .iter()
2286 .any(|remote| authority_carries_userinfo(remote))
2287 {
2288 return Err(ConfigError::InvalidRuntimeConfig {
2289 key: "git_digest.remotes".to_owned(),
2290 reason: "an entry carries a user name or password before its host; \
2291 list the repository URL without credentials"
2292 .to_owned(),
2293 });
2294 }
2295 if let Some(remote) = self
2296 .git_digest
2297 .remotes
2298 .iter()
2299 .find(|remote| !remote.starts_with("https://"))
2300 {
2301 return Err(ConfigError::InvalidRuntimeConfig {
2302 key: "git_digest.remotes".to_owned(),
2303 reason: format!("{} is not an https:// URL", quoted_remote(remote)),
2304 });
2305 }
2306 if let Some(remote) = self
2307 .git_digest
2308 .remotes
2309 .iter()
2310 .find(|remote| !names_one_repository(remote))
2311 {
2312 return Err(ConfigError::InvalidRuntimeConfig {
2313 key: "git_digest.remotes".to_owned(),
2314 reason: format!(
2315 "{} does not name one repository: an entry is a full https://host/owner/repo URL, \
2316 never an owner, a host or a pattern",
2317 quoted_remote(remote)
2318 ),
2319 });
2320 }
2321
2322 let warm = self
2323 .runtime
2324 .warm_concurrency
2325 .unwrap_or(crate::config::DEFAULT_WARM_CONCURRENCY);
2326 let maintenance = self
2327 .runtime
2328 .maintenance_concurrency
2329 .unwrap_or(crate::config::DEFAULT_MAINTENANCE_CONCURRENCY);
2330 crate::resource_admission::WorkClassLimits::validate(warm, maintenance).map_err(
2331 |error| {
2332 let key = match &error {
2333 crate::resource_admission::ResourceError::InvalidLimit {
2334 class: crate::resource_admission::WorkClass::Warm,
2335 ..
2336 } => "warm_concurrency",
2337 crate::resource_admission::ResourceError::InvalidLimit {
2338 class: crate::resource_admission::WorkClass::Maintenance,
2339 ..
2340 } => "maintenance_concurrency",
2341 _ => "background_concurrency",
2342 };
2343 ConfigError::InvalidRuntimeConfig {
2344 key: key.to_owned(),
2345 reason: error.to_string(),
2346 }
2347 },
2348 )?;
2349
2350 crate::mount_config::validate_mounts(&self.mounts)?;
2351 self.git_write.validate_dev_loop()?;
2352 self.telemetry.validate()?;
2353 self.web.validate()?;
2354 if let Some(computer) = &self.computer {
2355 computer.validate()?;
2356 }
2357 computer::validate_actor_computer(self.computer.as_ref(), self.actor.computer.as_deref())?;
2358 if let Some(share) = &self.share {
2359 share.validate()?;
2360 }
2361 crate::credentials::CredentialConfig::validate_all(&self.credentials)?;
2362 if let Some(receipts) = &self.visibility_receipts {
2363 receipts.validate(&self.credentials)?;
2364 }
2365 self.channel.validate()?;
2366
2367 if let Some(value) = self.db.as_deref() {
2372 if !value.is_empty() {
2373 return Err(ConfigError::UnsupportedTopLevelDb {
2374 value: value.to_string(),
2375 });
2376 }
2377 }
2378
2379 if cfg!(target_os = "macos") {
2383 if self.exec.limits.address_space.is_some() {
2384 return Err(ConfigError::InvalidExecConfig {
2385 key: "limits.address_space".to_string(),
2386 reason: "unsupported_on_platform: macOS does not enforce an address-space rlimit per process".to_string(),
2387 });
2388 }
2389 if self.exec.limits.nproc.is_some() {
2390 return Err(ConfigError::InvalidExecConfig {
2391 key: "limits.nproc".to_string(),
2392 reason: "unsupported_on_platform: RLIMIT_NPROC counts every process of the uid, not one run".to_string(),
2393 });
2394 }
2395 }
2396 let default_timeout = self.exec.timeout_default_s.unwrap_or(30.0);
2400 let maximum_timeout = self.exec.timeout_max_s.unwrap_or(600.0);
2401 for (key, value) in [
2402 ("timeout_default_s", default_timeout),
2403 ("timeout_max_s", maximum_timeout),
2404 ] {
2405 let duration = value
2406 .is_finite()
2407 .then(|| std::time::Duration::try_from_secs_f64(value).ok())
2408 .flatten()
2409 .filter(|duration| !duration.is_zero());
2410 if duration
2411 .is_none_or(|duration| std::time::Instant::now().checked_add(duration).is_none())
2412 {
2413 return Err(ConfigError::InvalidExecConfig {
2414 key: key.to_string(),
2415 reason: "must be positive, finite, and representable as a deadline".to_string(),
2416 });
2417 }
2418 }
2419 if default_timeout > maximum_timeout {
2420 return Err(ConfigError::InvalidExecConfig {
2421 key: "timeout_default_s".to_string(),
2422 reason: format!(
2423 "default {default_timeout} exceeds timeout_max_s {maximum_timeout}"
2424 ),
2425 });
2426 }
2427 let binary_digest_timeout = self
2428 .exec
2429 .binary_digest_timeout_s
2430 .unwrap_or(DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S);
2431 if !(1..=MAX_EXEC_BINARY_DIGEST_TIMEOUT_S).contains(&binary_digest_timeout) {
2432 return Err(ConfigError::InvalidExecConfig {
2433 key: "binary_digest_timeout_s".to_string(),
2434 reason: format!("must be between 1 and {MAX_EXEC_BINARY_DIGEST_TIMEOUT_S} seconds"),
2435 });
2436 }
2437
2438 if let Some(value) = self.runtime.blob_hydration_bytes {
2439 let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
2440 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
2441 if value < min || value > max {
2442 return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
2443 }
2444 }
2445
2446 if let Some(id) = self.actor.id.as_deref() {
2449 if id.is_empty() {
2450 return Err(ConfigError::InvalidActorId {
2451 id: id.to_string(),
2452 reason: "actor.id must not be empty; remove the key or provide a value"
2453 .to_string(),
2454 });
2455 }
2456 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
2457 id: id.to_string(),
2458 reason: e.to_string(),
2459 })?;
2460 }
2461
2462 self.actor
2463 .mailbox_gate(std::sync::Arc::new(khive_gate::AllowAllGate))
2464 .map_err(|error| ConfigError::InvalidMailboxReaders {
2465 reason: error.to_string(),
2466 })?;
2467
2468 if let Some(ref vis) = self.actor.visible_namespaces {
2469 for ns_str in vis {
2470 if ns_str.is_empty() {
2471 return Err(ConfigError::InvalidActorId {
2472 id: ns_str.clone(),
2473 reason: "visible_namespaces entries must not be empty".to_string(),
2474 });
2475 }
2476 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2477 id: ns_str.clone(),
2478 reason: format!("invalid visible namespace: {e}"),
2479 })?;
2480 }
2481 }
2482
2483 if !self.actor.owned_namespaces.is_empty() {
2487 let Some(actor_id) = self.actor.id.as_deref() else {
2488 return Err(ConfigError::InvalidActorId {
2489 id: String::new(),
2490 reason: "owned_namespaces requires an explicit [actor] id".to_string(),
2491 });
2492 };
2493 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2494 for ns_str in &self.actor.owned_namespaces {
2495 if ns_str.is_empty() {
2496 return Err(ConfigError::InvalidActorId {
2497 id: ns_str.clone(),
2498 reason: "owned_namespaces entries must not be empty".to_string(),
2499 });
2500 }
2501 let parsed = Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2502 id: ns_str.clone(),
2503 reason: format!("invalid owned namespace: {e}"),
2504 })?;
2505 if parsed.as_str() == Namespace::LOCAL {
2506 return Err(ConfigError::InvalidActorId {
2507 id: ns_str.clone(),
2508 reason: "owned_namespaces must not list the shared namespace `local`"
2509 .to_string(),
2510 });
2511 }
2512 if parsed.as_str() == actor_id {
2513 return Err(ConfigError::InvalidActorId {
2514 id: ns_str.clone(),
2515 reason: "owned_namespaces must not list the actor's own id".to_string(),
2516 });
2517 }
2518 if !seen.insert(parsed.as_str().to_string()) {
2519 return Err(ConfigError::InvalidActorId {
2520 id: ns_str.clone(),
2521 reason: "owned_namespaces entries must be unique".to_string(),
2522 });
2523 }
2524 }
2525 }
2526
2527 if let Some(gate) = &self.gate {
2528 khive_gate::CallerEnrollmentGate::validate_write_denials(&gate.deny_writes_for)
2529 .map_err(|error| ConfigError::InvalidWriteDenyPatterns {
2530 reason: error.to_string(),
2531 })?;
2532 for id in &gate.granted_actors {
2533 if id.is_empty() {
2534 return Err(ConfigError::InvalidGrantedActorId {
2535 id: id.clone(),
2536 reason: "actor ids must not be empty".to_string(),
2537 });
2538 }
2539 Namespace::parse(id).map_err(|error| ConfigError::InvalidGrantedActorId {
2540 id: id.clone(),
2541 reason: error.to_string(),
2542 })?;
2543 }
2544 }
2545
2546 for ns_str in &self.actor.allowed_outbound_namespaces {
2548 if ns_str.is_empty() {
2549 return Err(ConfigError::InvalidActorId {
2550 id: ns_str.clone(),
2551 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
2552 });
2553 }
2554 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2555 id: ns_str.clone(),
2556 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
2557 })?;
2558 }
2559
2560 if !self.backends.is_empty() {
2562 let mut seen_backends = std::collections::HashSet::new();
2563 for backend in &self.backends {
2564 BackendId::parse(&backend.name).map_err(|error| {
2565 ConfigError::InvalidBackendName {
2566 name: backend.name.clone(),
2567 reason: error.to_string(),
2568 }
2569 })?;
2570 if backend
2571 .served_kinds
2572 .as_ref()
2573 .is_some_and(BTreeSet::is_empty)
2574 {
2575 return Err(ConfigError::EmptyBackendServedKinds {
2576 name: backend.name.clone(),
2577 });
2578 }
2579 if !seen_backends.insert(backend.name.clone()) {
2580 return Err(ConfigError::DuplicateBackendName {
2581 name: backend.name.clone(),
2582 });
2583 }
2584
2585 if backend.wal_ceiling_bytes.is_some() {
2589 resolve_wal_ceiling(
2590 backend.wal_ceiling_bytes,
2591 None,
2592 &backend.name,
2593 backend.kind.clone(),
2594 backend
2595 .journal_mode
2596 .as_deref()
2597 .is_none_or(|mode| mode.eq_ignore_ascii_case("wal")),
2598 backend.read_only,
2599 )?;
2600 }
2601
2602 backend.resolve_disk_guard(&khive_db::DiskGuardEnvironment::default())?;
2603
2604 if backend.cache_mb.is_some() {
2607 return Err(ConfigError::UnsupportedBackendField {
2608 name: backend.name.clone(),
2609 field: "cache_mb",
2610 });
2611 }
2612 if backend.journal_mode.is_some() {
2613 return Err(ConfigError::UnsupportedBackendField {
2614 name: backend.name.clone(),
2615 field: "journal_mode",
2616 });
2617 }
2618 }
2619 }
2620
2621 let defined: Vec<&str> = if self.backends.is_empty() {
2622 vec![BackendId::MAIN]
2623 } else {
2624 self.backends.iter().map(|b| b.name.as_str()).collect()
2625 };
2626 for (pack_name, pack_cfg) in &self.packs {
2627 if !defined.contains(&pack_cfg.backend.as_str()) {
2628 return Err(ConfigError::UnknownPackBackend {
2629 pack: pack_name.clone(),
2630 backend: pack_cfg.backend.clone(),
2631 defined: defined.join(", "),
2632 });
2633 }
2634 }
2635
2636 if !self.backends.is_empty() {
2637 let missing: Vec<_> = [SubstrateKind::Note, SubstrateKind::Entity]
2638 .into_iter()
2639 .filter(|kind| {
2640 !self.backends.iter().any(|backend| {
2641 backend
2642 .served_kinds
2643 .as_ref()
2644 .is_none_or(|served| served.contains(kind))
2645 })
2646 })
2647 .collect();
2648 if !missing.is_empty() {
2649 return Err(ConfigError::MissingBackendSearchKinds {
2650 kinds: missing,
2651 defined: defined.join(", "),
2652 });
2653 }
2654 }
2655
2656 if let Some(tz) = self.display.timezone.as_deref() {
2659 if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
2660 return Err(ConfigError::InvalidDisplayTimezone {
2661 timezone: tz.to_string(),
2662 });
2663 }
2664 }
2665
2666 for entry in &self.git_write.allowed {
2675 if entry.repo.trim().is_empty() {
2676 return Err(ConfigError::InvalidGitWriteEntry {
2677 repo: entry.repo.clone(),
2678 reason: "repo must not be empty".to_string(),
2679 });
2680 }
2681 if !Path::new(&entry.repo).is_absolute() {
2682 return Err(ConfigError::InvalidGitWriteEntry {
2683 repo: entry.repo.clone(),
2684 reason: "repo must be an absolute path".to_string(),
2685 });
2686 }
2687 match entry.access {
2688 GitRepoAccess::Write if entry.branches.is_empty() => {
2689 return Err(ConfigError::InvalidGitWriteEntry {
2690 repo: entry.repo.clone(),
2691 reason: "branches must not be empty".to_string(),
2692 });
2693 }
2694 GitRepoAccess::Read if !entry.branches.is_empty() => {
2695 return Err(ConfigError::InvalidGitWriteEntry {
2696 repo: entry.repo.clone(),
2697 reason: "a read entry names no branches".to_string(),
2698 });
2699 }
2700 _ => {}
2701 }
2702 if entry.branches.iter().any(|b| b.trim().is_empty()) {
2703 return Err(ConfigError::InvalidGitWriteEntry {
2704 repo: entry.repo.clone(),
2705 reason: "branches entries must not be empty".to_string(),
2706 });
2707 }
2708 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
2713 return Err(ConfigError::InvalidGitWriteEntry {
2714 repo: entry.repo.clone(),
2715 reason: format!(
2716 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
2717 ),
2718 });
2719 }
2720 }
2721
2722 validate_peer_engines(&self.engines)
2723 }
2724
2725 pub fn default_engine(&self) -> Option<&EngineConfig> {
2727 self.engines.first()
2728 }
2729}
2730
2731pub fn config_from_env() -> KhiveConfig {
2745 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
2746 .ok()
2747 .filter(|s| !s.trim().is_empty());
2748 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
2749 .ok()
2750 .unwrap_or_default();
2751 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
2752 .into_iter()
2753 .filter(|s| !s.is_empty())
2754 .collect();
2755
2756 if primary_model.is_none() && additional.is_empty() {
2757 return KhiveConfig::default();
2758 }
2759
2760 tracing::info!(
2761 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
2762 );
2763
2764 config_from_env_parts(primary_model, additional)
2765}
2766
2767fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
2770 let mut engines = Vec::new();
2771
2772 let primary =
2773 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
2774 for model in std::iter::once(primary).chain(additional) {
2775 let name = canonical_engine_name(&model);
2776 if engines
2777 .iter()
2778 .any(|engine: &EngineConfig| engine.name == name)
2779 {
2780 continue;
2781 }
2782 engines.push(EngineConfig {
2783 name,
2784 weight: 1.0,
2785 dims: None,
2786 });
2787 }
2788
2789 KhiveConfig {
2790 engines,
2791 ..KhiveConfig::default()
2792 }
2793}
2794
2795#[cfg(test)]
2796#[path = "engine_config_schema_tests.rs"]
2797mod schema_tests;
2798
2799#[cfg(test)]
2804#[path = "engine_config_tests.rs"]
2805mod tests;
2806
2807#[cfg(test)]
2808mod background_limit_tests {
2809 use super::*;
2810
2811 #[test]
2812 fn optional_background_limits_parse_and_validate() {
2813 let config: KhiveConfig =
2814 toml::from_str("[runtime]\nwarm_concurrency = 3\nmaintenance_concurrency = 2\n")
2815 .unwrap();
2816 config.validate().unwrap();
2817 assert_eq!(config.runtime.warm_concurrency, Some(3));
2818 assert_eq!(config.runtime.maintenance_concurrency, Some(2));
2819 }
2820
2821 #[test]
2822 fn zero_and_overflow_limits_report_the_actual_runtime_key() {
2823 for key in ["warm_concurrency", "maintenance_concurrency"] {
2824 for value in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] {
2825 let mut config: KhiveConfig = toml::from_str("").unwrap();
2826 if key == "warm_concurrency" {
2827 config.runtime.warm_concurrency = Some(value);
2828 } else {
2829 config.runtime.maintenance_concurrency = Some(value);
2830 }
2831 assert!(matches!(config.validate(),
2832 Err(ConfigError::InvalidRuntimeConfig { key: found, .. }) if found == key
2833 ));
2834 }
2835 }
2836 }
2837
2838 #[test]
2839 fn negative_toml_background_limits_are_not_deserialized() {
2840 for key in ["warm_concurrency", "maintenance_concurrency"] {
2841 let text = format!("[runtime]\n{key} = -1\n");
2842 assert!(toml::from_str::<KhiveConfig>(&text).is_err());
2843 }
2844 }
2845
2846 #[test]
2847 fn limits_keep_base_and_override_values_on_both_mapping_branches() {
2848 for engines_declared in [false, true] {
2849 let mut config: KhiveConfig =
2850 toml::from_str("[runtime]\nwarm_concurrency = 5\n").unwrap();
2851 config.engines_declared = engines_declared;
2852 let base = crate::RuntimeConfig {
2853 warm_concurrency: 3,
2854 maintenance_concurrency: 2,
2855 ..crate::RuntimeConfig::no_embeddings()
2856 };
2857 let mapped = crate::config::runtime_config_from_khive_config(&config, base);
2858 assert_eq!(mapped.warm_concurrency, 5);
2859 assert_eq!(mapped.maintenance_concurrency, 2);
2860 }
2861 }
2862
2863 #[test]
2864 fn defaults_use_the_named_validated_background_constants() {
2865 let config = crate::RuntimeConfig::default();
2866 assert_eq!(
2867 config.warm_concurrency,
2868 crate::config::DEFAULT_WARM_CONCURRENCY
2869 );
2870 assert_eq!(
2871 config.maintenance_concurrency,
2872 crate::config::DEFAULT_MAINTENANCE_CONCURRENCY
2873 );
2874 crate::resource_admission::WorkClassLimits::validate(
2875 config.warm_concurrency,
2876 config.maintenance_concurrency,
2877 )
2878 .unwrap();
2879 }
2880}