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