Skip to main content

khive_runtime/
engine_config.rs

1//! TOML-based embedding engine configuration for khive.
2//!
3//! Loads `.khive/config.toml` (or `--config` / `KHIVE_CONFIG`) and exposes an
4//! `[[engines]]` array for arbitrary-N embedding engine registration. Falls back
5//! to `KHIVE_EMBEDDING_MODEL` env vars when no config file is present.
6
7use 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// ---- Error type ----
29
30/// Errors produced while loading or validating a `KhiveConfig`.
31#[derive(Debug, Error)]
32pub enum ConfigError {
33    #[error("[storage.blob] backend = \"s3\" requires the blob-s3 feature")]
34    BlobS3FeatureDisabled,
35
36    #[error(transparent)]
37    Credential(#[from] crate::credentials::CredentialError),
38
39    #[error("mount configuration: {reason}")]
40    InvalidMountConfig { reason: String },
41
42    #[error("channel configuration: {reason}")]
43    InvalidChannelConfig { reason: String },
44
45    #[error("config file I/O: {0}")]
46    Io(#[from] std::io::Error),
47
48    #[error("config TOML parse error in {path}: {source}")]
49    Parse {
50        path: PathBuf,
51        #[source]
52        source: toml::de::Error,
53    },
54
55    #[error("config TOML policy error in {path}, key {key}: {source}")]
56    SchemaParse {
57        path: PathBuf,
58        key: &'static str,
59        #[source]
60        source: Box<toml::de::Error>,
61    },
62
63    #[error("exactly one engine must be marked `default = true`; found {found}")]
64    DefaultCount { found: usize },
65
66    #[error("duplicate engine name: {name:?}")]
67    DuplicateName { name: String },
68
69    #[error(
70        "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
71    )]
72    UnknownModel { name: String, model: String },
73
74    #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
75    InvalidFusionWeight { name: String, value: f64 },
76
77    #[error(
78        "engine {name:?}: fusion_weight is not applied by current retrieval; \
79         remove it until weighted multi-engine fusion is wired"
80    )]
81    UnsupportedFusionWeight { name: String },
82
83    #[error("engine name must not be empty: {name:?}")]
84    InvalidEngineName { name: String },
85
86    #[error("engine {name:?} collides with another engine after alias canonicalization to {canonical:?}; remove the duplicate declaration")]
87    AliasCollision { name: String, canonical: String },
88
89    #[error("engine {name:?}: weight must be finite and strictly positive, got {value}")]
90    InvalidEngineWeight { name: String, value: f64 },
91
92    #[error("engine {name:?}: non-unit weight is refused until configured weights reach every activated retrieval path")]
93    UnsupportedEngineWeight { name: String },
94
95    #[error("engine {name:?}: dims must be positive and at most 4294967295, got {value}")]
96    InvalidEngineDimensions { name: String, value: i64 },
97
98    #[error(
99        "engine {name:?}: configured dims {expected} do not match provider dimensions {actual}"
100    )]
101    EngineDimensionMismatch {
102        name: String,
103        expected: i64,
104        actual: usize,
105    },
106
107    #[error("engine {name:?}: cannot mix legacy model/default/fusion_weight entries with canonical name/weight entries")]
108    EngineKeyConflict { name: String },
109
110    #[error("engines {name:?} and {other:?} share the storage key {key:?}; distinct engine identities require distinct bindings")]
111    EngineKeyCollision {
112        name: String,
113        other: String,
114        key: String,
115    },
116
117    #[error("actor.id {id:?} is not a valid namespace: {reason}")]
118    InvalidActorId { id: String, reason: String },
119
120    #[error("[actor].mailbox_readers: {reason}")]
121    InvalidMailboxReaders { reason: String },
122
123    #[error("[gate].granted_actors entry {id:?} is not a valid actor id: {reason}")]
124    InvalidGrantedActorId { id: String, reason: String },
125    #[error("[gate].deny_writes_for is invalid: {reason}")]
126    InvalidWriteDenyPatterns { reason: String },
127
128    #[error("duplicate backend name: {name:?}")]
129    DuplicateBackendName { name: String },
130
131    #[error("invalid backend name {name:?}: {reason}")]
132    InvalidBackendName { name: String, reason: String },
133
134    #[error("backend {name:?}: `served_kinds` must not be empty when declared")]
135    EmptyBackendServedKinds { name: String },
136
137    #[error("backend {name:?}: invalid disk guard configuration: {reason}")]
138    InvalidBackendDiskGuard { name: String, reason: String },
139
140    #[error(
141        "backends {first_backend:?} and {second_backend:?} name the same database but resolve \
142         different disk reserve/deadline policies"
143    )]
144    DiskGuardAliasConflict {
145        first_backend: String,
146        second_backend: String,
147    },
148
149    #[error("KHIVE_SQLITE_WAL_CEILING_BYTES must be an unsigned decimal byte count")]
150    InvalidWalCeilingEnvironment { value: String },
151
152    #[error(
153        "backend {name:?}: wal_ceiling_bytes {value} exceeds supported SQLite offset arithmetic"
154    )]
155    WalCeilingOffsetOverflow { name: String, value: u64 },
156
157    #[error(
158        "backend {name:?}: nonzero wal_ceiling_bytes {value} requires a file-backed SQLite backend"
159    )]
160    WalCeilingMemoryBackend { name: String, value: u64 },
161
162    #[error("backend {name:?}: nonzero wal_ceiling_bytes {value} requires SQLite WAL mode")]
163    WalCeilingNonWalBackend { name: String, value: u64 },
164
165    #[error(
166        "backends {first_backend:?} and {second_backend:?} name the same database at {} \
167         but resolve different WAL ceilings ({first_bytes} and {second_bytes} bytes)",
168        crate::secret_gate::bounded_masked_log_text(&path.to_string_lossy())
169    )]
170    WalCeilingAliasConflict {
171        first_backend: String,
172        second_backend: String,
173        path: PathBuf,
174        first_bytes: u64,
175        second_bytes: u64,
176    },
177
178    #[error(
179        "backend configuration leaves searchable substrate kinds {kinds:?} unserved; \
180         defined backends: {defined}"
181    )]
182    MissingBackendSearchKinds {
183        kinds: Vec<SubstrateKind>,
184        defined: String,
185    },
186
187    #[error(
188        "[packs.{pack}].backend = {backend:?} references an unknown backend; \
189         defined backends: {defined}"
190    )]
191    UnknownPackBackend {
192        pack: String,
193        backend: String,
194        defined: String,
195    },
196
197    #[error(
198        "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
199         remove it from the config or wait for a future release that implements it"
200    )]
201    UnsupportedBackendField { name: String, field: &'static str },
202
203    #[error(
204        "top-level `db = {value:?}` is not a supported config-file key; \
205         use `--db` / `KHIVE_DB` to select a single-file database, or \
206         `[[backends]].path` to declare storage backend topology"
207    )]
208    UnsupportedTopLevelDb { value: String },
209
210    #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
211    InvalidGitWriteEntry { repo: String, reason: String },
212
213    #[error("[git_write] {key}: {reason}")]
214    InvalidGitWriteConfig { key: String, reason: String },
215
216    #[error("[exec] {key}: {reason}")]
217    InvalidExecConfig { key: String, reason: String },
218
219    #[error("{entry}: {reason}")]
220    InvalidTelemetryConfig { entry: String, reason: String },
221
222    #[error("[web] {key}: {reason}")]
223    InvalidWebConfig { key: String, reason: String },
224
225    #[error("[runtime] {key}: {reason}")]
226    InvalidRuntimeConfig { key: String, reason: String },
227
228    #[error(
229        "[runtime] blob_hydration_bytes must be between {min} and {max} bytes inclusive; got {value}"
230    )]
231    InvalidBlobHydrationBytes { value: u64, min: u64, max: u64 },
232
233    #[error("the explicitly selected config file does not exist: {path}")]
234    ExplicitConfigMissing { path: PathBuf },
235
236    /// Retained for source compatibility with callers that matched the
237    /// fail-loud behavior of older builds. Supported `[gate]` sections no
238    /// longer produce this error.
239    #[error("[gate] configuration is not supported by this build")]
240    UnsupportedGateSection,
241
242    #[error(
243        "[display] timezone {timezone:?} is not a recognized IANA zone name (e.g. \"America/New_York\", \"UTC\")"
244    )]
245    InvalidDisplayTimezone { timezone: String },
246
247    /// Loader-context wrapper attaching the config file the error came from.
248    ///
249    /// Added as a wrapping variant, rather than reshaping the existing
250    /// variants, so every existing constructor, field access, and the
251    /// `From<std::io::Error>` conversion survive unchanged. The enum is not
252    /// `#[non_exhaustive]`, so an exhaustive `match` on `ConfigError` must
253    /// still add an arm for this variant — either matching `InFile` and
254    /// recursing into `source`, or a wildcard. `Parse` already carries its
255    /// path and is never wrapped.
256    #[error("{source} (config file: {})", path.display())]
257    InFile {
258        path: PathBuf,
259        #[source]
260        source: Box<ConfigError>,
261    },
262
263    /// A discovery-tier file the loader does not use failed to load while it
264    /// was read only for `[actor] require_attributed`, which is ORed across
265    /// every tier. Still a refusal: the key could not be read from the file.
266    #[error(
267        "config file {} is not the file in use (in use: {}); it was read only to look for \
268         `[actor] require_attributed`, which could not be read from it: {source}",
269        path.display(),
270        in_use.as_deref().map_or_else(|| "none".to_string(), |used| used.display().to_string())
271    )]
272    ShadowedTier {
273        path: PathBuf,
274        /// The discovery-tier file the loader uses, if any exists.
275        in_use: Option<PathBuf>,
276        #[source]
277        source: Box<ConfigError>,
278    },
279}
280
281impl ConfigError {
282    /// Attach the loading config file's path unless the error already names
283    /// one (`Parse`, `ExplicitConfigMissing`) or is already wrapped.
284    fn in_file(self, path: &Path) -> Self {
285        match self {
286            already @ (ConfigError::Parse { .. }
287            | ConfigError::SchemaParse { .. }
288            | ConfigError::ExplicitConfigMissing { .. }
289            | ConfigError::InFile { .. }) => already,
290            other => ConfigError::InFile {
291                path: path.to_path_buf(),
292                source: Box::new(other),
293            },
294        }
295    }
296}
297
298// ---- Config structs ----
299
300/// Actor configuration — the default namespace / identity for this khive instance.
301///
302/// Corresponds to the `[actor]` TOML section. `id` is used as the
303/// `default_namespace` for gate/attribution policy input. OSS dispatch pins
304/// writes to the shared `local` namespace regardless of this value (ADR-007
305/// Rev 4 Rule 0); cloud deployments derive the namespace from an authenticated
306/// `NamespaceToken` instead.
307///
308/// ```toml
309/// [actor]
310/// id = "lambda:alice"                          # attribution identity (required)
311/// display_name = "example actor"   # human label (optional)
312/// visible_namespaces = ["lambda:khive", "local"]  # widens default read scope (ADR-007 Rev 4 Rule 3b)
313/// require_attributed = true                       # refuse comm without an actor (optional)
314/// ```
315///
316/// `visible_namespaces` is consumed by OSS dispatch to widen the DEFAULT
317/// multi-record read scope to `['local'] ∪ visible_namespaces` (ADR-007 Rev 4
318/// Rule 3b). Writes remain pinned to `'local'`. An explicit `namespace=` request
319/// param is a precise single-namespace escape and is not widened. A cloud gate
320/// may also consult this list as policy input at its own layer.
321///
322/// The table is closed. Both keys above are authorization input, so a misspelled
323/// key fails startup instead of silently applying its default, and a `[gate]` key
324/// written here is reported rather than discarded.
325#[derive(Debug, Clone, Deserialize, Default)]
326#[serde(deny_unknown_fields)]
327pub struct ActorConfig {
328    /// Namespace identifier used as the default actor for all operations.
329    ///
330    /// Must be a valid `Namespace` string (e.g. `"local"`, `"lambda:khive"`).
331    /// Defaults to `"local"` when absent — backward-compatible with pre-actor
332    /// deployments.
333    #[serde(default)]
334    pub id: Option<String>,
335
336    /// Optional human-readable label for this actor. Not used by the runtime;
337    /// surfaced in introspection and log output only.
338    #[serde(default)]
339    pub display_name: Option<String>,
340
341    /// Exact actor labels permitted to inspect this explicit actor's mailbox.
342    ///
343    /// A nonempty list requires an explicit non-local `id`. Labels are bounded
344    /// to 255 bytes, nonblank, and contain no control characters; `local` is
345    /// forbidden. At most 256 entries are accepted before deduplication. This
346    /// is trusted serving-host policy, never inferred from environment identity
347    /// or supplied by a request. Changes take effect in a new server epoch.
348    #[serde(default)]
349    pub mailbox_readers: Vec<String>,
350
351    /// Additional namespaces that widen the DEFAULT multi-record read scope
352    /// to `['local'] ∪ visible_namespaces` (ADR-007 Rev 4 Rule 3b). Each string
353    /// must be a valid `Namespace`. Writes remain pinned to `'local'`. An
354    /// explicit `namespace=` request param is a precise escape and is not widened
355    /// by this list. A cloud gate may also consult it as policy input.
356    #[serde(default)]
357    pub visible_namespaces: Option<Vec<String>>,
358
359    /// Namespaces this actor's comm.send/reply may deliver messages INTO
360    /// (outbound, sender-side). Empty by default — cross-namespace delivery
361    /// denied unless explicitly declared. The comm handler uses an ordinary
362    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
363    /// the token itself is NOT type-enforced write-only. The recipient-side
364    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
365    /// a future cloud-path authorization ADR (not yet written).
366    ///
367    /// Each entry must be a valid `Namespace` string; validated at
368    /// config-load time. An empty list preserves the prior deny-all behavior
369    /// for any actor that does not add this field.
370    #[serde(default)]
371    pub allowed_outbound_namespaces: Vec<String>,
372
373    /// Namespaces whose rows this actor may rewrite through `memory.apply_batch`
374    /// (ADR-021 Delta 1). Empty by default. Ownership is declared by name and
375    /// never inferred: `visible_namespaces` grants read access only, and a
376    /// namespace that shares this actor's id as a prefix is not owned unless it
377    /// is listed here. Each entry must be a valid `Namespace` other than `local`
378    /// and this actor's own `id`; entries must be unique, and a nonempty list
379    /// requires an explicit `id`. Validated at config-load time. The list is
380    /// read by the apply-batch old-row namespace check alone: it grants no write
381    /// into an owned namespace and widens no read.
382    #[serde(default)]
383    pub owned_namespaces: Vec<String>,
384
385    /// Strict attributed-actor mode while the `comm` pack is loaded, exactly as
386    /// `KHIVE_REQUIRE_ATTRIBUTED_ACTOR=1`; either one turns it on and neither can
387    /// turn the other off. An actor is unattributed when it is absent, empty or
388    /// `local`. A server refuses to start and `kkernel exec` refuses to run when
389    /// its own actor is unattributed, and a daemon refuses each request whose
390    /// frame carries an unattributed actor, before anything dispatches.
391    /// Every other key comes from the first config file found; this one is ORed
392    /// across the database-anchored file and every existing discovery tier (cwd
393    /// `khive.toml`, cwd `.khive/config.toml`, `~/.khive/config.toml`), so a
394    /// project file without it cannot shadow a home file that sets it. An
395    /// explicit `--config`/`KHIVE_CONFIG` file is hermetic and is the only one
396    /// read. Valid without `id`. Defaults to `false`.
397    #[serde(default)]
398    pub require_attributed: bool,
399}
400
401/// Built-in caller-enrollment policy configured by `[gate]`.
402///
403/// The table is intentionally closed: misspelled or future keys fail startup
404/// instead of being silently ignored at an authorization boundary. Presence
405/// installs [`khive_gate::CallerEnrollmentGate`]; absence preserves the gate
406/// already supplied in the base [`crate::RuntimeConfig`].
407#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
408#[serde(deny_unknown_fields)]
409pub struct GateSectionConfig {
410    /// Exact resolved actor ids permitted to dispatch requests.
411    #[serde(default)]
412    pub granted_actors: Vec<String>,
413
414    /// Whether the implicit anonymous/local caller is admitted.
415    #[serde(default)]
416    pub grant_unattributed: bool,
417
418    /// Whole actor-ID patterns denying all but explicitly reviewed reads.
419    /// Case-sensitive; only `*` is a wildcard. Does not enroll a caller.
420    #[serde(default)]
421    pub deny_writes_for: Vec<String>,
422}
423
424// ---- Per-pack backend config (ADR-028) ----
425
426/// Storage backend kind.
427#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
428#[serde(rename_all = "lowercase")]
429pub enum BackendKind {
430    /// SQLite file-backed database (default).
431    #[default]
432    Sqlite,
433    /// In-memory database — for testing only; state is lost on restart.
434    Memory,
435}
436
437/// The configured WAL ceiling and the writer policy actually enforced by a backend.
438///
439/// A read-only SQLite backend retains its configured value for reporting but
440/// has no writer policy, so `effective_bytes` is zero.
441#[derive(Debug, Clone, Copy, PartialEq, Eq)]
442pub struct ResolvedWalCeiling {
443    /// Selected field, environment, or default value before read-only handling.
444    pub configured_bytes: u64,
445    /// Writer-enforced value; zero for a read-only backend.
446    pub effective_bytes: u64,
447    /// Origin of `configured_bytes`.
448    pub source: khive_db::WalCeilingSource,
449}
450
451/// Resolve the ceiling with backend-field precedence over the environment.
452///
453/// `env_value` is a construction-time snapshot supplied by the host. This
454/// function never reads process environment, so forwarding and backend opening
455/// can validate the same policy even when the environment later changes.
456pub fn resolve_wal_ceiling(
457    backend_field: Option<u64>,
458    env_value: Option<&str>,
459    backend_name: &str,
460    kind: BackendKind,
461    wal_mode: bool,
462    read_only: bool,
463) -> Result<ResolvedWalCeiling, ConfigError> {
464    if kind == BackendKind::Memory && backend_field.is_none() {
465        return Ok(ResolvedWalCeiling {
466            configured_bytes: 0,
467            effective_bytes: 0,
468            source: khive_db::WalCeilingSource::Default,
469        });
470    }
471    let (configured_bytes, source) = if let Some(bytes) = backend_field {
472        (bytes, khive_db::WalCeilingSource::BackendField)
473    } else if let Some(raw) = env_value {
474        if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
475            return Err(ConfigError::InvalidWalCeilingEnvironment {
476                value: raw.to_owned(),
477            });
478        }
479        let bytes = raw
480            .parse::<u64>()
481            .map_err(|_| ConfigError::InvalidWalCeilingEnvironment {
482                value: raw.to_owned(),
483            })?;
484        (bytes, khive_db::WalCeilingSource::Environment)
485    } else {
486        (0, khive_db::WalCeilingSource::Default)
487    };
488
489    if configured_bytes != 0 {
490        if i64::try_from(configured_bytes).is_err() {
491            return Err(ConfigError::WalCeilingOffsetOverflow {
492                name: backend_name.to_owned(),
493                value: configured_bytes,
494            });
495        }
496        if kind == BackendKind::Memory {
497            return Err(ConfigError::WalCeilingMemoryBackend {
498                name: backend_name.to_owned(),
499                value: configured_bytes,
500            });
501        }
502        if !wal_mode {
503            return Err(ConfigError::WalCeilingNonWalBackend {
504                name: backend_name.to_owned(),
505                value: configured_bytes,
506            });
507        }
508    }
509
510    Ok(ResolvedWalCeiling {
511        configured_bytes,
512        effective_bytes: if read_only { 0 } else { configured_bytes },
513        source,
514    })
515}
516
517/// Configuration for a named storage backend.
518///
519/// Corresponds to a `[[backends]]` entry in `khive.toml`.
520/// When no `[[backends]]` section is present, a single implicit `main` backend
521/// is synthesised from the existing `--db` / `KHIVE_DB` / default-path resolution.
522/// All packs fall back to `main` when their name is absent from `[packs]`.
523/// `cache_mb` and `journal_mode` are parsed but rejected during validation
524/// because per-backend tuning is not implemented.
525///
526/// ```toml
527/// [[backends]]
528/// name = "main"
529/// kind = "sqlite"
530/// path = "~/.khive/khive.db"
531/// read_only = false
532/// ```
533#[derive(Debug, Clone, Deserialize)]
534#[serde(deny_unknown_fields)]
535pub struct BackendConfig {
536    /// Unique backend name. Referenced by `[packs.<name>].backend`.
537    pub name: String,
538    /// Storage backend kind. Defaults to `sqlite`.
539    #[serde(default)]
540    pub kind: BackendKind,
541    /// Filesystem path for `sqlite` kind. Tilde is expanded to `$HOME`.
542    /// `None` for `memory` kind (path is ignored when present).
543    pub path: Option<std::path::PathBuf>,
544    /// SQLite page-cache size in MiB. Parsed but rejected as unsupported.
545    pub cache_mb: Option<u32>,
546    /// SQLite journal mode (e.g. `"wal"`). Parsed but rejected as unsupported.
547    pub journal_mode: Option<String>,
548    /// Substrate kinds this backend serves.
549    ///
550    /// Omission preserves conservative fan-out to this backend. An explicit
551    /// declaration is closed over [`SubstrateKind`] and must not be empty.
552    /// The backend set must cover both `note` and `entity` search.
553    #[serde(default)]
554    pub served_kinds: Option<BTreeSet<SubstrateKind>>,
555    /// Open the backend read-only. Defaults to `false`.
556    #[serde(default)]
557    pub read_only: bool,
558    /// WAL extent ceiling in bytes. `None` inherits the environment setting;
559    /// zero disables the ceiling. Read-only backends retain the configured
560    /// value for reporting but enforce no writer policy.
561    pub wal_ceiling_bytes: Option<u64>,
562    /// SQLite disk reserve, in bytes. Zero explicitly disables the floor.
563    #[serde(default)]
564    pub disk_reserve_bytes: Option<u64>,
565    /// Volume-guard acquisition deadline, in milliseconds (100..=10000).
566    #[serde(default)]
567    pub disk_guard_deadline_ms: Option<u64>,
568}
569
570/// Operator declaration for a readable code map.
571///
572/// Corresponds to one `[[code_maps]]` entry in `config.toml`. Filesystem
573/// validation is performed by the runtime registry loader so one rejected map
574/// does not prevent other declarations from loading.
575/// Known fields with TOML values of the wrong type remain configuration errors.
576#[derive(Debug, Clone, Deserialize, Default)]
577pub struct CodeMapConfig {
578    /// Unique name used to resolve this map.
579    #[serde(default)]
580    pub name: Option<String>,
581    /// Absolute database path bounded by `code_map_root`.
582    #[serde(default)]
583    pub path: Option<String>,
584    /// Absolute source tree described by the map contents.
585    #[serde(default)]
586    pub source_root: Option<String>,
587    /// Unknown keys are retained for per-entry rejection by the registry loader.
588    #[serde(default, flatten)]
589    pub unknown_fields: BTreeMap<String, toml::Value>,
590}
591
592/// Per-pack backend assignment.
593///
594/// Corresponds to a `[packs.<pack-name>]` entry in `khive.toml`.
595/// Packs whose name is absent from `[packs]` fall back to the `main` backend.
596///
597/// ```toml
598/// [packs.knowledge]
599/// backend = "knowledge"
600///
601/// [packs.comm]
602/// backend = "comm"
603/// no_embed = true
604/// ```
605#[derive(Debug, Clone, Deserialize)]
606pub struct PackConfig {
607    /// Backend name this pack is assigned to. Must match a `[[backends]].name`,
608    /// or `main` when no backends are declared.
609    #[serde(default = "default_pack_backend")]
610    pub backend: String,
611    /// Public handlers disabled by the operator. Names must belong to this loaded pack.
612    #[serde(default)]
613    pub verbs_disabled: Vec<String>,
614    /// Disable vector embedding for this pack's runtime: rows it writes get
615    /// FTS and metadata only, no `vec_*` rows and no ANN participation. The
616    /// opt-out covers pack-owned writes on the pack's own backend; it does
617    /// NOT cover `core()`-routed concept writes, which embed with the MAIN
618    /// runtime's embedders (the boot path wires them in via
619    /// `with_core_embedders_from`) so the shared graph stays uniformly
620    /// searchable. Fits packs whose own rows are structural rather than
621    /// retrieval targets (e.g. comm). Effective in multi-backend boot, where
622    /// each pack gets its own runtime. Defaults to `false`.
623    #[serde(default)]
624    pub no_embed: bool,
625}
626
627fn default_pack_backend() -> String {
628    BackendId::MAIN.to_owned()
629}
630
631// ---- Blob store config (ADR-111 Amendment 2) ----
632
633/// `[storage.blob]` section: a closed `backend = "fs" | "s3"` selector.
634/// The `s3` backend requires the opt-in `blob-s3` Cargo feature.
635///
636/// Internally tagged on `backend` with `deny_unknown_fields`: an unknown
637/// top-level key, a field that belongs to the other backend variant (e.g.
638/// `bucket` under `backend = "fs"`), or an S3 credential field (never
639/// accepted in TOML -- ADR-111 Amendment 2 reads credentials from the
640/// process environment only) are all rejected at config-load time by the
641/// same mechanism, since each variant only declares its own fields.
642///
643/// ```toml
644/// [storage.blob]
645/// backend = "fs"
646/// root = "/var/lib/khive/blobs"
647/// floor_bytes = 100000000000
648/// ```
649///
650/// ```toml
651/// [storage.blob]
652/// backend = "s3"
653/// bucket = "khive-blobs"
654/// region = "us-east-1"
655/// endpoint = "https://objects.example.invalid"
656/// prefix = "blobs"
657/// ```
658#[derive(Debug, Clone, Deserialize)]
659#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
660pub enum BlobConfig {
661    /// Filesystem-backed blob storage (`FsBlobStore`). Root resolution is
662    /// unchanged from khive#292: `KHIVE_BLOB_ROOT` env var, then this
663    /// `root`, then `<db_dir>/blobs`.
664    Fs {
665        #[serde(default)]
666        root: Option<String>,
667        /// Free-space floor in bytes. Absent: 2% of the volume holding the
668        /// root, at least 5 GiB (ADR-111 Amendment 6); `0` disables it.
669        #[serde(default)]
670        floor_bytes: Option<u64>,
671    },
672    /// S3-compatible blob storage (`S3BlobStore`). `KHIVE_BLOB_ROOT` has no
673    /// effect for this backend. Credentials always come from
674    /// `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`/`AWS_SESSION_TOKEN` in the
675    /// process environment, never from this section.
676    S3 {
677        bucket: String,
678        region: String,
679        #[serde(default)]
680        endpoint: Option<String>,
681        #[serde(default)]
682        prefix: Option<String>,
683        #[serde(default)]
684        allow_http: Option<bool>,
685    },
686}
687
688/// `[blob]` pack policy, separate from the `[storage.blob]` backend selector.
689#[derive(Debug, Clone, Deserialize, Default)]
690#[serde(deny_unknown_fields)]
691pub struct BlobSectionConfig {
692    /// Permit server-local file transfers. Absent means disabled.
693    #[serde(default)]
694    pub file_transfers: bool,
695}
696
697/// `[storage]` section in `khive.toml`. Holds storage-layer config not
698/// already covered by `[[backends]]` (ADR-028). Unknown fields are rejected
699/// so an unsupported database selector cannot silently select the default store.
700#[derive(Debug, Clone, Deserialize, Default)]
701#[serde(deny_unknown_fields)]
702pub struct StorageSectionConfig {
703    /// Blob store backend selector (ADR-111 Amendment 2). Absent means
704    /// `FsBlobStore` at the existing root-resolution precedence, unchanged
705    /// from khive#292 -- existing configurations keep behaving exactly as
706    /// they did before this section existed.
707    #[serde(default)]
708    pub blob: Option<BlobConfig>,
709}
710
711/// `[brain]` read policy resolved by the serving process.
712#[derive(Debug, Clone, Deserialize, Serialize, Default)]
713#[serde(deny_unknown_fields)]
714pub struct BrainSectionConfig {
715    /// Actor ids permitted to request fleet-wide `brain.event_counts` reads.
716    #[serde(default)]
717    pub fleet_readers: Vec<String>,
718}
719
720// ---- git-write policy (ADR-108 Amendment) ----
721
722/// One `[[git_write.allowed]]` entry: a repo this operator has declared
723/// trusted for khive-mediated git writes, plus the branches on it a write
724/// verb (`git.commit`/`git.branch`/`git.update_ref`/`git.push`) may target.
725///
726/// ```toml
727/// [[git_write.allowed]]
728/// repo = "/abs/path/repo"
729/// branches = ["feat/*", "fix/*"]
730/// ```
731#[derive(Debug, Clone, Deserialize, Serialize)]
732pub struct GitWriteEntryConfig {
733    /// Absolute local path to the allowlisted repository.
734    pub repo: String,
735    /// Non-empty list of exact branch names or single-`*`-wildcard globs
736    /// this repo entry permits writes against.
737    pub branches: Vec<String>,
738}
739
740/// `[git_write]` section — the closed repo/branch allowlist consulted by
741/// `khive-pack-git`'s write verbs at the handler level (ADR-108 Amendment),
742/// independent of Gate policy. Absent or empty `allowed` is the fail-closed
743/// default: the write verbs report themselves unavailable rather than
744/// defaulting open.
745///
746/// ```toml
747/// [[git_write.allowed]]
748/// repo = "/abs/path/repo"
749/// branches = ["feat/*", "fix/*"]
750/// ```
751#[derive(Debug, Clone, Deserialize, Serialize)]
752pub struct GitWriteSectionConfig {
753    /// Absolute git executable override; absent preserves PATH resolution.
754    #[serde(default)]
755    pub program: Option<PathBuf>,
756    #[serde(default)]
757    pub allowed: Vec<GitWriteEntryConfig>,
758    #[serde(default)]
759    pub actors: BTreeMap<String, GitWriteActorConfig>,
760    #[serde(default)]
761    pub repositories: BTreeMap<String, GitWriteRepositoryConfig>,
762    #[serde(default = "default_git_credential_resolver")]
763    pub credential_resolver: Vec<String>,
764    #[serde(default)]
765    pub contract_faults: bool,
766    #[serde(default)]
767    pub fault: Option<String>,
768}
769
770#[derive(Debug, Clone, Deserialize, Serialize)]
771#[serde(deny_unknown_fields)]
772pub struct GitWriteRepositoryConfig {
773    /// HTTPS platform remote, or an absolute path / file:/// URL with an empty slug.
774    pub remote: String,
775    /// owner/name for HTTPS; empty explicitly opts into credential-free local pushes.
776    pub slug: String,
777    pub visibility: String,
778    /// Merge dispatch refusals for this repository (ADR-182 Amendment 7):
779    /// `opener` refuses a `git.pr_merge` dispatched by the account or actor
780    /// that opened the pull request; `last_pusher` refuses one dispatched by
781    /// the login on the newest push receipt for `expected_head`. Empty (the
782    /// default) refuses neither.
783    #[serde(default)]
784    pub merge_refusals: Vec<String>,
785}
786
787impl GitWriteRepositoryConfig {
788    pub const MERGE_REFUSALS: [&'static str; 2] = ["opener", "last_pusher"];
789
790    /// Whether this repository row lists the named merge refusal.
791    pub fn refuses_merge_by(&self, entry: &str) -> bool {
792        self.merge_refusals.iter().any(|listed| listed == entry)
793    }
794}
795
796#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
797#[serde(deny_unknown_fields)]
798pub struct GitWriteActorConfig {
799    pub name: String,
800    pub email: String,
801    pub credential_ref: String,
802    pub platform_identity: String,
803}
804
805fn default_git_credential_resolver() -> Vec<String> {
806    [
807        "/usr/bin/security",
808        "find-generic-password",
809        "-w",
810        "-s",
811        "{ref}",
812    ]
813    .into_iter()
814    .map(str::to_string)
815    .collect()
816}
817
818impl Default for GitWriteSectionConfig {
819    fn default() -> Self {
820        Self {
821            program: None,
822            allowed: Vec::new(),
823            actors: BTreeMap::new(),
824            repositories: BTreeMap::new(),
825            credential_resolver: default_git_credential_resolver(),
826            contract_faults: false,
827            fault: None,
828        }
829    }
830}
831
832impl GitWriteSectionConfig {
833    pub fn git_program(&self) -> &Path {
834        self.program.as_deref().unwrap_or_else(|| Path::new("git"))
835    }
836
837    pub fn validate_dev_loop(&self) -> Result<(), ConfigError> {
838        let invalid = |key: &str, reason: &str| ConfigError::InvalidGitWriteConfig {
839            key: key.to_string(),
840            reason: reason.to_string(),
841        };
842        if let Some(program) = &self.program {
843            if !program.is_absolute() {
844                return Err(invalid("git_write.program", "must be absolute"));
845            }
846            let metadata = std::fs::metadata(program).map_err(|error| {
847                if error.kind() == std::io::ErrorKind::NotFound {
848                    invalid("git_write.program", "does not exist")
849                } else {
850                    invalid("git_write.program", &format!("is not executable: {error}"))
851                }
852            })?;
853            #[cfg(unix)]
854            let executable = {
855                use std::os::unix::fs::PermissionsExt;
856                metadata.permissions().mode() & 0o111 != 0
857            };
858            #[cfg(windows)]
859            let executable = program
860                .extension()
861                .and_then(|extension| extension.to_str())
862                .is_some_and(|extension| {
863                    extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
864                });
865            #[cfg(not(any(unix, windows)))]
866            let executable = false;
867            if !metadata.is_file() || !executable {
868                return Err(invalid("git_write.program", "is not executable"));
869            }
870        }
871        if self.contract_faults && !cfg!(feature = "contract-faults") {
872            tracing::error!(
873                target: "khive.boot",
874                "[git_write] contract_faults requires the test-only contract-faults build feature"
875            );
876            return Err(invalid(
877                "contract_faults",
878                "requires the test-only contract-faults build feature",
879            ));
880        }
881        if let Some(fault) = &self.fault {
882            if !self.contract_faults {
883                return Err(invalid("fault", "requires contract_faults = true"));
884            }
885            let valid = fault.split_once(':').is_some_and(|(verb, point)| {
886                matches!(verb, "git.push" | "git.pr_merge")
887                    && matches!(
888                        point,
889                        "reply-lost-after-effect" | "audit-fails-after-effect"
890                    )
891            });
892            if !valid {
893                return Err(invalid("fault", "unsupported contract fault selector"));
894            }
895        }
896        for (path, repository) in &self.repositories {
897            let key = format!("repositories.{path}.merge_refusals");
898            let mut seen: Vec<&str> = Vec::new();
899            for entry in &repository.merge_refusals {
900                if !GitWriteRepositoryConfig::MERGE_REFUSALS.contains(&entry.as_str()) {
901                    return Err(invalid(&key, "entries must be opener or last_pusher"));
902                }
903                if seen.contains(&entry.as_str()) {
904                    return Err(invalid(&key, "entries must not repeat"));
905                }
906                seen.push(entry);
907            }
908        }
909        // The default keychain program is Unix-only. Legacy configurations with
910        // no actor mappings cannot invoke it, so they remain loadable elsewhere.
911        if !cfg!(unix)
912            && self.actors.is_empty()
913            && self.credential_resolver == default_git_credential_resolver()
914        {
915            return Ok(());
916        }
917        let argv = &self.credential_resolver;
918        let Some(program) = argv.first() else {
919            return Err(invalid("credential_resolver", "argv must not be empty"));
920        };
921        let program_path = Path::new(program);
922        if !program_path.is_absolute() {
923            return Err(invalid(
924                "credential_resolver",
925                "argv[0] must be an absolute path",
926            ));
927        }
928        let program_name = program_path
929            .file_name()
930            .and_then(|name| name.to_str())
931            .unwrap_or_default()
932            .to_ascii_lowercase();
933        if matches!(
934            program_name.trim_end_matches(".exe"),
935            "sh" | "bash"
936                | "dash"
937                | "zsh"
938                | "ksh"
939                | "fish"
940                | "csh"
941                | "tcsh"
942                | "cmd"
943                | "powershell"
944                | "pwsh"
945                | "env"
946        ) {
947            return Err(invalid(
948                "credential_resolver",
949                "shell or env launcher is not allowed",
950            ));
951        }
952        if argv.iter().any(|arg| arg.chars().any(char::is_control)) {
953            return Err(invalid(
954                "credential_resolver",
955                "argv must not contain control characters",
956            ));
957        }
958        if program.contains(['{', '}'])
959            || argv[1..]
960                .iter()
961                .any(|arg| arg != "{ref}" && arg.contains(['{', '}']))
962        {
963            return Err(invalid(
964                "credential_resolver",
965                "{ref} must be a complete argument and is the only allowed template",
966            ));
967        }
968        if !argv[1..].iter().any(|arg| arg == "{ref}") {
969            return Err(invalid(
970                "credential_resolver",
971                "argv must contain a {ref} argument",
972            ));
973        }
974        for (actor, identity) in &self.actors {
975            if actor.trim().is_empty() || actor.chars().any(char::is_control) {
976                return Err(invalid(
977                    "actors",
978                    "actor labels must be nonempty and contain no control characters",
979                ));
980            }
981            for (field, value) in [
982                ("name", &identity.name),
983                ("email", &identity.email),
984                ("credential_ref", &identity.credential_ref),
985                ("platform_identity", &identity.platform_identity),
986            ] {
987                if value.trim().is_empty() || value.chars().any(char::is_control) {
988                    return Err(invalid(
989                        &format!("actors.{actor}.{field}"),
990                        "must be nonempty and contain no control characters",
991                    ));
992                }
993            }
994            if identity.name.contains(['<', '>']) || identity.email.contains(['<', '>']) {
995                return Err(invalid(
996                    &format!("actors.{actor}"),
997                    "name and email must not contain Git identity delimiters",
998                ));
999            }
1000        }
1001        Ok(())
1002    }
1003}
1004
1005// ---- exec sandbox (ADR-181) ----
1006
1007/// `[exec.limits]`: per-run resource limits applied to the sandboxed child
1008/// and inherited by its descendants (`setrlimit` before exec).
1009#[derive(Debug, Clone, Deserialize, Default)]
1010pub struct ExecLimitsConfig {
1011    #[serde(default)]
1012    pub cpu_seconds: Option<u64>,
1013    #[serde(default)]
1014    pub address_space: Option<u64>,
1015    #[serde(default)]
1016    pub file_size: Option<u64>,
1017    #[serde(default)]
1018    pub nproc: Option<u64>,
1019}
1020
1021/// `[exec]` section (ADR-181): where runs materialize, what they may read,
1022/// which caller environment keys pass through, which executable paths the
1023/// `never` list matches, and the output caps, wall-clock defaults and resource
1024/// limits. `never` matches paths, not a program's capabilities (ADR-181 A9).
1025///
1026/// ```toml
1027/// [exec]
1028/// root = "/var/lib/khive/exec"
1029/// read_roots = ["/opt/toolchains/python3.11"]
1030/// env = ["SOURCE_DATE_EPOCH"]
1031/// # The never list matches resolved executable paths, not renamed copies.
1032/// never = ["/usr/bin/curl"]
1033/// max_output_bytes = 1048576
1034/// timeout_default_s = 30
1035/// timeout_max_s = 600
1036/// binary_digest_timeout_s = 10 # 1..=60; independent of run timeout
1037/// keep = false
1038///
1039/// [exec.limits]
1040/// cpu_seconds = 60
1041/// file_size = 104857600
1042/// ```
1043#[derive(Debug, Clone, Deserialize, Default)]
1044#[serde(deny_unknown_fields)]
1045pub struct ExecSectionConfig {
1046    #[serde(default)]
1047    pub root: Option<String>,
1048    #[serde(default)]
1049    pub read_roots: Vec<String>,
1050    #[serde(default)]
1051    pub env: Vec<String>,
1052    #[serde(default)]
1053    pub never: Vec<String>,
1054    #[serde(default)]
1055    pub max_output_bytes: Option<u64>,
1056    #[serde(default)]
1057    pub timeout_default_s: Option<f64>,
1058    #[serde(default)]
1059    pub timeout_max_s: Option<f64>,
1060    /// Stalled-mount guard for hashing an authorized binary (1..=60 seconds).
1061    #[serde(default)]
1062    pub binary_digest_timeout_s: Option<u64>,
1063    #[serde(default)]
1064    pub keep: bool,
1065    #[serde(default)]
1066    pub limits: ExecLimitsConfig,
1067}
1068
1069pub const DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 10;
1070pub const MAX_EXEC_BINARY_DIGEST_TIMEOUT_S: u64 = 60;
1071
1072// ---- web fetch/search policy (ADR-175 Amendment 1, carried into ADR-191 D3) ----
1073
1074/// One `[[web.allowlist]]` entry: an exclusive host the operator has opted
1075/// into reachability for `web.fetch`/`web.search`. Presence of ANY entry
1076/// makes the allowlist exclusive (ADR-175 A1.2.3); absence leaves the public
1077/// internet reachable subject to the other egress rules. Matched by exact,
1078/// normalized (lowercase, trailing-dot-stripped) host equality only — no
1079/// suffix wildcarding, unlike `[[web.credentials]].hosts` (A1.2.6).
1080#[derive(Debug, Clone, Deserialize, Serialize)]
1081#[serde(deny_unknown_fields)]
1082pub struct WebAllowlistEntry {
1083    pub host: String,
1084}
1085
1086/// One `[[web.credentials]]` entry: a named secret, read from the process
1087/// environment at request time (never accepted as a verb argument), bound to
1088/// the set of hosts it may be presented to. Each `hosts` entry is either an
1089/// exact IP-literal address (matched exactly, never as a suffix) or a
1090/// hostname suffix (`example.com` matches `example.com` and any
1091/// `*.example.com` at a DNS label boundary) — ADR-175 A1.2.6.
1092#[derive(Debug, Clone, Deserialize, Serialize)]
1093#[serde(deny_unknown_fields)]
1094pub struct WebCredentialConfig {
1095    /// Name the caller passes as `web.fetch`'s `credential` argument.
1096    pub name: String,
1097    /// Process environment variable holding the secret value.
1098    pub env_var: String,
1099    /// Non-empty set of hosts (exact IP literals or hostname suffixes) this
1100    /// credential may be presented to.
1101    pub hosts: Vec<String>,
1102}
1103
1104/// One canned result inside a `kind = "fixture"` `[[web.search_providers]]`
1105/// entry — deterministic, non-networked search results (demos, offline
1106/// corpora, and the fixture arm of `web.search`'s own test suite).
1107#[derive(Debug, Clone, Deserialize, Serialize)]
1108#[serde(deny_unknown_fields)]
1109pub struct WebFixtureResult {
1110    pub title: String,
1111    pub url: String,
1112    pub snippet: String,
1113}
1114
1115/// One `[[web.search_providers]]` entry (ADR-175 A1.3). The provider is
1116/// operator configuration; `web.search`'s `provider` argument only selects
1117/// among entries declared here by `name`. Closed, tagged on `kind`.
1118#[derive(Debug, Clone, Deserialize, Serialize)]
1119#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
1120pub enum WebSearchProviderConfig {
1121    /// Deterministic canned results — no outbound request.
1122    Fixture {
1123        name: String,
1124        #[serde(default)]
1125        default: bool,
1126        results: Vec<WebFixtureResult>,
1127    },
1128    /// A real HTTP GET search backend. `url_template` must contain the
1129    /// literal substring `{query}`, replaced with the percent-encoded query
1130    /// at request time; `{limit}` is replaced with the effective limit when
1131    /// present. The response body is JSON: an array of `{title, url,
1132    /// snippet}` objects. `api_key_env`, when set, is a process environment
1133    /// variable sent as `Authorization: Bearer <value>`.
1134    Http {
1135        name: String,
1136        #[serde(default)]
1137        default: bool,
1138        url_template: String,
1139        #[serde(default)]
1140        api_key_env: Option<String>,
1141        /// Hosts (exact IP literals or hostname suffixes) `api_key_env`'s
1142        /// value may be presented to, modeled on
1143        /// `[[web.credentials]].hosts`. Required non-empty whenever
1144        /// `api_key_env` is set (`validate` enforces this) — an unscoped key
1145        /// would ride along to whatever host `url_template` resolves to,
1146        /// which defeats the point of scoping it at all.
1147        #[serde(default)]
1148        hosts: Vec<String>,
1149    },
1150}
1151
1152impl WebSearchProviderConfig {
1153    pub fn name(&self) -> &str {
1154        match self {
1155            WebSearchProviderConfig::Fixture { name, .. } => name,
1156            WebSearchProviderConfig::Http { name, .. } => name,
1157        }
1158    }
1159
1160    pub fn is_default(&self) -> bool {
1161        match self {
1162            WebSearchProviderConfig::Fixture { default, .. } => *default,
1163            WebSearchProviderConfig::Http { default, .. } => *default,
1164        }
1165    }
1166}
1167
1168/// `[web]` section (ADR-175 Amendment 1, ADR-191 D3): operator policy for
1169/// `web.fetch` and `web.search` — ceilings, the address allowlist, credential
1170/// host-set bindings, and configured search providers.
1171///
1172/// No generic per-pack settings map exists in this file today (`PackConfig`
1173/// carries only `backend`/`no_embed`, both storage-routing concerns) so this
1174/// follows the established precedent for a pack needing rich operator policy:
1175/// a dedicated top-level section threaded through `RuntimeConfig`, the same
1176/// shape as `[exec]` and `[git_write]`.
1177///
1178/// ```toml
1179/// [web]
1180/// timeout_default_s = 30
1181/// timeout_max_s = 120
1182/// max_bytes_default = 5242880
1183/// max_bytes_max = 52428800
1184/// search_limit_default = 10
1185/// search_limit_max = 50
1186///
1187/// [[web.allowlist]]
1188/// host = "example.com"
1189///
1190/// [[web.credentials]]
1191/// name = "example-token"
1192/// env_var = "EXAMPLE_API_TOKEN"
1193/// hosts = ["example.com"]
1194///
1195/// [[web.search_providers]]
1196/// kind = "fixture"
1197/// name = "demo"
1198/// default = true
1199/// results = [{ title = "Example", url = "https://example.com", snippet = "..." }]
1200/// ```
1201#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1202#[serde(deny_unknown_fields)]
1203pub struct WebSectionConfig {
1204    #[serde(default)]
1205    pub timeout_default_s: Option<u64>,
1206    #[serde(default)]
1207    pub timeout_max_s: Option<u64>,
1208    #[serde(default)]
1209    pub max_bytes_default: Option<u64>,
1210    #[serde(default)]
1211    pub max_bytes_max: Option<u64>,
1212    #[serde(default)]
1213    pub search_limit_default: Option<u32>,
1214    #[serde(default)]
1215    pub search_limit_max: Option<u32>,
1216    #[serde(default)]
1217    pub allowlist: Vec<WebAllowlistEntry>,
1218    #[serde(default)]
1219    pub credentials: Vec<WebCredentialConfig>,
1220    #[serde(default)]
1221    pub search_providers: Vec<WebSearchProviderConfig>,
1222    /// Directories `web.ingest`'s disk mode may read from, modeled on
1223    /// `[exec] read_roots`. Absent or empty fails closed: disk ingest is
1224    /// refused entirely until the operator names at least one root.
1225    #[serde(default)]
1226    pub read_roots: Vec<String>,
1227}
1228
1229/// Effective operator bounds shared by file validation and programmatic web dispatch.
1230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1231pub struct WebCeilings {
1232    pub timeout_default_s: u64,
1233    pub timeout_max_s: u64,
1234    pub max_bytes_default: u64,
1235    pub max_bytes_max: u64,
1236    pub search_limit_default: u32,
1237    pub search_limit_max: u32,
1238}
1239
1240impl Default for WebCeilings {
1241    fn default() -> Self {
1242        Self {
1243            timeout_default_s: 30,
1244            timeout_max_s: 120,
1245            max_bytes_default: 5 * 1024 * 1024,
1246            max_bytes_max: 50 * 1024 * 1024,
1247            search_limit_default: 10,
1248            search_limit_max: 50,
1249        }
1250    }
1251}
1252
1253impl WebSectionConfig {
1254    pub fn resolved_ceilings(&self) -> Result<WebCeilings, ConfigError> {
1255        let defaults = WebCeilings::default();
1256        let bounds = WebCeilings {
1257            timeout_default_s: self.timeout_default_s.unwrap_or(defaults.timeout_default_s),
1258            timeout_max_s: self.timeout_max_s.unwrap_or(defaults.timeout_max_s),
1259            max_bytes_default: self.max_bytes_default.unwrap_or(defaults.max_bytes_default),
1260            max_bytes_max: self.max_bytes_max.unwrap_or(defaults.max_bytes_max),
1261            search_limit_default: self
1262                .search_limit_default
1263                .unwrap_or(defaults.search_limit_default),
1264            search_limit_max: self.search_limit_max.unwrap_or(defaults.search_limit_max),
1265        };
1266        for (key, default, maximum, maximum_key) in [
1267            (
1268                "timeout_default_s",
1269                bounds.timeout_default_s,
1270                bounds.timeout_max_s,
1271                "timeout_max_s",
1272            ),
1273            (
1274                "max_bytes_default",
1275                bounds.max_bytes_default,
1276                bounds.max_bytes_max,
1277                "max_bytes_max",
1278            ),
1279            (
1280                "search_limit_default",
1281                u64::from(bounds.search_limit_default),
1282                u64::from(bounds.search_limit_max),
1283                "search_limit_max",
1284            ),
1285        ] {
1286            if default == 0 || default > maximum {
1287                return Err(ConfigError::InvalidWebConfig {
1288                    key: key.into(),
1289                    reason: format!(
1290                        "resolved default must be positive and not exceed {maximum_key}={maximum}"
1291                    ),
1292                });
1293            }
1294        }
1295        if std::time::Instant::now()
1296            .checked_add(std::time::Duration::from_secs(bounds.timeout_max_s))
1297            .is_none()
1298        {
1299            return Err(ConfigError::InvalidWebConfig {
1300                key: "timeout_max_s".into(),
1301                reason: "cannot be represented as a request deadline".into(),
1302            });
1303        }
1304        Ok(bounds)
1305    }
1306
1307    pub fn validate(&self) -> Result<(), ConfigError> {
1308        self.resolved_ceilings()?;
1309        let invalid = |key: &str, reason: &str| ConfigError::InvalidWebConfig {
1310            key: key.to_string(),
1311            reason: reason.to_string(),
1312        };
1313        let mut seen_hosts = std::collections::HashSet::new();
1314        for entry in &self.allowlist {
1315            let normalized = entry.host.trim().trim_end_matches('.').to_ascii_lowercase();
1316            if normalized.is_empty() {
1317                return Err(invalid("allowlist.host", "must not be empty"));
1318            }
1319            if !seen_hosts.insert(normalized) {
1320                return Err(invalid("allowlist.host", "duplicate host entry"));
1321            }
1322        }
1323        let mut seen_credentials = std::collections::HashSet::new();
1324        for credential in &self.credentials {
1325            if credential.name.trim().is_empty() {
1326                return Err(invalid("credentials.name", "must not be empty"));
1327            }
1328            if !seen_credentials.insert(credential.name.clone()) {
1329                return Err(invalid("credentials.name", "duplicate credential name"));
1330            }
1331            if credential.env_var.trim().is_empty() {
1332                return Err(invalid("credentials.env_var", "must not be empty"));
1333            }
1334            if credential.hosts.is_empty() {
1335                return Err(invalid(
1336                    "credentials.hosts",
1337                    "must name at least one host or suffix",
1338                ));
1339            }
1340        }
1341        let mut seen_providers = std::collections::HashSet::new();
1342        let mut default_count = 0;
1343        for provider in &self.search_providers {
1344            let name = provider.name();
1345            if name.trim().is_empty() {
1346                return Err(invalid("search_providers.name", "must not be empty"));
1347            }
1348            if !seen_providers.insert(name.to_string()) {
1349                return Err(invalid("search_providers.name", "duplicate provider name"));
1350            }
1351            if provider.is_default() {
1352                default_count += 1;
1353            }
1354            if let WebSearchProviderConfig::Http {
1355                url_template,
1356                api_key_env,
1357                hosts,
1358                ..
1359            } = provider
1360            {
1361                if !url_template.contains("{query}") {
1362                    return Err(invalid(
1363                        "search_providers.url_template",
1364                        "must contain the literal substring {query}",
1365                    ));
1366                }
1367                if api_key_env.is_some() && hosts.is_empty() {
1368                    return Err(invalid(
1369                        "search_providers.hosts",
1370                        "an api_key_env-bearing provider must name at least one host or suffix",
1371                    ));
1372                }
1373            }
1374        }
1375        if default_count > 1 {
1376            return Err(invalid(
1377                "search_providers",
1378                "at most one provider may set default = true",
1379            ));
1380        }
1381        Ok(())
1382    }
1383}
1384
1385/// Explicit import schema policy. Missing or empty sections preserve strict
1386/// admission. Unknown keys are ignored with a loader warning (ADR-035).
1387#[derive(Debug, Clone, Deserialize, Serialize)]
1388pub struct SchemaSectionConfig {
1389    #[serde(default = "schema_strict_default")]
1390    pub strict: bool,
1391}
1392
1393fn schema_strict_default() -> bool {
1394    true
1395}
1396
1397impl Default for SchemaSectionConfig {
1398    fn default() -> Self {
1399        Self { strict: true }
1400    }
1401}
1402
1403// Parse the original text, rather than a TOML Value, so type errors retain the
1404// source span. Other sections remain under the full loader's validation.
1405#[derive(Deserialize)]
1406struct SchemaSyntaxProbe {
1407    #[serde(default, deserialize_with = "deserialize_schema_table")]
1408    schema: SchemaSectionConfig,
1409}
1410
1411fn deserialize_schema_table<'de, D>(deserializer: D) -> Result<SchemaSectionConfig, D::Error>
1412where
1413    D: serde::Deserializer<'de>,
1414{
1415    struct SchemaTableVisitor;
1416    impl<'de> serde::de::Visitor<'de> for SchemaTableVisitor {
1417        type Value = SchemaSectionConfig;
1418
1419        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1420            formatter.write_str("a schema configuration table")
1421        }
1422
1423        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1424        where
1425            A: serde::de::MapAccess<'de>,
1426        {
1427            SchemaSectionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
1428        }
1429    }
1430    deserializer.deserialize_map(SchemaTableVisitor)
1431}
1432
1433/// Top-level khive configuration loaded from `khive.toml` or `config.toml`.
1434///
1435/// Sections consumed today:
1436/// - `[[engines]]`: embedding engine declarations
1437/// - `[actor]`: default namespace / identity (OSS actor model)
1438/// - `[gate]`: built-in caller enrollment
1439/// - `[schema]`: explicit import unknown-entity-kind admission
1440/// - `[embed].batch_size`: explicit reindex batch size
1441/// - `[runtime]`: runtime knobs (pack selection, brain profile, output format)
1442/// - `[brain]`: actor read policy
1443/// - `[telemetry]`: stream and channel carrier policy
1444/// - `[[backends]]`: storage backend declarations (ADR-028)
1445/// - `[packs.<name>]`: per-pack backend assignments (ADR-028)
1446/// - `code_map_root` and `[[code_maps]]`: registered code maps (ADR-139)
1447/// - `[display]`: rendering timezone (ADR-169)
1448/// - `[blob]`: server-local file-transfer opt-in
1449///
1450/// Unknown top-level keys are silently ignored by serde for forward
1451/// compatibility. The `[actor]`, `[gate]`, `[brain]`, `[blob]`, and `[telemetry]` tables are closed
1452/// with `deny_unknown_fields` so a misspelled policy key always fails startup.
1453/// `[storage]`, `[[backends]]` entries and `[exec]` are also closed so unknown
1454/// destination keys cannot be silently dropped, as are `[web]` and `[[mounts]]` entries.
1455#[derive(Debug, Clone, Deserialize, Default)]
1456pub struct KhiveConfig {
1457    /// Admission policy for explicit KG imports only; never VCS sync or create.
1458    #[serde(default)]
1459    pub schema: SchemaSectionConfig,
1460
1461    /// Explicit reindex batch size; automatic embedding settings remain separate.
1462    #[serde(default, deserialize_with = "embed_batch::deserialize_table")]
1463    pub embed: EmbedSectionConfig,
1464
1465    /// Read by `credentials::read_tables` at load, never by this derive.
1466    #[serde(skip)]
1467    pub credentials: Vec<crate::credentials::CredentialConfig>,
1468
1469    #[serde(skip)]
1470    pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
1471
1472    /// Opaque `[channel.*]` values. Registered components validate their own
1473    /// values at activation; unregistered values remain stored without effect.
1474    #[serde(default)]
1475    pub channel: crate::channel_section::ChannelSectionConfig,
1476
1477    #[serde(default)]
1478    pub mounts: Vec<crate::mount_config::MountConfig>,
1479
1480    /// Typed only so a top-level `db` key can be rejected loudly by
1481    /// [`KhiveConfig::validate`] instead of being silently ignored as an
1482    /// unknown key. Not a supported config-file storage selector: single-file
1483    /// database selection is `--db`/`KHIVE_DB`, and storage topology is
1484    /// `[[backends]].path`.
1485    #[serde(default)]
1486    pub db: Option<String>,
1487
1488    /// Embedding engine declarations.
1489    #[serde(default)]
1490    pub engines: Vec<EngineConfig>,
1491
1492    /// Distinguishes a file's explicit `engines = []` from an omitted engine list.
1493    /// Use [`Self::load`] for file input; direct deserialization does not track
1494    /// presence or perform legacy engine conversion.
1495    #[serde(skip)]
1496    pub engines_declared: bool,
1497
1498    /// Default actor identity for this khive instance.
1499    ///
1500    /// When present, `actor.id` feeds configuration identity and gate/attribution
1501    /// policy input.  A non-`'local'` `actor.id` is folded into the default READ
1502    /// visible-set at config load (ADR-007 Rev 4 Rule 3b) — it widens what default
1503    /// multi-record reads return, but never routes writes or sets `default_namespace`.
1504    /// Cloud model derives actor identity from an authenticated token.
1505    #[serde(default)]
1506    pub actor: ActorConfig,
1507
1508    /// Optional caller-enrollment policy. A present, even empty, table is an
1509    /// explicit fail-closed policy; an absent table preserves the runtime's
1510    /// existing gate.
1511    #[serde(default)]
1512    pub gate: Option<GateSectionConfig>,
1513
1514    /// Runtime knobs: namespace overrides, brain profile, etc.
1515    #[serde(default)]
1516    pub runtime: RuntimeSectionConfig,
1517
1518    /// Named storage backends (ADR-028).
1519    ///
1520    /// When absent or empty, a single implicit `main` backend is used and all
1521    /// packs share it — identical to pre-ADR-028 behavior.
1522    #[serde(default)]
1523    pub backends: Vec<BackendConfig>,
1524
1525    /// Absolute directory that bounds registered code-map files (ADR-139).
1526    #[serde(default)]
1527    pub code_map_root: Option<String>,
1528
1529    /// Operator-registered code-map database files (ADR-139).
1530    #[serde(default)]
1531    pub code_maps: Vec<CodeMapConfig>,
1532
1533    /// Per-pack backend assignments (ADR-028).
1534    ///
1535    /// Maps pack name to backend name. Packs absent from this map fall back to
1536    /// the `main` backend. Validated at load time: every referenced backend name
1537    /// must appear in `backends`.
1538    #[serde(default)]
1539    pub packs: std::collections::HashMap<String, PackConfig>,
1540
1541    /// Actor read policy. An absent or empty list grants no fleet-wide reads.
1542    #[serde(default)]
1543    pub brain: BrainSectionConfig,
1544
1545    /// Git-write policy allowlist (ADR-108 Amendment). Absent or empty
1546    /// `allowed` fails closed — `khive-pack-git`'s write verbs are
1547    /// unavailable until this section is populated.
1548    #[serde(default)]
1549    pub git_write: GitWriteSectionConfig,
1550
1551    /// Server-local file-transfer opt-in. Other blob verbs are unaffected.
1552    #[serde(default)]
1553    pub blob: BlobSectionConfig,
1554
1555    /// Storage-layer config not covered by `[[backends]]` (ADR-111
1556    /// Amendment 2: `[storage.blob]`'s `fs`/`s3` selector).
1557    #[serde(default)]
1558    pub storage: StorageSectionConfig,
1559
1560    /// Exec sandbox section (ADR-181). Absent means no runs: the exec pack
1561    /// refuses every `exec.run` until `[exec] read_roots` names a toolchain.
1562    #[serde(default)]
1563    pub exec: ExecSectionConfig,
1564
1565    /// Stream and channel carrier policy. Unclassified kinds default to ephemeral.
1566    #[serde(default)]
1567    pub telemetry: crate::telemetry_config::TelemetryConfig,
1568
1569    /// Rendering timezone configuration (ADR-169). Absent `timezone` resolves
1570    /// to the host's local zone at [`RuntimeConfig`](crate::RuntimeConfig)
1571    /// construction time.
1572    #[serde(default)]
1573    pub display: DisplaySectionConfig,
1574
1575    /// `web.fetch`/`web.search` operator policy (ADR-175 Amendment 1).
1576    /// Absent is the fail-closed default for search (no provider configured)
1577    /// and the permissive-subject-to-address-rules default for fetch (no
1578    /// allowlist configured).
1579    #[serde(default)]
1580    pub web: WebSectionConfig,
1581}
1582
1583/// `[runtime]` section in `khive.toml`.
1584///
1585/// Carries runtime knobs resolved during process construction. Most mirror a
1586/// CLI flag / environment tier; field documentation calls out exceptions.
1587/// All fields are optional and preserve their already-resolved base value when
1588/// absent.
1589#[derive(Debug, Clone, Deserialize, Default)]
1590pub struct RuntimeSectionConfig {
1591    /// Maximum simultaneous background warm jobs in one serving host.
1592    /// Absent preserves the resolved base; zero and unsupported capacities fail.
1593    #[serde(default)]
1594    pub warm_concurrency: Option<usize>,
1595
1596    /// Maximum simultaneous background maintenance jobs in one serving host.
1597    /// Interactive dispatch does not use this admission limit.
1598    #[serde(default)]
1599    pub maintenance_concurrency: Option<usize>,
1600
1601    /// Packs to load when neither `--pack` nor `KHIVE_PACKS` selects them.
1602    /// An absent or empty list preserves the built-in production default.
1603    #[serde(default)]
1604    pub packs: Option<Vec<String>>,
1605
1606    /// Brain profile ID to use for `memory.feedback` / `knowledge.feedback`
1607    /// and recall-time score boosting (ADR-035 §Brain profile configuration).
1608    ///
1609    /// Mirrors `--brain-profile` / `KHIVE_BRAIN_PROFILE`. When absent, the
1610    /// namespace-bound profile (via `brain.resolve`) is tried, then the
1611    /// global tuning prior is used as the final fallback.
1612    #[serde(default)]
1613    pub brain_profile: Option<String>,
1614
1615    /// Default output serialization format (ADR-078).
1616    ///
1617    /// Mirrors `--output-format` / `KHIVE_OUTPUT_FORMAT`. Precedence (highest to lowest):
1618    /// per-request `format` field → `KHIVE_OUTPUT_FORMAT` → this field → builtin `json`.
1619    ///
1620    /// Accepted values: `"json"` (default), `"auto"`, `"table"`.
1621    #[serde(default)]
1622    pub default_output_format: Option<OutputFormat>,
1623
1624    /// Aggregate process-local admission budget for digest-verified blob
1625    /// hydration (ADR-160 D3), in raw bytes.
1626    ///
1627    /// This knob has no environment-variable counterpart. When absent, the
1628    /// resolved runtime keeps its built-in 256 MiB default (or a value supplied
1629    /// directly through `RuntimeConfig`).
1630    #[serde(default)]
1631    pub blob_hydration_bytes: Option<u64>,
1632}
1633
1634/// `[display]` section in `khive.toml` — the timezone khive anchors date-only
1635/// input to (ADR-169 Implementation step 1).
1636///
1637/// ```toml
1638/// [display]
1639/// timezone = "America/New_York"
1640/// ```
1641#[derive(Debug, Clone, Deserialize, Default)]
1642pub struct DisplaySectionConfig {
1643    /// IANA zone name (e.g. `"America/New_York"`, `"Asia/Tokyo"`, `"UTC"`).
1644    /// Validated at load time against `chrono_tz::Tz`'s zone table — an
1645    /// unrecognized name is a startup error, not a silent fallback. Absent →
1646    /// the host's local zone, resolved once via `iana-time-zone` and falling
1647    /// back to UTC when the host zone cannot be determined.
1648    #[serde(default)]
1649    pub timezone: Option<String>,
1650}
1651
1652impl KhiveConfig {
1653    /// Load and validate a `KhiveConfig` from an explicit path.
1654    ///
1655    /// Search order:
1656    /// 1. `path` argument (explicit override — e.g. from `--config` / `KHIVE_CONFIG`)
1657    /// 2. `./.khive/config.toml` (project-local config, relative to the MCP server cwd)
1658    ///
1659    /// The project-local default collocates config with the `khive-test.db` that already
1660    /// lives under `.khive/` in each project directory. `~/.khive/config.toml` is searched
1661    /// by [`KhiveConfig::load_with_home_fallback`] when the project-local file is absent.
1662    ///
1663    /// If the resolved file does **not exist**, returns `Ok(None)`.
1664    /// A missing config is not an error — callers fall back to the env-var path.
1665    ///
1666    /// If the file exists but cannot be parsed, returns a `ConfigError`.
1667    /// After parsing, `validate()` runs and any logical errors are returned.
1668    pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
1669        let resolved = match path {
1670            Some(p) => p.to_path_buf(),
1671            None => PathBuf::from(".khive/config.toml"),
1672        };
1673
1674        if !resolved.exists() {
1675            return Ok(None);
1676        }
1677
1678        // Diagnostics name the canonical path so an error is actionable from
1679        // any cwd; resolution keeps using `resolved` as given.
1680        let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
1681        let raw = std::fs::read_to_string(&resolved)
1682            .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
1683        let mut document: toml::Value =
1684            toml::from_str(&raw).map_err(|source| ConfigError::Parse {
1685                path: diagnostic_path.clone(),
1686                source,
1687            })?;
1688        let schema_probe: SchemaSyntaxProbe =
1689            toml::from_str(&raw).map_err(|source| ConfigError::SchemaParse {
1690                path: diagnostic_path.clone(),
1691                key: if document
1692                    .get("schema")
1693                    .is_some_and(|value| !value.is_table())
1694                {
1695                    "schema"
1696                } else {
1697                    "schema.strict"
1698                },
1699                source: Box::new(source),
1700            })?;
1701        let unknown_schema_keys: Vec<String> = document
1702            .get("schema")
1703            .and_then(toml::Value::as_table)
1704            .map(|table| {
1705                table
1706                    .keys()
1707                    .filter(|key| key.as_str() != "strict")
1708                    .cloned()
1709                    .collect()
1710            })
1711            .unwrap_or_default();
1712        let (embed, unknown_embed_keys) = embed_batch::parse(&raw, &document, &diagnostic_path)?;
1713        let engines_declared = peers::normalize_engine_input(&mut document, &diagnostic_path)
1714            .map_err(|error| error.in_file(&diagnostic_path))?;
1715        let mut cfg: KhiveConfig = document.try_into().map_err(|source| ConfigError::Parse {
1716            path: diagnostic_path.clone(),
1717            source,
1718        })?;
1719        cfg.schema = schema_probe.schema;
1720        cfg.embed = embed;
1721        cfg.engines_declared = engines_declared;
1722        crate::credentials::read_tables(&raw, &mut cfg)
1723            .map_err(|error| ConfigError::from(error).in_file(&diagnostic_path))?;
1724        cfg.validate()
1725            .map_err(|error| error.in_file(&diagnostic_path))?;
1726        for engine in &mut cfg.engines {
1727            engine.name = canonical_engine_name(&engine.name);
1728        }
1729        for key in unknown_schema_keys {
1730            tracing::warn!(target: "khive.config.schema",
1731                key = %crate::secret_gate::bounded_masked_log_text(&key),
1732                file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1733                "ignoring unknown schema configuration key");
1734        }
1735        for key in unknown_embed_keys {
1736            tracing::warn!(target: "khive.config.embed",
1737                key = %crate::secret_gate::bounded_masked_log_text(&key),
1738                file = %crate::secret_gate::bounded_masked_log_text(&diagnostic_path.to_string_lossy()),
1739                "ignoring unknown embed configuration key");
1740        }
1741        Ok(Some(cfg))
1742    }
1743
1744    /// Load config with the full resolution order:
1745    ///
1746    /// 1. Explicit `path` (from `--config` / `KHIVE_CONFIG`)
1747    /// 2. `./khive.toml` (project-local, project root)
1748    /// 3. `<db-dir>/config.toml` (project-local, anchored to the resolved database's
1749    ///    own directory — see `project_config_anchor_dir`)
1750    /// 4. `~/.khive/config.toml` (user-global)
1751    ///
1752    /// Returns the first file found, or `Ok(None)` when none exist.
1753    /// Parse errors are propagated immediately — a malformed config is always
1754    /// an error regardless of which tier it came from.
1755    ///
1756    /// The explicit tier (1) is stricter than the discovery tiers: a `path`
1757    /// that names a file which does not exist returns
1758    /// [`ConfigError::ExplicitConfigMissing`] instead of falling through to
1759    /// tiers 2-4 — an operator-selected config that is missing is the same
1760    /// class of mistake as one that is malformed, and silently discovering a
1761    /// different file would boot against a config the operator did not select
1762    /// (ADR-035).
1763    ///
1764    /// `db_path` should be the same database path the caller is about to open
1765    /// (or has already resolved). Passing it makes tier 3 resolve identically
1766    /// for any two processes that target the same database, regardless of
1767    /// their process working directory — this is what lets a thin client and
1768    /// a warm daemon serving the same database agree on one config file. Pass
1769    /// `None` when no database path is known yet; tier 3 then falls back to
1770    /// the process cwd, matching the pre-existing behavior.
1771    pub fn load_with_home_fallback(
1772        path: Option<&Path>,
1773        db_path: Option<&Path>,
1774    ) -> Result<Option<Self>, ConfigError> {
1775        Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
1776    }
1777
1778    /// Load config with the full resolution order and retain the exact file
1779    /// that supplied it.
1780    ///
1781    /// This is the diagnostic-preserving form of
1782    /// [`KhiveConfig::load_with_home_fallback`]. Runtime callers that need to
1783    /// tell an operator which selected file must be edited should use this
1784    /// method instead of reconstructing the discovery order independently.
1785    pub fn load_with_home_fallback_and_source(
1786        path: Option<&Path>,
1787        db_path: Option<&Path>,
1788    ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1789        // Tier 1: explicit path (highest priority). An explicit selection
1790        // naming a MISSING file fails loud here — once, at the loader, for
1791        // every entry point — instead of silently falling through to the
1792        // discovery tiers: a mistyped path would otherwise boot against a
1793        // config the operator did not select (ADR-035: an entry point must
1794        // not document an explicit tier while silently falling back to
1795        // discovery). Tiers 2-4 keep their tolerant contract.
1796        if let Some(p) = path {
1797            if !p.exists() {
1798                return Err(ConfigError::ExplicitConfigMissing {
1799                    path: p.to_path_buf(),
1800                });
1801            }
1802            return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
1803        }
1804
1805        // Tiers 2-4: search project root, db-anchored hidden dir, user-global.
1806        let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1807        let home_root = std::env::var_os("HOME").map(PathBuf::from);
1808        Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
1809    }
1810
1811    /// Testable inner search: tiers 2-4, given explicit roots instead of
1812    /// reading `cwd` and `HOME` from process state.
1813    ///
1814    /// - Tier 2: `<project_root>/khive.toml` (still cwd-anchored — unchanged)
1815    /// - Tier 3: `<db_dir>/config.toml`, anchored to `db_path` rather than
1816    ///   `project_root` (see `project_config_anchor_dir`); falls back to
1817    ///   `<project_root>/.khive/config.toml` when `db_path` is `None`
1818    /// - Tier 4: `<home_root>/.khive/config.toml` (skipped when `None`)
1819    #[cfg(test)]
1820    pub(crate) fn load_with_roots(
1821        project_root: &Path,
1822        home_root: Option<&Path>,
1823        db_path: Option<&Path>,
1824    ) -> Result<Option<Self>, ConfigError> {
1825        Ok(
1826            Self::load_with_roots_and_source(project_root, home_root, db_path)?
1827                .map(|(config, _)| config),
1828        )
1829    }
1830
1831    fn load_with_roots_and_source(
1832        project_root: &Path,
1833        home_root: Option<&Path>,
1834        db_path: Option<&Path>,
1835    ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
1836        // Tier 2: project root khive.toml.
1837        let tier2 = project_root.join("khive.toml");
1838        if tier2.exists() {
1839            return Ok(Self::load(Some(&tier2))?
1840                .map(|config| (config, Self::diagnostic_config_path(&tier2))));
1841        }
1842
1843        // Tier 3: project-local hidden dir, anchored to the resolved database's
1844        // own directory instead of the process cwd.
1845        let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
1846        if tier3.exists() {
1847            return Ok(Self::load(Some(&tier3))?
1848                .map(|config| (config, Self::diagnostic_config_path(&tier3))));
1849        }
1850
1851        // Tier 4: user-global ~/.khive/config.toml.
1852        if let Some(home) = home_root {
1853            let tier4 = home.join(".khive/config.toml");
1854            if tier4.exists() {
1855                return Ok(Self::load(Some(&tier4))?
1856                    .map(|config| (config, Self::diagnostic_config_path(&tier4))));
1857            }
1858        }
1859
1860        Ok(None)
1861    }
1862
1863    /// Whether `[actor].require_attributed` is set in the explicit file, or with
1864    /// none, in any existing discovery tier, the database-anchored one included.
1865    /// A file that fails to load is an error, never a silent `false`.
1866    pub fn require_attributed_in_any_tier(
1867        path: Option<&Path>,
1868        db_path: Option<&Path>,
1869    ) -> Result<bool, ConfigError> {
1870        if let Some(p) = path {
1871            if !p.exists() {
1872                return Err(ConfigError::ExplicitConfigMissing {
1873                    path: p.to_path_buf(),
1874                });
1875            }
1876            return Ok(Self::load(Some(p))?.is_some_and(|cfg| cfg.actor.require_attributed));
1877        }
1878        let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1879        let home_root = std::env::var_os("HOME").map(PathBuf::from);
1880        Self::require_attributed_in_tiers(&project_root, home_root.as_deref(), db_path)
1881    }
1882
1883    /// Every file the loader's tiers 2-4 may read (`load_with_roots_and_source`), plus the
1884    /// cwd `.khive/config.toml`, which tier 3 reads when no database path is given.
1885    pub(crate) fn require_attributed_in_tiers(
1886        project_root: &Path,
1887        home_root: Option<&Path>,
1888        db_path: Option<&Path>,
1889    ) -> Result<bool, ConfigError> {
1890        let mut files = vec![
1891            project_root.join("khive.toml"),
1892            Self::project_config_anchor_dir(db_path, project_root).join("config.toml"),
1893            project_root.join(".khive/config.toml"),
1894        ];
1895        let home_file = home_root.map(|home| home.join(".khive/config.toml"));
1896        // The file `load_with_roots_and_source` reads: the first existing of tiers 2-4.
1897        let in_use = [Some(&files[0]), Some(&files[1]), home_file.as_ref()]
1898            .into_iter()
1899            .flatten()
1900            .find(|file| file.exists())
1901            .cloned();
1902        files.extend(home_file);
1903        files.dedup();
1904        for file in files.iter().filter(|file| file.exists()) {
1905            let loaded = Self::load(Some(file)).map_err(|source| match &in_use {
1906                Some(used) if used == file => source,
1907                _ => ConfigError::ShadowedTier {
1908                    path: Self::diagnostic_config_path(file),
1909                    in_use: in_use.as_deref().map(Self::diagnostic_config_path),
1910                    source: Box::new(source),
1911                },
1912            })?;
1913            if loaded.is_some_and(|cfg| cfg.actor.require_attributed) {
1914                return Ok(true);
1915            }
1916        }
1917        Ok(false)
1918    }
1919
1920    fn diagnostic_config_path(path: &Path) -> PathBuf {
1921        std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1922    }
1923
1924    /// Resolve the directory searched for the tier-3 project-local config file.
1925    ///
1926    /// Anchored to the directory containing the resolved database file, not the
1927    /// process cwd: two processes at different working directories that open the
1928    /// same database agree on this directory, which is what keeps their
1929    /// `config_id` fingerprints in sync (a client and a warm daemon serving the
1930    /// same database must resolve identical config so the daemon accepts the
1931    /// client's forwarded requests instead of rejecting them on a config
1932    /// mismatch).
1933    ///
1934    /// `db_path` is canonicalized first so symlinks/relative components collapse
1935    /// to the same absolute directory regardless of caller cwd. The database file
1936    /// may not exist yet (first run before anything has been written) — in that
1937    /// case canonicalization fails and the path is absolutized against
1938    /// `project_root` instead (or used as-is if already absolute); this must
1939    /// never panic, it is the expected cold-start case.
1940    ///
1941    /// If `db_dir` (the resolved database's parent directory) is itself named
1942    /// `.khive`, the config lives directly inside it (`<db_dir>/config.toml`) —
1943    /// this is the common case where the database is `<root>/.khive/khive.db`.
1944    /// Otherwise the config lives in a `.khive` subdirectory of `db_dir`.
1945    ///
1946    /// `db_path == None` (e.g. an in-memory database, or no database path known
1947    /// yet) falls back to `<project_root>/.khive`, preserving the pre-existing
1948    /// cwd-anchored behavior for callers with no database to anchor on.
1949    fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
1950        let Some(db_path) = db_path else {
1951            return project_root.join(".khive");
1952        };
1953
1954        let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
1955            if db_path.is_absolute() {
1956                db_path.to_path_buf()
1957            } else {
1958                project_root.join(db_path)
1959            }
1960        });
1961
1962        let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
1963
1964        if db_dir.file_name().is_some_and(|name| name == ".khive") {
1965            db_dir
1966        } else {
1967            db_dir.join(".khive")
1968        }
1969    }
1970
1971    /// Validate the parsed config for logical consistency.
1972    ///
1973    /// Checks:
1974    /// Engine names and storage keys are unique; dimensions and weights are
1975    /// positive. Non-unit weights remain refused until retrieval applies them.
1976    pub fn validate(&self) -> Result<(), ConfigError> {
1977        #[cfg(not(feature = "blob-s3"))]
1978        if matches!(&self.storage.blob, Some(BlobConfig::S3 { .. })) {
1979            return Err(ConfigError::BlobS3FeatureDisabled);
1980        }
1981
1982        let warm = self
1983            .runtime
1984            .warm_concurrency
1985            .unwrap_or(crate::config::DEFAULT_WARM_CONCURRENCY);
1986        let maintenance = self
1987            .runtime
1988            .maintenance_concurrency
1989            .unwrap_or(crate::config::DEFAULT_MAINTENANCE_CONCURRENCY);
1990        crate::resource_admission::WorkClassLimits::validate(warm, maintenance).map_err(
1991            |error| {
1992                let key = match &error {
1993                    crate::resource_admission::ResourceError::InvalidLimit {
1994                        class: crate::resource_admission::WorkClass::Warm,
1995                        ..
1996                    } => "warm_concurrency",
1997                    crate::resource_admission::ResourceError::InvalidLimit {
1998                        class: crate::resource_admission::WorkClass::Maintenance,
1999                        ..
2000                    } => "maintenance_concurrency",
2001                    _ => "background_concurrency",
2002                };
2003                ConfigError::InvalidRuntimeConfig {
2004                    key: key.to_owned(),
2005                    reason: error.to_string(),
2006                }
2007            },
2008        )?;
2009
2010        crate::mount_config::validate_mounts(&self.mounts)?;
2011        self.git_write.validate_dev_loop()?;
2012        self.telemetry.validate()?;
2013        self.web.validate()?;
2014        crate::credentials::CredentialConfig::validate_all(&self.credentials)?;
2015        if let Some(receipts) = &self.visibility_receipts {
2016            receipts.validate(&self.credentials)?;
2017        }
2018        self.channel.validate()?;
2019
2020        // Reject a top-level `db` key loudly instead of letting serde's
2021        // forward-compatible unknown-key tolerance silently swallow it: a
2022        // config author expecting `db=` to select the database would
2023        // otherwise get silent divergence from `--db`/`KHIVE_DB`.
2024        if let Some(value) = self.db.as_deref() {
2025            if !value.is_empty() {
2026                return Err(ConfigError::UnsupportedTopLevelDb {
2027                    value: value.to_string(),
2028                });
2029            }
2030        }
2031
2032        // ADR-181 resource limits: macOS returns EINVAL for RLIMIT_AS and
2033        // RLIMIT_DATA, and RLIMIT_NPROC counts every process of the uid, so
2034        // neither can bound one run. Refuse loudly instead of pretending.
2035        if cfg!(target_os = "macos") {
2036            if self.exec.limits.address_space.is_some() {
2037                return Err(ConfigError::InvalidExecConfig {
2038                    key: "limits.address_space".to_string(),
2039                    reason: "unsupported_on_platform: macOS does not enforce an address-space rlimit per process".to_string(),
2040                });
2041            }
2042            if self.exec.limits.nproc.is_some() {
2043                return Err(ConfigError::InvalidExecConfig {
2044                    key: "limits.nproc".to_string(),
2045                    reason: "unsupported_on_platform: RLIMIT_NPROC counts every process of the uid, not one run".to_string(),
2046                });
2047            }
2048        }
2049        // These defaults must agree with the exec pack's resolved defaults.
2050        // Validate the effective pair, including one-sided overrides, before
2051        // Duration conversion or a deadline can panic in exec.run.
2052        let default_timeout = self.exec.timeout_default_s.unwrap_or(30.0);
2053        let maximum_timeout = self.exec.timeout_max_s.unwrap_or(600.0);
2054        for (key, value) in [
2055            ("timeout_default_s", default_timeout),
2056            ("timeout_max_s", maximum_timeout),
2057        ] {
2058            let duration = value
2059                .is_finite()
2060                .then(|| std::time::Duration::try_from_secs_f64(value).ok())
2061                .flatten()
2062                .filter(|duration| !duration.is_zero());
2063            if duration
2064                .is_none_or(|duration| std::time::Instant::now().checked_add(duration).is_none())
2065            {
2066                return Err(ConfigError::InvalidExecConfig {
2067                    key: key.to_string(),
2068                    reason: "must be positive, finite, and representable as a deadline".to_string(),
2069                });
2070            }
2071        }
2072        if default_timeout > maximum_timeout {
2073            return Err(ConfigError::InvalidExecConfig {
2074                key: "timeout_default_s".to_string(),
2075                reason: format!(
2076                    "default {default_timeout} exceeds timeout_max_s {maximum_timeout}"
2077                ),
2078            });
2079        }
2080        let binary_digest_timeout = self
2081            .exec
2082            .binary_digest_timeout_s
2083            .unwrap_or(DEFAULT_EXEC_BINARY_DIGEST_TIMEOUT_S);
2084        if !(1..=MAX_EXEC_BINARY_DIGEST_TIMEOUT_S).contains(&binary_digest_timeout) {
2085            return Err(ConfigError::InvalidExecConfig {
2086                key: "binary_digest_timeout_s".to_string(),
2087                reason: format!("must be between 1 and {MAX_EXEC_BINARY_DIGEST_TIMEOUT_S} seconds"),
2088            });
2089        }
2090
2091        if let Some(value) = self.runtime.blob_hydration_bytes {
2092            let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
2093            let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
2094            if value < min || value > max {
2095                return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
2096            }
2097        }
2098
2099        // Validate actor.id when present — an invalid namespace is a startup error,
2100        // not a silent fallback.
2101        if let Some(id) = self.actor.id.as_deref() {
2102            if id.is_empty() {
2103                return Err(ConfigError::InvalidActorId {
2104                    id: id.to_string(),
2105                    reason: "actor.id must not be empty; remove the key or provide a value"
2106                        .to_string(),
2107                });
2108            }
2109            Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
2110                id: id.to_string(),
2111                reason: e.to_string(),
2112            })?;
2113        }
2114
2115        self.actor
2116            .mailbox_gate(std::sync::Arc::new(khive_gate::AllowAllGate))
2117            .map_err(|error| ConfigError::InvalidMailboxReaders {
2118                reason: error.to_string(),
2119            })?;
2120
2121        if let Some(ref vis) = self.actor.visible_namespaces {
2122            for ns_str in vis {
2123                if ns_str.is_empty() {
2124                    return Err(ConfigError::InvalidActorId {
2125                        id: ns_str.clone(),
2126                        reason: "visible_namespaces entries must not be empty".to_string(),
2127                    });
2128                }
2129                Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2130                    id: ns_str.clone(),
2131                    reason: format!("invalid visible namespace: {e}"),
2132                })?;
2133            }
2134        }
2135
2136        // Validate actor.owned_namespaces (fail-closed at startup). Ownership is
2137        // declared by name, so every entry is checked exactly: it must parse, must
2138        // not be the shared namespace or the actor's own id, and must be unique.
2139        if !self.actor.owned_namespaces.is_empty() {
2140            let Some(actor_id) = self.actor.id.as_deref() else {
2141                return Err(ConfigError::InvalidActorId {
2142                    id: String::new(),
2143                    reason: "owned_namespaces requires an explicit [actor] id".to_string(),
2144                });
2145            };
2146            let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2147            for ns_str in &self.actor.owned_namespaces {
2148                if ns_str.is_empty() {
2149                    return Err(ConfigError::InvalidActorId {
2150                        id: ns_str.clone(),
2151                        reason: "owned_namespaces entries must not be empty".to_string(),
2152                    });
2153                }
2154                let parsed = Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2155                    id: ns_str.clone(),
2156                    reason: format!("invalid owned namespace: {e}"),
2157                })?;
2158                if parsed.as_str() == Namespace::LOCAL {
2159                    return Err(ConfigError::InvalidActorId {
2160                        id: ns_str.clone(),
2161                        reason: "owned_namespaces must not list the shared namespace `local`"
2162                            .to_string(),
2163                    });
2164                }
2165                if parsed.as_str() == actor_id {
2166                    return Err(ConfigError::InvalidActorId {
2167                        id: ns_str.clone(),
2168                        reason: "owned_namespaces must not list the actor's own id".to_string(),
2169                    });
2170                }
2171                if !seen.insert(parsed.as_str().to_string()) {
2172                    return Err(ConfigError::InvalidActorId {
2173                        id: ns_str.clone(),
2174                        reason: "owned_namespaces entries must be unique".to_string(),
2175                    });
2176                }
2177            }
2178        }
2179
2180        if let Some(gate) = &self.gate {
2181            khive_gate::CallerEnrollmentGate::validate_write_denials(&gate.deny_writes_for)
2182                .map_err(|error| ConfigError::InvalidWriteDenyPatterns {
2183                    reason: error.to_string(),
2184                })?;
2185            for id in &gate.granted_actors {
2186                if id.is_empty() {
2187                    return Err(ConfigError::InvalidGrantedActorId {
2188                        id: id.clone(),
2189                        reason: "actor ids must not be empty".to_string(),
2190                    });
2191                }
2192                Namespace::parse(id).map_err(|error| ConfigError::InvalidGrantedActorId {
2193                    id: id.clone(),
2194                    reason: error.to_string(),
2195                })?;
2196            }
2197        }
2198
2199        // Validate actor.allowed_outbound_namespaces (fail-closed at startup on malformed entry).
2200        for ns_str in &self.actor.allowed_outbound_namespaces {
2201            if ns_str.is_empty() {
2202                return Err(ConfigError::InvalidActorId {
2203                    id: ns_str.clone(),
2204                    reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
2205                });
2206            }
2207            Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
2208                id: ns_str.clone(),
2209                reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
2210            })?;
2211        }
2212
2213        // Backend names must be unique.
2214        if !self.backends.is_empty() {
2215            let mut seen_backends = std::collections::HashSet::new();
2216            for backend in &self.backends {
2217                BackendId::parse(&backend.name).map_err(|error| {
2218                    ConfigError::InvalidBackendName {
2219                        name: backend.name.clone(),
2220                        reason: error.to_string(),
2221                    }
2222                })?;
2223                if backend
2224                    .served_kinds
2225                    .as_ref()
2226                    .is_some_and(BTreeSet::is_empty)
2227                {
2228                    return Err(ConfigError::EmptyBackendServedKinds {
2229                        name: backend.name.clone(),
2230                    });
2231                }
2232                if !seen_backends.insert(backend.name.clone()) {
2233                    return Err(ConfigError::DuplicateBackendName {
2234                        name: backend.name.clone(),
2235                    });
2236                }
2237
2238                // The field's static invariants are checked when the config
2239                // file loads. The host resolves the environment fallback once
2240                // for every effective backend before forwarding or opening it.
2241                if backend.wal_ceiling_bytes.is_some() {
2242                    resolve_wal_ceiling(
2243                        backend.wal_ceiling_bytes,
2244                        None,
2245                        &backend.name,
2246                        backend.kind.clone(),
2247                        backend
2248                            .journal_mode
2249                            .as_deref()
2250                            .is_none_or(|mode| mode.eq_ignore_ascii_case("wal")),
2251                        backend.read_only,
2252                    )?;
2253                }
2254
2255                backend.resolve_disk_guard(&khive_db::DiskGuardEnvironment::default())?;
2256
2257                // Reject fields that are parsed but not yet implemented: silently
2258                // accepting them would let misconfiguration slip past startup.
2259                if backend.cache_mb.is_some() {
2260                    return Err(ConfigError::UnsupportedBackendField {
2261                        name: backend.name.clone(),
2262                        field: "cache_mb",
2263                    });
2264                }
2265                if backend.journal_mode.is_some() {
2266                    return Err(ConfigError::UnsupportedBackendField {
2267                        name: backend.name.clone(),
2268                        field: "journal_mode",
2269                    });
2270                }
2271            }
2272        }
2273
2274        let defined: Vec<&str> = if self.backends.is_empty() {
2275            vec![BackendId::MAIN]
2276        } else {
2277            self.backends.iter().map(|b| b.name.as_str()).collect()
2278        };
2279        for (pack_name, pack_cfg) in &self.packs {
2280            if !defined.contains(&pack_cfg.backend.as_str()) {
2281                return Err(ConfigError::UnknownPackBackend {
2282                    pack: pack_name.clone(),
2283                    backend: pack_cfg.backend.clone(),
2284                    defined: defined.join(", "),
2285                });
2286            }
2287        }
2288
2289        if !self.backends.is_empty() {
2290            let missing: Vec<_> = [SubstrateKind::Note, SubstrateKind::Entity]
2291                .into_iter()
2292                .filter(|kind| {
2293                    !self.backends.iter().any(|backend| {
2294                        backend
2295                            .served_kinds
2296                            .as_ref()
2297                            .is_none_or(|served| served.contains(kind))
2298                    })
2299                })
2300                .collect();
2301            if !missing.is_empty() {
2302                return Err(ConfigError::MissingBackendSearchKinds {
2303                    kinds: missing,
2304                    defined: defined.join(", "),
2305                });
2306            }
2307        }
2308
2309        // Validate [display] timezone (ADR-169): an unrecognized IANA zone
2310        // name is a startup error, not a silent fallback to the host zone.
2311        if let Some(tz) = self.display.timezone.as_deref() {
2312            if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
2313                return Err(ConfigError::InvalidDisplayTimezone {
2314                    timezone: tz.to_string(),
2315                });
2316            }
2317        }
2318
2319        // Validate [[git_write.allowed]] entries (ADR-108 Amendment): each
2320        // repo must be a non-empty absolute path, and each entry must carry
2321        // at least one branch pattern — an entry with an empty `branches`
2322        // list would silently allowlist a repo for no branch at all, which
2323        // reads as "configured" while behaving identically to "not
2324        // allowlisted"; reject it loudly instead of leaving that trap.
2325        for entry in &self.git_write.allowed {
2326            if entry.repo.trim().is_empty() {
2327                return Err(ConfigError::InvalidGitWriteEntry {
2328                    repo: entry.repo.clone(),
2329                    reason: "repo must not be empty".to_string(),
2330                });
2331            }
2332            if !Path::new(&entry.repo).is_absolute() {
2333                return Err(ConfigError::InvalidGitWriteEntry {
2334                    repo: entry.repo.clone(),
2335                    reason: "repo must be an absolute path".to_string(),
2336                });
2337            }
2338            if entry.branches.is_empty() {
2339                return Err(ConfigError::InvalidGitWriteEntry {
2340                    repo: entry.repo.clone(),
2341                    reason: "branches must not be empty".to_string(),
2342                });
2343            }
2344            if entry.branches.iter().any(|b| b.trim().is_empty()) {
2345                return Err(ConfigError::InvalidGitWriteEntry {
2346                    repo: entry.repo.clone(),
2347                    reason: "branches entries must not be empty".to_string(),
2348                });
2349            }
2350            // ADR-108 specifies exact name or a SINGLE-star wildcard per
2351            // branch pattern -- a pattern with two or more `*` (e.g. `**`,
2352            // `rel-*-*-final`) is a wider grammar than the ADR authorizes
2353            // and must be rejected at config load, not silently accepted.
2354            if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
2355                return Err(ConfigError::InvalidGitWriteEntry {
2356                    repo: entry.repo.clone(),
2357                    reason: format!(
2358                        "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
2359                    ),
2360                });
2361            }
2362        }
2363
2364        validate_peer_engines(&self.engines)
2365    }
2366
2367    /// First peer used by single-engine compatibility APIs, if any.
2368    pub fn default_engine(&self) -> Option<&EngineConfig> {
2369        self.engines.first()
2370    }
2371}
2372
2373// ---- Env-var fallback ----
2374
2375/// Build an in-memory `KhiveConfig` from the legacy env-var path.
2376///
2377/// Used when no config file is present. Emits `tracing::info!` directing
2378/// operators to migrate to `~/.khive/config.toml`.
2379///
2380/// The primary model (`KHIVE_EMBEDDING_MODEL`) becomes the first peer;
2381/// additional models follow in their existing order. When only
2382/// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` is set, the built-in default model is
2383/// synthesized as the primary — the additional list is additive, never a
2384/// replacement for the primary (khive#1221; matches `RuntimeConfig::default()`,
2385/// which resolves an unset `KHIVE_EMBEDDING_MODEL` to the built-in default).
2386pub fn config_from_env() -> KhiveConfig {
2387    let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
2388        .ok()
2389        .filter(|s| !s.trim().is_empty());
2390    let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
2391        .ok()
2392        .unwrap_or_default();
2393    let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
2394        .into_iter()
2395        .filter(|s| !s.is_empty())
2396        .collect();
2397
2398    if primary_model.is_none() && additional.is_empty() {
2399        return KhiveConfig::default();
2400    }
2401
2402    tracing::info!(
2403        "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
2404    );
2405
2406    config_from_env_parts(primary_model, additional)
2407}
2408
2409/// Pure core of [`config_from_env`], separated so the engine-list derivation
2410/// is testable without mutating process-global environment variables.
2411fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
2412    let mut engines = Vec::new();
2413
2414    let primary =
2415        primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
2416    for model in std::iter::once(primary).chain(additional) {
2417        let name = canonical_engine_name(&model);
2418        if engines
2419            .iter()
2420            .any(|engine: &EngineConfig| engine.name == name)
2421        {
2422            continue;
2423        }
2424        engines.push(EngineConfig {
2425            name,
2426            weight: 1.0,
2427            dims: None,
2428        });
2429    }
2430
2431    KhiveConfig {
2432        engines,
2433        ..KhiveConfig::default()
2434    }
2435}
2436
2437#[cfg(test)]
2438#[path = "engine_config_schema_tests.rs"]
2439mod schema_tests;
2440
2441// ---- Tests ----
2442
2443// Kept in-crate (not tests/): exercises private ConfigError variants not part
2444// of the public API.
2445#[cfg(test)]
2446#[path = "engine_config_tests.rs"]
2447mod tests;
2448
2449#[cfg(test)]
2450mod background_limit_tests {
2451    use super::*;
2452
2453    #[test]
2454    fn optional_background_limits_parse_and_validate() {
2455        let config: KhiveConfig =
2456            toml::from_str("[runtime]\nwarm_concurrency = 3\nmaintenance_concurrency = 2\n")
2457                .unwrap();
2458        config.validate().unwrap();
2459        assert_eq!(config.runtime.warm_concurrency, Some(3));
2460        assert_eq!(config.runtime.maintenance_concurrency, Some(2));
2461    }
2462
2463    #[test]
2464    fn zero_and_overflow_limits_report_the_actual_runtime_key() {
2465        for key in ["warm_concurrency", "maintenance_concurrency"] {
2466            for value in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] {
2467                let mut config: KhiveConfig = toml::from_str("").unwrap();
2468                if key == "warm_concurrency" {
2469                    config.runtime.warm_concurrency = Some(value);
2470                } else {
2471                    config.runtime.maintenance_concurrency = Some(value);
2472                }
2473                assert!(matches!(config.validate(),
2474                    Err(ConfigError::InvalidRuntimeConfig { key: found, .. }) if found == key
2475                ));
2476            }
2477        }
2478    }
2479
2480    #[test]
2481    fn negative_toml_background_limits_are_not_deserialized() {
2482        for key in ["warm_concurrency", "maintenance_concurrency"] {
2483            let text = format!("[runtime]\n{key} = -1\n");
2484            assert!(toml::from_str::<KhiveConfig>(&text).is_err());
2485        }
2486    }
2487
2488    #[test]
2489    fn limits_keep_base_and_override_values_on_both_mapping_branches() {
2490        for engines_declared in [false, true] {
2491            let mut config: KhiveConfig =
2492                toml::from_str("[runtime]\nwarm_concurrency = 5\n").unwrap();
2493            config.engines_declared = engines_declared;
2494            let base = crate::RuntimeConfig {
2495                warm_concurrency: 3,
2496                maintenance_concurrency: 2,
2497                ..crate::RuntimeConfig::no_embeddings()
2498            };
2499            let mapped = crate::config::runtime_config_from_khive_config(&config, base);
2500            assert_eq!(mapped.warm_concurrency, 5);
2501            assert_eq!(mapped.maintenance_concurrency, 2);
2502        }
2503    }
2504
2505    #[test]
2506    fn defaults_use_the_named_validated_background_constants() {
2507        let config = crate::RuntimeConfig::default();
2508        assert_eq!(
2509            config.warm_concurrency,
2510            crate::config::DEFAULT_WARM_CONCURRENCY
2511        );
2512        assert_eq!(
2513            config.maintenance_concurrency,
2514            crate::config::DEFAULT_MAINTENANCE_CONCURRENCY
2515        );
2516        crate::resource_admission::WorkClassLimits::validate(
2517            config.warm_concurrency,
2518            config.maintenance_concurrency,
2519        )
2520        .unwrap();
2521    }
2522}