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