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
879/// Preserve ASCII letters and digits; replace every other Unicode character with `_`.
880/// Used for model-name table suffixes; this mapping does not preserve uniqueness.
881#[doc(hidden)]
882pub fn sanitize_key(s: &str) -> String {
883    s.chars()
884        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
885        .collect()
886}
887
888pub(crate) fn build_embedder_registry(
889    config: &RuntimeConfig,
890) -> (crate::embedder_registry::EmbedderRegistry, Arc<str>) {
891    use crate::embedder_registry::{EmbedderRegistry, LatticeEmbedderProvider};
892    let mut registry = EmbedderRegistry::new();
893    for model in configured_embedding_models(config) {
894        registry.register_builtin(LatticeEmbedderProvider::new(model));
895    }
896    let default_embedder_name = config
897        .embedding_model
898        .map(|model| Arc::<str>::from(model.to_string()))
899        .unwrap_or_else(|| Arc::<str>::from(""));
900    (registry, default_embedder_name)
901}
902
903fn configured_embedding_models(config: &RuntimeConfig) -> Vec<EmbeddingModel> {
904    let mut models: Vec<EmbeddingModel> = Vec::new();
905    if let Some(model) = config.embedding_model {
906        models.push(model);
907    }
908    for model in config.additional_embedding_models.iter().copied() {
909        if !models.contains(&model) {
910            models.push(model);
911        }
912    }
913    models
914}
915
916pub(crate) fn register_configured_embedding_models(
917    backend: &StorageBackend,
918    config: &RuntimeConfig,
919) -> RuntimeResult<()> {
920    for model in configured_embedding_models(config) {
921        backend.register_embedding_model(
922            &model.to_string(),
923            model.model_id(),
924            model.key_version(),
925            model.dimensions() as u32,
926        )?;
927    }
928    Ok(())
929}
930
931/// Build a `RuntimeConfig` from a parsed `KhiveConfig`.
932///
933/// For each `[[engines]]` entry:
934/// - The engine flagged `default = true` becomes `RuntimeConfig::embedding_model`.
935/// - All other engines become `RuntimeConfig::additional_embedding_models`.
936///
937/// `KhiveConfig::validate()` rejects an unrecognized engine model at load time.
938/// A caller-constructed config that bypasses validation still skips an invalid
939/// engine with a warning here.
940///
941/// If `khive_cfg.engines` is empty, the returned `RuntimeConfig` uses the
942/// env-var-derived defaults from `RuntimeConfig::default()`.
943///
944/// When both a config file and `KHIVE_EMBEDDING_MODEL` env var are present,
945/// the caller is responsible for emitting a warning that env vars are overridden.
946/// This function purely converts `KhiveConfig` to `RuntimeConfig` fields.
947pub fn runtime_config_from_khive_config(
948    khive_cfg: &crate::engine_config::KhiveConfig,
949    base: RuntimeConfig,
950) -> RuntimeConfig {
951    // `[actor] id` never becomes the storage namespace (writes always pin to
952    // `local`); it only widens the read visible-set below.
953    let default_namespace = base.default_namespace.clone();
954    let mounts = khive_cfg.mounts.clone();
955    let credentials = khive_cfg.credentials.clone();
956    let visibility_receipts = khive_cfg.visibility_receipts.clone();
957
958    // base.brain_profile must carry only the explicit CLI tier, never an env
959    // value: env sits below toml in precedence and is applied later by the MCP resolver.
960    let brain_profile = base.brain_profile.clone().or_else(|| {
961        khive_cfg
962            .runtime
963            .brain_profile
964            .clone()
965            .filter(|s| !s.trim().is_empty())
966    });
967
968    let visible_namespaces: Vec<Namespace> = khive_cfg
969        .actor
970        .visible_namespaces
971        .as_deref()
972        .unwrap_or_default()
973        .iter()
974        .filter_map(|s| match Namespace::parse(s) {
975            Ok(ns) => Some(ns),
976            Err(e) => {
977                tracing::warn!(ns = %s, error = %e, "actor.visible_namespaces: invalid namespace; skipped");
978                None
979            }
980        })
981        .collect();
982
983    // Fold actor.id's namespace into visible_namespaces so default reads widen
984    // to {local} ∪ {actor namespace}; skipped when it parses to `local` (would
985    // duplicate the primary namespace already minted) or is already present.
986    let visible_namespaces = if let Some(id) = khive_cfg.actor.id.as_deref() {
987        match Namespace::parse(id) {
988            Ok(actor_ns) if actor_ns != Namespace::local() => {
989                let mut v = visible_namespaces;
990                if !v.contains(&actor_ns) {
991                    v.push(actor_ns);
992                }
993                v
994            }
995            _ => visible_namespaces,
996        }
997    } else {
998        visible_namespaces
999    };
1000
1001    // KhiveConfig::validate() guarantees these are valid Namespace strings, so
1002    // parse failures here are unreachable for validated configs; filter_map+warn
1003    // guards against a validation bug panicking instead.
1004    let allowed_outbound_namespaces: Vec<Namespace> = khive_cfg
1005        .actor
1006        .allowed_outbound_namespaces
1007        .iter()
1008        .filter_map(|s| match Namespace::parse(s) {
1009            Ok(ns) => Some(ns),
1010            Err(e) => {
1011                tracing::warn!(ns = %s, error = %e, "actor.allowed_outbound_namespaces: invalid namespace; skipped");
1012                None
1013            }
1014        })
1015        .collect();
1016
1017    // Precedence: TOML `[actor] id` > `base.actor_id` (env/CLI-resolved) >
1018    // anonymous. Falls back to `base.actor_id` rather than `None` when
1019    // `[actor] id` is absent: otherwise an env-resolved actor like
1020    // `KHIVE_ACTOR` is silently dropped whenever a project config exists
1021    // without an `[actor]` block.
1022    let actor_id = khive_cfg
1023        .actor
1024        .id
1025        .clone()
1026        .filter(|s| !s.trim().is_empty())
1027        .or_else(|| base.actor_id.clone());
1028
1029    let gate = khive_cfg
1030        .gate
1031        .as_ref()
1032        .map(|gate| {
1033            Arc::new(khive_gate::CallerEnrollmentGate::with_write_denials(
1034                gate.granted_actors.clone(),
1035                gate.grant_unattributed,
1036                gate.deny_writes_for.clone(),
1037            )) as GateRef
1038        })
1039        .unwrap_or_else(|| base.gate.clone());
1040    let gate = crate::mailbox_view::configured_mailbox_gate(&khive_cfg.actor, gate);
1041
1042    let brain = khive_cfg.brain.clone();
1043    let git_write = khive_cfg.git_write.clone();
1044    let blob = crate::engine_config::BlobSectionConfig {
1045        file_transfers: khive_cfg.blob.file_transfers || base.blob.file_transfers,
1046    };
1047    let exec = khive_cfg.exec.clone();
1048    let telemetry = khive_cfg.telemetry.clone();
1049    let web = khive_cfg.web.clone();
1050    let blob_hydration_bytes = khive_cfg
1051        .runtime
1052        .blob_hydration_bytes
1053        .unwrap_or(base.blob_hydration_bytes);
1054
1055    // KhiveConfig::validate() guarantees a present timezone parses as a valid
1056    // chrono_tz::Tz, so the fallback to base.display_timezone below is only
1057    // reachable for an unvalidated caller-constructed KhiveConfig, not a
1058    // config loaded via KhiveConfig::load.
1059    let display_timezone = khive_cfg
1060        .display
1061        .timezone
1062        .as_deref()
1063        .and_then(|s| s.parse::<chrono_tz::Tz>().ok())
1064        .unwrap_or(base.display_timezone);
1065
1066    if khive_cfg.engines.is_empty() {
1067        return RuntimeConfig {
1068            credentials,
1069            visibility_receipts,
1070            default_namespace,
1071            brain_profile,
1072            visible_namespaces,
1073            allowed_outbound_namespaces,
1074            actor_id,
1075            gate,
1076            brain,
1077            git_write,
1078            blob,
1079            exec,
1080            telemetry,
1081            mounts,
1082            blob_hydration_bytes,
1083            display_timezone,
1084            web,
1085            ..base
1086        };
1087    }
1088
1089    let mut embedding_model: Option<EmbeddingModel> = None;
1090    let mut additional: Vec<EmbeddingModel> = Vec::new();
1091
1092    for engine in &khive_cfg.engines {
1093        match parse_embedding_model_alias(&engine.model) {
1094            Some(model) => {
1095                if engine.default {
1096                    embedding_model = Some(model);
1097                } else {
1098                    additional.push(model);
1099                }
1100            }
1101            None => {
1102                tracing::warn!(
1103                    engine = %engine.name,
1104                    model = %engine.model,
1105                    "engine config: unknown model name; engine will be skipped"
1106                );
1107            }
1108        }
1109    }
1110
1111    RuntimeConfig {
1112        credentials,
1113        visibility_receipts,
1114        embedding_model,
1115        additional_embedding_models: additional,
1116        default_namespace,
1117        brain_profile,
1118        visible_namespaces,
1119        allowed_outbound_namespaces,
1120        actor_id,
1121        gate,
1122        brain,
1123        git_write,
1124        blob,
1125        exec,
1126        telemetry,
1127        mounts,
1128        blob_hydration_bytes,
1129        display_timezone,
1130        web,
1131        ..base
1132    }
1133}
1134
1135#[cfg(test)]
1136mod display_timezone_tests {
1137    use super::resolve_default_display_timezone;
1138
1139    // The host's actual zone is environment-dependent (CI runners are
1140    // typically UTC), so this only asserts the resolver always produces some
1141    // valid, non-panicking Tz — never that it matches a specific zone.
1142    #[test]
1143    fn resolve_default_display_timezone_never_panics() {
1144        let _tz = resolve_default_display_timezone();
1145    }
1146}
1147
1148/// Parse a comma- or whitespace-separated list of embedding model names.
1149fn parse_embedding_model_list(s: &str) -> Vec<EmbeddingModel> {
1150    parse_pack_list(s)
1151        .into_iter()
1152        .filter_map(|raw| {
1153            let parsed = parse_embedding_model_alias(&raw);
1154            if parsed.is_none() && !raw.trim().is_empty() {
1155                tracing::warn!(
1156                    model = %raw,
1157                    "KHIVE_ADDITIONAL_EMBEDDING_MODELS contains unknown model name; ignored. \
1158                     Valid forms: short alias like 'paraphrase' or a fully-qualified key \
1159                     from lattice_embed::EmbeddingModel::from_str."
1160                );
1161            }
1162            parsed
1163        })
1164        .collect()
1165}
1166
1167pub(crate) fn parse_embedding_model_alias(name: &str) -> Option<EmbeddingModel> {
1168    let normalized = name.trim().to_ascii_lowercase().replace('_', "-");
1169    match normalized.as_str() {
1170        "paraphrase" => Some(EmbeddingModel::ParaphraseMultilingualMiniLmL12V2),
1171        _ => normalized.parse().ok(),
1172    }
1173}
1174
1175#[cfg(test)]
1176mod resolve_db_anchor_tests {
1177    use super::resolve_db_anchor;
1178
1179    #[test]
1180    fn memory_sentinel_maps_to_none() {
1181        assert_eq!(resolve_db_anchor(Some(":memory:")), None);
1182    }
1183
1184    #[test]
1185    fn explicit_path_maps_to_some() {
1186        assert_eq!(
1187            resolve_db_anchor(Some("/tmp/khive-anchor-test.db")),
1188            Some(std::path::PathBuf::from("/tmp/khive-anchor-test.db"))
1189        );
1190    }
1191
1192    #[test]
1193    fn absent_maps_to_home_default() {
1194        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
1195        let expected = std::path::PathBuf::from(format!("{home}/.khive/khive.db"));
1196        assert_eq!(resolve_db_anchor(None), Some(expected));
1197    }
1198}
1199
1200#[cfg(test)]
1201mod assert_db_anchor_consistent_tests {
1202    use super::{assert_captured_db_anchor_consistent, resolve_db_anchor};
1203    use crate::assert_db_anchor_consistent;
1204
1205    #[test]
1206    fn diverging_db_path_is_rejected_naming_both_paths() {
1207        let args_db = "/tmp/khive-anchor-guard-real.db";
1208        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1209        let wrong = std::path::PathBuf::from("/tmp/khive-anchor-guard-wrong.db");
1210
1211        let err =
1212            assert_captured_db_anchor_consistent(Some(wrong.as_path()), Some(anchor.as_path()))
1213                .expect_err("a resolved db_path diverging from the anchor must be rejected");
1214
1215        let msg = err.to_string();
1216        assert!(
1217            msg.contains(&wrong.display().to_string()),
1218            "error must name the resolved (wrong) path: {msg}"
1219        );
1220        assert!(
1221            msg.contains(&anchor.display().to_string()),
1222            "error must name the canonical anchor path: {msg}"
1223        );
1224    }
1225
1226    #[test]
1227    fn matching_explicit_db_path_passes() {
1228        let args_db = "/tmp/khive-anchor-guard-consistent.db";
1229        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1230        assert!(assert_captured_db_anchor_consistent(
1231            Some(anchor.as_path()),
1232            Some(anchor.as_path())
1233        )
1234        .is_ok());
1235    }
1236
1237    #[test]
1238    fn memory_sentinel_anchor_is_inert() {
1239        // `resolve_db_anchor(":memory:")` yields `None` — there is no canonical
1240        // path to assert against, so the guard passes regardless of what
1241        // `resolved_db_path` happens to carry.
1242        let bogus = std::path::PathBuf::from("/tmp/should-not-matter.db");
1243        assert!(assert_captured_db_anchor_consistent(Some(bogus.as_path()), None).is_ok());
1244        assert!(assert_captured_db_anchor_consistent(None, None).is_ok());
1245    }
1246
1247    #[test]
1248    fn normal_boot_with_db_unset_passes_silently() {
1249        // Mirrors a normal boot with `--db` unset: `resolve_db_anchor(None)`
1250        // always resolves to `Some(..)` (HOME-set or -unset both produce a
1251        // concrete anchor), so a runtime whose resolved `db_path` matches
1252        // passes silently.
1253        let anchor = resolve_db_anchor(None);
1254        assert!(assert_captured_db_anchor_consistent(anchor.as_deref(), anchor.as_deref()).is_ok());
1255    }
1256
1257    #[test]
1258    fn public_compatibility_wrapper_accepts_path_and_memory_sentinel() {
1259        let args_db = "/tmp/khive-anchor-guard-public-api.db";
1260        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1261        assert!(assert_db_anchor_consistent(Some(anchor.as_path()), Some(args_db)).is_ok());
1262
1263        let unrelated = std::path::Path::new("/tmp/khive-anchor-guard-unrelated.db");
1264        assert!(assert_db_anchor_consistent(Some(unrelated), Some(":memory:")).is_ok());
1265    }
1266}
1267
1268#[cfg(test)]
1269mod resolve_project_actor_id_tests {
1270    use super::resolve_project_actor_id;
1271
1272    fn write_toml(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
1273        let path = dir.path().join("config.toml");
1274        std::fs::write(&path, body).expect("write config.toml");
1275        path
1276    }
1277
1278    #[test]
1279    fn extracts_non_empty_actor_id_from_explicit_path() {
1280        let dir = tempfile::tempdir().expect("tempdir");
1281        let path = write_toml(&dir, "[actor]\nid = \"lambda:explicit-actor\"\n");
1282
1283        assert_eq!(
1284            resolve_project_actor_id(Some(&path)).expect("no error"),
1285            Some("lambda:explicit-actor".to_string())
1286        );
1287    }
1288
1289    #[test]
1290    fn missing_explicit_path_fails_loud() {
1291        // The explicit tier is enforced inside the loader
1292        // (`KhiveConfig::load_with_home_fallback_and_source` returns
1293        // `ExplicitConfigMissing`): a nonexistent explicit path is an error,
1294        // never a silent `None` (ADR-035).
1295        let missing = std::path::PathBuf::from("/nonexistent/khive-project-actor-test/config.toml");
1296        let err = resolve_project_actor_id(Some(&missing))
1297            .expect_err("a missing explicit path must fail loud");
1298        assert!(
1299            matches!(
1300                err,
1301                crate::engine_config::ConfigError::ExplicitConfigMissing { .. }
1302            ),
1303            "expected ExplicitConfigMissing, got {err:?}"
1304        );
1305    }
1306
1307    #[test]
1308    fn propagates_load_error_for_invalid_actor_id() {
1309        // `KhiveConfig::load`'s `validate()` rejects an empty `[actor] id` before
1310        // the emptiness filter in `resolve_project_actor_id` ever sees it; this
1311        // asserts the error surfaces rather than being swallowed into `Ok(None)`.
1312        let dir = tempfile::tempdir().expect("tempdir");
1313        let path = write_toml(&dir, "[actor]\nid = \"\"\n");
1314
1315        let err = resolve_project_actor_id(Some(&path)).expect_err("invalid actor.id must error");
1316        let root = match &err {
1317            crate::engine_config::ConfigError::InFile { source, .. } => source.as_ref(),
1318            other => other,
1319        };
1320        assert!(
1321            matches!(
1322                root,
1323                crate::engine_config::ConfigError::InvalidActorId { .. }
1324            ),
1325            "expected InvalidActorId, got {err:?}"
1326        );
1327    }
1328
1329    #[test]
1330    fn returns_none_when_config_has_no_actor_section() {
1331        let dir = tempfile::tempdir().expect("tempdir");
1332        let path = write_toml(
1333            &dir,
1334            "[[engines]]\nname = \"primary\"\nmodel = \"bge-small-en-v1.5\"\ndefault = true\n",
1335        );
1336
1337        assert_eq!(
1338            resolve_project_actor_id(Some(&path)).expect("no error"),
1339            None,
1340            "a config file with no [actor] section must resolve to None"
1341        );
1342    }
1343}
1344
1345#[cfg(test)]
1346mod no_embeddings_tests {
1347    use super::*;
1348    use serial_test::serial;
1349
1350    #[test]
1351    fn no_embeddings_clears_both_fields() {
1352        let config = RuntimeConfig::no_embeddings();
1353        assert_eq!(config.embedding_model, None);
1354        assert!(config.additional_embedding_models.is_empty());
1355        assert!(
1356            configured_embedding_models(&config).is_empty(),
1357            "no_embeddings() must yield zero configured embedders"
1358        );
1359    }
1360
1361    #[test]
1362    fn blob_hydration_default_is_four_portable_whole_objects() {
1363        assert_eq!(
1364            RuntimeConfig::default().blob_hydration_bytes,
1365            4 * khive_storage::MAX_BLOB_WHOLE_BYTES
1366        );
1367    }
1368
1369    #[test]
1370    #[serial]
1371    fn no_embeddings_ignores_additional_env_override() {
1372        // no_embeddings() is an unconditional opt-out: even if the caller's
1373        // environment sets KHIVE_ADDITIONAL_EMBEDDING_MODELS, the resulting
1374        // config must still report zero embedders.
1375        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1376        let config = RuntimeConfig::no_embeddings();
1377        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1378
1379        assert!(config.additional_embedding_models.is_empty());
1380        assert!(configured_embedding_models(&config).is_empty());
1381    }
1382
1383    #[test]
1384    #[serial]
1385    fn default_computes_additional_models_independently_of_no_embeddings() {
1386        // `Default` must keep computing `embedding_model` and
1387        // `additional_embedding_models` independently; `no_embeddings()` is a
1388        // separate opt-out constructor, not a change to `Default`'s seeding.
1389        // The env var is SET here rather than cleared: since Default now ships
1390        // no secondary engine, an unset env would make Default and
1391        // no_embeddings() indistinguishable and the test would stop
1392        // discriminating the thing it exists to discriminate.
1393        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1394        let config = RuntimeConfig::default();
1395        let buggy_form = RuntimeConfig {
1396            embedding_model: None,
1397            ..RuntimeConfig::default()
1398        };
1399        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1400
1401        assert_eq!(
1402            config.additional_embedding_models,
1403            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1404        );
1405
1406        // Overriding only `embedding_model` via struct-update syntax does not
1407        // clear `additional_embedding_models`.
1408        assert!(
1409            !buggy_form.additional_embedding_models.is_empty(),
1410            "Default's independent-field seeding must remain unchanged; \
1411             no_embeddings() is the fix, not a change to Default"
1412        );
1413    }
1414
1415    #[test]
1416    #[serial]
1417    fn default_ships_a_single_engine_when_env_unset() {
1418        // A secondary engine is embedded on every write and searched on every
1419        // read. That cost is opted into, not inherited.
1420        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1421        let config = RuntimeConfig::default();
1422
1423        assert!(
1424            config.additional_embedding_models.is_empty(),
1425            "shipped default must register one engine; a second is opt-in via \
1426             KHIVE_ADDITIONAL_EMBEDDING_MODELS"
1427        );
1428        assert_eq!(
1429            configured_embedding_models(&config),
1430            vec![EmbeddingModel::AllMiniLmL6V2]
1431        );
1432    }
1433}
1434
1435#[cfg(test)]
1436mod ann_fresh_tail_config_tests {
1437    use super::ann_fresh_tail_enabled_from_value;
1438
1439    #[test]
1440    fn only_exact_zero_disables_fresh_tail() {
1441        assert!(ann_fresh_tail_enabled_from_value(None));
1442        assert!(!ann_fresh_tail_enabled_from_value(Some("0")));
1443        assert!(ann_fresh_tail_enabled_from_value(Some("1")));
1444        assert!(ann_fresh_tail_enabled_from_value(Some("false")));
1445        assert!(ann_fresh_tail_enabled_from_value(Some(" 0")));
1446    }
1447}
1448
1449#[cfg(test)]
1450mod configured_embedding_models_order_tests {
1451    use super::*;
1452
1453    /// Issue #1115: the configured engine list must preserve declaration
1454    /// order (primary first, then `additional_embedding_models` in order)
1455    /// instead of alphabetizing — any consumer that treats the list as
1456    /// ordered (e.g. recall fan-out) otherwise gets the wrong primary.
1457    #[test]
1458    fn preserves_primary_first_then_additional_in_declared_order() {
1459        let config = RuntimeConfig {
1460            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1461            additional_embedding_models: vec![
1462                EmbeddingModel::Qwen3Embedding4B,
1463                EmbeddingModel::BgeSmallEnV15,
1464            ],
1465            ..RuntimeConfig::default()
1466        };
1467
1468        assert_eq!(
1469            configured_embedding_models(&config),
1470            vec![
1471                EmbeddingModel::AllMiniLmL6V2,
1472                EmbeddingModel::Qwen3Embedding4B,
1473                EmbeddingModel::BgeSmallEnV15,
1474            ],
1475            "order must be primary-first, then additional models as declared, \
1476             not alphabetized"
1477        );
1478    }
1479
1480    /// A model repeated in both `embedding_model` and `additional_embedding_models`
1481    /// must be deduped to a single entry, keeping its first (primary) position.
1482    #[test]
1483    fn dedupes_model_shared_between_primary_and_additional() {
1484        let config = RuntimeConfig {
1485            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1486            additional_embedding_models: vec![
1487                EmbeddingModel::AllMiniLmL6V2,
1488                EmbeddingModel::BgeSmallEnV15,
1489            ],
1490            ..RuntimeConfig::default()
1491        };
1492
1493        assert_eq!(
1494            configured_embedding_models(&config),
1495            vec![EmbeddingModel::AllMiniLmL6V2, EmbeddingModel::BgeSmallEnV15],
1496            "the shared model must appear once, in its primary position"
1497        );
1498    }
1499}