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#[derive(Debug, Error)]
40pub enum ConfigError {
41 #[error("[storage.blob] backend = \"s3\" requires the blob-s3 feature")]
42 BlobS3FeatureDisabled,
43
44 #[error(transparent)]
45 Credential(#[from] crate::credentials::CredentialError),
46
47 #[error("mount configuration: {reason}")]
48 InvalidMountConfig { reason: String },
49
50 #[error("channel configuration: {reason}")]
51 InvalidChannelConfig { reason: String },
52
53 #[error("config file I/O: {0}")]
54 Io(#[from] std::io::Error),
55
56 #[error("config TOML parse error in {path}: {source}")]
57 Parse {
58 path: PathBuf,
59 #[source]
60 source: toml::de::Error,
61 },
62
63 #[error("config TOML policy error in {path}, key {key}: {source}")]
64 SchemaParse {
65 path: PathBuf,
66 key: &'static str,
67 #[source]
68 source: Box<toml::de::Error>,
69 },
70
71 #[error("exactly one engine must be marked `default = true`; found {found}")]
72 DefaultCount { found: usize },
73
74 #[error("duplicate engine name: {name:?}")]
75 DuplicateName { name: String },
76
77 #[error(
78 "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
79 )]
80 UnknownModel { name: String, model: String },
81
82 #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
83 InvalidFusionWeight { name: String, value: f64 },
84
85 #[error(
86 "engine {name:?}: fusion_weight is not applied by current retrieval; \
87 remove it until weighted multi-engine fusion is wired"
88 )]
89 UnsupportedFusionWeight { name: String },
90
91 #[error("engine name must not be empty: {name:?}")]
92 InvalidEngineName { name: String },
93
94 #[error("engine {name:?} collides with another engine after alias canonicalization to {canonical:?}; remove the duplicate declaration")]
95 AliasCollision { name: String, canonical: String },
96
97 #[error("engine {name:?}: weight must be finite and strictly positive, got {value}")]
98 InvalidEngineWeight { name: String, value: f64 },
99
100 #[error("engine {name:?}: non-unit weight is refused until configured weights reach every activated retrieval path")]
101 UnsupportedEngineWeight { name: String },
102
103 #[error("engine {name:?}: dims must be positive and at most 4294967295, got {value}")]
104 InvalidEngineDimensions { name: String, value: i64 },
105
106 #[error(
107 "engine {name:?}: configured dims {expected} do not match provider dimensions {actual}"
108 )]
109 EngineDimensionMismatch {
110 name: String,
111 expected: i64,
112 actual: usize,
113 },
114
115 #[error("engine {name:?}: cannot mix legacy model/default/fusion_weight entries with canonical name/weight entries")]
116 EngineKeyConflict { name: String },
117
118 #[error("engines {name:?} and {other:?} share the storage key {key:?}; distinct engine identities require distinct bindings")]
119 EngineKeyCollision {
120 name: String,
121 other: String,
122 key: String,
123 },
124
125 #[error("actor.id {id:?} is not a valid namespace: {reason}")]
126 InvalidActorId { id: String, reason: String },
127
128 #[error("[actor].mailbox_readers: {reason}")]
129 InvalidMailboxReaders { reason: String },
130
131 #[error("[gate].granted_actors entry {id:?} is not a valid actor id: {reason}")]
132 InvalidGrantedActorId { id: String, reason: String },
133 #[error("[gate].deny_writes_for is invalid: {reason}")]
134 InvalidWriteDenyPatterns { reason: String },
135
136 #[error("duplicate backend name: {name:?}")]
137 DuplicateBackendName { name: String },
138
139 #[error("invalid backend name {name:?}: {reason}")]
140 InvalidBackendName { name: String, reason: String },
141
142 #[error("backend {name:?}: `served_kinds` must not be empty when declared")]
143 EmptyBackendServedKinds { name: String },
144
145 #[error("backend {name:?}: invalid disk guard configuration: {reason}")]
146 InvalidBackendDiskGuard { name: String, reason: String },
147
148 #[error(
149 "backends {first_backend:?} and {second_backend:?} name the same database but resolve \
150 different disk reserve/deadline policies"
151 )]
152 DiskGuardAliasConflict {
153 first_backend: String,
154 second_backend: String,
155 },
156
157 #[error("KHIVE_SQLITE_WAL_CEILING_BYTES must be an unsigned decimal byte count")]
158 InvalidWalCeilingEnvironment { value: String },
159
160 #[error(
161 "backend {name:?}: wal_ceiling_bytes {value} exceeds supported SQLite offset arithmetic"
162 )]
163 WalCeilingOffsetOverflow { name: String, value: u64 },
164
165 #[error(
166 "backend {name:?}: nonzero wal_ceiling_bytes {value} requires a file-backed SQLite backend"
167 )]
168 WalCeilingMemoryBackend { name: String, value: u64 },
169
170 #[error("backend {name:?}: nonzero wal_ceiling_bytes {value} requires SQLite WAL mode")]
171 WalCeilingNonWalBackend { name: String, value: u64 },
172
173 #[error(
174 "backends {first_backend:?} and {second_backend:?} name the same database at {} \
175 but resolve different WAL ceilings ({first_bytes} and {second_bytes} bytes)",
176 crate::secret_gate::bounded_masked_log_text(&path.to_string_lossy())
177 )]
178 WalCeilingAliasConflict {
179 first_backend: String,
180 second_backend: String,
181 path: PathBuf,
182 first_bytes: u64,
183 second_bytes: u64,
184 },
185
186 #[error(
187 "backend configuration leaves searchable substrate kinds {kinds:?} unserved; \
188 defined backends: {defined}"
189 )]
190 MissingBackendSearchKinds {
191 kinds: Vec<SubstrateKind>,
192 defined: String,
193 },
194
195 #[error(
196 "[packs.{pack}].backend = {backend:?} references an unknown backend; \
197 defined backends: {defined}"
198 )]
199 UnknownPackBackend {
200 pack: String,
201 backend: String,
202 defined: String,
203 },
204
205 #[error(
206 "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
207 remove it from the config or wait for a future release that implements it"
208 )]
209 UnsupportedBackendField { name: String, field: &'static str },
210
211 #[error(
212 "top-level `db = {value:?}` is not a supported config-file key; \
213 use `--db` / `KHIVE_DB` to select a single-file database, or \
214 `[[backends]].path` to declare storage backend topology"
215 )]
216 UnsupportedTopLevelDb { value: String },
217
218 #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
219 InvalidGitWriteEntry { repo: String, reason: String },
220
221 #[error("[git_write] {key}: {reason}")]
222 InvalidGitWriteConfig { key: String, reason: String },
223
224 #[error("[exec] {key}: {reason}")]
225 InvalidExecConfig { key: String, reason: String },
226
227 #[error("{entry}: {reason}")]
228 InvalidTelemetryConfig { entry: String, reason: String },
229
230 #[error("[web] {key}: {reason}")]
231 InvalidWebConfig { key: String, reason: String },
232
233 #[error("[computer].{key}: {reason}")]
234 InvalidComputerConfig { key: String, reason: String },
235
236 #[error("[actor].computer {reason}")]
237 InvalidActorComputer { reason: String },
238
239 #[error("[runtime] {key}: {reason}")]
240 InvalidRuntimeConfig { key: String, reason: String },
241
242 #[error(
243 "[runtime] blob_hydration_bytes must be between {min} and {max} bytes inclusive; got {value}"
244 )]
245 InvalidBlobHydrationBytes { value: u64, min: u64, max: u64 },
246
247 #[error("the explicitly selected config file does not exist: {path}")]
248 ExplicitConfigMissing { path: PathBuf },
249
250 #[error("[gate] configuration is not supported by this build")]
254 UnsupportedGateSection,
255
256 #[error(
257 "[display] timezone {timezone:?} is not a recognized IANA zone name (e.g. \"America/New_York\", \"UTC\")"
258 )]
259 InvalidDisplayTimezone { timezone: String },
260
261 #[error("{source} (config file: {})", path.display())]
271 InFile {
272 path: PathBuf,
273 #[source]
274 source: Box<ConfigError>,
275 },
276
277 #[error(
281 "config file {} is not the file in use (in use: {}); it was read only to look for \
282 `[actor] require_attributed`, which could not be read from it: {source}",
283 path.display(),
284 in_use.as_deref().map_or_else(|| "none".to_string(), |used| used.display().to_string())
285 )]
286 ShadowedTier {
287 path: PathBuf,
288 in_use: Option<PathBuf>,
290 #[source]
291 source: Box<ConfigError>,
292 },
293}
294
295impl ConfigError {
296 fn in_file(self, path: &Path) -> Self {
299 match self {
300 already @ (ConfigError::Parse { .. }
301 | ConfigError::SchemaParse { .. }
302 | ConfigError::ExplicitConfigMissing { .. }
303 | ConfigError::InFile { .. }) => already,
304 other => ConfigError::InFile {
305 path: path.to_path_buf(),
306 source: Box::new(other),
307 },
308 }
309 }
310}
311
312#[derive(Debug, Clone, Deserialize, Default)]
341#[serde(deny_unknown_fields)]
342pub struct ActorConfig {
343 #[serde(default)]
349 pub id: Option<String>,
350
351 #[serde(default)]
354 pub display_name: Option<String>,
355
356 #[serde(default)]
364 pub mailbox_readers: Vec<String>,
365
366 #[serde(default)]
372 pub visible_namespaces: Option<Vec<String>>,
373
374 #[serde(default)]
386 pub allowed_outbound_namespaces: Vec<String>,
387
388 #[serde(default)]
398 pub owned_namespaces: Vec<String>,
399
400 #[serde(default)]
413 pub require_attributed: bool,
414
415 #[serde(default)]
422 pub computer: Option<String>,
423}
424
425#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
432#[serde(deny_unknown_fields)]
433pub struct GateSectionConfig {
434 #[serde(default)]
436 pub granted_actors: Vec<String>,
437
438 #[serde(default)]
440 pub grant_unattributed: bool,
441
442 #[serde(default)]
445 pub deny_writes_for: Vec<String>,
446}
447
448#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
452#[serde(rename_all = "lowercase")]
453pub enum BackendKind {
454 #[default]
456 Sqlite,
457 Memory,
459}
460
461#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466pub struct ResolvedWalCeiling {
467 pub configured_bytes: u64,
469 pub effective_bytes: u64,
471 pub source: khive_db::WalCeilingSource,
473}
474
475pub fn resolve_wal_ceiling(
481 backend_field: Option<u64>,
482 env_value: Option<&str>,
483 backend_name: &str,
484 kind: BackendKind,
485 wal_mode: bool,
486 read_only: bool,
487) -> Result<ResolvedWalCeiling, ConfigError> {
488 if kind == BackendKind::Memory && backend_field.is_none() {
489 return Ok(ResolvedWalCeiling {
490 configured_bytes: 0,
491 effective_bytes: 0,
492 source: khive_db::WalCeilingSource::Default,
493 });
494 }
495 let (configured_bytes, source) = if let Some(bytes) = backend_field {
496 (bytes, khive_db::WalCeilingSource::BackendField)
497 } else if let Some(raw) = env_value {
498 if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
499 return Err(ConfigError::InvalidWalCeilingEnvironment {
500 value: raw.to_owned(),
501 });
502 }
503 let bytes = raw
504 .parse::<u64>()
505 .map_err(|_| ConfigError::InvalidWalCeilingEnvironment {
506 value: raw.to_owned(),
507 })?;
508 (bytes, khive_db::WalCeilingSource::Environment)
509 } else {
510 (0, khive_db::WalCeilingSource::Default)
511 };
512
513 if configured_bytes != 0 {
514 if i64::try_from(configured_bytes).is_err() {
515 return Err(ConfigError::WalCeilingOffsetOverflow {
516 name: backend_name.to_owned(),
517 value: configured_bytes,
518 });
519 }
520 if kind == BackendKind::Memory {
521 return Err(ConfigError::WalCeilingMemoryBackend {
522 name: backend_name.to_owned(),
523 value: configured_bytes,
524 });
525 }
526 if !wal_mode {
527 return Err(ConfigError::WalCeilingNonWalBackend {
528 name: backend_name.to_owned(),
529 value: configured_bytes,
530 });
531 }
532 }
533
534 Ok(ResolvedWalCeiling {
535 configured_bytes,
536 effective_bytes: if read_only { 0 } else { configured_bytes },
537 source,
538 })
539}
540
541#[derive(Debug, Clone, Deserialize)]
558#[serde(deny_unknown_fields)]
559pub struct BackendConfig {
560 pub name: String,
562 #[serde(default)]
564 pub kind: BackendKind,
565 pub path: Option<std::path::PathBuf>,
568 pub cache_mb: Option<u32>,
570 pub journal_mode: Option<String>,
572 #[serde(default)]
578 pub served_kinds: Option<BTreeSet<SubstrateKind>>,
579 #[serde(default)]
581 pub read_only: bool,
582 pub wal_ceiling_bytes: Option<u64>,
586 #[serde(default)]
588 pub disk_reserve_bytes: Option<u64>,
589 #[serde(default)]
591 pub disk_guard_deadline_ms: Option<u64>,
592}
593
594#[derive(Debug, Clone, Deserialize, Default)]
601pub struct CodeMapConfig {
602 #[serde(default)]
604 pub name: Option<String>,
605 #[serde(default)]
607 pub path: Option<String>,
608 #[serde(default)]
610 pub source_root: Option<String>,
611 #[serde(default, flatten)]
613 pub unknown_fields: BTreeMap<String, toml::Value>,
614}
615
616#[derive(Debug, Clone, Deserialize)]
630pub struct PackConfig {
631 #[serde(default = "default_pack_backend")]
634 pub backend: String,
635 #[serde(default)]
637 pub verbs_disabled: Vec<String>,
638 #[serde(default)]
648 pub no_embed: bool,
649}
650
651fn default_pack_backend() -> String {
652 BackendId::MAIN.to_owned()
653}
654
655#[derive(Debug, Clone, Deserialize)]
683#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
684pub enum BlobConfig {
685 Fs {
689 #[serde(default)]
690 root: Option<String>,
691 #[serde(default)]
694 floor_bytes: Option<u64>,
695 },
696 S3 {
701 bucket: String,
702 region: String,
703 #[serde(default)]
704 endpoint: Option<String>,
705 #[serde(default)]
706 prefix: Option<String>,
707 #[serde(default)]
708 allow_http: Option<bool>,
709 },
710}
711
712#[derive(Debug, Clone, Deserialize, Default)]
714#[serde(deny_unknown_fields)]
715pub struct BlobSectionConfig {
716 #[serde(default)]
718 pub file_transfers: bool,
719}
720
721#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
723#[serde(deny_unknown_fields)]
724pub struct KnowledgeSectionConfig {
725 #[serde(default)]
729 pub import_roots: Vec<std::path::PathBuf>,
730}
731
732fn names_one_repository(remote: &str) -> bool {
737 let Some(rest) = remote.strip_prefix("https://") else {
738 return false;
739 };
740 if rest.contains(['*', '?', '#', '[', ']']) {
741 return false;
742 }
743 let rest = rest.trim_end_matches('/');
744 let rest = rest.strip_suffix(".git").unwrap_or(rest);
745 let mut segments = rest.split('/');
746 let host = segments.next().unwrap_or("");
747 let path: Vec<&str> = segments.collect();
748 !host.is_empty() && path.len() >= 2 && path.iter().all(|segment| !segment.is_empty())
749}
750
751fn authority_carries_userinfo(remote: &str) -> bool {
758 let rest = match remote.split_once(':') {
759 Some((scheme, rest)) if !scheme.contains(['@', '/']) => rest,
760 _ => remote,
761 };
762 rest.trim_start_matches(['/', '\\'])
763 .split('/')
764 .next()
765 .is_some_and(|authority| authority.contains('@'))
766}
767
768fn quoted_remote(remote: &str) -> String {
772 if remote.contains('@') {
773 "an entry holding '@'".to_owned()
774 } else {
775 format!("{remote:?}")
776 }
777}
778
779#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
788#[serde(deny_unknown_fields)]
789pub struct GitDigestSectionConfig {
790 #[serde(default)]
792 pub local_roots: Vec<std::path::PathBuf>,
793 #[serde(default)]
796 pub remotes: Vec<String>,
797}
798
799#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
802#[serde(deny_unknown_fields)]
803pub struct CodeIngestSectionConfig {
804 #[serde(default)]
807 pub roots: Vec<std::path::PathBuf>,
808}
809
810impl KnowledgeSectionConfig {
811 pub fn resolved_import_roots(&self) -> Vec<std::path::PathBuf> {
814 self.import_roots
815 .iter()
816 .filter_map(|root| std::fs::canonicalize(root).ok())
817 .filter(|root| root.is_dir())
818 .collect()
819 }
820}
821
822#[derive(Debug, Clone, Deserialize, Default)]
826#[serde(deny_unknown_fields)]
827pub struct StorageSectionConfig {
828 #[serde(default)]
833 pub blob: Option<BlobConfig>,
834}
835
836#[derive(Debug, Clone, Deserialize, Serialize, Default)]
838#[serde(deny_unknown_fields)]
839pub struct BrainSectionConfig {
840 #[serde(default)]
842 pub fleet_readers: Vec<String>,
843}
844
845#[derive(Debug, Clone, Deserialize, Serialize)]
857pub struct GitWriteEntryConfig {
858 pub repo: String,
860 pub branches: Vec<String>,
863}
864
865#[derive(Debug, Clone, Deserialize, Serialize)]
877pub struct GitWriteSectionConfig {
878 #[serde(default)]
880 pub program: Option<PathBuf>,
881 #[serde(default)]
882 pub allowed: Vec<GitWriteEntryConfig>,
883 #[serde(default)]
884 pub actors: BTreeMap<String, GitWriteActorConfig>,
885 #[serde(default)]
886 pub repositories: BTreeMap<String, GitWriteRepositoryConfig>,
887 #[serde(default = "default_git_credential_resolver")]
888 pub credential_resolver: Vec<String>,
889 #[serde(default)]
890 pub contract_faults: bool,
891 #[serde(default)]
892 pub fault: Option<String>,
893}
894
895#[derive(Debug, Clone, Deserialize, Serialize)]
896#[serde(deny_unknown_fields)]
897pub struct GitWriteRepositoryConfig {
898 pub remote: String,
900 pub slug: String,
902 pub visibility: String,
903 #[serde(default)]
909 pub merge_refusals: Vec<String>,
910}
911
912impl GitWriteRepositoryConfig {
913 pub const MERGE_REFUSALS: [&'static str; 2] = ["opener", "last_pusher"];
914
915 pub fn refuses_merge_by(&self, entry: &str) -> bool {
917 self.merge_refusals.iter().any(|listed| listed == entry)
918 }
919}
920
921#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
922#[serde(deny_unknown_fields)]
923pub struct GitWriteActorConfig {
924 pub name: String,
925 pub email: String,
926 pub credential_ref: String,
927 pub platform_identity: String,
928}
929
930fn default_git_credential_resolver() -> Vec<String> {
931 [
932 "/usr/bin/security",
933 "find-generic-password",
934 "-w",
935 "-s",
936 "{ref}",
937 ]
938 .into_iter()
939 .map(str::to_string)
940 .collect()
941}
942
943impl Default for GitWriteSectionConfig {
944 fn default() -> Self {
945 Self {
946 program: None,
947 allowed: Vec::new(),
948 actors: BTreeMap::new(),
949 repositories: BTreeMap::new(),
950 credential_resolver: default_git_credential_resolver(),
951 contract_faults: false,
952 fault: None,
953 }
954 }
955}
956
957impl GitWriteSectionConfig {
958 pub fn git_program(&self) -> &Path {
959 self.program.as_deref().unwrap_or_else(|| Path::new("git"))
960 }
961
962 pub fn validate_dev_loop(&self) -> Result<(), ConfigError> {
963 let invalid = |key: &str, reason: &str| ConfigError::InvalidGitWriteConfig {
964 key: key.to_string(),
965 reason: reason.to_string(),
966 };
967 if let Some(program) = &self.program {
968 if !program.is_absolute() {
969 return Err(invalid("git_write.program", "must be absolute"));
970 }
971 let metadata = std::fs::metadata(program).map_err(|error| {
972 if error.kind() == std::io::ErrorKind::NotFound {
973 invalid("git_write.program", "does not exist")
974 } else {
975 invalid("git_write.program", &format!("is not executable: {error}"))
976 }
977 })?;
978 #[cfg(unix)]
979 let executable = {
980 use std::os::unix::fs::PermissionsExt;
981 metadata.permissions().mode() & 0o111 != 0
982 };
983 #[cfg(windows)]
984 let executable = program
985 .extension()
986 .and_then(|extension| extension.to_str())
987 .is_some_and(|extension| {
988 extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
989 });
990 #[cfg(not(any(unix, windows)))]
991 let executable = false;
992 if !metadata.is_file() || !executable {
993 return Err(invalid("git_write.program", "is not executable"));
994 }
995 }
996 if self.contract_faults && !cfg!(feature = "contract-faults") {
997 tracing::error!(
998 target: "khive.boot",
999 "[git_write] contract_faults requires the test-only contract-faults build feature"
1000 );
1001 return Err(invalid(
1002 "contract_faults",
1003 "requires the test-only contract-faults build feature",
1004 ));
1005 }
1006 if let Some(fault) = &self.fault {
1007 if !self.contract_faults {
1008 return Err(invalid("fault", "requires contract_faults = true"));
1009 }
1010 let valid = fault.split_once(':').is_some_and(|(verb, point)| {
1011 matches!(verb, "git.push" | "git.pr_merge")
1012 && matches!(
1013 point,
1014 "reply-lost-after-effect" | "audit-fails-after-effect"
1015 )
1016 });
1017 if !valid {
1018 return Err(invalid("fault", "unsupported contract fault selector"));
1019 }
1020 }
1021 for (path, repository) in &self.repositories {
1022 let key = format!("repositories.{path}.merge_refusals");
1023 let mut seen: Vec<&str> = Vec::new();
1024 for entry in &repository.merge_refusals {
1025 if !GitWriteRepositoryConfig::MERGE_REFUSALS.contains(&entry.as_str()) {
1026 return Err(invalid(&key, "entries must be opener or last_pusher"));
1027 }
1028 if seen.contains(&entry.as_str()) {
1029 return Err(invalid(&key, "entries must not repeat"));
1030 }
1031 seen.push(entry);
1032 }
1033 }
1034 if !cfg!(unix)
1037 && self.actors.is_empty()
1038 && self.credential_resolver == default_git_credential_resolver()
1039 {
1040 return Ok(());
1041 }
1042 let argv = &self.credential_resolver;
1043 let Some(program) = argv.first() else {
1044 return Err(invalid("credential_resolver", "argv must not be empty"));
1045 };
1046 let program_path = Path::new(program);
1047 if !program_path.is_absolute() {
1048 return Err(invalid(
1049 "credential_resolver",
1050 "argv[0] must be an absolute path",
1051 ));
1052 }
1053 let program_name = program_path
1054 .file_name()
1055 .and_then(|name| name.to_str())
1056 .unwrap_or_default()
1057 .to_ascii_lowercase();
1058 if matches!(
1059 program_name.trim_end_matches(".exe"),
1060 "sh" | "bash"
1061 | "dash"
1062 | "zsh"
1063 | "ksh"
1064 | "fish"
1065 | "csh"
1066 | "tcsh"
1067 | "cmd"
1068 | "powershell"
1069 | "pwsh"
1070 | "env"
1071 ) {
1072 return Err(invalid(
1073 "credential_resolver",
1074 "shell or env launcher is not allowed",
1075 ));
1076 }
1077 if argv.iter().any(|arg| arg.chars().any(char::is_control)) {
1078 return Err(invalid(
1079 "credential_resolver",
1080 "argv must not contain control characters",
1081 ));
1082 }
1083 if program.contains(['{', '}'])
1084 || argv[1..]
1085 .iter()
1086 .any(|arg| arg != "{ref}" && arg.contains(['{', '}']))
1087 {
1088 return Err(invalid(
1089 "credential_resolver",
1090 "{ref} must be a complete argument and is the only allowed template",
1091 ));
1092 }
1093 if !argv[1..].iter().any(|arg| arg == "{ref}") {
1094 return Err(invalid(
1095 "credential_resolver",
1096 "argv must contain a {ref} argument",
1097 ));
1098 }
1099 for (actor, identity) in &self.actors {
1100 if actor.trim().is_empty() || actor.chars().any(char::is_control) {
1101 return Err(invalid(
1102 "actors",
1103 "actor labels must be nonempty and contain no control characters",
1104 ));
1105 }
1106 for (field, value) in [
1107 ("name", &identity.name),
1108 ("email", &identity.email),
1109 ("credential_ref", &identity.credential_ref),
1110 ("platform_identity", &identity.platform_identity),
1111 ] {
1112 if value.trim().is_empty() || value.chars().any(char::is_control) {
1113 return Err(invalid(
1114 &format!("actors.{actor}.{field}"),
1115 "must be nonempty and contain no control characters",
1116 ));
1117 }
1118 }
1119 if identity.name.contains(['<', '>']) || identity.email.contains(['<', '>']) {
1120 return Err(invalid(
1121 &format!("actors.{actor}"),
1122 "name and email must not contain Git identity delimiters",
1123 ));
1124 }
1125 }
1126 Ok(())
1127 }
1128}
1129
1130#[derive(Debug, Clone, Deserialize, Default)]
1135pub struct ExecLimitsConfig {
1136 #[serde(default)]
1137 pub cpu_seconds: Option<u64>,
1138 #[serde(default)]
1139 pub address_space: Option<u64>,
1140 #[serde(default)]
1141 pub file_size: Option<u64>,
1142 #[serde(default)]
1143 pub nproc: Option<u64>,
1144}
1145
1146#[derive(Debug, Clone, Deserialize, Default)]
1169#[serde(deny_unknown_fields)]
1170pub struct ExecSectionConfig {
1171 #[serde(default)]
1172 pub root: Option<String>,
1173 #[serde(default)]
1174 pub read_roots: Vec<String>,
1175 #[serde(default)]
1179 pub cache_roots: Vec<String>,
1180 #[serde(default)]
1181 pub env: Vec<String>,
1182 #[serde(default)]
1183 pub never: Vec<String>,
1184 #[serde(default)]
1185 pub max_output_bytes: Option<u64>,
1186 #[serde(default)]
1187 pub timeout_default_s: Option<f64>,
1188 #[serde(default)]
1189 pub timeout_max_s: Option<f64>,
1190 #[serde(default)]
1192 pub binary_digest_timeout_s: Option<u64>,
1193 #[serde(default)]
1194 pub keep: bool,
1195 #[serde(default)]
1196 pub limits: ExecLimitsConfig,
1197 #[serde(default)]
1200 pub tool_profiles: Vec<ExecToolProfileConfig>,
1201}
1202
1203#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
1215#[serde(deny_unknown_fields)]
1216pub struct ExecToolProfileConfig {
1217 pub tool: String,
1219 #[serde(default)]
1222 pub metal: bool,
1223 #[serde(default)]
1229 pub unix_sockets: bool,
1230 #[serde(default)]
1232 pub files: Vec<String>,
1233 #[serde(default)]
1236 pub list_dirs: Vec<String>,
1237}
1238
1239pub const DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 10;
1240pub const MAX_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 60;
1241
1242#[derive(Debug, Clone, Deserialize, Serialize)]
1251#[serde(deny_unknown_fields)]
1252pub struct WebAllowlistEntry {
1253 pub host: String,
1254}
1255
1256#[derive(Debug, Clone, Deserialize, Serialize)]
1263#[serde(deny_unknown_fields)]
1264pub struct WebCredentialConfig {
1265 pub name: String,
1267 pub env_var: String,
1269 pub hosts: Vec<String>,
1272}
1273
1274#[derive(Debug, Clone, Deserialize, Serialize)]
1278#[serde(deny_unknown_fields)]
1279pub struct WebFixtureResult {
1280 pub title: String,
1281 pub url: String,
1282 pub snippet: String,
1283}
1284
1285#[derive(Debug, Clone, Deserialize, Serialize)]
1289#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
1290pub enum WebSearchProviderConfig {
1291 Fixture {
1293 name: String,
1294 #[serde(default)]
1295 default: bool,
1296 results: Vec<WebFixtureResult>,
1297 },
1298 Http {
1305 name: String,
1306 #[serde(default)]
1307 default: bool,
1308 url_template: String,
1309 #[serde(default)]
1310 api_key_env: Option<String>,
1311 #[serde(default)]
1318 hosts: Vec<String>,
1319 },
1320}
1321
1322impl WebSearchProviderConfig {
1323 pub fn name(&self) -> &str {
1324 match self {
1325 WebSearchProviderConfig::Fixture { name, .. } => name,
1326 WebSearchProviderConfig::Http { name, .. } => name,
1327 }
1328 }
1329
1330 pub fn is_default(&self) -> bool {
1331 match self {
1332 WebSearchProviderConfig::Fixture { default, .. } => *default,
1333 WebSearchProviderConfig::Http { default, .. } => *default,
1334 }
1335 }
1336}
1337
1338#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1372#[serde(deny_unknown_fields)]
1373pub struct WebSectionConfig {
1374 #[serde(default)]
1375 pub timeout_default_s: Option<u64>,
1376 #[serde(default)]
1377 pub timeout_max_s: Option<u64>,
1378 #[serde(default)]
1379 pub max_bytes_default: Option<u64>,
1380 #[serde(default)]
1381 pub max_bytes_max: Option<u64>,
1382 #[serde(default)]
1383 pub search_limit_default: Option<u32>,
1384 #[serde(default)]
1385 pub search_limit_max: Option<u32>,
1386 #[serde(default)]
1387 pub allowlist: Vec<WebAllowlistEntry>,
1388 #[serde(default)]
1389 pub credentials: Vec<WebCredentialConfig>,
1390 #[serde(default)]
1391 pub search_providers: Vec<WebSearchProviderConfig>,
1392 #[serde(default)]
1396 pub read_roots: Vec<String>,
1397}
1398
1399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1401pub struct WebCeilings {
1402 pub timeout_default_s: u64,
1403 pub timeout_max_s: u64,
1404 pub max_bytes_default: u64,
1405 pub max_bytes_max: u64,
1406 pub search_limit_default: u32,
1407 pub search_limit_max: u32,
1408}
1409
1410impl Default for WebCeilings {
1411 fn default() -> Self {
1412 Self {
1413 timeout_default_s: 30,
1414 timeout_max_s: 120,
1415 max_bytes_default: 5 * 1024 * 1024,
1416 max_bytes_max: 50 * 1024 * 1024,
1417 search_limit_default: 10,
1418 search_limit_max: 50,
1419 }
1420 }
1421}
1422
1423impl WebSectionConfig {
1424 pub fn resolved_ceilings(&self) -> Result<WebCeilings, ConfigError> {
1425 let defaults = WebCeilings::default();
1426 let bounds = WebCeilings {
1427 timeout_default_s: self.timeout_default_s.unwrap_or(defaults.timeout_default_s),
1428 timeout_max_s: self.timeout_max_s.unwrap_or(defaults.timeout_max_s),
1429 max_bytes_default: self.max_bytes_default.unwrap_or(defaults.max_bytes_default),
1430 max_bytes_max: self.max_bytes_max.unwrap_or(defaults.max_bytes_max),
1431 search_limit_default: self
1432 .search_limit_default
1433 .unwrap_or(defaults.search_limit_default),
1434 search_limit_max: self.search_limit_max.unwrap_or(defaults.search_limit_max),
1435 };
1436 for (key, default, maximum, maximum_key) in [
1437 (
1438 "timeout_default_s",
1439 bounds.timeout_default_s,
1440 bounds.timeout_max_s,
1441 "timeout_max_s",
1442 ),
1443 (
1444 "max_bytes_default",
1445 bounds.max_bytes_default,
1446 bounds.max_bytes_max,
1447 "max_bytes_max",
1448 ),
1449 (
1450 "search_limit_default",
1451 u64::from(bounds.search_limit_default),
1452 u64::from(bounds.search_limit_max),
1453 "search_limit_max",
1454 ),
1455 ] {
1456 if default == 0 || default > maximum {
1457 return Err(ConfigError::InvalidWebConfig {
1458 key: key.into(),
1459 reason: format!(
1460 "resolved default must be positive and not exceed {maximum_key}={maximum}"
1461 ),
1462 });
1463 }
1464 }
1465 if std::time::Instant::now()
1466 .checked_add(std::time::Duration::from_secs(bounds.timeout_max_s))
1467 .is_none()
1468 {
1469 return Err(ConfigError::InvalidWebConfig {
1470 key: "timeout_max_s".into(),
1471 reason: "cannot be represented as a request deadline".into(),
1472 });
1473 }
1474 Ok(bounds)
1475 }
1476
1477 pub fn validate(&self) -> Result<(), ConfigError> {
1478 self.resolved_ceilings()?;
1479 let invalid = |key: &str, reason: &str| ConfigError::InvalidWebConfig {
1480 key: key.to_string(),
1481 reason: reason.to_string(),
1482 };
1483 let mut seen_hosts = std::collections::HashSet::new();
1484 for entry in &self.allowlist {
1485 let normalized = entry.host.trim().trim_end_matches('.').to_ascii_lowercase();
1486 if normalized.is_empty() {
1487 return Err(invalid("allowlist.host", "must not be empty"));
1488 }
1489 if !seen_hosts.insert(normalized) {
1490 return Err(invalid("allowlist.host", "duplicate host entry"));
1491 }
1492 }
1493 let mut seen_credentials = std::collections::HashSet::new();
1494 for credential in &self.credentials {
1495 if credential.name.trim().is_empty() {
1496 return Err(invalid("credentials.name", "must not be empty"));
1497 }
1498 if !seen_credentials.insert(credential.name.clone()) {
1499 return Err(invalid("credentials.name", "duplicate credential name"));
1500 }
1501 if credential.env_var.trim().is_empty() {
1502 return Err(invalid("credentials.env_var", "must not be empty"));
1503 }
1504 if credential.hosts.is_empty() {
1505 return Err(invalid(
1506 "credentials.hosts",
1507 "must name at least one host or suffix",
1508 ));
1509 }
1510 }
1511 let mut seen_providers = std::collections::HashSet::new();
1512 let mut default_count = 0;
1513 for provider in &self.search_providers {
1514 let name = provider.name();
1515 if name.trim().is_empty() {
1516 return Err(invalid("search_providers.name", "must not be empty"));
1517 }
1518 if !seen_providers.insert(name.to_string()) {
1519 return Err(invalid("search_providers.name", "duplicate provider name"));
1520 }
1521 if provider.is_default() {
1522 default_count += 1;
1523 }
1524 if let WebSearchProviderConfig::Http {
1525 url_template,
1526 api_key_env,
1527 hosts,
1528 ..
1529 } = provider
1530 {
1531 if !url_template.contains("{query}") {
1532 return Err(invalid(
1533 "search_providers.url_template",
1534 "must contain the literal substring {query}",
1535 ));
1536 }
1537 if api_key_env.is_some() && hosts.is_empty() {
1538 return Err(invalid(
1539 "search_providers.hosts",
1540 "an api_key_env-bearing provider must name at least one host or suffix",
1541 ));
1542 }
1543 }
1544 }
1545 if default_count > 1 {
1546 return Err(invalid(
1547 "search_providers",
1548 "at most one provider may set default = true",
1549 ));
1550 }
1551 Ok(())
1552 }
1553}
1554
1555#[derive(Debug, Clone, Deserialize, Serialize)]
1558pub struct SchemaSectionConfig {
1559 #[serde(default = "schema_strict_default")]
1560 pub strict: bool,
1561}
1562
1563fn schema_strict_default() -> bool {
1564 true
1565}
1566
1567impl Default for SchemaSectionConfig {
1568 fn default() -> Self {
1569 Self { strict: true }
1570 }
1571}
1572
1573#[derive(Deserialize)]
1576struct SchemaSyntaxProbe {
1577 #[serde(default, deserialize_with = "deserialize_schema_table")]
1578 schema: SchemaSectionConfig,
1579}
1580
1581fn deserialize_schema_table<'de, D>(deserializer: D) -> Result<SchemaSectionConfig, D::Error>
1582where
1583 D: serde::Deserializer<'de>,
1584{
1585 struct SchemaTableVisitor;
1586 impl<'de> serde::de::Visitor<'de> for SchemaTableVisitor {
1587 type Value = SchemaSectionConfig;
1588
1589 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1590 formatter.write_str("a schema configuration table")
1591 }
1592
1593 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1594 where
1595 A: serde::de::MapAccess<'de>,
1596 {
1597 SchemaSectionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
1598 }
1599 }
1600 deserializer.deserialize_map(SchemaTableVisitor)
1601}
1602
1603#[derive(Debug, Clone, Deserialize, Default)]
1629pub struct KhiveConfig {
1630 #[serde(default)]
1632 pub schema: SchemaSectionConfig,
1633
1634 #[serde(default, deserialize_with = "embed_batch::deserialize_table")]
1636 pub embed: EmbedSectionConfig,
1637
1638 #[serde(skip)]
1640 pub credentials: Vec<crate::credentials::CredentialConfig>,
1641
1642 #[serde(skip)]
1643 pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
1644
1645 #[serde(default)]
1648 pub channel: crate::channel_section::ChannelSectionConfig,
1649
1650 #[serde(default)]
1651 pub mounts: Vec<crate::mount_config::MountConfig>,
1652
1653 #[serde(default)]
1659 pub db: Option<String>,
1660
1661 #[serde(default)]
1663 pub engines: Vec<EngineConfig>,
1664
1665 #[serde(skip)]
1669 pub engines_declared: bool,
1670
1671 #[serde(default)]
1679 pub actor: ActorConfig,
1680
1681 #[serde(default)]
1685 pub gate: Option<GateSectionConfig>,
1686
1687 #[serde(default)]
1689 pub runtime: RuntimeSectionConfig,
1690
1691 #[serde(default)]
1696 pub backends: Vec<BackendConfig>,
1697
1698 #[serde(default)]
1700 pub code_map_root: Option<String>,
1701
1702 #[serde(default)]
1704 pub code_maps: Vec<CodeMapConfig>,
1705
1706 #[serde(default)]
1712 pub packs: std::collections::HashMap<String, PackConfig>,
1713
1714 #[serde(default)]
1716 pub brain: BrainSectionConfig,
1717
1718 #[serde(default)]
1722 pub git_write: GitWriteSectionConfig,
1723
1724 #[serde(default)]
1726 pub blob: BlobSectionConfig,
1727
1728 #[serde(default)]
1730 pub knowledge: KnowledgeSectionConfig,
1731
1732 #[serde(default)]
1734 pub git_digest: GitDigestSectionConfig,
1735
1736 #[serde(default)]
1738 pub code_ingest: CodeIngestSectionConfig,
1739
1740 #[serde(default)]
1743 pub storage: StorageSectionConfig,
1744
1745 #[serde(default)]
1748 pub exec: ExecSectionConfig,
1749
1750 #[serde(default)]
1752 pub telemetry: crate::telemetry_config::TelemetryConfig,
1753
1754 #[serde(default)]
1758 pub display: DisplaySectionConfig,
1759
1760 #[serde(default)]
1765 pub web: WebSectionConfig,
1766
1767 #[serde(default)]
1772 pub computer: Option<ComputerSectionConfig>,
1773}
1774
1775#[derive(Debug, Clone, Deserialize, Default)]
1782pub struct RuntimeSectionConfig {
1783 #[serde(default)]
1786 pub warm_concurrency: Option<usize>,
1787
1788 #[serde(default)]
1791 pub maintenance_concurrency: Option<usize>,
1792
1793 #[serde(default)]
1796 pub packs: Option<Vec<String>>,
1797
1798 #[serde(default)]
1805 pub brain_profile: Option<String>,
1806
1807 #[serde(default)]
1814 pub default_output_format: Option<OutputFormat>,
1815
1816 #[serde(default)]
1823 pub blob_hydration_bytes: Option<u64>,
1824}
1825
1826#[derive(Debug, Clone, Deserialize, Default)]
1834pub struct DisplaySectionConfig {
1835 #[serde(default)]
1841 pub timezone: Option<String>,
1842}
1843
1844impl KhiveConfig {
1845 pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
1861 let resolved = match path {
1862 Some(p) => p.to_path_buf(),
1863 None => PathBuf::from(".khive/config.toml"),
1864 };
1865
1866 if !resolved.exists() {
1867 return Ok(None);
1868 }
1869
1870 let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
1873 let raw = std::fs::read_to_string(&resolved)
1874 .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
1875 let mut document: toml::Value =
1876 toml::from_str(&raw).map_err(|source| ConfigError::Parse {
1877 path: diagnostic_path.clone(),
1878 source,
1879 })?;
1880 let schema_probe: SchemaSyntaxProbe =
1881 toml::from_str(&raw).map_err(|source| ConfigError::SchemaParse {
1882 path: diagnostic_path.clone(),
1883 key: if document
1884 .get("schema")
1885 .is_some_and(|value| !value.is_table())
1886 {
1887 "schema"
1888 } else {
1889 "schema.strict"
1890 },
1891 source: Box::new(source),
1892 })?;
1893 let unknown_schema_keys: Vec<String> = document
1894 .get("schema")
1895 .and_then(toml::Value::as_table)
1896 .map(|table| {
1897 table
1898 .keys()
1899 .filter(|key| key.as_str() != "strict")
1900 .cloned()
1901 .collect()
1902 })
1903 .unwrap_or_default();
1904 let (embed, unknown_embed_keys) = embed_batch::parse(&raw, &document, &diagnostic_path)?;
1905 let engines_declared = peers::normalize_engine_input(&mut document, &diagnostic_path)
1906 .map_err(|error| error.in_file(&diagnostic_path))?;
1907 if let Some(table) = document.as_table_mut() {
1910 table.remove("embed");
1911 }
1912 let mut cfg: KhiveConfig = document.try_into().map_err(|source| ConfigError::Parse {
1913 path: diagnostic_path.clone(),
1914 source,
1915 })?;
1916 cfg.schema = schema_probe.schema;
1917 cfg.embed = embed;
1918 cfg.engines_declared = engines_declared;
1919 crate::credentials::read_tables(&raw, &mut cfg)
1920 .map_err(|error| ConfigError::from(error).in_file(&diagnostic_path))?;
1921 cfg.validate()
1922 .map_err(|error| error.in_file(&diagnostic_path))?;
1923 for engine in &mut cfg.engines {
1924 engine.name = canonical_engine_name(&engine.name);
1925 }
1926 for key in unknown_schema_keys {
1927 tracing::warn!(target: "khive.config.schema",
1928 key = %crate::secret_gate::bounded_masked_log_text(&key),
1929 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1930 "ignoring unknown schema configuration key");
1931 }
1932 for key in unknown_embed_keys {
1933 tracing::warn!(target: "khive.config.embed",
1934 key = %crate::secret_gate::bounded_masked_log_text(&key),
1935 file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1936 "ignoring unknown embed configuration key");
1937 }
1938 Ok(Some(cfg))
1939 }
1940
1941 pub fn load_with_home_fallback(
1969 path: Option<&Path>,
1970 db_path: Option<&Path>,
1971 ) -> Result<Option<Self>, ConfigError> {
1972 Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
1973 }
1974
1975 pub fn load_with_home_fallback_and_source(
1983 path: Option<&Path>,
1984 db_path: Option<&Path>,
1985 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1986 if let Some(p) = path {
1994 if !p.exists() {
1995 return Err(ConfigError::ExplicitConfigMissing {
1996 path: p.to_path_buf(),
1997 });
1998 }
1999 return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
2000 }
2001
2002 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
2004 let home_root = std::env::var_os("HOME").map(PathBuf::from);
2005 Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
2006 }
2007
2008 #[cfg(test)]
2017 pub(crate) fn load_with_roots(
2018 project_root: &Path,
2019 home_root: Option<&Path>,
2020 db_path: Option<&Path>,
2021 ) -> Result<Option<Self>, ConfigError> {
2022 Ok(
2023 Self::load_with_roots_and_source(project_root, home_root, db_path)?
2024 .map(|(config, _)| config),
2025 )
2026 }
2027
2028 fn load_with_roots_and_source(
2029 project_root: &Path,
2030 home_root: Option<&Path>,
2031 db_path: Option<&Path>,
2032 ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
2033 let tier2 = project_root.join("khive.toml");
2035 if tier2.exists() {
2036 return Ok(Self::load(Some(&tier2))?
2037 .map(|config| (config, Self::diagnostic_config_path(&tier2))));
2038 }
2039
2040 let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
2043 if tier3.exists() {
2044 return Ok(Self::load(Some(&tier3))?
2045 .map(|config| (config, Self::diagnostic_config_path(&tier3))));
2046 }
2047
2048 if let Some(home) = home_root {
2050 let tier4 = home.join(".khive/config.toml");
2051 if tier4.exists() {
2052 return Ok(Self::load(Some(&tier4))?
2053 .map(|config| (config, Self::diagnostic_config_path(&tier4))));
2054 }
2055 }
2056
2057 Ok(None)
2058 }
2059
2060 pub fn require_attributed_in_any_tier(
2064 path: Option<&Path>,
2065 db_path: Option<&Path>,
2066 ) -> Result<bool, ConfigError> {
2067 if let Some(p) = path {
2068 if !p.exists() {
2069 return Err(ConfigError::ExplicitConfigMissing {
2070 path: p.to_path_buf(),
2071 });
2072 }
2073 return Ok(Self::load(Some(p))?.is_some_and(|cfg| cfg.actor.require_attributed));
2074 }
2075 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
2076 let home_root = std::env::var_os("HOME").map(PathBuf::from);
2077 Self::require_attributed_in_tiers(&project_root, home_root.as_deref(), db_path)
2078 }
2079
2080 pub(crate) fn require_attributed_in_tiers(
2083 project_root: &Path,
2084 home_root: Option<&Path>,
2085 db_path: Option<&Path>,
2086 ) -> Result<bool, ConfigError> {
2087 let mut files = vec![
2088 project_root.join("khive.toml"),
2089 Self::project_config_anchor_dir(db_path, project_root).join("config.toml"),
2090 project_root.join(".khive/config.toml"),
2091 ];
2092 let home_file = home_root.map(|home| home.join(".khive/config.toml"));
2093 let in_use = [Some(&files[0]), Some(&files[1]), home_file.as_ref()]
2095 .into_iter()
2096 .flatten()
2097 .find(|file| file.exists())
2098 .cloned();
2099 files.extend(home_file);
2100 files.dedup();
2101 for file in files.iter().filter(|file| file.exists()) {
2102 let loaded = Self::load(Some(file)).map_err(|source| match &in_use {
2103 Some(used) if used == file => source,
2104 _ => ConfigError::ShadowedTier {
2105 path: Self::diagnostic_config_path(file),
2106 in_use: in_use.as_deref().map(Self::diagnostic_config_path),
2107 source: Box::new(source),
2108 },
2109 })?;
2110 if loaded.is_some_and(|cfg| cfg.actor.require_attributed) {
2111 return Ok(true);
2112 }
2113 }
2114 Ok(false)
2115 }
2116
2117 fn diagnostic_config_path(path: &Path) -> PathBuf {
2118 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
2119 }
2120
2121 fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
2147 let Some(db_path) = db_path else {
2148 return project_root.join(".khive");
2149 };
2150
2151 let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
2152 if db_path.is_absolute() {
2153 db_path.to_path_buf()
2154 } else {
2155 project_root.join(db_path)
2156 }
2157 });
2158
2159 let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
2160
2161 if db_dir.file_name().is_some_and(|name| name == ".khive") {
2162 db_dir
2163 } else {
2164 db_dir.join(".khive")
2165 }
2166 }
2167
2168 pub fn validate(&self) -> Result<(), ConfigError> {
2174 #[cfg(not(feature = "blob-s3"))]
2175 if matches!(&self.storage.blob, Some(BlobConfig::S3 { .. })) {
2176 return Err(ConfigError::BlobS3FeatureDisabled);
2177 }
2178
2179 if let Some(root) = self
2180 .knowledge
2181 .import_roots
2182 .iter()
2183 .find(|root| !root.is_absolute())
2184 {
2185 return Err(ConfigError::InvalidRuntimeConfig {
2186 key: "knowledge.import_roots".to_owned(),
2187 reason: format!("{root:?} is not an absolute path"),
2188 });
2189 }
2190 if let Some(root) = self
2191 .git_digest
2192 .local_roots
2193 .iter()
2194 .find(|root| !root.is_absolute())
2195 {
2196 return Err(ConfigError::InvalidRuntimeConfig {
2197 key: "git_digest.local_roots".to_owned(),
2198 reason: format!("{root:?} is not an absolute path"),
2199 });
2200 }
2201 if let Some(root) = self
2202 .code_ingest
2203 .roots
2204 .iter()
2205 .find(|root| !root.is_absolute())
2206 {
2207 return Err(ConfigError::InvalidRuntimeConfig {
2208 key: "code_ingest.roots".to_owned(),
2209 reason: format!("{root:?} is not an absolute path"),
2210 });
2211 }
2212 if self
2216 .git_digest
2217 .remotes
2218 .iter()
2219 .any(|remote| authority_carries_userinfo(remote))
2220 {
2221 return Err(ConfigError::InvalidRuntimeConfig {
2222 key: "git_digest.remotes".to_owned(),
2223 reason: "an entry carries a user name or password before its host; \
2224 list the repository URL without credentials"
2225 .to_owned(),
2226 });
2227 }
2228 if let Some(remote) = self
2229 .git_digest
2230 .remotes
2231 .iter()
2232 .find(|remote| !remote.starts_with("https://"))
2233 {
2234 return Err(ConfigError::InvalidRuntimeConfig {
2235 key: "git_digest.remotes".to_owned(),
2236 reason: format!("{} is not an https:// URL", quoted_remote(remote)),
2237 });
2238 }
2239 if let Some(remote) = self
2240 .git_digest
2241 .remotes
2242 .iter()
2243 .find(|remote| !names_one_repository(remote))
2244 {
2245 return Err(ConfigError::InvalidRuntimeConfig {
2246 key: "git_digest.remotes".to_owned(),
2247 reason: format!(
2248 "{} does not name one repository: an entry is a full https://host/owner/repo URL, \
2249 never an owner, a host or a pattern",
2250 quoted_remote(remote)
2251 ),
2252 });
2253 }
2254
2255 let warm = self
2256 .runtime
2257 .warm_concurrency
2258 .unwrap_or(crate::config::DEFAULT_WARM_CONCURRENCY);
2259 let maintenance = self
2260 .runtime
2261 .maintenance_concurrency
2262 .unwrap_or(crate::config::DEFAULT_MAINTENANCE_CONCURRENCY);
2263 crate::resource_admission::WorkClassLimits::validate(warm, maintenance).map_err(
2264 |error| {
2265 let key = match &error {
2266 crate::resource_admission::ResourceError::InvalidLimit {
2267 class: crate::resource_admission::WorkClass::Warm,
2268 ..
2269 } => "warm_concurrency",
2270 crate::resource_admission::ResourceError::InvalidLimit {
2271 class: crate::resource_admission::WorkClass::Maintenance,
2272 ..
2273 } => "maintenance_concurrency",
2274 _ => "background_concurrency",
2275 };
2276 ConfigError::InvalidRuntimeConfig {
2277 key: key.to_owned(),
2278 reason: error.to_string(),
2279 }
2280 },
2281 )?;
2282
2283 crate::mount_config::validate_mounts(&self.mounts)?;
2284 self.git_write.validate_dev_loop()?;
2285 self.telemetry.validate()?;
2286 self.web.validate()?;
2287 if let Some(computer) = &self.computer {
2288 computer.validate()?;
2289 }
2290 computer::validate_actor_computer(self.computer.as_ref(), self.actor.computer.as_deref())?;
2291 crate::credentials::CredentialConfig::validate_all(&self.credentials)?;
2292 if let Some(receipts) = &self.visibility_receipts {
2293 receipts.validate(&self.credentials)?;
2294 }
2295 self.channel.validate()?;
2296
2297 if let Some(value) = self.db.as_deref() {
2302 if !value.is_empty() {
2303 return Err(ConfigError::UnsupportedTopLevelDb {
2304 value: value.to_string(),
2305 });
2306 }
2307 }
2308
2309 if cfg!(target_os = "macos") {
2313 if self.exec.limits.address_space.is_some() {
2314 return Err(ConfigError::InvalidExecConfig {
2315 key: "limits.address_space".to_string(),
2316 reason: "unsupported_on_platform: macOS does not enforce an address-space rlimit per process".to_string(),
2317 });
2318 }
2319 if self.exec.limits.nproc.is_some() {
2320 return Err(ConfigError::InvalidExecConfig {
2321 key: "limits.nproc".to_string(),
2322 reason: "unsupported_on_platform: RLIMIT_NPROC counts every process of the uid, not one run".to_string(),
2323 });
2324 }
2325 }
2326 let default_timeout = self.exec.timeout_default_s.unwrap_or(30.0);
2330 let maximum_timeout = self.exec.timeout_max_s.unwrap_or(600.0);
2331 for (key, value) in [
2332 ("timeout_default_s", default_timeout),
2333 ("timeout_max_s", maximum_timeout),
2334 ] {
2335 let duration = value
2336 .is_finite()
2337 .then(|| std::time::Duration::try_from_secs_f64(value).ok())
2338 .flatten()
2339 .filter(|duration| !duration.is_zero());
2340 if duration
2341 .is_none_or(|duration| std::time::Instant::now().checked_add(duration).is_none())
2342 {
2343 return Err(ConfigError::InvalidExecConfig {
2344 key: key.to_string(),
2345 reason: "must be positive, finite, and representable as a deadline".to_string(),
2346 });
2347 }
2348 }
2349 if default_timeout > maximum_timeout {
2350 return Err(ConfigError::InvalidExecConfig {
2351 key: "timeout_default_s".to_string(),
2352 reason: format!(
2353 "default {default_timeout} exceeds timeout_max_s {maximum_timeout}"
2354 ),
2355 });
2356 }
2357 let binary_digest_timeout = self
2358 .exec
2359 .binary_digest_timeout_s
2360 .unwrap_or(DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S);
2361 if !(1..=MAX_EXEC_BINARY_DIGEST_TIMEOUT_S).contains(&binary_digest_timeout) {
2362 return Err(ConfigError::InvalidExecConfig {
2363 key: "binary_digest_timeout_s".to_string(),
2364 reason: format!("must be between 1 and {MAX_EXEC_BINARY_DIGEST_TIMEOUT_S} seconds"),
2365 });
2366 }
2367
2368 if let Some(value) = self.runtime.blob_hydration_bytes {
2369 let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
2370 let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
2371 if value < min || value > max {
2372 return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
2373 }
2374 }
2375
2376 if let Some(id) = self.actor.id.as_deref() {
2379 if id.is_empty() {
2380 return Err(ConfigError::InvalidActorId {
2381 id: id.to_string(),
2382 reason: "actor.id must not be empty; remove the key or provide a value"
2383 .to_string(),
2384 });
2385 }
2386 Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
2387 id: id.to_string(),
2388 reason: e.to_string(),
2389 })?;
2390 }
2391
2392 self.actor
2393 .mailbox_gate(std::sync::Arc::new(khive_gate::AllowAllGate))
2394 .map_err(|error| ConfigError::InvalidMailboxReaders {
2395 reason: error.to_string(),
2396 })?;
2397
2398 if let Some(ref vis) = self.actor.visible_namespaces {
2399 for ns_str in vis {
2400 if ns_str.is_empty() {
2401 return Err(ConfigError::InvalidActorId {
2402 id: ns_str.clone(),
2403 reason: "visible_namespaces entries must not be empty".to_string(),
2404 });
2405 }
2406 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2407 id: ns_str.clone(),
2408 reason: format!("invalid visible namespace: {e}"),
2409 })?;
2410 }
2411 }
2412
2413 if !self.actor.owned_namespaces.is_empty() {
2417 let Some(actor_id) = self.actor.id.as_deref() else {
2418 return Err(ConfigError::InvalidActorId {
2419 id: String::new(),
2420 reason: "owned_namespaces requires an explicit [actor] id".to_string(),
2421 });
2422 };
2423 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2424 for ns_str in &self.actor.owned_namespaces {
2425 if ns_str.is_empty() {
2426 return Err(ConfigError::InvalidActorId {
2427 id: ns_str.clone(),
2428 reason: "owned_namespaces entries must not be empty".to_string(),
2429 });
2430 }
2431 let parsed = Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2432 id: ns_str.clone(),
2433 reason: format!("invalid owned namespace: {e}"),
2434 })?;
2435 if parsed.as_str() == Namespace::LOCAL {
2436 return Err(ConfigError::InvalidActorId {
2437 id: ns_str.clone(),
2438 reason: "owned_namespaces must not list the shared namespace `local`"
2439 .to_string(),
2440 });
2441 }
2442 if parsed.as_str() == actor_id {
2443 return Err(ConfigError::InvalidActorId {
2444 id: ns_str.clone(),
2445 reason: "owned_namespaces must not list the actor's own id".to_string(),
2446 });
2447 }
2448 if !seen.insert(parsed.as_str().to_string()) {
2449 return Err(ConfigError::InvalidActorId {
2450 id: ns_str.clone(),
2451 reason: "owned_namespaces entries must be unique".to_string(),
2452 });
2453 }
2454 }
2455 }
2456
2457 if let Some(gate) = &self.gate {
2458 khive_gate::CallerEnrollmentGate::validate_write_denials(&gate.deny_writes_for)
2459 .map_err(|error| ConfigError::InvalidWriteDenyPatterns {
2460 reason: error.to_string(),
2461 })?;
2462 for id in &gate.granted_actors {
2463 if id.is_empty() {
2464 return Err(ConfigError::InvalidGrantedActorId {
2465 id: id.clone(),
2466 reason: "actor ids must not be empty".to_string(),
2467 });
2468 }
2469 Namespace::parse(id).map_err(|error| ConfigError::InvalidGrantedActorId {
2470 id: id.clone(),
2471 reason: error.to_string(),
2472 })?;
2473 }
2474 }
2475
2476 for ns_str in &self.actor.allowed_outbound_namespaces {
2478 if ns_str.is_empty() {
2479 return Err(ConfigError::InvalidActorId {
2480 id: ns_str.clone(),
2481 reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
2482 });
2483 }
2484 Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2485 id: ns_str.clone(),
2486 reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
2487 })?;
2488 }
2489
2490 if !self.backends.is_empty() {
2492 let mut seen_backends = std::collections::HashSet::new();
2493 for backend in &self.backends {
2494 BackendId::parse(&backend.name).map_err(|error| {
2495 ConfigError::InvalidBackendName {
2496 name: backend.name.clone(),
2497 reason: error.to_string(),
2498 }
2499 })?;
2500 if backend
2501 .served_kinds
2502 .as_ref()
2503 .is_some_and(BTreeSet::is_empty)
2504 {
2505 return Err(ConfigError::EmptyBackendServedKinds {
2506 name: backend.name.clone(),
2507 });
2508 }
2509 if !seen_backends.insert(backend.name.clone()) {
2510 return Err(ConfigError::DuplicateBackendName {
2511 name: backend.name.clone(),
2512 });
2513 }
2514
2515 if backend.wal_ceiling_bytes.is_some() {
2519 resolve_wal_ceiling(
2520 backend.wal_ceiling_bytes,
2521 None,
2522 &backend.name,
2523 backend.kind.clone(),
2524 backend
2525 .journal_mode
2526 .as_deref()
2527 .is_none_or(|mode| mode.eq_ignore_ascii_case("wal")),
2528 backend.read_only,
2529 )?;
2530 }
2531
2532 backend.resolve_disk_guard(&khive_db::DiskGuardEnvironment::default())?;
2533
2534 if backend.cache_mb.is_some() {
2537 return Err(ConfigError::UnsupportedBackendField {
2538 name: backend.name.clone(),
2539 field: "cache_mb",
2540 });
2541 }
2542 if backend.journal_mode.is_some() {
2543 return Err(ConfigError::UnsupportedBackendField {
2544 name: backend.name.clone(),
2545 field: "journal_mode",
2546 });
2547 }
2548 }
2549 }
2550
2551 let defined: Vec<&str> = if self.backends.is_empty() {
2552 vec![BackendId::MAIN]
2553 } else {
2554 self.backends.iter().map(|b| b.name.as_str()).collect()
2555 };
2556 for (pack_name, pack_cfg) in &self.packs {
2557 if !defined.contains(&pack_cfg.backend.as_str()) {
2558 return Err(ConfigError::UnknownPackBackend {
2559 pack: pack_name.clone(),
2560 backend: pack_cfg.backend.clone(),
2561 defined: defined.join(", "),
2562 });
2563 }
2564 }
2565
2566 if !self.backends.is_empty() {
2567 let missing: Vec<_> = [SubstrateKind::Note, SubstrateKind::Entity]
2568 .into_iter()
2569 .filter(|kind| {
2570 !self.backends.iter().any(|backend| {
2571 backend
2572 .served_kinds
2573 .as_ref()
2574 .is_none_or(|served| served.contains(kind))
2575 })
2576 })
2577 .collect();
2578 if !missing.is_empty() {
2579 return Err(ConfigError::MissingBackendSearchKinds {
2580 kinds: missing,
2581 defined: defined.join(", "),
2582 });
2583 }
2584 }
2585
2586 if let Some(tz) = self.display.timezone.as_deref() {
2589 if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
2590 return Err(ConfigError::InvalidDisplayTimezone {
2591 timezone: tz.to_string(),
2592 });
2593 }
2594 }
2595
2596 for entry in &self.git_write.allowed {
2603 if entry.repo.trim().is_empty() {
2604 return Err(ConfigError::InvalidGitWriteEntry {
2605 repo: entry.repo.clone(),
2606 reason: "repo must not be empty".to_string(),
2607 });
2608 }
2609 if !Path::new(&entry.repo).is_absolute() {
2610 return Err(ConfigError::InvalidGitWriteEntry {
2611 repo: entry.repo.clone(),
2612 reason: "repo must be an absolute path".to_string(),
2613 });
2614 }
2615 if entry.branches.is_empty() {
2616 return Err(ConfigError::InvalidGitWriteEntry {
2617 repo: entry.repo.clone(),
2618 reason: "branches must not be empty".to_string(),
2619 });
2620 }
2621 if entry.branches.iter().any(|b| b.trim().is_empty()) {
2622 return Err(ConfigError::InvalidGitWriteEntry {
2623 repo: entry.repo.clone(),
2624 reason: "branches entries must not be empty".to_string(),
2625 });
2626 }
2627 if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
2632 return Err(ConfigError::InvalidGitWriteEntry {
2633 repo: entry.repo.clone(),
2634 reason: format!(
2635 "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
2636 ),
2637 });
2638 }
2639 }
2640
2641 validate_peer_engines(&self.engines)
2642 }
2643
2644 pub fn default_engine(&self) -> Option<&EngineConfig> {
2646 self.engines.first()
2647 }
2648}
2649
2650pub fn config_from_env() -> KhiveConfig {
2664 let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
2665 .ok()
2666 .filter(|s| !s.trim().is_empty());
2667 let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
2668 .ok()
2669 .unwrap_or_default();
2670 let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
2671 .into_iter()
2672 .filter(|s| !s.is_empty())
2673 .collect();
2674
2675 if primary_model.is_none() && additional.is_empty() {
2676 return KhiveConfig::default();
2677 }
2678
2679 tracing::info!(
2680 "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
2681 );
2682
2683 config_from_env_parts(primary_model, additional)
2684}
2685
2686fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
2689 let mut engines = Vec::new();
2690
2691 let primary =
2692 primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
2693 for model in std::iter::once(primary).chain(additional) {
2694 let name = canonical_engine_name(&model);
2695 if engines
2696 .iter()
2697 .any(|engine: &EngineConfig| engine.name == name)
2698 {
2699 continue;
2700 }
2701 engines.push(EngineConfig {
2702 name,
2703 weight: 1.0,
2704 dims: None,
2705 });
2706 }
2707
2708 KhiveConfig {
2709 engines,
2710 ..KhiveConfig::default()
2711 }
2712}
2713
2714#[cfg(test)]
2715#[path = "engine_config_schema_tests.rs"]
2716mod schema_tests;
2717
2718#[cfg(test)]
2723#[path = "engine_config_tests.rs"]
2724mod tests;
2725
2726#[cfg(test)]
2727mod background_limit_tests {
2728 use super::*;
2729
2730 #[test]
2731 fn optional_background_limits_parse_and_validate() {
2732 let config: KhiveConfig =
2733 toml::from_str("[runtime]\nwarm_concurrency = 3\nmaintenance_concurrency = 2\n")
2734 .unwrap();
2735 config.validate().unwrap();
2736 assert_eq!(config.runtime.warm_concurrency, Some(3));
2737 assert_eq!(config.runtime.maintenance_concurrency, Some(2));
2738 }
2739
2740 #[test]
2741 fn zero_and_overflow_limits_report_the_actual_runtime_key() {
2742 for key in ["warm_concurrency", "maintenance_concurrency"] {
2743 for value in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] {
2744 let mut config: KhiveConfig = toml::from_str("").unwrap();
2745 if key == "warm_concurrency" {
2746 config.runtime.warm_concurrency = Some(value);
2747 } else {
2748 config.runtime.maintenance_concurrency = Some(value);
2749 }
2750 assert!(matches!(config.validate(),
2751 Err(ConfigError::InvalidRuntimeConfig { key: found, .. }) if found == key
2752 ));
2753 }
2754 }
2755 }
2756
2757 #[test]
2758 fn negative_toml_background_limits_are_not_deserialized() {
2759 for key in ["warm_concurrency", "maintenance_concurrency"] {
2760 let text = format!("[runtime]\n{key} = -1\n");
2761 assert!(toml::from_str::<KhiveConfig>(&text).is_err());
2762 }
2763 }
2764
2765 #[test]
2766 fn limits_keep_base_and_override_values_on_both_mapping_branches() {
2767 for engines_declared in [false, true] {
2768 let mut config: KhiveConfig =
2769 toml::from_str("[runtime]\nwarm_concurrency = 5\n").unwrap();
2770 config.engines_declared = engines_declared;
2771 let base = crate::RuntimeConfig {
2772 warm_concurrency: 3,
2773 maintenance_concurrency: 2,
2774 ..crate::RuntimeConfig::no_embeddings()
2775 };
2776 let mapped = crate::config::runtime_config_from_khive_config(&config, base);
2777 assert_eq!(mapped.warm_concurrency, 5);
2778 assert_eq!(mapped.maintenance_concurrency, 2);
2779 }
2780 }
2781
2782 #[test]
2783 fn defaults_use_the_named_validated_background_constants() {
2784 let config = crate::RuntimeConfig::default();
2785 assert_eq!(
2786 config.warm_concurrency,
2787 crate::config::DEFAULT_WARM_CONCURRENCY
2788 );
2789 assert_eq!(
2790 config.maintenance_concurrency,
2791 crate::config::DEFAULT_MAINTENANCE_CONCURRENCY
2792 );
2793 crate::resource_admission::WorkClassLimits::validate(
2794 config.warm_concurrency,
2795 config.maintenance_concurrency,
2796 )
2797 .unwrap();
2798 }
2799}