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