Skip to main content

khive_runtime/
config.rs

1//! RuntimeConfig, BackendId, NamespaceToken, and embedding model helpers.
2
3use std::sync::Arc;
4
5use khive_db::StorageBackend;
6pub use khive_db::WalCeilingSource;
7use khive_gate::{ActorRef, AllowAllGate, GateRef};
8use khive_types::Namespace;
9use lattice_embed::EmbeddingModel;
10
11use crate::error::RuntimeResult;
12
13// ---- BackendId ----
14
15/// Identifies a named backend in a multi-backend deployment.
16///
17/// The `main` backend is the default single-backend name. Multi-backend deployments
18/// assign each `[[backends]]` entry a distinct `BackendId`. The
19/// `SubstrateCoordinator` in `kkernel`
20/// uses `BackendId` for node-to-backend resolution and cross-backend edge routing.
21///
22/// A single-backend `KhiveRuntime` always has the `main` backend id by default.
23/// The boot path in `kkernel` or `khive-mcp` sets the id via `RuntimeConfig::backend_id`
24/// when constructing per-pack runtimes.
25#[derive(Clone, Debug, PartialEq, Eq, Hash)]
26pub struct BackendId(String);
27
28/// Validation error returned when a backend identifier is rejected.
29#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
30pub enum BackendIdError {
31    /// The supplied identifier was empty or contained only whitespace.
32    #[error("backend id must not be empty or whitespace-only")]
33    Empty,
34}
35
36impl BackendId {
37    /// The default single-backend name.
38    pub const MAIN: &'static str = "main";
39
40    /// Parse a nonempty backend identifier.
41    pub fn parse(name: impl Into<String>) -> Result<Self, BackendIdError> {
42        let name = name.into();
43        if name.trim().is_empty() {
44            return Err(BackendIdError::Empty);
45        }
46        Ok(Self(name))
47    }
48
49    /// The default `main` backend id.
50    pub fn main() -> Self {
51        Self(Self::MAIN.to_string())
52    }
53
54    /// Return the backend name as a `&str`.
55    pub fn as_str(&self) -> &str {
56        &self.0
57    }
58}
59
60impl TryFrom<String> for BackendId {
61    type Error = BackendIdError;
62
63    fn try_from(value: String) -> Result<Self, Self::Error> {
64        Self::parse(value)
65    }
66}
67
68impl TryFrom<&str> for BackendId {
69    type Error = BackendIdError;
70
71    fn try_from(value: &str) -> Result<Self, Self::Error> {
72        Self::parse(value)
73    }
74}
75
76impl std::str::FromStr for BackendId {
77    type Err = BackendIdError;
78
79    fn from_str(value: &str) -> Result<Self, Self::Err> {
80        Self::parse(value)
81    }
82}
83
84impl std::fmt::Display for BackendId {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.write_str(&self.0)
87    }
88}
89
90#[cfg(test)]
91mod backend_id_tests {
92    use super::BackendId;
93
94    #[test]
95    fn empty_and_whitespace_only_backend_ids_are_rejected() {
96        for invalid in ["", " ", "\t\n"] {
97            assert!(
98                BackendId::parse(invalid).is_err(),
99                "backend id {invalid:?} must be rejected"
100            );
101        }
102    }
103
104    #[test]
105    fn nonempty_backend_id_round_trips() {
106        let id = BackendId::parse("archive").expect("valid backend id");
107        assert_eq!(id.as_str(), "archive");
108        assert_eq!(id.to_string(), "archive");
109    }
110}
111
112// ---- Sealed token ----
113
114mod private {
115    #[derive(Clone, Debug)]
116    pub(crate) struct Sealed;
117}
118
119/// Authorization proof that a caller is permitted to access a specific namespace.
120///
121/// Created by [`crate::VerbRegistry::dispatch`] after the gate approves the request.
122/// The sealed inner field prevents external code from constructing a token
123/// without going through the authorization path.
124///
125/// The `namespace` field is the **write namespace**: all records created via
126/// this token land in that namespace. `visible` is the **read visibility set**:
127/// list/search/get operations will return records from any namespace in this
128/// set. The write namespace is always a member of the visible set.
129///
130/// Single-namespace behaviour (backward-compatible default): `visible` contains
131/// exactly `[namespace]` — identical to the old strict-equality checks.
132#[derive(Clone, Debug)]
133pub struct NamespaceToken {
134    namespace: Namespace,
135    gate_namespace: Namespace,
136    gate_explicit_namespace: Option<String>,
137    request_id: Option<u64>,
138    visible: Vec<Namespace>,
139    actor: ActorRef,
140    process_ref: Option<String>,
141    _sealed: private::Sealed,
142}
143
144impl NamespaceToken {
145    /// Mint an authorized token with an extended visibility set.
146    ///
147    /// `extra_visible` lists namespaces beyond the primary that the token may
148    /// read. The primary namespace is always included in the visible set
149    /// regardless of what `extra_visible` contains. Duplicates are removed.
150    pub(crate) fn mint_with_visibility(
151        namespace: Namespace,
152        extra_visible: Vec<Namespace>,
153        actor: ActorRef,
154    ) -> Self {
155        let mut visible = vec![namespace.clone()];
156        for ns in extra_visible {
157            if !visible.contains(&ns) {
158                visible.push(ns);
159            }
160        }
161        debug_assert!(!visible.is_empty(), "visible set must be non-empty");
162        Self {
163            gate_namespace: namespace.clone(),
164            gate_explicit_namespace: None,
165            request_id: None,
166            namespace,
167            visible,
168            actor,
169            process_ref: None,
170            _sealed: private::Sealed,
171        }
172    }
173
174    /// Mint an authorized token. Only callable from within `khive-runtime`.
175    ///
176    /// The visible set defaults to `[namespace]` — backward-compatible with
177    /// single-namespace enforcement.
178    pub(crate) fn mint_authorized(namespace: Namespace, actor: ActorRef) -> Self {
179        Self::mint_with_visibility(namespace, vec![], actor)
180    }
181
182    /// Convenience constructor for the local namespace with an anonymous actor.
183    ///
184    /// Only callable from within `khive-runtime`. External callers must use
185    /// [`KhiveRuntime::authorize`] to mint tokens.
186    // Used only in #[cfg(test)] blocks within this crate's src/ files.
187    #[allow(dead_code)]
188    pub(crate) fn local() -> Self {
189        Self::mint_authorized(Namespace::local(), ActorRef::anonymous())
190    }
191
192    /// Convenience constructor for a specific namespace with an anonymous actor.
193    ///
194    /// Only callable from within `khive-runtime`. External callers must use
195    /// [`KhiveRuntime::authorize`] to mint tokens.
196    // Used only in #[cfg(test)] blocks within this crate's src/ files.
197    #[allow(dead_code)]
198    pub(crate) fn for_namespace(ns: Namespace) -> Self {
199        Self::mint_authorized(ns, ActorRef::anonymous())
200    }
201
202    /// Return the write namespace this token authorises.
203    ///
204    /// All records created via this token land in this namespace.
205    pub fn namespace(&self) -> &Namespace {
206        &self.namespace
207    }
208
209    /// Return the namespace used by the originating dispatch's Gate check.
210    /// It can differ from the primary storage namespace on an implicit request.
211    /// Tokens minted directly, or reminted by `with_namespace`, use their primary.
212    pub fn gate_namespace(&self) -> &Namespace {
213        &self.gate_namespace
214    }
215
216    pub(crate) fn with_gate_namespace(mut self, namespace: Namespace) -> Self {
217        self.gate_namespace = namespace;
218        self
219    }
220
221    /// The exact submitted namespace argument, if the caller supplied one.
222    /// Pack handlers normally receive params after dispatch strips this key.
223    pub(crate) fn gate_explicit_namespace(&self) -> Option<&str> {
224        self.gate_explicit_namespace.as_deref()
225    }
226
227    pub(crate) fn with_gate_explicit_namespace(mut self, namespace: Option<String>) -> Self {
228        self.gate_explicit_namespace = namespace;
229        self
230    }
231
232    /// Correlates handler-internal Gate consultations with their dispatch audit.
233    pub(crate) fn request_id(&self) -> Option<u64> {
234        self.request_id
235    }
236
237    pub(crate) fn with_request_id(mut self, request_id: Option<u64>) -> Self {
238        self.request_id = request_id;
239        self
240    }
241
242    /// Return the read-visibility set.
243    ///
244    /// List, search, and get operations must accept records whose namespace is
245    /// a member of this set. The write namespace is always included.
246    pub fn visible_namespaces(&self) -> &[Namespace] {
247        &self.visible
248    }
249
250    /// Return a deduplicated list of visible namespace strings (borrowed).
251    ///
252    /// Convenience for passing directly to storage layer filters.
253    pub fn visible_namespace_strs(&self) -> Vec<&str> {
254        self.visible.iter().map(|ns| ns.as_str()).collect()
255    }
256
257    /// Return the actor reference embedded in this token.
258    pub fn actor(&self) -> &ActorRef {
259        &self.actor
260    }
261
262    /// Return the originating process's opaque attribution reference, when set.
263    ///
264    /// This is request metadata only. It never participates in gate checks,
265    /// namespace visibility, or actor identity.
266    pub fn process_ref(&self) -> Option<&str> {
267        self.process_ref.as_deref()
268    }
269
270    pub(crate) fn with_process_ref(mut self, process_ref: Option<String>) -> Self {
271        self.process_ref = process_ref;
272        self
273    }
274
275    /// Return a new token with the same actor but a different namespace.
276    /// The Gate namespace metadata is reset to the new primary namespace.
277    ///
278    /// The visible set is replaced with `[ns]`: this is a full read+write token
279    /// for `ns`, not a type-enforced write-only or append-only capability. It is
280    /// a capability-transfer primitive, not a policy gate: callers must enforce
281    /// any ACL check before calling this and use the minted token only within
282    /// the intended narrow scope (e.g. a single `create_note` call). A future
283    /// security model should replace this pattern with a type-enforced
284    /// append-only capability that goes through the Gate.
285    pub fn with_namespace(&self, ns: Namespace) -> Self {
286        Self::mint_authorized(ns, self.actor.clone()).with_process_ref(self.process_ref.clone())
287    }
288}
289
290/// Read the optional request-origin process reference without normalization.
291///
292/// A non-Unicode environment value cannot be represented in JSON and is
293/// treated as absent after emitting a warning that does not expose its bytes.
294pub fn process_ref_from_env() -> Option<String> {
295    match std::env::var("KHIVE_PROCESS_REF") {
296        Ok(value) => Some(value),
297        Err(std::env::VarError::NotPresent) => None,
298        Err(std::env::VarError::NotUnicode(_)) => {
299            tracing::warn!(
300                "KHIVE_PROCESS_REF is not valid Unicode and cannot be represented in request metadata"
301            );
302            None
303        }
304    }
305}
306
307// ---- RuntimeConfig ----
308
309/// Runtime configuration.
310///
311/// The `db_path` field remains for backward compatibility and as input to the
312/// supported async khive-mcp/kkernel host builders. Direct backend assembly is
313/// reserved for an already-coordinated database; use
314/// [`crate::KhiveRuntime::from_prepared_backend`] when that precondition has
315/// been established. `engines` is the ordered peer configuration; absent peers
316/// retain the legacy programmatic model shorthand until startup preparation.
317#[derive(Clone, Debug)]
318pub struct RuntimeConfig {
319    /// Maximum simultaneous background warm jobs in the host's shared domain.
320    /// Must be positive and fit Tokio's semaphore capacity.
321    pub warm_concurrency: usize,
322    /// Maximum simultaneous background maintenance jobs; interactive is unbounded.
323    pub maintenance_concurrency: usize,
324    /// Named custody references; secret material stays inside credential providers.
325    pub credentials: Vec<crate::credentials::CredentialConfig>,
326    /// Configured receipt key ring. Absence never generates a replacement key.
327    pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
328
329    pub mounts: Vec<crate::mount_config::MountConfig>,
330
331    /// Path to the SQLite database file. `None` = in-memory (tests).
332    ///
333    /// Production boot passes this value to the async khive-mcp/kkernel host
334    /// builders, which coordinate V21 before constructing runtimes. Tests and
335    /// already-current single-backend callers may still use it directly.
336    pub db_path: Option<std::path::PathBuf>,
337    /// Canonicalization boundary for registered code-map database files.
338    pub code_map_root: Option<String>,
339    /// Operator-declared code maps loaded into the runtime registry at construction.
340    pub code_maps: Vec<crate::engine_config::CodeMapConfig>,
341    /// Declared SQLite backend paths protected from code-map registration.
342    pub code_map_protected_database_paths: Vec<std::path::PathBuf>,
343    /// The WAL ceiling applied to this runtime's implicit main backend.
344    /// Zero means disabled, including for a read-only backend that retains a
345    /// nonzero configured value only for operator reporting.
346    pub wal_ceiling_bytes: u64,
347    /// The configured value before read-only writer-policy suppression.
348    pub wal_ceiling_configured_bytes: u64,
349    /// Where the configured ceiling came from.
350    pub wal_ceiling_source: WalCeilingSource,
351    /// Construction-time snapshot of the environment fallback. The host uses
352    /// this same value to resolve every named backend before forwarding or
353    /// opening it, without rereading mutable process environment.
354    pub wal_ceiling_env_raw: Option<String>,
355    /// One snapshot for named backend resolution and daemon compatibility.
356    pub disk_guard_environment: khive_db::DiskGuardEnvironment,
357    /// Captured implicit-main policy, or an explicit caller-supplied policy.
358    pub disk_guard_config: Option<khive_db::EffectiveDiskGuardConfig>,
359    /// Directory for the SQLite volume lock files, captured with the rest of
360    /// boot configuration from [`crate::daemon::volume_lock_dir`]. `None` means
361    /// no directory could be resolved; every writable file-backed open then
362    /// fails with a configuration error naming `KHIVE_VOLUME_LOCK_DIR`.
363    pub volume_lock_dir: Option<std::path::PathBuf>,
364    /// Namespace used when no explicit namespace is provided.
365    pub default_namespace: Namespace,
366    /// Ordered participating engines. `Some`, including an empty list, is
367    /// authoritative; `None` converts the legacy model fields at startup.
368    pub engines: Option<Vec<crate::engine_config::EngineConfig>>,
369    /// Legacy local embedding model, used when `engines` is absent and otherwise
370    /// projected from its first peer at startup. `None` alone does not disable embedding: setting
371    /// only this field to `None` while `additional_embedding_models` is
372    /// non-empty still registers those models. Both `embedding_model` and
373    /// `additional_embedding_models` must be empty to disable built-in
374    /// embedding model registration, at which point `hybrid_search` falls back
375    /// to text-only. Use [`RuntimeConfig::no_embeddings`] to clear both fields
376    /// together — it is the canonical constructor for this. Custom embedder
377    /// providers registered later by packs are not affected by this field.
378    ///
379    /// Deprecated: embedding engines move to a per-pack `EmbedderRegistry`.
380    /// This field persists for backward compatibility until the embedder registry
381    /// is fully plumbed.
382    pub embedding_model: Option<EmbeddingModel>,
383    /// Legacy additional embedding models, used when `engines` is absent and
384    /// otherwise projected from its remaining peers at startup.
385    ///
386    /// `embedding_model` remains the default used by existing `embed()` and
387    /// `embed_batch()` callers. This list adds non-default models that can be
388    /// selected with `embedder(name)`, `embed_with_model(...)`, memory
389    /// `remember.embedding_model`, and memory `recall.embedding_model`.
390    pub additional_embedding_models: Vec<EmbeddingModel>,
391    /// Authorization gate consulted before each verb dispatch.
392    /// Default: `AllowAllGate` (permissive). For production policy enforcement,
393    /// plug in a Rego- or capability-witness-backed impl.
394    pub gate: GateRef,
395    /// Names of packs the transport layer should register into the VerbRegistry.
396    /// The transport layer (e.g. `khive-mcp`) reads this list and instantiates
397    /// the matching concrete pack types. Unknown names are reported as errors
398    /// by the transport, not silently ignored.
399    /// Defaults to the shipped production set returned by
400    /// [`RuntimeConfig::built_in_packs`].
401    pub packs: Vec<String>,
402    /// Resolved aggregate admission budget for resident digest-verified blob
403    /// buffers (ADR-160 D3), in raw bytes.
404    ///
405    /// `[runtime].blob_hydration_bytes` may raise or lower the built-in 256 MiB
406    /// value, but config validation guarantees enough room for one maximum-size
407    /// whole-blob read.
408    pub blob_hydration_bytes: u64,
409    /// Identifies this runtime's backend in a multi-backend deployment.
410    ///
411    /// Set by the boot path when constructing per-pack runtimes from `khive.toml`.
412    /// Single-backend deployments use the default `BackendId::MAIN`.
413    pub backend_id: BackendId,
414    /// Brain profile to use for `memory.feedback` / `knowledge.feedback` and
415    /// recall-time score boosting (ADR-035 §Brain profile configuration).
416    ///
417    /// Resolution order (highest to lowest, ADR-035): CLI flag, then
418    /// `runtime.brain_profile` in project/global `khive.toml`, then the
419    /// `KHIVE_BRAIN_PROFILE` env var as fallback default. Callers must keep
420    /// env OUT of the base config they pass in (see `khive-mcp` serve.rs).
421    /// 1. `--brain-profile` CLI flag (explicit only)
422    /// 2. Namespace-bound profile resolved via `brain.resolve` at feedback time
423    /// 3. Pack-local global tuning prior (default fallback)
424    pub brain_profile: Option<String>,
425    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
426    ///
427    /// OSS dispatch widens the DEFAULT multi-record read scope to
428    /// `['local'] ∪ visible_namespaces`. Writes remain pinned to `'local'`.
429    /// An explicit `namespace=` request param is a precise single-namespace
430    /// escape and is not widened. Populated from `actor.visible_namespaces`
431    /// in `khive.toml`.
432    pub visible_namespaces: Vec<Namespace>,
433    /// Namespaces this actor's comm.send/reply may deliver messages INTO
434    /// (outbound, sender-side). Populated from `actor.allowed_outbound_namespaces`
435    /// in `khive.toml`. Empty by default — cross-namespace delivery denied
436    /// unless explicitly declared. The comm handler uses an ordinary
437    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
438    /// the token itself is NOT type-enforced write-only. The recipient-side
439    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
440    /// a future cloud-path authorization ADR (not yet written).
441    pub allowed_outbound_namespaces: Vec<Namespace>,
442    /// Configured actor identity label (ADR-057). Populated from `[actor] id` in
443    /// `khive.toml`. When `Some`, `authorize()` mints tokens carrying this actor
444    /// label so that `comm.inbox` filters by `to_actor` instead of falling back to
445    /// the party-line "local" behavior. When `None` (default), tokens carry
446    /// `ActorRef::anonymous()` and inbox is scoped to party-line messages —
447    /// those addressed to `"local"` or carrying no `to_actor` stamp.
448    pub actor_id: Option<String>,
449    /// Resolved `[brain]` policy from the serving process's configuration.
450    pub brain: crate::engine_config::BrainSectionConfig,
451    /// Resolved `[git_write]` policy allowlist (ADR-108 Amendment), populated
452    /// from `khive.toml`'s `[[git_write.allowed]]` entries by
453    /// [`runtime_config_from_khive_config`]. Threaded through so
454    /// `khive-pack-git`'s write-verb handlers read an already-resolved policy
455    /// instead of re-running config discovery (which would ignore an
456    /// explicit `--config` path not also exported as `KHIVE_CONFIG`).
457    pub git_write: crate::engine_config::GitWriteSectionConfig,
458    /// Effective `[blob]` file-transfer opt-in, resolved with the exact environment
459    /// opt-in during construction and retained by the blob pack.
460    pub blob: crate::engine_config::BlobSectionConfig,
461    /// Resolved `[exec]` sandbox section (ADR-181), threaded through like
462    /// `git_write` so the exec pack reads an already-resolved config.
463    pub exec: crate::engine_config::ExecSectionConfig,
464    /// Resolved carrier and failure policy for telemetry emission.
465    pub telemetry: crate::telemetry_config::TelemetryConfig,
466    /// Resolved rendering timezone (ADR-169), consumed today by date-only
467    /// `parse_due` anchoring. Populated from `[display] timezone` in
468    /// `khive.toml` by [`runtime_config_from_khive_config`]; when absent,
469    /// resolves once to the host's local IANA zone (falling back to UTC when
470    /// the host zone cannot be determined) via [`resolve_default_display_timezone`].
471    pub display_timezone: chrono_tz::Tz,
472    /// Events-daemon split (ADR-170). `None` = legacy behavior: events persist
473    /// in the main store. `Some` routes event persistence to the events database —
474    /// forwarded over the events daemon socket in daemon deployments, opened
475    /// directly in embedded/one-shot contexts. Populated by the transport
476    /// hosts (khive-mcp serve, kkernel exec); tests and in-memory runtimes
477    /// leave it `None`.
478    pub events_split: Option<crate::events_split::EventsSplitConfig>,
479    /// Resolved `[web]` policy (ADR-175 Amendment 1), threaded through like
480    /// `exec`/`git_write` so `khive-pack-web` reads an already-resolved config.
481    pub web: crate::engine_config::WebSectionConfig,
482}
483
484/// Parse a comma- or whitespace-separated pack list from a single string.
485///
486/// Empty entries are dropped, surrounding whitespace is trimmed.
487pub fn parse_pack_list(s: &str) -> Vec<String> {
488    s.split(|c: char| c == ',' || c.is_whitespace())
489        .map(str::trim)
490        .filter(|s| !s.is_empty())
491        .map(str::to_owned)
492        .collect()
493}
494
495const ANN_REBUILD_THRESHOLD_DEFAULT: f64 = 0.20;
496
497/// Read the ANN tail-rebuild fraction on each invocation (ADR-079 Amendment 2).
498///
499/// ADR-079's `ann_rebuild_threshold` default rationale describes the raw-row
500/// policy, its workload assumptions and its coupled maintenance/visibility roles.
501///
502/// The exact environment value must parse as `f64` and lie in `(0, 1]`;
503/// unset, non-Unicode, malformed and out-of-range values use `0.20`.
504/// This reader deliberately does not trim or cache the value.
505pub fn ann_rebuild_threshold_from_env() -> f64 {
506    let value = khive_types::env::env_parse_or(
507        "KHIVE_ANN_REBUILD_THRESHOLD",
508        ANN_REBUILD_THRESHOLD_DEFAULT,
509    );
510    if value > 0.0 && value <= 1.0 {
511        value
512    } else {
513        ANN_REBUILD_THRESHOLD_DEFAULT
514    }
515}
516
517#[cfg(test)]
518#[path = "config/ann_rebuild_threshold_tests.rs"]
519mod ann_rebuild_threshold_tests;
520
521/// Interpret the construction-time `KHIVE_ANN_FRESH_TAIL` value.
522///
523/// Preserve the escape hatch's existing semantics while moving its read out of
524/// request serving: only `0` disables; unset and every other value enable.
525fn ann_fresh_tail_enabled_from_value(value: Option<&str>) -> bool {
526    value != Some("0")
527}
528
529/// Sample ADR-118's fresh-tail escape hatch for runtime construction.
530///
531/// Callers must retain the returned value for the runtime's lifetime instead
532/// of re-reading the environment on a serving path. Only the exact value `0`
533/// disables; unset and every other value enable.
534pub fn ann_fresh_tail_enabled_from_env() -> bool {
535    let value = std::env::var("KHIVE_ANN_FRESH_TAIL").ok();
536    ann_fresh_tail_enabled_from_value(value.as_deref())
537}
538
539/// Resolve the host's local IANA zone name once, for [`RuntimeConfig`]'s
540/// default `display_timezone` (ADR-169). Falls back to UTC when the host
541/// zone cannot be determined (e.g. `TZ`/`/etc/localtime` unreadable) or does
542/// not parse as a known `chrono_tz::Tz` — this must never panic or block
543/// construction of a default `RuntimeConfig`.
544pub fn resolve_default_display_timezone() -> chrono_tz::Tz {
545    iana_time_zone::get_timezone()
546        .ok()
547        .and_then(|name| name.parse::<chrono_tz::Tz>().ok())
548        .unwrap_or(chrono_tz::Tz::UTC)
549}
550
551impl Default for RuntimeConfig {
552    fn default() -> Self {
553        let db_path = std::env::var("HOME")
554            .ok()
555            .map(|h| std::path::PathBuf::from(h).join(".khive/khive.db"));
556        let embedding_model = Some(khive_types::env::env_parse_or(
557            "KHIVE_EMBEDDING_MODEL",
558            EmbeddingModel::AllMiniLmL6V2,
559        ));
560        // Ships single-engine. A second engine is embedded on every write and
561        // searched on every read, which is cost a deployment should opt into
562        // rather than inherit: set KHIVE_ADDITIONAL_EMBEDDING_MODELS to add one.
563        let additional_embedding_models = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
564            .ok()
565            .map(|s| parse_embedding_model_list(&s))
566            .unwrap_or_default();
567        let packs = std::env::var("KHIVE_PACKS")
568            .ok()
569            .map(|s| parse_pack_list(&s))
570            .filter(|v| !v.is_empty())
571            .unwrap_or_else(Self::built_in_packs);
572        let brain_profile = std::env::var("KHIVE_BRAIN_PROFILE")
573            .ok()
574            .filter(|s| !s.trim().is_empty());
575        let actor_id = std::env::var("KHIVE_ACTOR")
576            .ok()
577            .filter(|s| !s.trim().is_empty());
578        Self {
579            warm_concurrency: DEFAULT_WARM_CONCURRENCY,
580            maintenance_concurrency: DEFAULT_MAINTENANCE_CONCURRENCY,
581            credentials: Vec::new(),
582            visibility_receipts: None,
583            db_path,
584            code_map_root: None,
585            code_maps: Vec::new(),
586            code_map_protected_database_paths: Vec::new(),
587            wal_ceiling_bytes: 0,
588            wal_ceiling_configured_bytes: 0,
589            wal_ceiling_source: WalCeilingSource::Default,
590            wal_ceiling_env_raw: std::env::var_os("KHIVE_SQLITE_WAL_CEILING_BYTES")
591                .map(|value| value.to_string_lossy().into_owned()),
592            disk_guard_environment: khive_db::DiskGuardEnvironment::capture(),
593            disk_guard_config: None,
594            volume_lock_dir: crate::daemon::volume_lock_dir().ok(),
595            default_namespace: Namespace::local(),
596            engines: None,
597            embedding_model,
598            additional_embedding_models,
599            gate: Arc::new(AllowAllGate),
600            packs,
601            blob_hydration_bytes: crate::blob::DEFAULT_BLOB_HYDRATION_BYTES,
602            backend_id: BackendId::main(),
603            brain_profile,
604            visible_namespaces: vec![],
605            allowed_outbound_namespaces: vec![],
606            actor_id,
607            brain: crate::engine_config::BrainSectionConfig::default(),
608            git_write: crate::engine_config::GitWriteSectionConfig::default(),
609            blob: crate::engine_config::BlobSectionConfig {
610                file_transfers: std::env::var("KHIVE_FILE_TRANSFERS")
611                    .map(|value| value == "1")
612                    .unwrap_or(false),
613            },
614            exec: crate::engine_config::ExecSectionConfig::default(),
615            telemetry: crate::telemetry_config::TelemetryConfig::default(),
616            mounts: Vec::new(),
617            display_timezone: resolve_default_display_timezone(),
618            events_split: None,
619            web: crate::engine_config::WebSectionConfig::default(),
620        }
621    }
622}
623
624impl RuntimeConfig {
625    /// Effective ordered peers with canonical built-in names, without binding
626    /// providers or mutating the configuration. Startup must still validate them.
627    pub fn configured_engines(&self) -> Vec<crate::engine_config::EngineConfig> {
628        match &self.engines {
629            Some(engines) => engines
630                .iter()
631                .cloned()
632                .map(|mut engine| {
633                    engine.name = crate::engine_config::canonical_engine_name(&engine.name);
634                    engine
635                })
636                .collect(),
637            None => configured_embedding_models(self)
638                .into_iter()
639                .map(|model| crate::engine_config::EngineConfig {
640                    name: model.to_string(),
641                    weight: 1.0,
642                    dims: None,
643                })
644                .collect(),
645        }
646    }
647
648    /// Validate and canonicalize ordered peers without resolving providers.
649    ///
650    /// Legacy programmatic model fields remain accepted when `engines` is
651    /// absent. Once prepared, those fields are projections of the peer list.
652    /// Hosts finalize provider binding after registering their custom providers.
653    pub fn prepare_engines(&mut self) -> RuntimeResult<()> {
654        let mut engines = self.configured_engines();
655        crate::engine_config::validate_peer_engines(self.engines.as_deref().unwrap_or(&engines))
656            .map_err(|error| crate::RuntimeError::InvalidInput(error.to_string()))?;
657
658        for engine in &mut engines {
659            engine.name = crate::engine_config::canonical_engine_name(&engine.name);
660        }
661        self.embedding_model = engines
662            .first()
663            .and_then(|engine| parse_embedding_model_alias(&engine.name));
664        self.additional_embedding_models = engines
665            .iter()
666            .skip(1)
667            .filter_map(|engine| parse_embedding_model_alias(&engine.name))
668            .collect();
669        self.engines = Some(engines);
670        Ok(())
671    }
672
673    /// Disable configured vector participation, including legacy model seeds.
674    pub fn disable_embedding_models(&mut self) {
675        self.engines = Some(Vec::new());
676        self.embedding_model = None;
677        self.additional_embedding_models.clear();
678    }
679
680    /// The WAL ceiling policy this config asks its implicit main backend to
681    /// open with. Preserves a configured ceiling for read-only reporting while
682    /// ensuring a directly constructed config cannot silently drop a nonzero
683    /// effective value: when the configured value is zero, the effective
684    /// `wal_ceiling_bytes` is used. Host openers validate the captured
685    /// environment through [`Self::resolve_wal_ceiling_policy`] first.
686    pub fn wal_ceiling_policy(&self) -> khive_db::WalCeilingPolicy {
687        khive_db::WalCeilingPolicy {
688            bytes: if self.wal_ceiling_configured_bytes == 0 {
689                self.wal_ceiling_bytes
690            } else {
691                self.wal_ceiling_configured_bytes
692            },
693            source: self.wal_ceiling_source,
694        }
695    }
696
697    /// Resolve the implicit backend against the config's captured environment,
698    /// retaining configured bytes separately from a read-only writer policy.
699    pub fn resolve_wal_ceiling_policy(
700        &mut self,
701        read_only: bool,
702    ) -> RuntimeResult<khive_db::WalCeilingPolicy> {
703        let policy = self.wal_ceiling_policy();
704        let backend_field = match self.wal_ceiling_source {
705            WalCeilingSource::BackendField => Some(policy.bytes),
706            WalCeilingSource::Environment if self.wal_ceiling_env_raw.is_some() => None,
707            _ if policy.bytes != 0 => Some(policy.bytes),
708            _ => None,
709        };
710        let kind = if self.db_path.is_some() {
711            crate::BackendKind::Sqlite
712        } else {
713            crate::BackendKind::Memory
714        };
715        let resolved = crate::resolve_wal_ceiling(
716            backend_field,
717            self.wal_ceiling_env_raw.as_deref(),
718            self.backend_id.as_str(),
719            kind,
720            true,
721            read_only,
722        )
723        .map_err(|error| khive_db::SqliteError::InvalidConfig(error.to_string()))?;
724        self.wal_ceiling_configured_bytes = resolved.configured_bytes;
725        self.wal_ceiling_bytes = resolved.effective_bytes;
726        self.wal_ceiling_source = resolved.source;
727        Ok(self.wal_ceiling_policy())
728    }
729
730    /// Resolve the implicit backend's disk reserve and guard deadline from the
731    /// config's captured environment, unless a caller already supplied a policy.
732    /// Read-only and in-memory backends have no writer to guard.
733    pub fn resolve_disk_guard_policy(
734        &mut self,
735        read_only: bool,
736    ) -> RuntimeResult<Option<khive_db::EffectiveDiskGuardConfig>> {
737        if self.db_path.is_none() {
738            if self
739                .disk_guard_config
740                .is_some_and(|policy| policy.reserve_bytes != 0)
741            {
742                return Err(khive_db::SqliteError::InvalidConfig(
743                    "nonzero disk_reserve_bytes requires a file-backed SQLite backend".into(),
744                )
745                .into());
746            }
747            return Ok(None);
748        }
749        if read_only {
750            return Ok(None);
751        }
752        let policy = match self.disk_guard_config {
753            Some(policy) => {
754                policy.validate()?;
755                policy
756            }
757            None => self.disk_guard_environment.resolve(None, None)?,
758        };
759        self.disk_guard_config = Some(policy);
760        Ok(Some(policy))
761    }
762
763    /// Pack-registry discovery has no file-backed writer to govern.
764    pub fn for_metadata_registry(mut self) -> Self {
765        self.db_path = None;
766        self.wal_ceiling_bytes = 0;
767        self.wal_ceiling_configured_bytes = 0;
768        self.wal_ceiling_source = WalCeilingSource::BackendField;
769        self.disk_guard_config = None;
770        self.disable_embedding_models();
771        self
772    }
773
774    /// Return the shipped pack set used when no CLI, environment, or
775    /// configuration-file selection is present.
776    pub fn built_in_packs() -> Vec<String> {
777        [
778            "kg",
779            "gtd",
780            "memory",
781            "brain",
782            "comm",
783            "schedule",
784            "knowledge",
785            "session",
786            "tool",
787            "exec",
788            "git",
789            "code",
790            "workspace",
791            "blob",
792        ]
793        .into_iter()
794        .map(String::from)
795        .collect()
796    }
797
798    /// Build a `RuntimeConfig` with embedding disabled entirely.
799    ///
800    /// `embedding_model` and `additional_embedding_models` are computed
801    /// independently inside [`Default::default`], so `RuntimeConfig {
802    /// embedding_model: None, ..RuntimeConfig::default() }` does NOT produce a
803    /// model-less runtime: `additional_embedding_models` still carries its
804    /// env-driven fallback seed, and the note-write path fans out embedding to
805    /// every registered model regardless of `embedding_model`: so the first
806    /// `memory.remember` on a machine without local model files hard-fails
807    /// instead of degrading to FTS-only.
808    ///
809    /// This constructor clears both fields together and ignores
810    /// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` unconditionally: the caller wants
811    /// zero embedders, not "zero unless the environment disagrees". Use it on
812    /// model-less machines (CI runners, fresh installs without local model
813    /// files) instead of the two-field struct-update form.
814    pub fn no_embeddings() -> Self {
815        Self {
816            embedding_model: None,
817            additional_embedding_models: Vec::new(),
818            ..Self::default()
819        }
820    }
821}
822
823/// Expand a leading `~` to `$HOME` in a path.
824///
825/// This is the single shared expansion point for every `RuntimeConfig.db_path`
826/// construction site (CLI `--db`, `KHIVE_DB`, declared `[[backends]].path`).
827/// [`resolve_db_anchor`] calls it so a `~`-prefixed override is expanded once,
828/// at resolution, before the path ever reaches boot (single- or multi-backend),
829/// `compute_config_id` fingerprinting, or the `--db` override equivalence
830/// guard — those consumers then agree on one expanded path instead of a raw
831/// `~` diverging from its already-expanded equivalent.
832pub fn expand_tilde(path: &std::path::Path) -> std::path::PathBuf {
833    let s = path.to_string_lossy();
834    if let Some(rest) = s.strip_prefix("~/") {
835        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
836        std::path::PathBuf::from(format!("{home}/{rest}"))
837    } else if s == "~" {
838        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
839        std::path::PathBuf::from(home)
840    } else {
841        path.to_path_buf()
842    }
843}
844
845/// Resolve the `--db`/`KHIVE_DB` value into the anchor path used for tier-3
846/// project-local `.khive/config.toml` discovery, mirroring the precedence
847/// `kkernel mcp` and `kkernel exec` use to open the database itself:
848/// `:memory:` has no file to anchor on (`None`); an explicit path anchors on
849/// that path (with a leading `~` expanded via [`expand_tilde`]); an unset
850/// value falls back to `$HOME/.khive/khive.db`, or `./.khive/khive.db` when
851/// `HOME` is unset.
852///
853/// Always resolves to a concrete anchor (unlike a 2-arm "override the
854/// default?" resolver): when `HOME` is unset this falls back to
855/// `./.khive/khive.db` rather than `None`, deliberately diverging from
856/// `RuntimeConfig::default()`: a caller anchoring config discovery needs a
857/// concrete directory to search even without `HOME`.
858pub fn resolve_db_anchor(db: Option<&str>) -> Option<std::path::PathBuf> {
859    match db {
860        Some(":memory:") => None,
861        Some(path) => Some(expand_tilde(std::path::Path::new(path))),
862        None => {
863            let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
864            Some(std::path::PathBuf::from(format!("{home}/.khive/khive.db")))
865        }
866    }
867}
868
869/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
870/// process's `config_id`: agrees with what [`resolve_db_anchor`] derives from
871/// the same raw `--db`/`KHIVE_DB` input.
872///
873/// This compatibility entry point preserves the raw-string API. Construction
874/// paths that already captured the anchor should call
875/// [`assert_captured_db_anchor_consistent`] so they do not re-read mutable
876/// process environment.
877pub fn assert_db_anchor_consistent(
878    resolved_db_path: Option<&std::path::Path>,
879    args_db: Option<&str>,
880) -> anyhow::Result<()> {
881    let db_anchor = resolve_db_anchor(args_db);
882    assert_captured_db_anchor_consistent(resolved_db_path, db_anchor.as_deref())
883}
884
885/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
886/// process's `config_id`: agrees with the database anchor captured from the
887/// same `--db`/`KHIVE_DB` input at the construction boundary.
888///
889/// Guards against a construction path recomputing `db_path` independently of
890/// `resolve_db_anchor`: left unchecked, that would silently desync `config_id`
891/// from a daemon or peer sharing the same database instead of failing loud.
892/// The caller passes the captured anchor so validation never re-reads mutable
893/// process environment. Inert (`Ok(())`) when the anchor itself is `None` (the
894/// `:memory:` sentinel) since there is nothing to compare against.
895pub fn assert_captured_db_anchor_consistent(
896    resolved_db_path: Option<&std::path::Path>,
897    db_anchor: Option<&std::path::Path>,
898) -> anyhow::Result<()> {
899    let Some(anchor) = db_anchor else {
900        return Ok(());
901    };
902    if resolved_db_path != Some(anchor) {
903        anyhow::bail!(
904            "db-path resolution drift at server construction: resolved db_path {:?} \
905             does not match the canonical anchor {:?} computed by resolve_db_anchor \
906             from the same --db input; this construction path likely recomputed the \
907             db path independently instead of routing through the shared resolver, \
908             which would desynchronize config_id from other processes sharing the \
909             same database",
910            resolved_db_path,
911            anchor
912        );
913    }
914    Ok(())
915}
916
917/// Resolve the per-connection attribution actor from the project/cwd-anchored
918/// config tier, independently of the database-anchored config load that
919/// governs `config_id`.
920///
921/// The database-anchored config load keeps `config_id` coherent between a
922/// short-lived client and a long-running daemon sharing one database, but
923/// when many per-project connections share one database under a single
924/// `HOME` (the daemon-multiplexed fleet case), that shared config carries no
925/// `[actor]` block, so every connection's write-stamp attribution collapses
926/// to the default identity.
927///
928/// This performs a separate, cwd-anchored lookup (`db_path: None`) and reads
929/// only `[actor].id`: it must not perturb `config_id` or `default_namespace`,
930/// which remain governed exclusively by the database-anchored load.
931///
932/// `config_path` is the same explicit `--config`/`KHIVE_CONFIG` override the
933/// caller's database-anchored load receives, so an explicit override wins
934/// here too.
935///
936/// Returns `Ok(None)` when no project-anchored config exists, or it exists
937/// but carries no non-empty `[actor].id`: callers fall through to their own
938/// env/anonymous tiers in that case. A `config_path` naming a file that does
939/// not exist is a loud error (`ExplicitConfigMissing`), matching the
940/// database-anchored load's explicit-tier contract (ADR-035) — in production
941/// that load errors first, so this lookup only ever sees an existing file.
942pub fn resolve_project_actor_id(
943    config_path: Option<&std::path::Path>,
944) -> Result<Option<String>, crate::engine_config::ConfigError> {
945    let khive_cfg = crate::engine_config::KhiveConfig::load_with_home_fallback(config_path, None)?;
946    Ok(khive_cfg
947        .and_then(|cfg| cfg.actor.id)
948        .filter(|s| !s.trim().is_empty()))
949}
950
951// ---- Embedding model helpers ----
952
953/// Sanitize an embedding model name into a valid SQL table suffix.
954/// e.g. `bge-small-en-v1.5` -> `bge_small_en_v1_5`
955#[cfg(test)]
956pub(crate) fn vec_model_key(model: EmbeddingModel) -> String {
957    sanitize_key(&model.to_string())
958}
959
960/// Preserve ASCII letters and digits; replace every other Unicode character with `_`.
961/// Used for model-name table suffixes; this mapping does not preserve uniqueness.
962#[doc(hidden)]
963pub fn sanitize_key(s: &str) -> String {
964    s.chars()
965        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
966        .collect()
967}
968
969pub(crate) fn build_embedder_registry(
970    config: &RuntimeConfig,
971) -> (crate::embedder_registry::EmbedderRegistry, Arc<str>) {
972    use crate::embedder_registry::{EmbedderRegistry, LatticeEmbedderProvider};
973    let mut registry = EmbedderRegistry::new();
974    for model in configured_embedding_models(config) {
975        registry.register_builtin(LatticeEmbedderProvider::new(model));
976    }
977    let default_embedder_name = config
978        .configured_engines()
979        .first()
980        .map(|engine| Arc::<str>::from(engine.name.as_str()))
981        .unwrap_or_else(|| Arc::<str>::from(""));
982    (registry, default_embedder_name)
983}
984
985fn configured_embedding_models(config: &RuntimeConfig) -> Vec<EmbeddingModel> {
986    if let Some(engines) = &config.engines {
987        return engines
988            .iter()
989            .filter_map(|engine| parse_embedding_model_alias(&engine.name))
990            .collect();
991    }
992    let mut models: Vec<EmbeddingModel> = Vec::new();
993    if let Some(model) = config.embedding_model {
994        models.push(model);
995    }
996    for model in config.additional_embedding_models.iter().copied() {
997        if !models.contains(&model) {
998            models.push(model);
999        }
1000    }
1001    models
1002}
1003
1004pub(crate) fn register_configured_embedding_models(
1005    backend: &StorageBackend,
1006    config: &RuntimeConfig,
1007) -> RuntimeResult<()> {
1008    for model in configured_embedding_models(config) {
1009        backend.register_embedding_model(
1010            &model.to_string(),
1011            model.model_id(),
1012            model.key_version(),
1013            model.dimensions() as u32,
1014        )?;
1015    }
1016    Ok(())
1017}
1018
1019/// Build a `RuntimeConfig` from a parsed `KhiveConfig`.
1020///
1021/// Declared engines preserve their order and dimension assertions. The first
1022/// peer is projected into the legacy single-model field when it is built-in;
1023/// hosts bind the complete list after provider registration, before serving.
1024/// An explicit empty list disables participation; an absent list preserves
1025/// the caller's base configuration, including environment-derived defaults.
1026/// Load file input with [`crate::KhiveConfig::load`] to preserve that distinction
1027/// and convert legacy declarations before calling this function.
1028///
1029/// When both a config file and `KHIVE_EMBEDDING_MODEL` env var are present,
1030/// the caller is responsible for emitting a warning that env vars are overridden.
1031/// This function purely converts `KhiveConfig` to `RuntimeConfig` fields.
1032pub fn runtime_config_from_khive_config(
1033    khive_cfg: &crate::engine_config::KhiveConfig,
1034    base: RuntimeConfig,
1035) -> RuntimeConfig {
1036    // `[actor] id` never becomes the storage namespace (writes always pin to
1037    // `local`); it only widens the read visible-set below.
1038    let default_namespace = base.default_namespace.clone();
1039    let mounts = khive_cfg.mounts.clone();
1040    let credentials = khive_cfg.credentials.clone();
1041    let visibility_receipts = khive_cfg.visibility_receipts.clone();
1042    let code_map_root = khive_cfg.code_map_root.clone();
1043    let code_maps = khive_cfg.code_maps.clone();
1044    let code_map_protected_database_paths = khive_cfg
1045        .backends
1046        .iter()
1047        .filter(|backend| backend.kind == crate::engine_config::BackendKind::Sqlite)
1048        .filter_map(|backend| {
1049            backend
1050                .path
1051                .as_deref()
1052                .map(|path| expand_tilde(std::path::Path::new(path)))
1053        })
1054        .collect();
1055
1056    // base.brain_profile must carry only the explicit CLI tier, never an env
1057    // value: env sits below toml in precedence and is applied later by the MCP resolver.
1058    let brain_profile = base.brain_profile.clone().or_else(|| {
1059        khive_cfg
1060            .runtime
1061            .brain_profile
1062            .clone()
1063            .filter(|s| !s.trim().is_empty())
1064    });
1065
1066    let visible_namespaces: Vec<Namespace> = khive_cfg
1067        .actor
1068        .visible_namespaces
1069        .as_deref()
1070        .unwrap_or_default()
1071        .iter()
1072        .filter_map(|s| match Namespace::parse(s) {
1073            Ok(ns) => Some(ns),
1074            Err(e) => {
1075                tracing::warn!(ns = %s, error = %e, "actor.visible_namespaces: invalid namespace; skipped");
1076                None
1077            }
1078        })
1079        .collect();
1080
1081    // Fold actor.id's namespace into visible_namespaces so default reads widen
1082    // to {local} ∪ {actor namespace}; skipped when it parses to `local` (would
1083    // duplicate the primary namespace already minted) or is already present.
1084    let visible_namespaces = if let Some(id) = khive_cfg.actor.id.as_deref() {
1085        match Namespace::parse(id) {
1086            Ok(actor_ns) if actor_ns != Namespace::local() => {
1087                let mut v = visible_namespaces;
1088                if !v.contains(&actor_ns) {
1089                    v.push(actor_ns);
1090                }
1091                v
1092            }
1093            _ => visible_namespaces,
1094        }
1095    } else {
1096        visible_namespaces
1097    };
1098
1099    // KhiveConfig::validate() guarantees these are valid Namespace strings, so
1100    // parse failures here are unreachable for validated configs; filter_map+warn
1101    // guards against a validation bug panicking instead.
1102    let allowed_outbound_namespaces: Vec<Namespace> = khive_cfg
1103        .actor
1104        .allowed_outbound_namespaces
1105        .iter()
1106        .filter_map(|s| match Namespace::parse(s) {
1107            Ok(ns) => Some(ns),
1108            Err(e) => {
1109                tracing::warn!(ns = %s, error = %e, "actor.allowed_outbound_namespaces: invalid namespace; skipped");
1110                None
1111            }
1112        })
1113        .collect();
1114
1115    // Precedence: TOML `[actor] id` > `base.actor_id` (env/CLI-resolved) >
1116    // anonymous. Falls back to `base.actor_id` rather than `None` when
1117    // `[actor] id` is absent: otherwise an env-resolved actor like
1118    // `KHIVE_ACTOR` is silently dropped whenever a project config exists
1119    // without an `[actor]` block.
1120    let actor_id = khive_cfg
1121        .actor
1122        .id
1123        .clone()
1124        .filter(|s| !s.trim().is_empty())
1125        .or_else(|| base.actor_id.clone());
1126
1127    let gate = khive_cfg
1128        .gate
1129        .as_ref()
1130        .map(|gate| {
1131            Arc::new(khive_gate::CallerEnrollmentGate::with_write_denials(
1132                gate.granted_actors.clone(),
1133                gate.grant_unattributed,
1134                gate.deny_writes_for.clone(),
1135            )) as GateRef
1136        })
1137        .unwrap_or_else(|| base.gate.clone());
1138    let gate = crate::mailbox_view::configured_mailbox_gate(&khive_cfg.actor, gate);
1139
1140    let brain = khive_cfg.brain.clone();
1141    let git_write = khive_cfg.git_write.clone();
1142    let blob = crate::engine_config::BlobSectionConfig {
1143        file_transfers: khive_cfg.blob.file_transfers || base.blob.file_transfers,
1144    };
1145    let exec = khive_cfg.exec.clone();
1146    let telemetry = khive_cfg.telemetry.clone();
1147    let web = khive_cfg.web.clone();
1148    let warm_concurrency = khive_cfg
1149        .runtime
1150        .warm_concurrency
1151        .unwrap_or(base.warm_concurrency);
1152    let maintenance_concurrency = khive_cfg
1153        .runtime
1154        .maintenance_concurrency
1155        .unwrap_or(base.maintenance_concurrency);
1156    let blob_hydration_bytes = khive_cfg
1157        .runtime
1158        .blob_hydration_bytes
1159        .unwrap_or(base.blob_hydration_bytes);
1160
1161    // KhiveConfig::validate() guarantees a present timezone parses as a valid
1162    // chrono_tz::Tz, so the fallback to base.display_timezone below is only
1163    // reachable for an unvalidated caller-constructed KhiveConfig, not a
1164    // config loaded via KhiveConfig::load.
1165    let display_timezone = khive_cfg
1166        .display
1167        .timezone
1168        .as_deref()
1169        .and_then(|s| s.parse::<chrono_tz::Tz>().ok())
1170        .unwrap_or(base.display_timezone);
1171
1172    if khive_cfg.engines.is_empty() && !khive_cfg.engines_declared {
1173        return RuntimeConfig {
1174            credentials,
1175            visibility_receipts,
1176            default_namespace,
1177            brain_profile,
1178            visible_namespaces,
1179            allowed_outbound_namespaces,
1180            actor_id,
1181            gate,
1182            brain,
1183            git_write,
1184            blob,
1185            exec,
1186            telemetry,
1187            mounts,
1188            code_map_root,
1189            code_maps,
1190            code_map_protected_database_paths,
1191            warm_concurrency,
1192            maintenance_concurrency,
1193            blob_hydration_bytes,
1194            display_timezone,
1195            web,
1196            ..base
1197        };
1198    }
1199
1200    let engines = khive_cfg.engines.clone();
1201    let embedding_model = engines
1202        .first()
1203        .and_then(|engine| parse_embedding_model_alias(&engine.name));
1204    let additional = engines
1205        .iter()
1206        .skip(1)
1207        .filter_map(|engine| parse_embedding_model_alias(&engine.name))
1208        .collect();
1209
1210    RuntimeConfig {
1211        credentials,
1212        visibility_receipts,
1213        engines: Some(engines),
1214        embedding_model,
1215        additional_embedding_models: additional,
1216        default_namespace,
1217        brain_profile,
1218        visible_namespaces,
1219        allowed_outbound_namespaces,
1220        actor_id,
1221        gate,
1222        brain,
1223        git_write,
1224        blob,
1225        exec,
1226        telemetry,
1227        mounts,
1228        code_map_root,
1229        code_maps,
1230        code_map_protected_database_paths,
1231        warm_concurrency,
1232        maintenance_concurrency,
1233        blob_hydration_bytes,
1234        display_timezone,
1235        web,
1236        ..base
1237    }
1238}
1239
1240#[cfg(test)]
1241mod display_timezone_tests {
1242    use super::resolve_default_display_timezone;
1243
1244    // The host's actual zone is environment-dependent (CI runners are
1245    // typically UTC), so this only asserts the resolver always produces some
1246    // valid, non-panicking Tz — never that it matches a specific zone.
1247    #[test]
1248    fn resolve_default_display_timezone_never_panics() {
1249        let _tz = resolve_default_display_timezone();
1250    }
1251}
1252
1253/// Parse a comma- or whitespace-separated list of embedding model names.
1254fn parse_embedding_model_list(s: &str) -> Vec<EmbeddingModel> {
1255    parse_pack_list(s)
1256        .into_iter()
1257        .filter_map(|raw| {
1258            let parsed = parse_embedding_model_alias(&raw);
1259            if parsed.is_none() && !raw.trim().is_empty() {
1260                tracing::warn!(
1261                    model = %raw,
1262                    "KHIVE_ADDITIONAL_EMBEDDING_MODELS contains unknown model name; ignored. \
1263                     Valid forms: short alias like 'paraphrase' or a fully-qualified key \
1264                     from lattice_embed::EmbeddingModel::from_str."
1265                );
1266            }
1267            parsed
1268        })
1269        .collect()
1270}
1271
1272pub(crate) fn parse_embedding_model_alias(name: &str) -> Option<EmbeddingModel> {
1273    let normalized = name.trim().to_ascii_lowercase().replace('_', "-");
1274    match normalized.as_str() {
1275        "paraphrase" => Some(EmbeddingModel::ParaphraseMultilingualMiniLmL12V2),
1276        _ => normalized.parse().ok(),
1277    }
1278}
1279
1280#[cfg(test)]
1281mod resolve_db_anchor_tests {
1282    use super::resolve_db_anchor;
1283
1284    #[test]
1285    fn memory_sentinel_maps_to_none() {
1286        assert_eq!(resolve_db_anchor(Some(":memory:")), None);
1287    }
1288
1289    #[test]
1290    fn explicit_path_maps_to_some() {
1291        assert_eq!(
1292            resolve_db_anchor(Some("/tmp/khive-anchor-test.db")),
1293            Some(std::path::PathBuf::from("/tmp/khive-anchor-test.db"))
1294        );
1295    }
1296
1297    #[test]
1298    fn absent_maps_to_home_default() {
1299        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
1300        let expected = std::path::PathBuf::from(format!("{home}/.khive/khive.db"));
1301        assert_eq!(resolve_db_anchor(None), Some(expected));
1302    }
1303}
1304
1305#[cfg(test)]
1306mod assert_db_anchor_consistent_tests {
1307    use super::{assert_captured_db_anchor_consistent, resolve_db_anchor};
1308    use crate::assert_db_anchor_consistent;
1309
1310    #[test]
1311    fn diverging_db_path_is_rejected_naming_both_paths() {
1312        let args_db = "/tmp/khive-anchor-guard-real.db";
1313        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1314        let wrong = std::path::PathBuf::from("/tmp/khive-anchor-guard-wrong.db");
1315
1316        let err =
1317            assert_captured_db_anchor_consistent(Some(wrong.as_path()), Some(anchor.as_path()))
1318                .expect_err("a resolved db_path diverging from the anchor must be rejected");
1319
1320        let msg = err.to_string();
1321        assert!(
1322            msg.contains(&wrong.display().to_string()),
1323            "error must name the resolved (wrong) path: {msg}"
1324        );
1325        assert!(
1326            msg.contains(&anchor.display().to_string()),
1327            "error must name the canonical anchor path: {msg}"
1328        );
1329    }
1330
1331    #[test]
1332    fn matching_explicit_db_path_passes() {
1333        let args_db = "/tmp/khive-anchor-guard-consistent.db";
1334        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1335        assert!(assert_captured_db_anchor_consistent(
1336            Some(anchor.as_path()),
1337            Some(anchor.as_path())
1338        )
1339        .is_ok());
1340    }
1341
1342    #[test]
1343    fn memory_sentinel_anchor_is_inert() {
1344        // `resolve_db_anchor(":memory:")` yields `None` — there is no canonical
1345        // path to assert against, so the guard passes regardless of what
1346        // `resolved_db_path` happens to carry.
1347        let bogus = std::path::PathBuf::from("/tmp/should-not-matter.db");
1348        assert!(assert_captured_db_anchor_consistent(Some(bogus.as_path()), None).is_ok());
1349        assert!(assert_captured_db_anchor_consistent(None, None).is_ok());
1350    }
1351
1352    #[test]
1353    fn normal_boot_with_db_unset_passes_silently() {
1354        // Mirrors a normal boot with `--db` unset: `resolve_db_anchor(None)`
1355        // always resolves to `Some(..)` (HOME-set or -unset both produce a
1356        // concrete anchor), so a runtime whose resolved `db_path` matches
1357        // passes silently.
1358        let anchor = resolve_db_anchor(None);
1359        assert!(assert_captured_db_anchor_consistent(anchor.as_deref(), anchor.as_deref()).is_ok());
1360    }
1361
1362    #[test]
1363    fn public_compatibility_wrapper_accepts_path_and_memory_sentinel() {
1364        let args_db = "/tmp/khive-anchor-guard-public-api.db";
1365        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1366        assert!(assert_db_anchor_consistent(Some(anchor.as_path()), Some(args_db)).is_ok());
1367
1368        let unrelated = std::path::Path::new("/tmp/khive-anchor-guard-unrelated.db");
1369        assert!(assert_db_anchor_consistent(Some(unrelated), Some(":memory:")).is_ok());
1370    }
1371}
1372
1373#[cfg(test)]
1374mod resolve_project_actor_id_tests {
1375    use super::resolve_project_actor_id;
1376
1377    fn write_toml(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
1378        let path = dir.path().join("config.toml");
1379        std::fs::write(&path, body).expect("write config.toml");
1380        path
1381    }
1382
1383    #[test]
1384    fn extracts_non_empty_actor_id_from_explicit_path() {
1385        let dir = tempfile::tempdir().expect("tempdir");
1386        let path = write_toml(&dir, "[actor]\nid = \"lambda:explicit-actor\"\n");
1387
1388        assert_eq!(
1389            resolve_project_actor_id(Some(&path)).expect("no error"),
1390            Some("lambda:explicit-actor".to_string())
1391        );
1392    }
1393
1394    #[test]
1395    fn missing_explicit_path_fails_loud() {
1396        // The explicit tier is enforced inside the loader
1397        // (`KhiveConfig::load_with_home_fallback_and_source` returns
1398        // `ExplicitConfigMissing`): a nonexistent explicit path is an error,
1399        // never a silent `None` (ADR-035).
1400        let missing = std::path::PathBuf::from("/nonexistent/khive-project-actor-test/config.toml");
1401        let err = resolve_project_actor_id(Some(&missing))
1402            .expect_err("a missing explicit path must fail loud");
1403        assert!(
1404            matches!(
1405                err,
1406                crate::engine_config::ConfigError::ExplicitConfigMissing { .. }
1407            ),
1408            "expected ExplicitConfigMissing, got {err:?}"
1409        );
1410    }
1411
1412    #[test]
1413    fn propagates_load_error_for_invalid_actor_id() {
1414        // `KhiveConfig::load`'s `validate()` rejects an empty `[actor] id` before
1415        // the emptiness filter in `resolve_project_actor_id` ever sees it; this
1416        // asserts the error surfaces rather than being swallowed into `Ok(None)`.
1417        let dir = tempfile::tempdir().expect("tempdir");
1418        let path = write_toml(&dir, "[actor]\nid = \"\"\n");
1419
1420        let err = resolve_project_actor_id(Some(&path)).expect_err("invalid actor.id must error");
1421        let root = match &err {
1422            crate::engine_config::ConfigError::InFile { source, .. } => source.as_ref(),
1423            other => other,
1424        };
1425        assert!(
1426            matches!(
1427                root,
1428                crate::engine_config::ConfigError::InvalidActorId { .. }
1429            ),
1430            "expected InvalidActorId, got {err:?}"
1431        );
1432    }
1433
1434    #[test]
1435    fn returns_none_when_config_has_no_actor_section() {
1436        let dir = tempfile::tempdir().expect("tempdir");
1437        let path = write_toml(
1438            &dir,
1439            "[[engines]]\nname = \"primary\"\nmodel = \"bge-small-en-v1.5\"\ndefault = true\n",
1440        );
1441
1442        assert_eq!(
1443            resolve_project_actor_id(Some(&path)).expect("no error"),
1444            None,
1445            "a config file with no [actor] section must resolve to None"
1446        );
1447    }
1448}
1449
1450#[cfg(test)]
1451mod no_embeddings_tests {
1452    use super::*;
1453    use serial_test::serial;
1454
1455    #[test]
1456    fn default_embedding_model_environment_keeps_typed_fallbacks() {
1457        if crate::test_process::run_in_child() {
1458            return;
1459        }
1460        const PRIMARY: &str = "KHIVE_EMBEDDING_MODEL";
1461        const ADDITIONAL: &str = "KHIVE_ADDITIONAL_EMBEDDING_MODELS";
1462        assert_eq!(
1463            RuntimeConfig::default().embedding_model,
1464            Some(EmbeddingModel::AllMiniLmL6V2)
1465        );
1466        std::env::set_var(ADDITIONAL, "paraphrase-multilingual-minilm-l12-v2");
1467        for (value, expected) in [
1468            ("invalid", EmbeddingModel::AllMiniLmL6V2),
1469            ("", EmbeddingModel::AllMiniLmL6V2),
1470            ("bge-small-en-v1.5", EmbeddingModel::BgeSmallEnV15),
1471            (" BAAI/BGE_SMALL_EN_V1.5 ", EmbeddingModel::BgeSmallEnV15),
1472            ("all-minilm", EmbeddingModel::AllMiniLmL6V2),
1473        ] {
1474            std::env::set_var(PRIMARY, value);
1475            let config = RuntimeConfig::default();
1476            assert_eq!(config.embedding_model, Some(expected), "{value:?}");
1477            assert_eq!(
1478                config.additional_embedding_models,
1479                vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1480            );
1481        }
1482        #[cfg(unix)]
1483        {
1484            use std::os::unix::ffi::OsStrExt;
1485            std::env::set_var(PRIMARY, std::ffi::OsStr::from_bytes(b"\xff"));
1486            assert_eq!(
1487                RuntimeConfig::default().embedding_model,
1488                Some(EmbeddingModel::AllMiniLmL6V2)
1489            );
1490        }
1491        std::env::remove_var(PRIMARY);
1492        let config = RuntimeConfig::default();
1493        assert_eq!(config.embedding_model, Some(EmbeddingModel::AllMiniLmL6V2));
1494        assert_eq!(
1495            config.additional_embedding_models,
1496            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1497        );
1498        std::env::remove_var(ADDITIONAL);
1499    }
1500
1501    #[test]
1502    fn no_embeddings_clears_both_fields() {
1503        let config = RuntimeConfig::no_embeddings();
1504        assert_eq!(config.embedding_model, None);
1505        assert!(config.additional_embedding_models.is_empty());
1506        assert!(
1507            configured_embedding_models(&config).is_empty(),
1508            "no_embeddings() must yield zero configured embedders"
1509        );
1510    }
1511
1512    #[test]
1513    fn blob_hydration_default_is_four_portable_whole_objects() {
1514        assert_eq!(
1515            RuntimeConfig::default().blob_hydration_bytes,
1516            4 * khive_storage::MAX_BLOB_WHOLE_BYTES
1517        );
1518    }
1519
1520    #[test]
1521    #[serial]
1522    fn no_embeddings_ignores_additional_env_override() {
1523        // no_embeddings() is an unconditional opt-out: even if the caller's
1524        // environment sets KHIVE_ADDITIONAL_EMBEDDING_MODELS, the resulting
1525        // config must still report zero embedders.
1526        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1527        let config = RuntimeConfig::no_embeddings();
1528        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1529
1530        assert!(config.additional_embedding_models.is_empty());
1531        assert!(configured_embedding_models(&config).is_empty());
1532    }
1533
1534    #[test]
1535    #[serial]
1536    fn default_computes_additional_models_independently_of_no_embeddings() {
1537        // `Default` must keep computing `embedding_model` and
1538        // `additional_embedding_models` independently; `no_embeddings()` is a
1539        // separate opt-out constructor, not a change to `Default`'s seeding.
1540        // The env var is SET here rather than cleared: since Default now ships
1541        // no secondary engine, an unset env would make Default and
1542        // no_embeddings() indistinguishable and the test would stop
1543        // discriminating the thing it exists to discriminate.
1544        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1545        let config = RuntimeConfig::default();
1546        let buggy_form = RuntimeConfig {
1547            embedding_model: None,
1548            ..RuntimeConfig::default()
1549        };
1550        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1551
1552        assert_eq!(
1553            config.additional_embedding_models,
1554            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1555        );
1556
1557        // Overriding only `embedding_model` via struct-update syntax does not
1558        // clear `additional_embedding_models`.
1559        assert!(
1560            !buggy_form.additional_embedding_models.is_empty(),
1561            "Default's independent-field seeding must remain unchanged; \
1562             no_embeddings() is the fix, not a change to Default"
1563        );
1564    }
1565
1566    #[test]
1567    #[serial]
1568    fn default_ships_a_single_engine_when_env_unset() {
1569        // A secondary engine is embedded on every write and searched on every
1570        // read. That cost is opted into, not inherited.
1571        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1572        let config = RuntimeConfig::default();
1573
1574        assert!(
1575            config.additional_embedding_models.is_empty(),
1576            "shipped default must register one engine; a second is opt-in via \
1577             KHIVE_ADDITIONAL_EMBEDDING_MODELS"
1578        );
1579        assert_eq!(
1580            configured_embedding_models(&config),
1581            vec![EmbeddingModel::AllMiniLmL6V2]
1582        );
1583    }
1584}
1585
1586#[cfg(test)]
1587mod ann_fresh_tail_config_tests {
1588    use super::ann_fresh_tail_enabled_from_value;
1589
1590    #[test]
1591    fn only_exact_zero_disables_fresh_tail() {
1592        assert!(ann_fresh_tail_enabled_from_value(None));
1593        assert!(!ann_fresh_tail_enabled_from_value(Some("0")));
1594        assert!(ann_fresh_tail_enabled_from_value(Some("1")));
1595        assert!(ann_fresh_tail_enabled_from_value(Some("false")));
1596        assert!(ann_fresh_tail_enabled_from_value(Some(" 0")));
1597    }
1598}
1599
1600#[cfg(test)]
1601mod configured_embedding_models_order_tests {
1602    use super::*;
1603
1604    /// Issue #1115: the configured engine list must preserve declaration
1605    /// order (primary first, then `additional_embedding_models` in order)
1606    /// instead of alphabetizing — any consumer that treats the list as
1607    /// ordered (e.g. recall fan-out) otherwise gets the wrong primary.
1608    #[test]
1609    fn preserves_primary_first_then_additional_in_declared_order() {
1610        let config = RuntimeConfig {
1611            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1612            additional_embedding_models: vec![
1613                EmbeddingModel::Qwen3Embedding4B,
1614                EmbeddingModel::BgeSmallEnV15,
1615            ],
1616            ..RuntimeConfig::default()
1617        };
1618
1619        assert_eq!(
1620            configured_embedding_models(&config),
1621            vec![
1622                EmbeddingModel::AllMiniLmL6V2,
1623                EmbeddingModel::Qwen3Embedding4B,
1624                EmbeddingModel::BgeSmallEnV15,
1625            ],
1626            "order must be primary-first, then additional models as declared, \
1627             not alphabetized"
1628        );
1629    }
1630
1631    /// A model repeated in both `embedding_model` and `additional_embedding_models`
1632    /// must be deduped to a single entry, keeping its first (primary) position.
1633    #[test]
1634    fn dedupes_model_shared_between_primary_and_additional() {
1635        let config = RuntimeConfig {
1636            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1637            additional_embedding_models: vec![
1638                EmbeddingModel::AllMiniLmL6V2,
1639                EmbeddingModel::BgeSmallEnV15,
1640            ],
1641            ..RuntimeConfig::default()
1642        };
1643
1644        assert_eq!(
1645            configured_embedding_models(&config),
1646            vec![EmbeddingModel::AllMiniLmL6V2, EmbeddingModel::BgeSmallEnV15],
1647            "the shared model must appear once, in its primary position"
1648        );
1649    }
1650}
1651
1652/// Policy from the 2026-10-20 00:00Z through 2026-10-27 04:40Z event window:
1653/// completed warm spans peaked at one with no observed overlap. Configured
1654/// knowledge warm was unobserved. This is a conservative policy, not capacity.
1655pub(crate) const DEFAULT_WARM_CONCURRENCY: usize = 1;
1656
1657/// Maintenance policy uses the same 2026-10-20 00:00Z through 2026-10-27 04:40Z
1658/// observation: warm peak one, no overlaps, configured knowledge warm absent.
1659/// Checkpoint work has warm attribution; other WAL/Vamana work was uninstrumented.
1660pub(crate) const DEFAULT_MAINTENANCE_CONCURRENCY: usize = 1;