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("config file I/O: {0}")]
43 Io(#[from] std::io::Error),
44
45 #[error("config TOML parse error in {path}: {source}")]
46 Parse {
47 path: PathBuf,
48 #[source]
49 source: toml::de::Error,
50 },
51
52 #[error("config TOML policy error in {path}, key {key}: {source}")]
53 SchemaParse {
54 path: PathBuf,
55 key: &'static str,
56 #[source]
57 source: Box<toml::de::Error>,
58 },
59
60 #[error("exactly one engine must be marked `default = true`; found {found}")]
61 DefaultCount { found: usize },
62
63 #[error("duplicate engine name: {name:?}")]
64 DuplicateName { name: String },
65
66 #[error(
67 "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
68 )]
69 UnknownModel { name: String, model: String },
70
71 #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
72 InvalidFusionWeight { name: String, value: f64 },
73
74 #[error(
75 "engine {name:?}: fusion_weight is not applied by current retrieval; \
76 remove it until weighted multi-engine fusion is wired"
77 )]
78 UnsupportedFusionWeight { name: String },
79
80 #[error("engine name must not be empty: {name:?}")]
81 InvalidEngineName { name: String },
82
83 #[error("engine {name:?} collides with another engine after alias canonicalization to {canonical:?}; remove the duplicate declaration")]
84 AliasCollision { name: String, canonical: String },
85
86 #[error("engine {name:?}: weight must be finite and strictly positive, got {value}")]
87 InvalidEngineWeight { name: String, value: f64 },
88
89 #[error("engine {name:?}: non-unit weight is refused until configured weights reach every activated retrieval path")]
90 UnsupportedEngineWeight { name: String },
91
92 #[error("engine {name:?}: dims must be positive and at most 4294967295, got {value}")]
93 InvalidEngineDimensions { name: String, value: i64 },
94
95 #[error(
96 "engine {name:?}: configured dims {expected} do not match provider dimensions {actual}"
97 )]
98 EngineDimensionMismatch {
99 name: String,
100 expected: i64,
101 actual: usize,
102 },
103
104 #[error("engine {name:?}: cannot mix legacy model/default/fusion_weight entries with canonical name/weight entries")]
105 EngineKeyConflict { name: String },
106
107 #[error("engines {name:?} and {other:?} share the storage key {key:?}; distinct engine identities require distinct bindings")]
108 EngineKeyCollision {
109 name: String,
110 other: String,
111 key: String,
112 },
113
114 #[error("actor.id {id:?} is not a valid namespace: {reason}")]
115 InvalidActorId { id: String, reason: String },
116
117 #[error("[actor].mailbox_readers: {reason}")]
118 InvalidMailboxReaders { reason: String },
119
120 #[error("[gate].granted_actors entry {id:?} is not a valid actor id: {reason}")]
121 InvalidGrantedActorId { id: String, reason: String },
122 #[error("[gate].deny_writes_for is invalid: {reason}")]
123 InvalidWriteDenyPatterns { reason: String },
124
125 #[error("duplicate backend name: {name:?}")]
126 DuplicateBackendName { name: String },
127
128 #[error("invalid backend name {name:?}: {reason}")]
129 InvalidBackendName { name: String, reason: String },
130
131 #[error("backend {name:?}: `served_kinds` must not be empty when declared")]
132 EmptyBackendServedKinds { name: String },
133
134 #[error("backend {name:?}: invalid disk guard configuration: {reason}")]
135 InvalidBackendDiskGuard { name: String, reason: String },
136
137 #[error(
138 "backends {first_backend:?} and {second_backend:?} name the same database but resolve \
139 different disk reserve/deadline policies"
140 )]
141 DiskGuardAliasConflict {
142 first_backend: String,
143 second_backend: String,
144 },
145
146 #[error("KHIVE_SQLITE_WAL_CEILING_BYTES must be an unsigned decimal byte count")]
147 InvalidWalCeilingEnvironment { value: String },
148
149 #[error(
150 "backend {name:?}: wal_ceiling_bytes {value} exceeds supported SQLite offset arithmetic"
151 )]
152 WalCeilingOffsetOverflow { name: String, value: u64 },
153
154 #[error(
155 "backend {name:?}: nonzero wal_ceiling_bytes {value} requires a file-backed SQLite backend"
156 )]
157 WalCeilingMemoryBackend { name: String, value: u64 },
158
159 #[error("backend {name:?}: nonzero wal_ceiling_bytes {value} requires SQLite WAL mode")]
160 WalCeilingNonWalBackend { name: String, value: u64 },
161
162 #[error(
163 "backends {first_backend:?} and {second_backend:?} name the same database at {} \
164 but resolve different WAL ceilings ({first_bytes} and {second_bytes} bytes)",
165 crate::secret_gate::bounded_masked_log_text(&path.to_string_lossy())
166 )]
167 WalCeilingAliasConflict {
168 first_backend: String,
169 second_backend: String,
170 path: PathBuf,
171 first_bytes: u64,
172 second_bytes: u64,
173 },
174
175 #[error(
176 "backend configuration leaves searchable substrate kinds {kinds:?} unserved; \
177 defined backends: {defined}"
178 )]
179 MissingBackendSearchKinds {
180 kinds: Vec<SubstrateKind>,
181 defined: String,
182 },
183
184 #[error(
185 "[packs.{pack}].backend = {backend:?} references an unknown backend; \
186 defined backends: {defined}"
187 )]
188 UnknownPackBackend {
189 pack: String,
190 backend: String,
191 defined: String,
192 },
193
194 #[error(
195 "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
196 remove it from the config or wait for a future release that implements it"
197 )]
198 UnsupportedBackendField { name: String, field: &'static str },
199
200 #[error(
201 "top-level `db = {value:?}` is not a supported config-file key; \
202 use `--db` / `KHIVE_DB` to select a single-file database, or \
203 `[[backends]].path` to declare storage backend topology"
204 )]
205 UnsupportedTopLevelDb { value: String },
206
207 #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
208 InvalidGitWriteEntry { repo: String, reason: String },
209
210 #[error("[git_write] {key}: {reason}")]
211 InvalidGitWriteConfig { key: String, reason: String },
212
213 #[error("[exec] {key}: {reason}")]
214 InvalidExecConfig { key: String, reason: String },
215
216 #[error("{entry}: {reason}")]
217 InvalidTelemetryConfig { entry: String, reason: String },
218
219 #[error("[web] {key}: {reason}")]
220 InvalidWebConfig { key: String, reason: String },
221
222 #[error("[runtime] {key}: {reason}")]
223 InvalidRuntimeConfig { key: String, reason: String },
224
225 #[error(
226 "[runtime] blob_hydration_bytes must be between {min} and {max} bytes inclusive; got {value}"
227 )]
228 InvalidBlobHydrationBytes { value: u64, min: u64, max: u64 },
229
230 #[error("the explicitly selected config file does not exist: {path}")]
231 ExplicitConfigMissing { path: PathBuf },
232
233 #[error("[gate] configuration is not supported by this build")]
237 UnsupportedGateSection,
238
239 #[error(
240 "[display] timezone {timezone:?} is not a recognized IANA zone name (e.g. \"America/New_York\", \"UTC\")"
241 )]
242 InvalidDisplayTimezone { timezone: String },
243
244 #[error("{source} (config file: {})", path.display())]
254 InFile {
255 path: PathBuf,
256 #[source]
257 source: Box<ConfigError>,
258 },
259}
260
261impl ConfigError {
262 fn in_file(self, path: &Path) -> Self {
265 match self {
266 already @ (ConfigError::Parse { .. }
267 | ConfigError::SchemaParse { .. }
268 | ConfigError::ExplicitConfigMissing { .. }
269 | ConfigError::InFile { .. }) => already,
270 other => ConfigError::InFile {
271 path: path.to_path_buf(),
272 source: Box::new(other),
273 },
274 }
275 }
276}
277
278#[derive(Debug, Clone, Deserialize, Default)]
305#[serde(deny_unknown_fields)]
306pub struct ActorConfig {
307 #[serde(default)]
313 pub id: Option<String>,
314
315 #[serde(default)]
318 pub display_name: Option<String>,
319
320 #[serde(default)]
328 pub mailbox_readers: Vec<String>,
329
330 #[serde(default)]
336 pub visible_namespaces: Option<Vec<String>>,
337
338 #[serde(default)]
350 pub allowed_outbound_namespaces: Vec<String>,
351}
352
353#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
360#[serde(deny_unknown_fields)]
361pub struct GateSectionConfig {
362 #[serde(default)]
364 pub granted_actors: Vec<String>,
365
366 #[serde(default)]
368 pub grant_unattributed: bool,
369
370 #[serde(default)]
373 pub deny_writes_for: Vec<String>,
374}
375
376#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
380#[serde(rename_all = "lowercase")]
381pub enum BackendKind {
382 #[default]
384 Sqlite,
385 Memory,
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub struct ResolvedWalCeiling {
395 pub configured_bytes: u64,
397 pub effective_bytes: u64,
399 pub source: khive_db::WalCeilingSource,
401}
402
403pub fn resolve_wal_ceiling(
409 backend_field: Option<u64>,
410 env_value: Option<&str>,
411 backend_name: &str,
412 kind: BackendKind,
413 wal_mode: bool,
414 read_only: bool,
415) -> Result<ResolvedWalCeiling, ConfigError> {
416 if kind == BackendKind::Memory && backend_field.is_none() {
417 return Ok(ResolvedWalCeiling {
418 configured_bytes: 0,
419 effective_bytes: 0,
420 source: khive_db::WalCeilingSource::Default,
421 });
422 }
423 let (configured_bytes, source) = if let Some(bytes) = backend_field {
424 (bytes, khive_db::WalCeilingSource::BackendField)
425 } else if let Some(raw) = env_value {
426 if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
427 return Err(ConfigError::InvalidWalCeilingEnvironment {
428 value: raw.to_owned(),
429 });
430 }
431 let bytes = raw
432 .parse::<u64>()
433 .map_err(|_| ConfigError::InvalidWalCeilingEnvironment {
434 value: raw.to_owned(),
435 })?;
436 (bytes, khive_db::WalCeilingSource::Environment)
437 } else {
438 (0, khive_db::WalCeilingSource::Default)
439 };
440
441 if configured_bytes != 0 {
442 if i64::try_from(configured_bytes).is_err() {
443 return Err(ConfigError::WalCeilingOffsetOverflow {
444 name: backend_name.to_owned(),
445 value: configured_bytes,
446 });
447 }
448 if kind == BackendKind::Memory {
449 return Err(ConfigError::WalCeilingMemoryBackend {
450 name: backend_name.to_owned(),
451 value: configured_bytes,
452 });
453 }
454 if !wal_mode {
455 return Err(ConfigError::WalCeilingNonWalBackend {
456 name: backend_name.to_owned(),
457 value: configured_bytes,
458 });
459 }
460 }
461
462 Ok(ResolvedWalCeiling {
463 configured_bytes,
464 effective_bytes: if read_only { 0 } else { configured_bytes },
465 source,
466 })
467}
468
469#[derive(Debug, Clone, Deserialize)]
486#[serde(deny_unknown_fields)]
487pub struct BackendConfig {
488 pub name: String,
490 #[serde(default)]
492 pub kind: BackendKind,
493 pub path: Option<std::path::PathBuf>,
496 pub cache_mb: Option<u32>,
498 pub journal_mode: Option<String>,
500 #[serde(default)]
506 pub served_kinds: Option<BTreeSet<SubstrateKind>>,
507 #[serde(default)]
509 pub read_only: bool,
510 pub wal_ceiling_bytes: Option<u64>,
514 #[serde(default)]
516 pub disk_reserve_bytes: Option<u64>,
517 #[serde(default)]
519 pub disk_guard_deadline_ms: Option<u64>,
520}
521
522#[derive(Debug, Clone, Deserialize, Default)]
529pub struct CodeMapConfig {
530 #[serde(default)]
532 pub name: Option<String>,
533 #[serde(default)]
535 pub path: Option<String>,
536 #[serde(default)]
538 pub source_root: Option<String>,
539 #[serde(default, flatten)]
541 pub unknown_fields: BTreeMap<String, toml::Value>,
542}
543
544#[derive(Debug, Clone, Deserialize)]
558pub struct PackConfig {
559 #[serde(default = "default_pack_backend")]
562 pub backend: String,
563 #[serde(default)]
565 pub verbs_disabled: Vec<String>,
566 #[serde(default)]
576 pub no_embed: bool,
577}
578
579fn default_pack_backend() -> String {
580 BackendId::MAIN.to_owned()
581}
582
583#[derive(Debug, Clone, Deserialize)]
611#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
612pub enum BlobConfig {
613 Fs {
617 #[serde(default)]
618 root: Option<String>,
619 #[serde(default)]
622 floor_bytes: Option<u64>,
623 },
624 S3 {
629 bucket: String,
630 region: String,
631 #[serde(default)]
632 endpoint: Option<String>,
633 #[serde(default)]
634 prefix: Option<String>,
635 #[serde(default)]
636 allow_http: Option<bool>,
637 },
638}
639
640#[derive(Debug, Clone, Deserialize, Default)]
642#[serde(deny_unknown_fields)]
643pub struct BlobSectionConfig {
644 #[serde(default)]
646 pub file_transfers: bool,
647}
648
649#[derive(Debug, Clone, Deserialize, Default)]
653#[serde(deny_unknown_fields)]
654pub struct StorageSectionConfig {
655 #[serde(default)]
660 pub blob: Option<BlobConfig>,
661}
662
663#[derive(Debug, Clone, Deserialize, Serialize, Default)]
665#[serde(deny_unknown_fields)]
666pub struct BrainSectionConfig {
667 #[serde(default)]
669 pub fleet_readers: Vec<String>,
670}
671
672#[derive(Debug, Clone, Deserialize, Serialize)]
684pub struct GitWriteEntryConfig {
685 pub repo: String,
687 pub branches: Vec<String>,
690}
691
692#[derive(Debug, Clone, Deserialize, Serialize)]
704pub struct GitWriteSectionConfig {
705 #[serde(default)]
707 pub program: Option<PathBuf>,
708 #[serde(default)]
709 pub allowed: Vec<GitWriteEntryConfig>,
710 #[serde(default)]
711 pub actors: BTreeMap<String, GitWriteActorConfig>,
712 #[serde(default)]
713 pub repositories: BTreeMap<String, GitWriteRepositoryConfig>,
714 #[serde(default = "default_git_credential_resolver")]
715 pub credential_resolver: Vec<String>,
716 #[serde(default)]
717 pub contract_faults: bool,
718 #[serde(default)]
719 pub fault: Option<String>,
720}
721
722#[derive(Debug, Clone, Deserialize, Serialize)]
723#[serde(deny_unknown_fields)]
724pub struct GitWriteRepositoryConfig {
725 pub remote: String,
727 pub slug: String,
729 pub visibility: String,
730 #[serde(default)]
736 pub merge_refusals: Vec<String>,
737}
738
739impl GitWriteRepositoryConfig {
740 pub const MERGE_REFUSALS: [&'static str; 2] = ["opener", "last_pusher"];
741
742 pub fn refuses_merge_by(&self, entry: &str) -> bool {
744 self.merge_refusals.iter().any(|listed| listed == entry)
745 }
746}
747
748#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
749#[serde(deny_unknown_fields)]
750pub struct GitWriteActorConfig {
751 pub name: String,
752 pub email: String,
753 pub credential_ref: String,
754 pub platform_identity: String,
755}
756
757fn default_git_credential_resolver() -> Vec<String> {
758 [
759 "/usr/bin/security",
760 "find-generic-password",
761 "-w",
762 "-s",
763 "{ref}",
764 ]
765 .into_iter()
766 .map(str::to_string)
767 .collect()
768}
769
770impl Default for GitWriteSectionConfig {
771 fn default() -> Self {
772 Self {
773 program: None,
774 allowed: Vec::new(),
775 actors: BTreeMap::new(),
776 repositories: BTreeMap::new(),
777 credential_resolver: default_git_credential_resolver(),
778 contract_faults: false,
779 fault: None,
780 }
781 }
782}
783
784impl GitWriteSectionConfig {
785 pub fn git_program(&self) -> &Path {
786 self.program.as_deref().unwrap_or_else(|| Path::new("git"))
787 }
788
789 pub fn validate_dev_loop(&self) -> Result<(), ConfigError> {
790 let invalid = |key: &str, reason: &str| ConfigError::InvalidGitWriteConfig {
791 key: key.to_string(),
792 reason: reason.to_string(),
793 };
794 if let Some(program) = &self.program {
795 if !program.is_absolute() {
796 return Err(invalid("git_write.program", "must be absolute"));
797 }
798 let metadata = std::fs::metadata(program).map_err(|error| {
799 if error.kind() == std::io::ErrorKind::NotFound {
800 invalid("git_write.program", "does not exist")
801 } else {
802 invalid("git_write.program", &format!("is not executable: {error}"))
803 }
804 })?;
805 #[cfg(unix)]
806 let executable = {
807 use std::os::unix::fs::PermissionsExt;
808 metadata.permissions().mode() & 0o111 != 0
809 };
810 #[cfg(windows)]
811 let executable = program
812 .extension()
813 .and_then(|extension| extension.to_str())
814 .is_some_and(|extension| {
815 extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
816 });
817 #[cfg(not(any(unix, windows)))]
818 let executable = false;
819 if !metadata.is_file() || !executable {
820 return Err(invalid("git_write.program", "is not executable"));
821 }
822 }
823 if self.contract_faults && !cfg!(feature = "contract-faults") {
824 tracing::error!(
825 target: "khive.boot",
826 "[git_write] contract_faults requires the test-only contract-faults build feature"
827 );
828 return Err(invalid(
829 "contract_faults",
830 "requires the test-only contract-faults build feature",
831 ));
832 }
833 if let Some(fault) = &self.fault {
834 if !self.contract_faults {
835 return Err(invalid("fault", "requires contract_faults = true"));
836 }
837 let valid = fault.split_once(':').is_some_and(|(verb, point)| {
838 matches!(verb, "git.push" | "git.pr_merge")
839 && matches!(
840 point,
841 "reply-lost-after-effect" | "audit-fails-after-effect"
842 )
843 });
844 if !valid {
845 return Err(invalid("fault", "unsupported contract fault selector"));
846 }
847 }
848 for (path, repository) in &self.repositories {
849 let key = format!("repositories.{path}.merge_refusals");
850 let mut seen: Vec<&str> = Vec::new();
851 for entry in &repository.merge_refusals {
852 if !GitWriteRepositoryConfig::MERGE_REFUSALS.contains(&entry.as_str()) {
853 return Err(invalid(&key, "entries must be opener or last_pusher"));
854 }
855 if seen.contains(&entry.as_str()) {
856 return Err(invalid(&key, "entries must not repeat"));
857 }
858 seen.push(entry);
859 }
860 }
861 if !cfg!(unix)
864 && self.actors.is_empty()
865 && self.credential_resolver == default_git_credential_resolver()
866 {
867 return Ok(());
868 }
869 let argv = &self.credential_resolver;
870 let Some(program) = argv.first() else {
871 return Err(invalid("credential_resolver", "argv must not be empty"));
872 };
873 let program_path = Path::new(program);
874 if !program_path.is_absolute() {
875 return Err(invalid(
876 "credential_resolver",
877 "argv[0] must be an absolute path",
878 ));
879 }
880 let program_name = program_path
881 .file_name()
882 .and_then(|name| name.to_str())
883 .unwrap_or_default()
884 .to_ascii_lowercase();
885 if matches!(
886 program_name.trim_end_matches(".exe"),
887 "sh" | "bash"
888 | "dash"
889 | "zsh"
890 | "ksh"
891 | "fish"
892 | "csh"
893 | "tcsh"
894 | "cmd"
895 | "powershell"
896 | "pwsh"
897 | "env"
898 ) {
899 return Err(invalid(
900 "credential_resolver",
901 "shell or env launcher is not allowed",
902 ));
903 }
904 if argv.iter().any(|arg| arg.chars().any(char::is_control)) {
905 return Err(invalid(
906 "credential_resolver",
907 "argv must not contain control characters",
908 ));
909 }
910 if program.contains(['{', '}'])
911 || argv[1..]
912 .iter()
913 .any(|arg| arg != "{ref}" && arg.contains(['{', '}']))
914 {
915 return Err(invalid(
916 "credential_resolver",
917 "{ref} must be a complete argument and is the only allowed template",
918 ));
919 }
920 if !argv[1..].iter().any(|arg| arg == "{ref}") {
921 return Err(invalid(
922 "credential_resolver",
923 "argv must contain a {ref} argument",
924 ));
925 }
926 for (actor, identity) in &self.actors {
927 if actor.trim().is_empty() || actor.chars().any(char::is_control) {
928 return Err(invalid(
929 "actors",
930 "actor labels must be nonempty and contain no control characters",
931 ));
932 }
933 for (field, value) in [
934 ("name", &identity.name),
935 ("email", &identity.email),
936 ("credential_ref", &identity.credential_ref),
937 ("platform_identity", &identity.platform_identity),
938 ] {
939 if value.trim().is_empty() || value.chars().any(char::is_control) {
940 return Err(invalid(
941 &format!("actors.{actor}.{field}"),
942 "must be nonempty and contain no control characters",
943 ));
944 }
945 }
946 if identity.name.contains(['<', '>']) || identity.email.contains(['<', '>']) {
947 return Err(invalid(
948 &format!("actors.{actor}"),
949 "name and email must not contain Git identity delimiters",
950 ));
951 }
952 }
953 Ok(())
954 }
955}
956
957#[derive(Debug, Clone, Deserialize, Default)]
962pub struct ExecLimitsConfig {
963 #[serde(default)]
964 pub cpu_seconds: Option<u64>,
965 #[serde(default)]
966 pub address_space: Option<u64>,
967 #[serde(default)]
968 pub file_size: Option<u64>,
969 #[serde(default)]
970 pub nproc: Option<u64>,
971}
972
973#[derive(Debug, Clone, Deserialize, Default)]
996#[serde(deny_unknown_fields)]
997pub struct ExecSectionConfig {
998 #[serde(default)]
999 pub root: Option<String>,
1000 #[serde(default)]
1001 pub read_roots: Vec<String>,
1002 #[serde(default)]
1003 pub env: Vec<String>,
1004 #[serde(default)]
1005 pub never: Vec<String>,
1006 #[serde(default)]
1007 pub max_output_bytes: Option<u64>,
1008 #[serde(default)]
1009 pub timeout_default_s: Option<f64>,
1010 #[serde(default)]
1011 pub timeout_max_s: Option<f64>,
1012 #[serde(default)]
1014 pub binary_digest_timeout_s: Option<u64>,
1015 #[serde(default)]
1016 pub keep: bool,
1017 #[serde(default)]
1018 pub limits: ExecLimitsConfig,
1019}
1020
1021pub const DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 10;
1022pub const MAX_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 60;
1023
1024#[derive(Debug, Clone, Deserialize, Serialize)]
1033#[serde(deny_unknown_fields)]
1034pub struct WebAllowlistEntry {
1035 pub host: String,
1036}
1037
1038#[derive(Debug, Clone, Deserialize, Serialize)]
1045#[serde(deny_unknown_fields)]
1046pub struct WebCredentialConfig {
1047 pub name: String,
1049 pub env_var: String,
1051 pub hosts: Vec<String>,
1054}
1055
1056#[derive(Debug, Clone, Deserialize, Serialize)]
1060#[serde(deny_unknown_fields)]
1061pub struct WebFixtureResult {
1062 pub title: String,
1063 pub url: String,
1064 pub snippet: String,
1065}
1066
1067#[derive(Debug, Clone, Deserialize, Serialize)]
1071#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
1072pub enum WebSearchProviderConfig {
1073 Fixture {
1075 name: String,
1076 #[serde(default)]
1077 default: bool,
1078 results: Vec<WebFixtureResult>,
1079 },
1080 Http {
1087 name: String,
1088 #[serde(default)]
1089 default: bool,
1090 url_template: String,
1091 #[serde(default)]
1092 api_key_env: Option<String>,
1093 #[serde(default)]
1100 hosts: Vec<String>,
1101 },
1102}
1103
1104impl WebSearchProviderConfig {
1105 pub fn name(&self) -> &str {
1106 match self {
1107 WebSearchProviderConfig::Fixture { name, .. } => name,
1108 WebSearchProviderConfig::Http { name, .. } => name,
1109 }
1110 }
1111
1112 pub fn is_default(&self) -> bool {
1113 match self {
1114 WebSearchProviderConfig::Fixture { default, .. } => *default,
1115 WebSearchProviderConfig::Http { default, .. } => *default,
1116 }
1117 }
1118}
1119
1120#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1154#[serde(deny_unknown_fields)]
1155pub struct WebSectionConfig {
1156 #[serde(default)]
1157 pub timeout_default_s: Option<u64>,
1158 #[serde(default)]
1159 pub timeout_max_s: Option<u64>,
1160 #[serde(default)]
1161 pub max_bytes_default: Option<u64>,
1162 #[serde(default)]
1163 pub max_bytes_max: Option<u64>,
1164 #[serde(default)]
1165 pub search_limit_default: Option<u32>,
1166 #[serde(default)]
1167 pub search_limit_max: Option<u32>,
1168 #[serde(default)]
1169 pub allowlist: Vec<WebAllowlistEntry>,
1170 #[serde(default)]
1171 pub credentials: Vec<WebCredentialConfig>,
1172 #[serde(default)]
1173 pub search_providers: Vec<WebSearchProviderConfig>,
1174 #[serde(default)]
1178 pub read_roots: Vec<String>,
1179}
1180
1181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1183pub struct WebCeilings {
1184 pub timeout_default_s: u64,
1185 pub timeout_max_s: u64,
1186 pub max_bytes_default: u64,
1187 pub max_bytes_max: u64,
1188 pub search_limit_default: u32,
1189 pub search_limit_max: u32,
1190}
1191
1192impl Default for WebCeilings {
1193 fn default() -> Self {
1194 Self {
1195 timeout_default_s: 30,
1196 timeout_max_s: 120,
1197 max_bytes_default: 5 * 1024 * 1024,
1198 max_bytes_max: 50 * 1024 * 1024,
1199 search_limit_default: 10,
1200 search_limit_max: 50,
1201 }
1202 }
1203}
1204
1205impl WebSectionConfig {
1206 pub fn resolved_ceilings(&self) -> Result<WebCeilings, ConfigError> {
1207 let defaults = WebCeilings::default();
1208 let bounds = WebCeilings {
1209 timeout_default_s: self.timeout_default_s.unwrap_or(defaults.timeout_default_s),
1210 timeout_max_s: self.timeout_max_s.unwrap_or(defaults.timeout_max_s),
1211 max_bytes_default: self.max_bytes_default.unwrap_or(defaults.max_bytes_default),
1212 max_bytes_max: self.max_bytes_max.unwrap_or(defaults.max_bytes_max),
1213 search_limit_default: self
1214 .search_limit_default
1215 .unwrap_or(defaults.search_limit_default),
1216 search_limit_max: self.search_limit_max.unwrap_or(defaults.search_limit_max),
1217 };
1218 for (key, default, maximum, maximum_key) in [
1219 (
1220 "timeout_default_s",
1221 bounds.timeout_default_s,
1222 bounds.timeout_max_s,
1223 "timeout_max_s",
1224 ),
1225 (
1226 "max_bytes_default",
1227 bounds.max_bytes_default,
1228 bounds.max_bytes_max,
1229 "max_bytes_max",
1230 ),
1231 (
1232 "search_limit_default",
1233 u64::from(bounds.search_limit_default),
1234 u64::from(bounds.search_limit_max),
1235 "search_limit_max",
1236 ),
1237 ] {
1238 if default == 0 || default > maximum {
1239 return Err(ConfigError::InvalidWebConfig {
1240 key: key.into(),
1241 reason: format!(
1242 "resolved default must be positive and not exceed {maximum_key}={maximum}"
1243 ),
1244 });
1245 }
1246 }
1247 if std::time::Instant::now()
1248 .checked_add(std::time::Duration::from_secs(bounds.timeout_max_s))
1249 .is_none()
1250 {
1251 return Err(ConfigError::InvalidWebConfig {
1252 key: "timeout_max_s".into(),
1253 reason: "cannot be represented as a request deadline".into(),
1254 });
1255 }
1256 Ok(bounds)
1257 }
1258
1259 pub fn validate(&self) -> Result<(), ConfigError> {
1260 self.resolved_ceilings()?;
1261 let invalid = |key: &str, reason: &str| ConfigError::InvalidWebConfig {
1262 key: key.to_string(),
1263 reason: reason.to_string(),
1264 };
1265 let mut seen_hosts = std::collections::HashSet::new();
1266 for entry in &self.allowlist {
1267 let normalized = entry.host.trim().trim_end_matches('.').to_ascii_lowercase();
1268 if normalized.is_empty() {
1269 return Err(invalid("allowlist.host", "must not be empty"));
1270 }
1271 if !seen_hosts.insert(normalized) {
1272 return Err(invalid("allowlist.host", "duplicate host entry"));
1273 }
1274 }
1275 let mut seen_credentials = std::collections::HashSet::new();
1276 for credential in &self.credentials {
1277 if credential.name.trim().is_empty() {
1278 return Err(invalid("credentials.name", "must not be empty"));
1279 }
1280 if !seen_credentials.insert(credential.name.clone()) {
1281 return Err(invalid("credentials.name", "duplicate credential name"));
1282 }
1283 if credential.env_var.trim().is_empty() {
1284 return Err(invalid("credentials.env_var", "must not be empty"));
1285 }
1286 if credential.hosts.is_empty() {
1287 return Err(invalid(
1288 "credentials.hosts",
1289 "must name at least one host or suffix",
1290 ));
1291 }
1292 }
1293 let mut seen_providers = std::collections::HashSet::new();
1294 let mut default_count = 0;
1295 for provider in &self.search_providers {
1296 let name = provider.name();
1297 if name.trim().is_empty() {
1298 return Err(invalid("search_providers.name", "must not be empty"));
1299 }
1300 if !seen_providers.insert(name.to_string()) {
1301 return Err(invalid("search_providers.name", "duplicate provider name"));
1302 }
1303 if provider.is_default() {
1304 default_count += 1;
1305 }
1306 if let WebSearchProviderConfig::Http {
1307 url_template,
1308 api_key_env,
1309 hosts,
1310 ..
1311 } = provider
1312 {
1313 if !url_template.contains("{query}") {
1314 return Err(invalid(
1315 "search_providers.url_template",
1316 "must contain the literal substring {query}",
1317 ));
1318 }
1319 if api_key_env.is_some() && hosts.is_empty() {
1320 return Err(invalid(
1321 "search_providers.hosts",
1322 "an api_key_env-bearing provider must name at least one host or suffix",
1323 ));
1324 }
1325 }
1326 }
1327 if default_count > 1 {
1328 return Err(invalid(
1329 "search_providers",
1330 "at most one provider may set default = true",
1331 ));
1332 }
1333 Ok(())
1334 }
1335}
1336
1337#[derive(Debug, Clone, Deserialize, Serialize)]
1340pub struct SchemaSectionConfig {
1341 #[serde(default = "schema_strict_default")]
1342 pub strict: bool,
1343}
1344
1345fn schema_strict_default() -> bool {
1346 true
1347}
1348
1349impl Default for SchemaSectionConfig {
1350 fn default() -> Self {
1351 Self { strict: true }
1352 }
1353}
1354
1355#[derive(Deserialize)]
1358struct SchemaSyntaxProbe {
1359 #[serde(default, deserialize_with = "deserialize_schema_table")]
1360 schema: SchemaSectionConfig,
1361}
1362
1363fn deserialize_schema_table<'de, D>(deserializer: D) -> Result<SchemaSectionConfig, D::Error>
1364where
1365 D: serde::Deserializer<'de>,
1366{
1367 struct SchemaTableVisitor;
1368 impl<'de> serde::de::Visitor<'de> for SchemaTableVisitor {
1369 type Value = SchemaSectionConfig;
1370
1371 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1372 formatter.write_str("a schema configuration table")
1373 }
1374
1375 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1376 where
1377 A: serde::de::MapAccess<'de>,
1378 {
1379 SchemaSectionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
1380 }
1381 }
1382 deserializer.deserialize_map(SchemaTableVisitor)
1383}
1384
1385#[derive(Debug, Clone, Deserialize, Default)]
1408pub struct KhiveConfig {
1409 #[serde(default)]
1411 pub schema: SchemaSectionConfig,
1412
1413 #[serde(default, deserialize_with = "embed_batch::deserialize_table")]
1415 pub embed: EmbedSectionConfig,
1416
1417 #[serde(skip)]
1419 pub credentials: Vec<crate::credentials::CredentialConfig>,
1420
1421 #[serde(skip)]
1422 pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
1423
1424 #[serde(default)]
1425 pub mounts: Vec<crate::mount_config::MountConfig>,
1426
1427 #[serde(default)]
1433 pub db: Option<String>,
1434
1435 #[serde(default)]
1437 pub engines: Vec<EngineConfig>,
1438
1439 #[serde(skip)]
1443 pub engines_declared: bool,
1444
1445 #[serde(default)]
1453 pub actor: ActorConfig,
1454
1455 #[serde(default)]
1459 pub gate: Option<GateSectionConfig>,
1460
1461 #[serde(default)]
1463 pub runtime: RuntimeSectionConfig,
1464
1465 #[serde(default)]
1470 pub backends: Vec<BackendConfig>,
1471
1472 #[serde(default)]
1474 pub code_map_root: Option<String>,
1475
1476 #[serde(default)]
1478 pub code_maps: Vec<CodeMapConfig>,
1479
1480 #[serde(default)]
1486 pub packs: std::collections::HashMap<String, PackConfig>,
1487
1488 #[serde(default)]
1490 pub brain: BrainSectionConfig,
1491
1492 #[serde(default)]
1496 pub git_write: GitWriteSectionConfig,
1497
1498 #[serde(default)]
1500 pub blob: BlobSectionConfig,
1501
1502 #[serde(default)]
1505 pub storage: StorageSectionConfig,
1506
1507 #[serde(default)]
1510 pub exec: ExecSectionConfig,
1511
1512 #[serde(default)]
1514 pub telemetry: crate::telemetry_config::TelemetryConfig,
1515
1516 #[serde(default)]
1520 pub display: DisplaySectionConfig,
1521
1522 #[serde(default)]
1527 pub web: WebSectionConfig,
1528}
1529
1530#[derive(Debug, Clone, Deserialize, Default)]
1537pub struct RuntimeSectionConfig {
1538 #[serde(default)]
1541 pub warm_concurrency: Option<usize>,
1542
1543 #[serde(default)]
1546 pub maintenance_concurrency: Option<usize>,
1547
1548 #[serde(default)]
1551 pub packs: Option<Vec<String>>,
1552
1553 #[serde(default)]
1560 pub brain_profile: Option<String>,
1561
1562 #[serde(default)]
1569 pub default_output_format: Option<OutputFormat>,
1570
1571 #[serde(default)]
1578 pub blob_hydration_bytes: Option<u64>,
1579}
1580
1581#[derive(Debug, Clone, Deserialize, Default)]
1589pub struct DisplaySectionConfig {
1590 #[serde(default)]
1596 pub timezone: Option<String>,
1597}
1598
1599impl KhiveConfig {
1600 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
1616 let resolved = match path {
1617 Some(p) => p.to_path_buf(),
1618 None => PathBuf::from(".khive/config.toml"),
1619 };
1620
1621 if !resolved.exists() {
1622 return Ok(None);
1623 }
1624
1625 let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
1628 let raw = std::fs::read_to_string(&resolved)
1629 .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
1630 let mut document: toml::Value =
1631 toml::from_str(&raw).map_err(|source| ConfigError::Parse {
1632 path: diagnostic_path.clone(),
1633 source,
1634 })?;
1635 let schema_probe: SchemaSyntaxProbe =
1636 toml::from_str(&raw).map_err(|source| ConfigError::SchemaParse {
1637 path: diagnostic_path.clone(),
1638 key: if document
1639 .get("schema")
1640 .is_some_and(|value| !value.is_table())
1641 {
1642 "schema"
1643 } else {
1644 "schema.strict"
1645 },
1646 source: Box::new(source),
1647 })?;
1648 let unknown_schema_keys: Vec<String> = document
1649 .get("schema")
1650 .and_then(toml::Value::as_table)
1651 .map(|table| {
1652 table
1653 .keys()
1654 .filter(|key| key.as_str() != "strict")
1655 .cloned()
1656 .collect()
1657 })
1658 .unwrap_or_default();
1659 let (embed, unknown_embed_keys) = embed_batch::parse(&raw, &document, &diagnostic_path)?;
1660 let engines_declared = peers::normalize_engine_input(&mut document, &diagnostic_path)
1661 .map_err(|error| error.in_file(&diagnostic_path))?;
1662 let mut cfg: KhiveConfig = document.try_into().map_err(|source| ConfigError::Parse {
1663 path: diagnostic_path.clone(),
1664 source,
1665 })?;
1666 cfg.schema = schema_probe.schema;
1667 cfg.embed = embed;
1668 cfg.engines_declared = engines_declared;
1669 crate::credentials::read_tables(&raw, &mut cfg)
1670 .map_err(|error| ConfigError::from(error).in_file(&diagnostic_path))?;
1671 cfg.validate()
1672 .map_err(|error| error.in_file(&diagnostic_path))?;
1673 for engine in &mut cfg.engines {
1674 engine.name = canonical_engine_name(&engine.name);
1675 }
1676 for key in unknown_schema_keys {
1677 tracing::warn!(target: "khive.config.schema",
1678 key = %crate::secret_gate::bounded_masked_log_text(&key),
1679 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1680 "ignoring unknown schema configuration key");
1681 }
1682 for key in unknown_embed_keys {
1683 tracing::warn!(target: "khive.config.embed",
1684 key = %crate::secret_gate::bounded_masked_log_text(&key),
1685 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1686 "ignoring unknown embed configuration key");
1687 }
1688 Ok(Some(cfg))
1689 }
1690
1691 pub fn load_with_home_fallback(
1719 path: Option<&Path>,
1720 db_path: Option<&Path>,
1721 ) -> Result<Option<Self>, ConfigError> {
1722 Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
1723 }
1724
1725 pub fn load_with_home_fallback_and_source(
1733 path: Option<&Path>,
1734 db_path: Option<&Path>,
1735 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1736 if let Some(p) = path {
1744 if !p.exists() {
1745 return Err(ConfigError::ExplicitConfigMissing {
1746 path: p.to_path_buf(),
1747 });
1748 }
1749 return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
1750 }
1751
1752 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1754 let home_root = std::env::var_os("HOME").map(PathBuf::from);
1755 Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
1756 }
1757
1758 #[cfg(test)]
1767 pub(crate) fn load_with_roots(
1768 project_root: &Path,
1769 home_root: Option<&Path>,
1770 db_path: Option<&Path>,
1771 ) -> Result<Option<Self>, ConfigError> {
1772 Ok(
1773 Self::load_with_roots_and_source(project_root, home_root, db_path)?
1774 .map(|(config, _)| config),
1775 )
1776 }
1777
1778 fn load_with_roots_and_source(
1779 project_root: &Path,
1780 home_root: Option<&Path>,
1781 db_path: Option<&Path>,
1782 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1783 let tier2 = project_root.join("khive.toml");
1785 if tier2.exists() {
1786 return Ok(Self::load(Some(&tier2))?
1787 .map(|config| (config, Self::diagnostic_config_path(&tier2))));
1788 }
1789
1790 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
1793 if tier3.exists() {
1794 return Ok(Self::load(Some(&tier3))?
1795 .map(|config| (config, Self::diagnostic_config_path(&tier3))));
1796 }
1797
1798 if let Some(home) = home_root {
1800 let tier4 = home.join(".khive/config.toml");
1801 if tier4.exists() {
1802 return Ok(Self::load(Some(&tier4))?
1803 .map(|config| (config, Self::diagnostic_config_path(&tier4))));
1804 }
1805 }
1806
1807 Ok(None)
1808 }
1809
1810 fn diagnostic_config_path(path: &Path) -> PathBuf {
1811 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1812 }
1813
1814 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
1840 let Some(db_path) = db_path else {
1841 return project_root.join(".khive");
1842 };
1843
1844 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
1845 if db_path.is_absolute() {
1846 db_path.to_path_buf()
1847 } else {
1848 project_root.join(db_path)
1849 }
1850 });
1851
1852 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
1853
1854 if db_dir.file_name().is_some_and(|name| name == ".khive") {
1855 db_dir
1856 } else {
1857 db_dir.join(".khive")
1858 }
1859 }
1860
1861 pub fn validate(&self) -> Result<(), ConfigError> {
1867 #[cfg(not(feature = "blob-s3"))]
1868 if matches!(&self.storage.blob, Some(BlobConfig::S3 { .. })) {
1869 return Err(ConfigError::BlobS3FeatureDisabled);
1870 }
1871
1872 let warm = self
1873 .runtime
1874 .warm_concurrency
1875 .unwrap_or(crate::config::DEFAULT_WARM_CONCURRENCY);
1876 let maintenance = self
1877 .runtime
1878 .maintenance_concurrency
1879 .unwrap_or(crate::config::DEFAULT_MAINTENANCE_CONCURRENCY);
1880 crate::resource_admission::WorkClassLimits::validate(warm, maintenance).map_err(
1881 |error| {
1882 let key = match &error {
1883 crate::resource_admission::ResourceError::InvalidLimit {
1884 class: crate::resource_admission::WorkClass::Warm,
1885 ..
1886 } => "warm_concurrency",
1887 crate::resource_admission::ResourceError::InvalidLimit {
1888 class: crate::resource_admission::WorkClass::Maintenance,
1889 ..
1890 } => "maintenance_concurrency",
1891 _ => "background_concurrency",
1892 };
1893 ConfigError::InvalidRuntimeConfig {
1894 key: key.to_owned(),
1895 reason: error.to_string(),
1896 }
1897 },
1898 )?;
1899
1900 crate::mount_config::validate_mounts(&self.mounts)?;
1901 self.git_write.validate_dev_loop()?;
1902 self.telemetry.validate()?;
1903 self.web.validate()?;
1904 crate::credentials::CredentialConfig::validate_all(&self.credentials)?;
1905 if let Some(receipts) = &self.visibility_receipts {
1906 receipts.validate(&self.credentials)?;
1907 }
1908
1909 if let Some(value) = self.db.as_deref() {
1914 if !value.is_empty() {
1915 return Err(ConfigError::UnsupportedTopLevelDb {
1916 value: value.to_string(),
1917 });
1918 }
1919 }
1920
1921 if cfg!(target_os = "macos") {
1925 if self.exec.limits.address_space.is_some() {
1926 return Err(ConfigError::InvalidExecConfig {
1927 key: "limits.address_space".to_string(),
1928 reason: "unsupported_on_platform: macOS does not enforce an address-space rlimit per process".to_string(),
1929 });
1930 }
1931 if self.exec.limits.nproc.is_some() {
1932 return Err(ConfigError::InvalidExecConfig {
1933 key: "limits.nproc".to_string(),
1934 reason: "unsupported_on_platform: RLIMIT_NPROC counts every process of the uid, not one run".to_string(),
1935 });
1936 }
1937 }
1938 let default_timeout = self.exec.timeout_default_s.unwrap_or(30.0);
1942 let maximum_timeout = self.exec.timeout_max_s.unwrap_or(600.0);
1943 for (key, value) in [
1944 ("timeout_default_s", default_timeout),
1945 ("timeout_max_s", maximum_timeout),
1946 ] {
1947 let duration = value
1948 .is_finite()
1949 .then(|| std::time::Duration::try_from_secs_f64(value).ok())
1950 .flatten()
1951 .filter(|duration| !duration.is_zero());
1952 if duration
1953 .is_none_or(|duration| std::time::Instant::now().checked_add(duration).is_none())
1954 {
1955 return Err(ConfigError::InvalidExecConfig {
1956 key: key.to_string(),
1957 reason: "must be positive, finite, and representable as a deadline".to_string(),
1958 });
1959 }
1960 }
1961 if default_timeout > maximum_timeout {
1962 return Err(ConfigError::InvalidExecConfig {
1963 key: "timeout_default_s".to_string(),
1964 reason: format!(
1965 "default {default_timeout} exceeds timeout_max_s {maximum_timeout}"
1966 ),
1967 });
1968 }
1969 let binary_digest_timeout = self
1970 .exec
1971 .binary_digest_timeout_s
1972 .unwrap_or(DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S);
1973 if !(1..=MAX_EXEC_BINARY_DIGEST_TIMEOUT_S).contains(&binary_digest_timeout) {
1974 return Err(ConfigError::InvalidExecConfig {
1975 key: "binary_digest_timeout_s".to_string(),
1976 reason: format!("must be between 1 and {MAX_EXEC_BINARY_DIGEST_TIMEOUT_S} seconds"),
1977 });
1978 }
1979
1980 if let Some(value) = self.runtime.blob_hydration_bytes {
1981 let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
1982 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
1983 if value < min || value > max {
1984 return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
1985 }
1986 }
1987
1988 if let Some(id) = self.actor.id.as_deref() {
1991 if id.is_empty() {
1992 return Err(ConfigError::InvalidActorId {
1993 id: id.to_string(),
1994 reason: "actor.id must not be empty; remove the key or provide a value"
1995 .to_string(),
1996 });
1997 }
1998 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
1999 id: id.to_string(),
2000 reason: e.to_string(),
2001 })?;
2002 }
2003
2004 self.actor
2005 .mailbox_gate(std::sync::Arc::new(khive_gate::AllowAllGate))
2006 .map_err(|error| ConfigError::InvalidMailboxReaders {
2007 reason: error.to_string(),
2008 })?;
2009
2010 if let Some(ref vis) = self.actor.visible_namespaces {
2011 for ns_str in vis {
2012 if ns_str.is_empty() {
2013 return Err(ConfigError::InvalidActorId {
2014 id: ns_str.clone(),
2015 reason: "visible_namespaces entries must not be empty".to_string(),
2016 });
2017 }
2018 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2019 id: ns_str.clone(),
2020 reason: format!("invalid visible namespace: {e}"),
2021 })?;
2022 }
2023 }
2024
2025 if let Some(gate) = &self.gate {
2026 khive_gate::CallerEnrollmentGate::validate_write_denials(&gate.deny_writes_for)
2027 .map_err(|error| ConfigError::InvalidWriteDenyPatterns {
2028 reason: error.to_string(),
2029 })?;
2030 for id in &gate.granted_actors {
2031 if id.is_empty() {
2032 return Err(ConfigError::InvalidGrantedActorId {
2033 id: id.clone(),
2034 reason: "actor ids must not be empty".to_string(),
2035 });
2036 }
2037 Namespace::parse(id).map_err(|error| ConfigError::InvalidGrantedActorId {
2038 id: id.clone(),
2039 reason: error.to_string(),
2040 })?;
2041 }
2042 }
2043
2044 for ns_str in &self.actor.allowed_outbound_namespaces {
2046 if ns_str.is_empty() {
2047 return Err(ConfigError::InvalidActorId {
2048 id: ns_str.clone(),
2049 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
2050 });
2051 }
2052 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2053 id: ns_str.clone(),
2054 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
2055 })?;
2056 }
2057
2058 if !self.backends.is_empty() {
2060 let mut seen_backends = std::collections::HashSet::new();
2061 for backend in &self.backends {
2062 BackendId::parse(&backend.name).map_err(|error| {
2063 ConfigError::InvalidBackendName {
2064 name: backend.name.clone(),
2065 reason: error.to_string(),
2066 }
2067 })?;
2068 if backend
2069 .served_kinds
2070 .as_ref()
2071 .is_some_and(BTreeSet::is_empty)
2072 {
2073 return Err(ConfigError::EmptyBackendServedKinds {
2074 name: backend.name.clone(),
2075 });
2076 }
2077 if !seen_backends.insert(backend.name.clone()) {
2078 return Err(ConfigError::DuplicateBackendName {
2079 name: backend.name.clone(),
2080 });
2081 }
2082
2083 if backend.wal_ceiling_bytes.is_some() {
2087 resolve_wal_ceiling(
2088 backend.wal_ceiling_bytes,
2089 None,
2090 &backend.name,
2091 backend.kind.clone(),
2092 backend
2093 .journal_mode
2094 .as_deref()
2095 .is_none_or(|mode| mode.eq_ignore_ascii_case("wal")),
2096 backend.read_only,
2097 )?;
2098 }
2099
2100 backend.resolve_disk_guard(&khive_db::DiskGuardEnvironment::default())?;
2101
2102 if backend.cache_mb.is_some() {
2105 return Err(ConfigError::UnsupportedBackendField {
2106 name: backend.name.clone(),
2107 field: "cache_mb",
2108 });
2109 }
2110 if backend.journal_mode.is_some() {
2111 return Err(ConfigError::UnsupportedBackendField {
2112 name: backend.name.clone(),
2113 field: "journal_mode",
2114 });
2115 }
2116 }
2117 }
2118
2119 let defined: Vec<&str> = if self.backends.is_empty() {
2120 vec![BackendId::MAIN]
2121 } else {
2122 self.backends.iter().map(|b| b.name.as_str()).collect()
2123 };
2124 for (pack_name, pack_cfg) in &self.packs {
2125 if !defined.contains(&pack_cfg.backend.as_str()) {
2126 return Err(ConfigError::UnknownPackBackend {
2127 pack: pack_name.clone(),
2128 backend: pack_cfg.backend.clone(),
2129 defined: defined.join(", "),
2130 });
2131 }
2132 }
2133
2134 if !self.backends.is_empty() {
2135 let missing: Vec<_> = [SubstrateKind::Note, SubstrateKind::Entity]
2136 .into_iter()
2137 .filter(|kind| {
2138 !self.backends.iter().any(|backend| {
2139 backend
2140 .served_kinds
2141 .as_ref()
2142 .is_none_or(|served| served.contains(kind))
2143 })
2144 })
2145 .collect();
2146 if !missing.is_empty() {
2147 return Err(ConfigError::MissingBackendSearchKinds {
2148 kinds: missing,
2149 defined: defined.join(", "),
2150 });
2151 }
2152 }
2153
2154 if let Some(tz) = self.display.timezone.as_deref() {
2157 if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
2158 return Err(ConfigError::InvalidDisplayTimezone {
2159 timezone: tz.to_string(),
2160 });
2161 }
2162 }
2163
2164 for entry in &self.git_write.allowed {
2171 if entry.repo.trim().is_empty() {
2172 return Err(ConfigError::InvalidGitWriteEntry {
2173 repo: entry.repo.clone(),
2174 reason: "repo must not be empty".to_string(),
2175 });
2176 }
2177 if !Path::new(&entry.repo).is_absolute() {
2178 return Err(ConfigError::InvalidGitWriteEntry {
2179 repo: entry.repo.clone(),
2180 reason: "repo must be an absolute path".to_string(),
2181 });
2182 }
2183 if entry.branches.is_empty() {
2184 return Err(ConfigError::InvalidGitWriteEntry {
2185 repo: entry.repo.clone(),
2186 reason: "branches must not be empty".to_string(),
2187 });
2188 }
2189 if entry.branches.iter().any(|b| b.trim().is_empty()) {
2190 return Err(ConfigError::InvalidGitWriteEntry {
2191 repo: entry.repo.clone(),
2192 reason: "branches entries must not be empty".to_string(),
2193 });
2194 }
2195 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
2200 return Err(ConfigError::InvalidGitWriteEntry {
2201 repo: entry.repo.clone(),
2202 reason: format!(
2203 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
2204 ),
2205 });
2206 }
2207 }
2208
2209 validate_peer_engines(&self.engines)
2210 }
2211
2212 pub fn default_engine(&self) -> Option<&EngineConfig> {
2214 self.engines.first()
2215 }
2216}
2217
2218pub fn config_from_env() -> KhiveConfig {
2232 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
2233 .ok()
2234 .filter(|s| !s.trim().is_empty());
2235 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
2236 .ok()
2237 .unwrap_or_default();
2238 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
2239 .into_iter()
2240 .filter(|s| !s.is_empty())
2241 .collect();
2242
2243 if primary_model.is_none() && additional.is_empty() {
2244 return KhiveConfig::default();
2245 }
2246
2247 tracing::info!(
2248 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
2249 );
2250
2251 config_from_env_parts(primary_model, additional)
2252}
2253
2254fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
2257 let mut engines = Vec::new();
2258
2259 let primary =
2260 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
2261 for model in std::iter::once(primary).chain(additional) {
2262 let name = canonical_engine_name(&model);
2263 if engines
2264 .iter()
2265 .any(|engine: &EngineConfig| engine.name == name)
2266 {
2267 continue;
2268 }
2269 engines.push(EngineConfig {
2270 name,
2271 weight: 1.0,
2272 dims: None,
2273 });
2274 }
2275
2276 KhiveConfig {
2277 engines,
2278 ..KhiveConfig::default()
2279 }
2280}
2281
2282#[cfg(test)]
2283#[path = "engine_config_schema_tests.rs"]
2284mod schema_tests;
2285
2286#[cfg(test)]
2291#[path = "engine_config_tests.rs"]
2292mod tests;
2293
2294#[cfg(test)]
2295mod background_limit_tests {
2296 use super::*;
2297
2298 #[test]
2299 fn optional_background_limits_parse_and_validate() {
2300 let config: KhiveConfig =
2301 toml::from_str("[runtime]\nwarm_concurrency = 3\nmaintenance_concurrency = 2\n")
2302 .unwrap();
2303 config.validate().unwrap();
2304 assert_eq!(config.runtime.warm_concurrency, Some(3));
2305 assert_eq!(config.runtime.maintenance_concurrency, Some(2));
2306 }
2307
2308 #[test]
2309 fn zero_and_overflow_limits_report_the_actual_runtime_key() {
2310 for key in ["warm_concurrency", "maintenance_concurrency"] {
2311 for value in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] {
2312 let mut config: KhiveConfig = toml::from_str("").unwrap();
2313 if key == "warm_concurrency" {
2314 config.runtime.warm_concurrency = Some(value);
2315 } else {
2316 config.runtime.maintenance_concurrency = Some(value);
2317 }
2318 assert!(matches!(config.validate(),
2319 Err(ConfigError::InvalidRuntimeConfig { key: found, .. }) if found == key
2320 ));
2321 }
2322 }
2323 }
2324
2325 #[test]
2326 fn negative_toml_background_limits_are_not_deserialized() {
2327 for key in ["warm_concurrency", "maintenance_concurrency"] {
2328 let text = format!("[runtime]\n{key} = -1\n");
2329 assert!(toml::from_str::<KhiveConfig>(&text).is_err());
2330 }
2331 }
2332
2333 #[test]
2334 fn limits_keep_base_and_override_values_on_both_mapping_branches() {
2335 for engines_declared in [false, true] {
2336 let mut config: KhiveConfig =
2337 toml::from_str("[runtime]\nwarm_concurrency = 5\n").unwrap();
2338 config.engines_declared = engines_declared;
2339 let base = crate::RuntimeConfig {
2340 warm_concurrency: 3,
2341 maintenance_concurrency: 2,
2342 ..crate::RuntimeConfig::no_embeddings()
2343 };
2344 let mapped = crate::config::runtime_config_from_khive_config(&config, base);
2345 assert_eq!(mapped.warm_concurrency, 5);
2346 assert_eq!(mapped.maintenance_concurrency, 2);
2347 }
2348 }
2349
2350 #[test]
2351 fn defaults_use_the_named_validated_background_constants() {
2352 let config = crate::RuntimeConfig::default();
2353 assert_eq!(
2354 config.warm_concurrency,
2355 crate::config::DEFAULT_WARM_CONCURRENCY
2356 );
2357 assert_eq!(
2358 config.maintenance_concurrency,
2359 crate::config::DEFAULT_MAINTENANCE_CONCURRENCY
2360 );
2361 crate::resource_admission::WorkClassLimits::validate(
2362 config.warm_concurrency,
2363 config.maintenance_concurrency,
2364 )
2365 .unwrap();
2366 }
2367}