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