Skip to main content

khive_runtime/
engine_config.rs

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