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. `embedding_model` remains as the primary-model config
316/// shorthand beside the provider registry.
317#[derive(Clone, Debug)]
318pub struct RuntimeConfig {
319    /// Named custody references; secret material stays inside credential providers.
320    pub credentials: Vec<crate::credentials::CredentialConfig>,
321    /// Configured receipt key ring. Absence never generates a replacement key.
322    pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
323
324    pub mounts: Vec<crate::mount_config::MountConfig>,
325
326    /// Path to the SQLite database file. `None` = in-memory (tests).
327    ///
328    /// Production boot passes this value to the async khive-mcp/kkernel host
329    /// builders, which coordinate V21 before constructing runtimes. Tests and
330    /// already-current single-backend callers may still use it directly.
331    pub db_path: Option<std::path::PathBuf>,
332    /// The WAL ceiling applied to this runtime's implicit main backend.
333    /// Zero means disabled, including for a read-only backend that retains a
334    /// nonzero configured value only for operator reporting.
335    pub wal_ceiling_bytes: u64,
336    /// The configured value before read-only writer-policy suppression.
337    pub wal_ceiling_configured_bytes: u64,
338    /// Where the configured ceiling came from.
339    pub wal_ceiling_source: WalCeilingSource,
340    /// Construction-time snapshot of the environment fallback. The host uses
341    /// this same value to resolve every named backend before forwarding or
342    /// opening it, without rereading mutable process environment.
343    pub wal_ceiling_env_raw: Option<String>,
344    /// One snapshot for named backend resolution and daemon compatibility.
345    pub disk_guard_environment: khive_db::DiskGuardEnvironment,
346    /// Captured implicit-main policy, or an explicit caller-supplied policy.
347    pub disk_guard_config: Option<khive_db::EffectiveDiskGuardConfig>,
348    /// Directory for the SQLite volume lock files, captured with the rest of
349    /// boot configuration from [`crate::daemon::volume_lock_dir`]. `None` means
350    /// no directory could be resolved; every writable file-backed open then
351    /// fails with a configuration error naming `KHIVE_VOLUME_LOCK_DIR`.
352    pub volume_lock_dir: Option<std::path::PathBuf>,
353    /// Namespace used when no explicit namespace is provided.
354    pub default_namespace: Namespace,
355    /// Local embedding model. `None` alone does not disable embedding: setting
356    /// only this field to `None` while `additional_embedding_models` is
357    /// non-empty still registers those models. Both `embedding_model` and
358    /// `additional_embedding_models` must be empty to disable built-in
359    /// embedding model registration, at which point `hybrid_search` falls back
360    /// to text-only. Use [`RuntimeConfig::no_embeddings`] to clear both fields
361    /// together — it is the canonical constructor for this. Custom embedder
362    /// providers registered later by packs are not affected by this field.
363    ///
364    /// Deprecated: embedding engines move to a per-pack `EmbedderRegistry`.
365    /// This field persists for backward compatibility until the embedder registry
366    /// is fully plumbed.
367    pub embedding_model: Option<EmbeddingModel>,
368    /// Additional embedding models to make available by request name.
369    ///
370    /// `embedding_model` remains the default used by existing `embed()` and
371    /// `embed_batch()` callers. This list adds non-default models that can be
372    /// selected with `embedder(name)`, `embed_with_model(...)`, memory
373    /// `remember.embedding_model`, and memory `recall.embedding_model`.
374    pub additional_embedding_models: Vec<EmbeddingModel>,
375    /// Authorization gate consulted before each verb dispatch.
376    /// Default: `AllowAllGate` (permissive). For production policy enforcement,
377    /// plug in a Rego- or capability-witness-backed impl.
378    pub gate: GateRef,
379    /// Names of packs the transport layer should register into the VerbRegistry.
380    /// The transport layer (e.g. `khive-mcp`) reads this list and instantiates
381    /// the matching concrete pack types. Unknown names are reported as errors
382    /// by the transport, not silently ignored.
383    /// Defaults to the shipped production set returned by
384    /// [`RuntimeConfig::built_in_packs`].
385    pub packs: Vec<String>,
386    /// Resolved aggregate admission budget for resident digest-verified blob
387    /// buffers (ADR-160 D3), in raw bytes.
388    ///
389    /// `[runtime].blob_hydration_bytes` may raise or lower the built-in 256 MiB
390    /// value, but config validation guarantees enough room for one maximum-size
391    /// whole-blob read.
392    pub blob_hydration_bytes: u64,
393    /// Identifies this runtime's backend in a multi-backend deployment.
394    ///
395    /// Set by the boot path when constructing per-pack runtimes from `khive.toml`.
396    /// Single-backend deployments use the default `BackendId::MAIN`.
397    pub backend_id: BackendId,
398    /// Brain profile to use for `memory.feedback` / `knowledge.feedback` and
399    /// recall-time score boosting (ADR-035 §Brain profile configuration).
400    ///
401    /// Resolution order (highest to lowest, ADR-035): CLI flag, then
402    /// `runtime.brain_profile` in project/global `khive.toml`, then the
403    /// `KHIVE_BRAIN_PROFILE` env var as fallback default. Callers must keep
404    /// env OUT of the base config they pass in (see `khive-mcp` serve.rs).
405    /// 1. `--brain-profile` CLI flag (explicit only)
406    /// 2. Namespace-bound profile resolved via `brain.resolve` at feedback time
407    /// 3. Pack-local global tuning prior (default fallback)
408    pub brain_profile: Option<String>,
409    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
410    ///
411    /// OSS dispatch widens the DEFAULT multi-record read scope to
412    /// `['local'] ∪ visible_namespaces`. Writes remain pinned to `'local'`.
413    /// An explicit `namespace=` request param is a precise single-namespace
414    /// escape and is not widened. Populated from `actor.visible_namespaces`
415    /// in `khive.toml`.
416    pub visible_namespaces: Vec<Namespace>,
417    /// Namespaces this actor's comm.send/reply may deliver messages INTO
418    /// (outbound, sender-side). Populated from `actor.allowed_outbound_namespaces`
419    /// in `khive.toml`. Empty by default — cross-namespace delivery denied
420    /// unless explicitly declared. The comm handler uses an ordinary
421    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
422    /// the token itself is NOT type-enforced write-only. The recipient-side
423    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
424    /// a future cloud-path authorization ADR (not yet written).
425    pub allowed_outbound_namespaces: Vec<Namespace>,
426    /// Configured actor identity label (ADR-057). Populated from `[actor] id` in
427    /// `khive.toml`. When `Some`, `authorize()` mints tokens carrying this actor
428    /// label so that `comm.inbox` filters by `to_actor` instead of falling back to
429    /// the party-line "local" behavior. When `None` (default), tokens carry
430    /// `ActorRef::anonymous()` and inbox is scoped to party-line messages —
431    /// those addressed to `"local"` or carrying no `to_actor` stamp.
432    pub actor_id: Option<String>,
433    /// Resolved `[brain]` policy from the serving process's configuration.
434    pub brain: crate::engine_config::BrainSectionConfig,
435    /// Resolved `[git_write]` policy allowlist (ADR-108 Amendment), populated
436    /// from `khive.toml`'s `[[git_write.allowed]]` entries by
437    /// [`runtime_config_from_khive_config`]. Threaded through so
438    /// `khive-pack-git`'s write-verb handlers read an already-resolved policy
439    /// instead of re-running config discovery (which would ignore an
440    /// explicit `--config` path not also exported as `KHIVE_CONFIG`).
441    pub git_write: crate::engine_config::GitWriteSectionConfig,
442    /// Effective `[blob]` file-transfer opt-in, resolved with the exact environment
443    /// opt-in during construction and retained by the blob pack.
444    pub blob: crate::engine_config::BlobSectionConfig,
445    /// Resolved `[exec]` sandbox section (ADR-181), threaded through like
446    /// `git_write` so the exec pack reads an already-resolved config.
447    pub exec: crate::engine_config::ExecSectionConfig,
448    /// Resolved carrier and failure policy for telemetry emission.
449    pub telemetry: crate::telemetry_config::TelemetryConfig,
450    /// Resolved rendering timezone (ADR-169), consumed today by date-only
451    /// `parse_due` anchoring. Populated from `[display] timezone` in
452    /// `khive.toml` by [`runtime_config_from_khive_config`]; when absent,
453    /// resolves once to the host's local IANA zone (falling back to UTC when
454    /// the host zone cannot be determined) via [`resolve_default_display_timezone`].
455    pub display_timezone: chrono_tz::Tz,
456    /// Events-daemon split (ADR-170). `None` = legacy behavior: events persist
457    /// in the main store. `Some` routes event persistence to the events database —
458    /// forwarded over the events daemon socket in daemon deployments, opened
459    /// directly in embedded/one-shot contexts. Populated by the transport
460    /// hosts (khive-mcp serve, kkernel exec); tests and in-memory runtimes
461    /// leave it `None`.
462    pub events_split: Option<crate::events_split::EventsSplitConfig>,
463    /// Resolved `[web]` policy (ADR-175 Amendment 1), threaded through like
464    /// `exec`/`git_write` so `khive-pack-web` reads an already-resolved config.
465    pub web: crate::engine_config::WebSectionConfig,
466}
467
468/// Parse a comma- or whitespace-separated pack list from a single string.
469///
470/// Empty entries are dropped, surrounding whitespace is trimmed.
471pub fn parse_pack_list(s: &str) -> Vec<String> {
472    s.split(|c: char| c == ',' || c.is_whitespace())
473        .map(str::trim)
474        .filter(|s| !s.is_empty())
475        .map(str::to_owned)
476        .collect()
477}
478
479const ANN_REBUILD_THRESHOLD_DEFAULT: f64 = 0.20;
480
481/// Read the ANN tail-rebuild fraction on each invocation (ADR-079 Amendment 2).
482///
483/// ADR-079's `ann_rebuild_threshold` default rationale describes the raw-row
484/// policy, its workload assumptions and its coupled maintenance/visibility roles.
485///
486/// The exact environment value must parse as `f64` and lie in `(0, 1]`;
487/// unset, non-Unicode, malformed and out-of-range values use `0.20`.
488/// This reader deliberately does not trim or cache the value.
489pub fn ann_rebuild_threshold_from_env() -> f64 {
490    std::env::var("KHIVE_ANN_REBUILD_THRESHOLD")
491        .ok()
492        .and_then(|v| v.parse::<f64>().ok())
493        .filter(|v| *v > 0.0 && *v <= 1.0)
494        .unwrap_or(ANN_REBUILD_THRESHOLD_DEFAULT)
495}
496
497#[cfg(test)]
498#[path = "config/ann_rebuild_threshold_tests.rs"]
499mod ann_rebuild_threshold_tests;
500
501/// Interpret the construction-time `KHIVE_ANN_FRESH_TAIL` value.
502///
503/// Preserve the escape hatch's existing semantics while moving its read out of
504/// request serving: only `0` disables; unset and every other value enable.
505fn ann_fresh_tail_enabled_from_value(value: Option<&str>) -> bool {
506    value != Some("0")
507}
508
509/// Sample ADR-118's fresh-tail escape hatch for runtime construction.
510///
511/// Callers must retain the returned value for the runtime's lifetime instead
512/// of re-reading the environment on a serving path. Only the exact value `0`
513/// disables; unset and every other value enable.
514pub fn ann_fresh_tail_enabled_from_env() -> bool {
515    let value = std::env::var("KHIVE_ANN_FRESH_TAIL").ok();
516    ann_fresh_tail_enabled_from_value(value.as_deref())
517}
518
519/// Resolve the host's local IANA zone name once, for [`RuntimeConfig`]'s
520/// default `display_timezone` (ADR-169). Falls back to UTC when the host
521/// zone cannot be determined (e.g. `TZ`/`/etc/localtime` unreadable) or does
522/// not parse as a known `chrono_tz::Tz` — this must never panic or block
523/// construction of a default `RuntimeConfig`.
524pub fn resolve_default_display_timezone() -> chrono_tz::Tz {
525    iana_time_zone::get_timezone()
526        .ok()
527        .and_then(|name| name.parse::<chrono_tz::Tz>().ok())
528        .unwrap_or(chrono_tz::Tz::UTC)
529}
530
531impl Default for RuntimeConfig {
532    fn default() -> Self {
533        let db_path = std::env::var("HOME")
534            .ok()
535            .map(|h| std::path::PathBuf::from(h).join(".khive/khive.db"));
536        let embedding_model = std::env::var("KHIVE_EMBEDDING_MODEL")
537            .ok()
538            .and_then(|s| s.parse().ok())
539            .or(Some(EmbeddingModel::AllMiniLmL6V2));
540        // Ships single-engine. A second engine is embedded on every write and
541        // searched on every read, which is cost a deployment should opt into
542        // rather than inherit: set KHIVE_ADDITIONAL_EMBEDDING_MODELS to add one.
543        let additional_embedding_models = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
544            .ok()
545            .map(|s| parse_embedding_model_list(&s))
546            .unwrap_or_default();
547        let packs = std::env::var("KHIVE_PACKS")
548            .ok()
549            .map(|s| parse_pack_list(&s))
550            .filter(|v| !v.is_empty())
551            .unwrap_or_else(Self::built_in_packs);
552        let brain_profile = std::env::var("KHIVE_BRAIN_PROFILE")
553            .ok()
554            .filter(|s| !s.trim().is_empty());
555        let actor_id = std::env::var("KHIVE_ACTOR")
556            .ok()
557            .filter(|s| !s.trim().is_empty());
558        Self {
559            credentials: Vec::new(),
560            visibility_receipts: None,
561            db_path,
562            wal_ceiling_bytes: 0,
563            wal_ceiling_configured_bytes: 0,
564            wal_ceiling_source: WalCeilingSource::Default,
565            wal_ceiling_env_raw: std::env::var_os("KHIVE_SQLITE_WAL_CEILING_BYTES")
566                .map(|value| value.to_string_lossy().into_owned()),
567            disk_guard_environment: khive_db::DiskGuardEnvironment::capture(),
568            disk_guard_config: None,
569            volume_lock_dir: crate::daemon::volume_lock_dir().ok(),
570            default_namespace: Namespace::local(),
571            embedding_model,
572            additional_embedding_models,
573            gate: Arc::new(AllowAllGate),
574            packs,
575            blob_hydration_bytes: crate::blob::DEFAULT_BLOB_HYDRATION_BYTES,
576            backend_id: BackendId::main(),
577            brain_profile,
578            visible_namespaces: vec![],
579            allowed_outbound_namespaces: vec![],
580            actor_id,
581            brain: crate::engine_config::BrainSectionConfig::default(),
582            git_write: crate::engine_config::GitWriteSectionConfig::default(),
583            blob: crate::engine_config::BlobSectionConfig {
584                file_transfers: std::env::var("KHIVE_FILE_TRANSFERS")
585                    .map(|value| value == "1")
586                    .unwrap_or(false),
587            },
588            exec: crate::engine_config::ExecSectionConfig::default(),
589            telemetry: crate::telemetry_config::TelemetryConfig::default(),
590            mounts: Vec::new(),
591            display_timezone: resolve_default_display_timezone(),
592            events_split: None,
593            web: crate::engine_config::WebSectionConfig::default(),
594        }
595    }
596}
597
598impl RuntimeConfig {
599    /// The WAL ceiling policy this config asks its implicit main backend to
600    /// open with. Preserves a configured ceiling for read-only reporting while
601    /// ensuring a directly constructed config cannot silently drop a nonzero
602    /// effective value: when the configured value is zero, the effective
603    /// `wal_ceiling_bytes` is used. Host openers validate the captured
604    /// environment through [`Self::resolve_wal_ceiling_policy`] first.
605    pub fn wal_ceiling_policy(&self) -> khive_db::WalCeilingPolicy {
606        khive_db::WalCeilingPolicy {
607            bytes: if self.wal_ceiling_configured_bytes == 0 {
608                self.wal_ceiling_bytes
609            } else {
610                self.wal_ceiling_configured_bytes
611            },
612            source: self.wal_ceiling_source,
613        }
614    }
615
616    /// Resolve the implicit backend against the config's captured environment,
617    /// retaining configured bytes separately from a read-only writer policy.
618    pub fn resolve_wal_ceiling_policy(
619        &mut self,
620        read_only: bool,
621    ) -> RuntimeResult<khive_db::WalCeilingPolicy> {
622        let policy = self.wal_ceiling_policy();
623        let backend_field = match self.wal_ceiling_source {
624            WalCeilingSource::BackendField => Some(policy.bytes),
625            WalCeilingSource::Environment if self.wal_ceiling_env_raw.is_some() => None,
626            _ if policy.bytes != 0 => Some(policy.bytes),
627            _ => None,
628        };
629        let kind = if self.db_path.is_some() {
630            crate::BackendKind::Sqlite
631        } else {
632            crate::BackendKind::Memory
633        };
634        let resolved = crate::resolve_wal_ceiling(
635            backend_field,
636            self.wal_ceiling_env_raw.as_deref(),
637            self.backend_id.as_str(),
638            kind,
639            true,
640            read_only,
641        )
642        .map_err(|error| khive_db::SqliteError::InvalidConfig(error.to_string()))?;
643        self.wal_ceiling_configured_bytes = resolved.configured_bytes;
644        self.wal_ceiling_bytes = resolved.effective_bytes;
645        self.wal_ceiling_source = resolved.source;
646        Ok(self.wal_ceiling_policy())
647    }
648
649    /// Resolve the implicit backend's disk reserve and guard deadline from the
650    /// config's captured environment, unless a caller already supplied a policy.
651    /// Read-only and in-memory backends have no writer to guard.
652    pub fn resolve_disk_guard_policy(
653        &mut self,
654        read_only: bool,
655    ) -> RuntimeResult<Option<khive_db::EffectiveDiskGuardConfig>> {
656        if self.db_path.is_none() {
657            if self
658                .disk_guard_config
659                .is_some_and(|policy| policy.reserve_bytes != 0)
660            {
661                return Err(khive_db::SqliteError::InvalidConfig(
662                    "nonzero disk_reserve_bytes requires a file-backed SQLite backend".into(),
663                )
664                .into());
665            }
666            return Ok(None);
667        }
668        if read_only {
669            return Ok(None);
670        }
671        let policy = match self.disk_guard_config {
672            Some(policy) => {
673                policy.validate()?;
674                policy
675            }
676            None => self.disk_guard_environment.resolve(None, None)?,
677        };
678        self.disk_guard_config = Some(policy);
679        Ok(Some(policy))
680    }
681
682    /// Pack-registry discovery has no file-backed writer to govern.
683    pub fn for_metadata_registry(mut self) -> Self {
684        self.db_path = None;
685        self.wal_ceiling_bytes = 0;
686        self.wal_ceiling_configured_bytes = 0;
687        self.wal_ceiling_source = WalCeilingSource::BackendField;
688        self.disk_guard_config = None;
689        self.embedding_model = None;
690        self.additional_embedding_models.clear();
691        self
692    }
693
694    /// Return the shipped pack set used when no CLI, environment, or
695    /// configuration-file selection is present.
696    pub fn built_in_packs() -> Vec<String> {
697        [
698            "kg",
699            "gtd",
700            "memory",
701            "brain",
702            "comm",
703            "schedule",
704            "knowledge",
705            "session",
706            "tool",
707            "exec",
708            "git",
709            "code",
710            "workspace",
711            "blob",
712        ]
713        .into_iter()
714        .map(String::from)
715        .collect()
716    }
717
718    /// Build a `RuntimeConfig` with embedding disabled entirely.
719    ///
720    /// `embedding_model` and `additional_embedding_models` are computed
721    /// independently inside [`Default::default`], so `RuntimeConfig {
722    /// embedding_model: None, ..RuntimeConfig::default() }` does NOT produce a
723    /// model-less runtime: `additional_embedding_models` still carries its
724    /// env-driven fallback seed, and the note-write path fans out embedding to
725    /// every registered model regardless of `embedding_model`: so the first
726    /// `memory.remember` on a machine without local model files hard-fails
727    /// instead of degrading to FTS-only.
728    ///
729    /// This constructor clears both fields together and ignores
730    /// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` unconditionally: the caller wants
731    /// zero embedders, not "zero unless the environment disagrees". Use it on
732    /// model-less machines (CI runners, fresh installs without local model
733    /// files) instead of the two-field struct-update form.
734    pub fn no_embeddings() -> Self {
735        Self {
736            embedding_model: None,
737            additional_embedding_models: Vec::new(),
738            ..Self::default()
739        }
740    }
741}
742
743/// Expand a leading `~` to `$HOME` in a path.
744///
745/// This is the single shared expansion point for every `RuntimeConfig.db_path`
746/// construction site (CLI `--db`, `KHIVE_DB`, declared `[[backends]].path`).
747/// [`resolve_db_anchor`] calls it so a `~`-prefixed override is expanded once,
748/// at resolution, before the path ever reaches boot (single- or multi-backend),
749/// `compute_config_id` fingerprinting, or the `--db` override equivalence
750/// guard — those consumers then agree on one expanded path instead of a raw
751/// `~` diverging from its already-expanded equivalent.
752pub fn expand_tilde(path: &std::path::Path) -> std::path::PathBuf {
753    let s = path.to_string_lossy();
754    if let Some(rest) = s.strip_prefix("~/") {
755        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
756        std::path::PathBuf::from(format!("{home}/{rest}"))
757    } else if s == "~" {
758        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
759        std::path::PathBuf::from(home)
760    } else {
761        path.to_path_buf()
762    }
763}
764
765/// Resolve the `--db`/`KHIVE_DB` value into the anchor path used for tier-3
766/// project-local `.khive/config.toml` discovery, mirroring the precedence
767/// `kkernel mcp` and `kkernel exec` use to open the database itself:
768/// `:memory:` has no file to anchor on (`None`); an explicit path anchors on
769/// that path (with a leading `~` expanded via [`expand_tilde`]); an unset
770/// value falls back to `$HOME/.khive/khive.db`, or `./.khive/khive.db` when
771/// `HOME` is unset.
772///
773/// Always resolves to a concrete anchor (unlike a 2-arm "override the
774/// default?" resolver): when `HOME` is unset this falls back to
775/// `./.khive/khive.db` rather than `None`, deliberately diverging from
776/// `RuntimeConfig::default()`: a caller anchoring config discovery needs a
777/// concrete directory to search even without `HOME`.
778pub fn resolve_db_anchor(db: Option<&str>) -> Option<std::path::PathBuf> {
779    match db {
780        Some(":memory:") => None,
781        Some(path) => Some(expand_tilde(std::path::Path::new(path))),
782        None => {
783            let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
784            Some(std::path::PathBuf::from(format!("{home}/.khive/khive.db")))
785        }
786    }
787}
788
789/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
790/// process's `config_id`: agrees with what [`resolve_db_anchor`] derives from
791/// the same raw `--db`/`KHIVE_DB` input.
792///
793/// This compatibility entry point preserves the raw-string API. Construction
794/// paths that already captured the anchor should call
795/// [`assert_captured_db_anchor_consistent`] so they do not re-read mutable
796/// process environment.
797pub fn assert_db_anchor_consistent(
798    resolved_db_path: Option<&std::path::Path>,
799    args_db: Option<&str>,
800) -> anyhow::Result<()> {
801    let db_anchor = resolve_db_anchor(args_db);
802    assert_captured_db_anchor_consistent(resolved_db_path, db_anchor.as_deref())
803}
804
805/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
806/// process's `config_id`: agrees with the database anchor captured from the
807/// same `--db`/`KHIVE_DB` input at the construction boundary.
808///
809/// Guards against a construction path recomputing `db_path` independently of
810/// `resolve_db_anchor`: left unchecked, that would silently desync `config_id`
811/// from a daemon or peer sharing the same database instead of failing loud.
812/// The caller passes the captured anchor so validation never re-reads mutable
813/// process environment. Inert (`Ok(())`) when the anchor itself is `None` (the
814/// `:memory:` sentinel) since there is nothing to compare against.
815pub fn assert_captured_db_anchor_consistent(
816    resolved_db_path: Option<&std::path::Path>,
817    db_anchor: Option<&std::path::Path>,
818) -> anyhow::Result<()> {
819    let Some(anchor) = db_anchor else {
820        return Ok(());
821    };
822    if resolved_db_path != Some(anchor) {
823        anyhow::bail!(
824            "db-path resolution drift at server construction: resolved db_path {:?} \
825             does not match the canonical anchor {:?} computed by resolve_db_anchor \
826             from the same --db input; this construction path likely recomputed the \
827             db path independently instead of routing through the shared resolver, \
828             which would desynchronize config_id from other processes sharing the \
829             same database",
830            resolved_db_path,
831            anchor
832        );
833    }
834    Ok(())
835}
836
837/// Resolve the per-connection attribution actor from the project/cwd-anchored
838/// config tier, independently of the database-anchored config load that
839/// governs `config_id`.
840///
841/// The database-anchored config load keeps `config_id` coherent between a
842/// short-lived client and a long-running daemon sharing one database, but
843/// when many per-project connections share one database under a single
844/// `HOME` (the daemon-multiplexed fleet case), that shared config carries no
845/// `[actor]` block, so every connection's write-stamp attribution collapses
846/// to the default identity.
847///
848/// This performs a separate, cwd-anchored lookup (`db_path: None`) and reads
849/// only `[actor].id`: it must not perturb `config_id` or `default_namespace`,
850/// which remain governed exclusively by the database-anchored load.
851///
852/// `config_path` is the same explicit `--config`/`KHIVE_CONFIG` override the
853/// caller's database-anchored load receives, so an explicit override wins
854/// here too.
855///
856/// Returns `Ok(None)` when no project-anchored config exists, or it exists
857/// but carries no non-empty `[actor].id`: callers fall through to their own
858/// env/anonymous tiers in that case. A `config_path` naming a file that does
859/// not exist is a loud error (`ExplicitConfigMissing`), matching the
860/// database-anchored load's explicit-tier contract (ADR-035) — in production
861/// that load errors first, so this lookup only ever sees an existing file.
862pub fn resolve_project_actor_id(
863    config_path: Option<&std::path::Path>,
864) -> Result<Option<String>, crate::engine_config::ConfigError> {
865    let khive_cfg = crate::engine_config::KhiveConfig::load_with_home_fallback(config_path, None)?;
866    Ok(khive_cfg
867        .and_then(|cfg| cfg.actor.id)
868        .filter(|s| !s.trim().is_empty()))
869}
870
871// ---- Embedding model helpers ----
872
873/// Sanitize an embedding model name into a valid SQL table suffix.
874/// e.g. `bge-small-en-v1.5` -> `bge_small_en_v1_5`
875pub(crate) fn vec_model_key(model: EmbeddingModel) -> String {
876    sanitize_key(&model.to_string())
877}
878
879pub(crate) fn sanitize_key(s: &str) -> String {
880    s.chars()
881        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
882        .collect()
883}
884
885pub(crate) fn build_embedder_registry(
886    config: &RuntimeConfig,
887) -> (crate::embedder_registry::EmbedderRegistry, Arc<str>) {
888    use crate::embedder_registry::{EmbedderRegistry, LatticeEmbedderProvider};
889    let mut registry = EmbedderRegistry::new();
890    for model in configured_embedding_models(config) {
891        registry.register_builtin(LatticeEmbedderProvider::new(model));
892    }
893    let default_embedder_name = config
894        .embedding_model
895        .map(|model| Arc::<str>::from(model.to_string()))
896        .unwrap_or_else(|| Arc::<str>::from(""));
897    (registry, default_embedder_name)
898}
899
900fn configured_embedding_models(config: &RuntimeConfig) -> Vec<EmbeddingModel> {
901    let mut models: Vec<EmbeddingModel> = Vec::new();
902    if let Some(model) = config.embedding_model {
903        models.push(model);
904    }
905    for model in config.additional_embedding_models.iter().copied() {
906        if !models.contains(&model) {
907            models.push(model);
908        }
909    }
910    models
911}
912
913pub(crate) fn register_configured_embedding_models(
914    backend: &StorageBackend,
915    config: &RuntimeConfig,
916) -> RuntimeResult<()> {
917    for model in configured_embedding_models(config) {
918        backend.register_embedding_model(
919            &model.to_string(),
920            model.model_id(),
921            model.key_version(),
922            model.dimensions() as u32,
923        )?;
924    }
925    Ok(())
926}
927
928/// Build a `RuntimeConfig` from a parsed `KhiveConfig`.
929///
930/// For each `[[engines]]` entry:
931/// - The engine flagged `default = true` becomes `RuntimeConfig::embedding_model`.
932/// - All other engines become `RuntimeConfig::additional_embedding_models`.
933///
934/// `KhiveConfig::validate()` rejects an unrecognized engine model at load time.
935/// A caller-constructed config that bypasses validation still skips an invalid
936/// engine with a warning here.
937///
938/// If `khive_cfg.engines` is empty, the returned `RuntimeConfig` uses the
939/// env-var-derived defaults from `RuntimeConfig::default()`.
940///
941/// When both a config file and `KHIVE_EMBEDDING_MODEL` env var are present,
942/// the caller is responsible for emitting a warning that env vars are overridden.
943/// This function purely converts `KhiveConfig` to `RuntimeConfig` fields.
944pub fn runtime_config_from_khive_config(
945    khive_cfg: &crate::engine_config::KhiveConfig,
946    base: RuntimeConfig,
947) -> RuntimeConfig {
948    // `[actor] id` never becomes the storage namespace (writes always pin to
949    // `local`); it only widens the read visible-set below.
950    let default_namespace = base.default_namespace.clone();
951    let mounts = khive_cfg.mounts.clone();
952    let credentials = khive_cfg.credentials.clone();
953    let visibility_receipts = khive_cfg.visibility_receipts.clone();
954
955    // base.brain_profile must carry only the explicit CLI tier, never an env
956    // value: env sits below toml in precedence and is applied later by the MCP resolver.
957    let brain_profile = base.brain_profile.clone().or_else(|| {
958        khive_cfg
959            .runtime
960            .brain_profile
961            .clone()
962            .filter(|s| !s.trim().is_empty())
963    });
964
965    let visible_namespaces: Vec<Namespace> = khive_cfg
966        .actor
967        .visible_namespaces
968        .as_deref()
969        .unwrap_or_default()
970        .iter()
971        .filter_map(|s| match Namespace::parse(s) {
972            Ok(ns) => Some(ns),
973            Err(e) => {
974                tracing::warn!(ns = %s, error = %e, "actor.visible_namespaces: invalid namespace; skipped");
975                None
976            }
977        })
978        .collect();
979
980    // Fold actor.id's namespace into visible_namespaces so default reads widen
981    // to {local} ∪ {actor namespace}; skipped when it parses to `local` (would
982    // duplicate the primary namespace already minted) or is already present.
983    let visible_namespaces = if let Some(id) = khive_cfg.actor.id.as_deref() {
984        match Namespace::parse(id) {
985            Ok(actor_ns) if actor_ns != Namespace::local() => {
986                let mut v = visible_namespaces;
987                if !v.contains(&actor_ns) {
988                    v.push(actor_ns);
989                }
990                v
991            }
992            _ => visible_namespaces,
993        }
994    } else {
995        visible_namespaces
996    };
997
998    // KhiveConfig::validate() guarantees these are valid Namespace strings, so
999    // parse failures here are unreachable for validated configs; filter_map+warn
1000    // guards against a validation bug panicking instead.
1001    let allowed_outbound_namespaces: Vec<Namespace> = khive_cfg
1002        .actor
1003        .allowed_outbound_namespaces
1004        .iter()
1005        .filter_map(|s| match Namespace::parse(s) {
1006            Ok(ns) => Some(ns),
1007            Err(e) => {
1008                tracing::warn!(ns = %s, error = %e, "actor.allowed_outbound_namespaces: invalid namespace; skipped");
1009                None
1010            }
1011        })
1012        .collect();
1013
1014    // Precedence: TOML `[actor] id` > `base.actor_id` (env/CLI-resolved) >
1015    // anonymous. Falls back to `base.actor_id` rather than `None` when
1016    // `[actor] id` is absent: otherwise an env-resolved actor like
1017    // `KHIVE_ACTOR` is silently dropped whenever a project config exists
1018    // without an `[actor]` block.
1019    let actor_id = khive_cfg
1020        .actor
1021        .id
1022        .clone()
1023        .filter(|s| !s.trim().is_empty())
1024        .or_else(|| base.actor_id.clone());
1025
1026    let gate = khive_cfg
1027        .gate
1028        .as_ref()
1029        .map(|gate| {
1030            Arc::new(khive_gate::CallerEnrollmentGate::with_write_denials(
1031                gate.granted_actors.clone(),
1032                gate.grant_unattributed,
1033                gate.deny_writes_for.clone(),
1034            )) as GateRef
1035        })
1036        .unwrap_or_else(|| base.gate.clone());
1037    let gate = crate::mailbox_view::configured_mailbox_gate(&khive_cfg.actor, gate);
1038
1039    let brain = khive_cfg.brain.clone();
1040    let git_write = khive_cfg.git_write.clone();
1041    let blob = crate::engine_config::BlobSectionConfig {
1042        file_transfers: khive_cfg.blob.file_transfers || base.blob.file_transfers,
1043    };
1044    let exec = khive_cfg.exec.clone();
1045    let telemetry = khive_cfg.telemetry.clone();
1046    let web = khive_cfg.web.clone();
1047    let blob_hydration_bytes = khive_cfg
1048        .runtime
1049        .blob_hydration_bytes
1050        .unwrap_or(base.blob_hydration_bytes);
1051
1052    // KhiveConfig::validate() guarantees a present timezone parses as a valid
1053    // chrono_tz::Tz, so the fallback to base.display_timezone below is only
1054    // reachable for an unvalidated caller-constructed KhiveConfig, not a
1055    // config loaded via KhiveConfig::load.
1056    let display_timezone = khive_cfg
1057        .display
1058        .timezone
1059        .as_deref()
1060        .and_then(|s| s.parse::<chrono_tz::Tz>().ok())
1061        .unwrap_or(base.display_timezone);
1062
1063    if khive_cfg.engines.is_empty() {
1064        return RuntimeConfig {
1065            credentials,
1066            visibility_receipts,
1067            default_namespace,
1068            brain_profile,
1069            visible_namespaces,
1070            allowed_outbound_namespaces,
1071            actor_id,
1072            gate,
1073            brain,
1074            git_write,
1075            blob,
1076            exec,
1077            telemetry,
1078            mounts,
1079            blob_hydration_bytes,
1080            display_timezone,
1081            web,
1082            ..base
1083        };
1084    }
1085
1086    let mut embedding_model: Option<EmbeddingModel> = None;
1087    let mut additional: Vec<EmbeddingModel> = Vec::new();
1088
1089    for engine in &khive_cfg.engines {
1090        match parse_embedding_model_alias(&engine.model) {
1091            Some(model) => {
1092                if engine.default {
1093                    embedding_model = Some(model);
1094                } else {
1095                    additional.push(model);
1096                }
1097            }
1098            None => {
1099                tracing::warn!(
1100                    engine = %engine.name,
1101                    model = %engine.model,
1102                    "engine config: unknown model name; engine will be skipped"
1103                );
1104            }
1105        }
1106    }
1107
1108    RuntimeConfig {
1109        credentials,
1110        visibility_receipts,
1111        embedding_model,
1112        additional_embedding_models: additional,
1113        default_namespace,
1114        brain_profile,
1115        visible_namespaces,
1116        allowed_outbound_namespaces,
1117        actor_id,
1118        gate,
1119        brain,
1120        git_write,
1121        blob,
1122        exec,
1123        telemetry,
1124        mounts,
1125        blob_hydration_bytes,
1126        display_timezone,
1127        web,
1128        ..base
1129    }
1130}
1131
1132#[cfg(test)]
1133mod display_timezone_tests {
1134    use super::resolve_default_display_timezone;
1135
1136    // The host's actual zone is environment-dependent (CI runners are
1137    // typically UTC), so this only asserts the resolver always produces some
1138    // valid, non-panicking Tz — never that it matches a specific zone.
1139    #[test]
1140    fn resolve_default_display_timezone_never_panics() {
1141        let _tz = resolve_default_display_timezone();
1142    }
1143}
1144
1145/// Parse a comma- or whitespace-separated list of embedding model names.
1146fn parse_embedding_model_list(s: &str) -> Vec<EmbeddingModel> {
1147    parse_pack_list(s)
1148        .into_iter()
1149        .filter_map(|raw| {
1150            let parsed = parse_embedding_model_alias(&raw);
1151            if parsed.is_none() && !raw.trim().is_empty() {
1152                tracing::warn!(
1153                    model = %raw,
1154                    "KHIVE_ADDITIONAL_EMBEDDING_MODELS contains unknown model name; ignored. \
1155                     Valid forms: short alias like 'paraphrase' or a fully-qualified key \
1156                     from lattice_embed::EmbeddingModel::from_str."
1157                );
1158            }
1159            parsed
1160        })
1161        .collect()
1162}
1163
1164pub(crate) fn parse_embedding_model_alias(name: &str) -> Option<EmbeddingModel> {
1165    let normalized = name.trim().to_ascii_lowercase().replace('_', "-");
1166    match normalized.as_str() {
1167        "paraphrase" => Some(EmbeddingModel::ParaphraseMultilingualMiniLmL12V2),
1168        _ => normalized.parse().ok(),
1169    }
1170}
1171
1172#[cfg(test)]
1173mod resolve_db_anchor_tests {
1174    use super::resolve_db_anchor;
1175
1176    #[test]
1177    fn memory_sentinel_maps_to_none() {
1178        assert_eq!(resolve_db_anchor(Some(":memory:")), None);
1179    }
1180
1181    #[test]
1182    fn explicit_path_maps_to_some() {
1183        assert_eq!(
1184            resolve_db_anchor(Some("/tmp/khive-anchor-test.db")),
1185            Some(std::path::PathBuf::from("/tmp/khive-anchor-test.db"))
1186        );
1187    }
1188
1189    #[test]
1190    fn absent_maps_to_home_default() {
1191        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
1192        let expected = std::path::PathBuf::from(format!("{home}/.khive/khive.db"));
1193        assert_eq!(resolve_db_anchor(None), Some(expected));
1194    }
1195}
1196
1197#[cfg(test)]
1198mod assert_db_anchor_consistent_tests {
1199    use super::{assert_captured_db_anchor_consistent, resolve_db_anchor};
1200    use crate::assert_db_anchor_consistent;
1201
1202    #[test]
1203    fn diverging_db_path_is_rejected_naming_both_paths() {
1204        let args_db = "/tmp/khive-anchor-guard-real.db";
1205        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1206        let wrong = std::path::PathBuf::from("/tmp/khive-anchor-guard-wrong.db");
1207
1208        let err =
1209            assert_captured_db_anchor_consistent(Some(wrong.as_path()), Some(anchor.as_path()))
1210                .expect_err("a resolved db_path diverging from the anchor must be rejected");
1211
1212        let msg = err.to_string();
1213        assert!(
1214            msg.contains(&wrong.display().to_string()),
1215            "error must name the resolved (wrong) path: {msg}"
1216        );
1217        assert!(
1218            msg.contains(&anchor.display().to_string()),
1219            "error must name the canonical anchor path: {msg}"
1220        );
1221    }
1222
1223    #[test]
1224    fn matching_explicit_db_path_passes() {
1225        let args_db = "/tmp/khive-anchor-guard-consistent.db";
1226        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1227        assert!(assert_captured_db_anchor_consistent(
1228            Some(anchor.as_path()),
1229            Some(anchor.as_path())
1230        )
1231        .is_ok());
1232    }
1233
1234    #[test]
1235    fn memory_sentinel_anchor_is_inert() {
1236        // `resolve_db_anchor(":memory:")` yields `None` — there is no canonical
1237        // path to assert against, so the guard passes regardless of what
1238        // `resolved_db_path` happens to carry.
1239        let bogus = std::path::PathBuf::from("/tmp/should-not-matter.db");
1240        assert!(assert_captured_db_anchor_consistent(Some(bogus.as_path()), None).is_ok());
1241        assert!(assert_captured_db_anchor_consistent(None, None).is_ok());
1242    }
1243
1244    #[test]
1245    fn normal_boot_with_db_unset_passes_silently() {
1246        // Mirrors a normal boot with `--db` unset: `resolve_db_anchor(None)`
1247        // always resolves to `Some(..)` (HOME-set or -unset both produce a
1248        // concrete anchor), so a runtime whose resolved `db_path` matches
1249        // passes silently.
1250        let anchor = resolve_db_anchor(None);
1251        assert!(assert_captured_db_anchor_consistent(anchor.as_deref(), anchor.as_deref()).is_ok());
1252    }
1253
1254    #[test]
1255    fn public_compatibility_wrapper_accepts_path_and_memory_sentinel() {
1256        let args_db = "/tmp/khive-anchor-guard-public-api.db";
1257        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1258        assert!(assert_db_anchor_consistent(Some(anchor.as_path()), Some(args_db)).is_ok());
1259
1260        let unrelated = std::path::Path::new("/tmp/khive-anchor-guard-unrelated.db");
1261        assert!(assert_db_anchor_consistent(Some(unrelated), Some(":memory:")).is_ok());
1262    }
1263}
1264
1265#[cfg(test)]
1266mod resolve_project_actor_id_tests {
1267    use super::resolve_project_actor_id;
1268
1269    fn write_toml(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
1270        let path = dir.path().join("config.toml");
1271        std::fs::write(&path, body).expect("write config.toml");
1272        path
1273    }
1274
1275    #[test]
1276    fn extracts_non_empty_actor_id_from_explicit_path() {
1277        let dir = tempfile::tempdir().expect("tempdir");
1278        let path = write_toml(&dir, "[actor]\nid = \"lambda:explicit-actor\"\n");
1279
1280        assert_eq!(
1281            resolve_project_actor_id(Some(&path)).expect("no error"),
1282            Some("lambda:explicit-actor".to_string())
1283        );
1284    }
1285
1286    #[test]
1287    fn missing_explicit_path_fails_loud() {
1288        // The explicit tier is enforced inside the loader
1289        // (`KhiveConfig::load_with_home_fallback_and_source` returns
1290        // `ExplicitConfigMissing`): a nonexistent explicit path is an error,
1291        // never a silent `None` (ADR-035).
1292        let missing = std::path::PathBuf::from("/nonexistent/khive-project-actor-test/config.toml");
1293        let err = resolve_project_actor_id(Some(&missing))
1294            .expect_err("a missing explicit path must fail loud");
1295        assert!(
1296            matches!(
1297                err,
1298                crate::engine_config::ConfigError::ExplicitConfigMissing { .. }
1299            ),
1300            "expected ExplicitConfigMissing, got {err:?}"
1301        );
1302    }
1303
1304    #[test]
1305    fn propagates_load_error_for_invalid_actor_id() {
1306        // `KhiveConfig::load`'s `validate()` rejects an empty `[actor] id` before
1307        // the emptiness filter in `resolve_project_actor_id` ever sees it; this
1308        // asserts the error surfaces rather than being swallowed into `Ok(None)`.
1309        let dir = tempfile::tempdir().expect("tempdir");
1310        let path = write_toml(&dir, "[actor]\nid = \"\"\n");
1311
1312        let err = resolve_project_actor_id(Some(&path)).expect_err("invalid actor.id must error");
1313        let root = match &err {
1314            crate::engine_config::ConfigError::InFile { source, .. } => source.as_ref(),
1315            other => other,
1316        };
1317        assert!(
1318            matches!(
1319                root,
1320                crate::engine_config::ConfigError::InvalidActorId { .. }
1321            ),
1322            "expected InvalidActorId, got {err:?}"
1323        );
1324    }
1325
1326    #[test]
1327    fn returns_none_when_config_has_no_actor_section() {
1328        let dir = tempfile::tempdir().expect("tempdir");
1329        let path = write_toml(
1330            &dir,
1331            "[[engines]]\nname = \"primary\"\nmodel = \"bge-small-en-v1.5\"\ndefault = true\n",
1332        );
1333
1334        assert_eq!(
1335            resolve_project_actor_id(Some(&path)).expect("no error"),
1336            None,
1337            "a config file with no [actor] section must resolve to None"
1338        );
1339    }
1340}
1341
1342#[cfg(test)]
1343mod no_embeddings_tests {
1344    use super::*;
1345    use serial_test::serial;
1346
1347    #[test]
1348    fn no_embeddings_clears_both_fields() {
1349        let config = RuntimeConfig::no_embeddings();
1350        assert_eq!(config.embedding_model, None);
1351        assert!(config.additional_embedding_models.is_empty());
1352        assert!(
1353            configured_embedding_models(&config).is_empty(),
1354            "no_embeddings() must yield zero configured embedders"
1355        );
1356    }
1357
1358    #[test]
1359    fn blob_hydration_default_is_four_portable_whole_objects() {
1360        assert_eq!(
1361            RuntimeConfig::default().blob_hydration_bytes,
1362            4 * khive_storage::MAX_BLOB_WHOLE_BYTES
1363        );
1364    }
1365
1366    #[test]
1367    #[serial]
1368    fn no_embeddings_ignores_additional_env_override() {
1369        // no_embeddings() is an unconditional opt-out: even if the caller's
1370        // environment sets KHIVE_ADDITIONAL_EMBEDDING_MODELS, the resulting
1371        // config must still report zero embedders.
1372        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1373        let config = RuntimeConfig::no_embeddings();
1374        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1375
1376        assert!(config.additional_embedding_models.is_empty());
1377        assert!(configured_embedding_models(&config).is_empty());
1378    }
1379
1380    #[test]
1381    #[serial]
1382    fn default_computes_additional_models_independently_of_no_embeddings() {
1383        // `Default` must keep computing `embedding_model` and
1384        // `additional_embedding_models` independently; `no_embeddings()` is a
1385        // separate opt-out constructor, not a change to `Default`'s seeding.
1386        // The env var is SET here rather than cleared: since Default now ships
1387        // no secondary engine, an unset env would make Default and
1388        // no_embeddings() indistinguishable and the test would stop
1389        // discriminating the thing it exists to discriminate.
1390        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1391        let config = RuntimeConfig::default();
1392        let buggy_form = RuntimeConfig {
1393            embedding_model: None,
1394            ..RuntimeConfig::default()
1395        };
1396        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1397
1398        assert_eq!(
1399            config.additional_embedding_models,
1400            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1401        );
1402
1403        // Overriding only `embedding_model` via struct-update syntax does not
1404        // clear `additional_embedding_models`.
1405        assert!(
1406            !buggy_form.additional_embedding_models.is_empty(),
1407            "Default's independent-field seeding must remain unchanged; \
1408             no_embeddings() is the fix, not a change to Default"
1409        );
1410    }
1411
1412    #[test]
1413    #[serial]
1414    fn default_ships_a_single_engine_when_env_unset() {
1415        // A secondary engine is embedded on every write and searched on every
1416        // read. That cost is opted into, not inherited.
1417        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1418        let config = RuntimeConfig::default();
1419
1420        assert!(
1421            config.additional_embedding_models.is_empty(),
1422            "shipped default must register one engine; a second is opt-in via \
1423             KHIVE_ADDITIONAL_EMBEDDING_MODELS"
1424        );
1425        assert_eq!(
1426            configured_embedding_models(&config),
1427            vec![EmbeddingModel::AllMiniLmL6V2]
1428        );
1429    }
1430}
1431
1432#[cfg(test)]
1433mod ann_fresh_tail_config_tests {
1434    use super::ann_fresh_tail_enabled_from_value;
1435
1436    #[test]
1437    fn only_exact_zero_disables_fresh_tail() {
1438        assert!(ann_fresh_tail_enabled_from_value(None));
1439        assert!(!ann_fresh_tail_enabled_from_value(Some("0")));
1440        assert!(ann_fresh_tail_enabled_from_value(Some("1")));
1441        assert!(ann_fresh_tail_enabled_from_value(Some("false")));
1442        assert!(ann_fresh_tail_enabled_from_value(Some(" 0")));
1443    }
1444}
1445
1446#[cfg(test)]
1447mod configured_embedding_models_order_tests {
1448    use super::*;
1449
1450    /// Issue #1115: the configured engine list must preserve declaration
1451    /// order (primary first, then `additional_embedding_models` in order)
1452    /// instead of alphabetizing — any consumer that treats the list as
1453    /// ordered (e.g. recall fan-out) otherwise gets the wrong primary.
1454    #[test]
1455    fn preserves_primary_first_then_additional_in_declared_order() {
1456        let config = RuntimeConfig {
1457            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1458            additional_embedding_models: vec![
1459                EmbeddingModel::Qwen3Embedding4B,
1460                EmbeddingModel::BgeSmallEnV15,
1461            ],
1462            ..RuntimeConfig::default()
1463        };
1464
1465        assert_eq!(
1466            configured_embedding_models(&config),
1467            vec![
1468                EmbeddingModel::AllMiniLmL6V2,
1469                EmbeddingModel::Qwen3Embedding4B,
1470                EmbeddingModel::BgeSmallEnV15,
1471            ],
1472            "order must be primary-first, then additional models as declared, \
1473             not alphabetized"
1474        );
1475    }
1476
1477    /// A model repeated in both `embedding_model` and `additional_embedding_models`
1478    /// must be deduped to a single entry, keeping its first (primary) position.
1479    #[test]
1480    fn dedupes_model_shared_between_primary_and_additional() {
1481        let config = RuntimeConfig {
1482            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1483            additional_embedding_models: vec![
1484                EmbeddingModel::AllMiniLmL6V2,
1485                EmbeddingModel::BgeSmallEnV15,
1486            ],
1487            ..RuntimeConfig::default()
1488        };
1489
1490        assert_eq!(
1491            configured_embedding_models(&config),
1492            vec![EmbeddingModel::AllMiniLmL6V2, EmbeddingModel::BgeSmallEnV15],
1493            "the shared model must appear once, in its primary position"
1494        );
1495    }
1496}