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