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;
6use khive_gate::{ActorRef, AllowAllGate, GateRef};
7use khive_types::Namespace;
8use lattice_embed::EmbeddingModel;
9
10use crate::error::RuntimeResult;
11
12// ---- BackendId ----
13
14/// Identifies a named backend in a multi-backend deployment.
15///
16/// The `main` backend is the default single-backend name. Multi-backend deployments
17/// assign each `[[backends]]` entry a distinct `BackendId`. The
18/// `SubstrateCoordinator` in `kkernel`
19/// uses `BackendId` for node-to-backend resolution and cross-backend edge routing.
20///
21/// A single-backend `KhiveRuntime` always has `BackendId("main")` by default.
22/// The boot path in `kkernel` or `khive-mcp` sets the id via `RuntimeConfig::backend_id`
23/// when constructing per-pack runtimes.
24#[derive(Clone, Debug, PartialEq, Eq, Hash)]
25pub struct BackendId(pub String);
26
27impl BackendId {
28    /// The default single-backend name.
29    pub const MAIN: &'static str = "main";
30
31    /// Construct from a string name.
32    pub fn new(name: impl Into<String>) -> Self {
33        Self(name.into())
34    }
35
36    /// The default `main` backend id.
37    pub fn main() -> Self {
38        Self(Self::MAIN.to_string())
39    }
40
41    /// Return the backend name as a `&str`.
42    pub fn as_str(&self) -> &str {
43        &self.0
44    }
45}
46
47impl std::fmt::Display for BackendId {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.write_str(&self.0)
50    }
51}
52
53// ---- Sealed token ----
54
55mod private {
56    #[derive(Clone, Debug)]
57    pub(crate) struct Sealed;
58}
59
60/// Authorization proof that a caller is permitted to access a specific namespace.
61///
62/// Created by [`crate::VerbRegistry::dispatch`] after the gate approves the request.
63/// The sealed inner field prevents external code from constructing a token
64/// without going through the authorization path.
65///
66/// The `namespace` field is the **write namespace**: all records created via
67/// this token land in that namespace. `visible` is the **read visibility set**:
68/// list/search/get operations will return records from any namespace in this
69/// set. The write namespace is always a member of the visible set.
70///
71/// Single-namespace behaviour (backward-compatible default): `visible` contains
72/// exactly `[namespace]` — identical to the old strict-equality checks.
73#[derive(Clone, Debug)]
74pub struct NamespaceToken {
75    namespace: Namespace,
76    visible: Vec<Namespace>,
77    actor: ActorRef,
78    _sealed: private::Sealed,
79}
80
81impl NamespaceToken {
82    /// Mint an authorized token with an extended visibility set.
83    ///
84    /// `extra_visible` lists namespaces beyond the primary that the token may
85    /// read. The primary namespace is always included in the visible set
86    /// regardless of what `extra_visible` contains. Duplicates are removed.
87    pub(crate) fn mint_with_visibility(
88        namespace: Namespace,
89        extra_visible: Vec<Namespace>,
90        actor: ActorRef,
91    ) -> Self {
92        let mut visible = vec![namespace.clone()];
93        for ns in extra_visible {
94            if !visible.contains(&ns) {
95                visible.push(ns);
96            }
97        }
98        debug_assert!(!visible.is_empty(), "visible set must be non-empty");
99        Self {
100            namespace,
101            visible,
102            actor,
103            _sealed: private::Sealed,
104        }
105    }
106
107    /// Mint an authorized token. Only callable from within `khive-runtime`.
108    ///
109    /// The visible set defaults to `[namespace]` — backward-compatible with
110    /// single-namespace enforcement.
111    pub(crate) fn mint_authorized(namespace: Namespace, actor: ActorRef) -> Self {
112        Self::mint_with_visibility(namespace, vec![], actor)
113    }
114
115    /// Convenience constructor for the local namespace with an anonymous actor.
116    ///
117    /// Only callable from within `khive-runtime`. External callers must use
118    /// [`KhiveRuntime::authorize`] to mint tokens.
119    // Used only in #[cfg(test)] blocks within this crate's src/ files.
120    #[allow(dead_code)]
121    pub(crate) fn local() -> Self {
122        Self::mint_authorized(Namespace::local(), ActorRef::anonymous())
123    }
124
125    /// Convenience constructor for a specific namespace with an anonymous actor.
126    ///
127    /// Only callable from within `khive-runtime`. External callers must use
128    /// [`KhiveRuntime::authorize`] to mint tokens.
129    // Used only in #[cfg(test)] blocks within this crate's src/ files.
130    #[allow(dead_code)]
131    pub(crate) fn for_namespace(ns: Namespace) -> Self {
132        Self::mint_authorized(ns, ActorRef::anonymous())
133    }
134
135    /// Return the write namespace this token authorises.
136    ///
137    /// All records created via this token land in this namespace.
138    pub fn namespace(&self) -> &Namespace {
139        &self.namespace
140    }
141
142    /// Return the read-visibility set.
143    ///
144    /// List, search, and get operations must accept records whose namespace is
145    /// a member of this set. The write namespace is always included.
146    pub fn visible_namespaces(&self) -> &[Namespace] {
147        &self.visible
148    }
149
150    /// Return a deduplicated list of visible namespace strings (borrowed).
151    ///
152    /// Convenience for passing directly to storage layer filters.
153    pub fn visible_namespace_strs(&self) -> Vec<&str> {
154        self.visible.iter().map(|ns| ns.as_str()).collect()
155    }
156
157    /// Return the actor reference embedded in this token.
158    pub fn actor(&self) -> &ActorRef {
159        &self.actor
160    }
161
162    /// Return a new token with the same actor but a different namespace.
163    ///
164    /// The visible set is replaced with `[ns]`: this is a full read+write token
165    /// for `ns`, not a type-enforced write-only or append-only capability. It is
166    /// a capability-transfer primitive, not a policy gate: callers must enforce
167    /// any ACL check before calling this and use the minted token only within
168    /// the intended narrow scope (e.g. a single `create_note` call). A future
169    /// security model should replace this pattern with a type-enforced
170    /// append-only capability that goes through the Gate.
171    pub fn with_namespace(&self, ns: Namespace) -> Self {
172        Self::mint_authorized(ns, self.actor.clone())
173    }
174}
175
176// ---- RuntimeConfig ----
177
178/// Runtime configuration.
179///
180/// The `db_path` and `embedding_model` fields are deprecated in favour of
181/// constructing the backend externally and calling [`crate::KhiveRuntime::from_backend`].
182/// They remain for backward compatibility with tests and single-binary deployments.
183#[derive(Clone, Debug)]
184pub struct RuntimeConfig {
185    /// Path to the SQLite database file. `None` = in-memory (tests).
186    ///
187    /// Deprecated: use [`crate::KhiveRuntime::from_backend`] instead. The boot path
188    /// constructs backends from `khive.toml` (`AppConfig`) and passes them to
189    /// `from_backend`. Direct `db_path` usage persists only in tests.
190    pub db_path: Option<std::path::PathBuf>,
191    /// Namespace used when no explicit namespace is provided.
192    pub default_namespace: Namespace,
193    /// Local embedding model. `None` alone does not disable embedding: setting
194    /// only this field to `None` while `additional_embedding_models` is
195    /// non-empty still registers those models. Both `embedding_model` and
196    /// `additional_embedding_models` must be empty to disable built-in
197    /// embedding model registration, at which point `hybrid_search` falls back
198    /// to text-only. Use [`RuntimeConfig::no_embeddings`] to clear both fields
199    /// together — it is the canonical constructor for this. Custom embedder
200    /// providers registered later by packs are not affected by this field.
201    ///
202    /// Deprecated: embedding engines move to a per-pack `EmbedderRegistry`.
203    /// This field persists for backward compatibility until the embedder registry
204    /// is fully plumbed.
205    pub embedding_model: Option<EmbeddingModel>,
206    /// Additional embedding models to make available by request name.
207    ///
208    /// `embedding_model` remains the default used by existing `embed()` and
209    /// `embed_batch()` callers. This list adds non-default models that can be
210    /// selected with `embedder(name)`, `embed_with_model(...)`, memory
211    /// `remember.embedding_model`, and memory `recall.embedding_model`.
212    pub additional_embedding_models: Vec<EmbeddingModel>,
213    /// Authorization gate consulted before each verb dispatch.
214    /// Default: `AllowAllGate` (permissive). For production policy enforcement,
215    /// plug in a Rego- or capability-witness-backed impl.
216    pub gate: GateRef,
217    /// Names of packs the transport layer should register into the VerbRegistry.
218    /// The transport layer (e.g. `khive-mcp`) reads this list and instantiates
219    /// the matching concrete pack types. Unknown names are reported as errors
220    /// by the transport, not silently ignored.
221    /// Default: `["kg"]`.
222    pub packs: Vec<String>,
223    /// Identifies this runtime's backend in a multi-backend deployment.
224    ///
225    /// Set by the boot path when constructing per-pack runtimes from `khive.toml`.
226    /// Single-backend deployments use the default `BackendId::MAIN`.
227    pub backend_id: BackendId,
228    /// Brain profile to use for `memory.feedback` / `knowledge.feedback` and
229    /// recall-time score boosting (ADR-035 §Brain profile configuration).
230    ///
231    /// Resolution order (highest to lowest, ADR-035): CLI flag, then
232    /// `runtime.brain_profile` in project/global `khive.toml`, then the
233    /// `KHIVE_BRAIN_PROFILE` env var as fallback default. Callers must keep
234    /// env OUT of the base config they pass in (see `khive-mcp` serve.rs).
235    /// 1. `--brain-profile` CLI flag (explicit only)
236    /// 2. Namespace-bound profile resolved via `brain.resolve` at feedback time
237    /// 3. Pack-local global tuning prior (default fallback)
238    pub brain_profile: Option<String>,
239    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
240    ///
241    /// OSS dispatch widens the DEFAULT multi-record read scope to
242    /// `['local'] ∪ visible_namespaces`. Writes remain pinned to `'local'`.
243    /// An explicit `namespace=` request param is a precise single-namespace
244    /// escape and is not widened. Populated from `actor.visible_namespaces`
245    /// in `khive.toml`.
246    pub visible_namespaces: Vec<Namespace>,
247    /// Namespaces this actor's comm.send/reply may deliver messages INTO
248    /// (outbound, sender-side). Populated from `actor.allowed_outbound_namespaces`
249    /// in `khive.toml`. Empty by default — cross-namespace delivery denied
250    /// unless explicitly declared. The comm handler uses an ordinary
251    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
252    /// the token itself is NOT type-enforced write-only. The recipient-side
253    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
254    /// a future cloud-path authorization ADR (not yet written).
255    pub allowed_outbound_namespaces: Vec<Namespace>,
256    /// Configured actor identity label (ADR-057). Populated from `[actor] id` in
257    /// `khive.toml`. When `Some`, `authorize()` mints tokens carrying this actor
258    /// label so that `comm.inbox` filters by `to_actor` instead of falling back to
259    /// the party-line "local" behavior. When `None` (default), tokens carry
260    /// `ActorRef::anonymous()` and inbox is scoped to party-line messages —
261    /// those addressed to `"local"` or carrying no `to_actor` stamp.
262    pub actor_id: Option<String>,
263}
264
265/// Parse a comma- or whitespace-separated pack list from a single string.
266///
267/// Empty entries are dropped, surrounding whitespace is trimmed.
268pub fn parse_pack_list(s: &str) -> Vec<String> {
269    s.split(|c: char| c == ',' || c.is_whitespace())
270        .map(str::trim)
271        .filter(|s| !s.is_empty())
272        .map(str::to_owned)
273        .collect()
274}
275
276impl Default for RuntimeConfig {
277    fn default() -> Self {
278        let db_path = std::env::var("HOME")
279            .ok()
280            .map(|h| std::path::PathBuf::from(h).join(".khive/khive.db"));
281        let embedding_model = std::env::var("KHIVE_EMBEDDING_MODEL")
282            .ok()
283            .and_then(|s| s.parse().ok())
284            .or(Some(EmbeddingModel::AllMiniLmL6V2));
285        let additional_embedding_models = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
286            .ok()
287            .map(|s| parse_embedding_model_list(&s))
288            .unwrap_or_else(|| vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]);
289        let packs = std::env::var("KHIVE_PACKS")
290            .ok()
291            .map(|s| parse_pack_list(&s))
292            .filter(|v| !v.is_empty())
293            .unwrap_or_else(|| {
294                vec![
295                    "kg",
296                    "gtd",
297                    "memory",
298                    "brain",
299                    "comm",
300                    "schedule",
301                    "knowledge",
302                    "session",
303                    "git",
304                    "code",
305                    "workspace",
306                ]
307                .into_iter()
308                .map(String::from)
309                .collect()
310            });
311        let brain_profile = std::env::var("KHIVE_BRAIN_PROFILE")
312            .ok()
313            .filter(|s| !s.trim().is_empty());
314        let actor_id = std::env::var("KHIVE_ACTOR")
315            .ok()
316            .filter(|s| !s.trim().is_empty());
317        Self {
318            db_path,
319            default_namespace: Namespace::local(),
320            embedding_model,
321            additional_embedding_models,
322            gate: Arc::new(AllowAllGate),
323            packs,
324            backend_id: BackendId::main(),
325            brain_profile,
326            visible_namespaces: vec![],
327            allowed_outbound_namespaces: vec![],
328            actor_id,
329        }
330    }
331}
332
333impl RuntimeConfig {
334    /// Build a `RuntimeConfig` with embedding disabled entirely.
335    ///
336    /// `embedding_model` and `additional_embedding_models` are computed
337    /// independently inside [`Default::default`], so `RuntimeConfig {
338    /// embedding_model: None, ..RuntimeConfig::default() }` does NOT produce a
339    /// model-less runtime: `additional_embedding_models` still carries its
340    /// env-driven fallback seed, and the note-write path fans out embedding to
341    /// every registered model regardless of `embedding_model`: so the first
342    /// `memory.remember` on a machine without local model files hard-fails
343    /// instead of degrading to FTS-only.
344    ///
345    /// This constructor clears both fields together and ignores
346    /// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` unconditionally: the caller wants
347    /// zero embedders, not "zero unless the environment disagrees". Use it on
348    /// model-less machines (CI runners, fresh installs without local model
349    /// files) instead of the two-field struct-update form.
350    pub fn no_embeddings() -> Self {
351        Self {
352            embedding_model: None,
353            additional_embedding_models: Vec::new(),
354            ..Self::default()
355        }
356    }
357}
358
359/// Resolve the `--db`/`KHIVE_DB` value into the anchor path used for tier-3
360/// project-local `.khive/config.toml` discovery, mirroring the precedence
361/// `kkernel mcp` and `kkernel exec` use to open the database itself:
362/// `:memory:` has no file to anchor on (`None`); an explicit path anchors on
363/// that path; an unset value falls back to `$HOME/.khive/khive.db`, or
364/// `./.khive/khive.db` when `HOME` is unset.
365///
366/// Always resolves to a concrete anchor (unlike a 2-arm "override the
367/// default?" resolver): when `HOME` is unset this falls back to
368/// `./.khive/khive.db` rather than `None`, deliberately diverging from
369/// `RuntimeConfig::default()`: a caller anchoring config discovery needs a
370/// concrete directory to search even without `HOME`.
371pub fn resolve_db_anchor(db: Option<&str>) -> Option<std::path::PathBuf> {
372    match db {
373        Some(":memory:") => None,
374        Some(path) => Some(std::path::PathBuf::from(path)),
375        None => {
376            let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
377            Some(std::path::PathBuf::from(format!("{home}/.khive/khive.db")))
378        }
379    }
380}
381
382/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
383/// process's `config_id`: agrees with what [`resolve_db_anchor`] derives from
384/// the same `--db`/`KHIVE_DB` input. Call this right after `db_path` is
385/// resolved at each construction boundary.
386///
387/// Guards against a construction path recomputing `db_path` independently of
388/// `resolve_db_anchor`: left unchecked, that would silently desync
389/// `config_id` from a daemon or peer sharing the same database instead of
390/// failing loud. Inert (`Ok(())`) when the anchor itself is `None` (the
391/// `:memory:` sentinel) since there is nothing to compare against.
392pub fn assert_db_anchor_consistent(
393    resolved_db_path: Option<&std::path::Path>,
394    args_db: Option<&str>,
395) -> anyhow::Result<()> {
396    let Some(anchor) = resolve_db_anchor(args_db) else {
397        return Ok(());
398    };
399    if resolved_db_path != Some(anchor.as_path()) {
400        anyhow::bail!(
401            "db-path resolution drift at server construction: resolved db_path {:?} \
402             does not match the canonical anchor {:?} computed by resolve_db_anchor \
403             from the same --db input; this construction path likely recomputed the \
404             db path independently instead of routing through the shared resolver, \
405             which would desynchronize config_id from other processes sharing the \
406             same database",
407            resolved_db_path,
408            anchor
409        );
410    }
411    Ok(())
412}
413
414/// Resolve the per-connection attribution actor from the project/cwd-anchored
415/// config tier, independently of the database-anchored config load that
416/// governs `config_id`.
417///
418/// The database-anchored config load keeps `config_id` coherent between a
419/// short-lived client and a long-running daemon sharing one database, but
420/// when many per-project connections share one database under a single
421/// `HOME` (the daemon-multiplexed fleet case), that shared config carries no
422/// `[actor]` block, so every connection's write-stamp attribution collapses
423/// to the default identity.
424///
425/// This performs a separate, cwd-anchored lookup (`db_path: None`) and reads
426/// only `[actor].id`: it must not perturb `config_id` or `default_namespace`,
427/// which remain governed exclusively by the database-anchored load.
428///
429/// `config_path` is the same explicit `--config`/`KHIVE_CONFIG` override the
430/// caller's database-anchored load receives, so an explicit override wins
431/// here too.
432///
433/// Returns `Ok(None)` when no project-anchored config exists, or it exists
434/// but carries no non-empty `[actor].id`: callers fall through to their own
435/// env/anonymous tiers in that case.
436pub fn resolve_project_actor_id(
437    config_path: Option<&std::path::Path>,
438) -> Result<Option<String>, crate::engine_config::ConfigError> {
439    let khive_cfg = crate::engine_config::KhiveConfig::load_with_home_fallback(config_path, None)?;
440    Ok(khive_cfg
441        .and_then(|cfg| cfg.actor.id)
442        .filter(|s| !s.trim().is_empty()))
443}
444
445// ---- Embedding model helpers ----
446
447/// Sanitize an embedding model name into a valid SQL table suffix.
448/// e.g. `bge-small-en-v1.5` -> `bge_small_en_v1_5`
449pub(crate) fn vec_model_key(model: EmbeddingModel) -> String {
450    sanitize_key(&model.to_string())
451}
452
453pub(crate) fn sanitize_key(s: &str) -> String {
454    s.chars()
455        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
456        .collect()
457}
458
459pub(crate) fn build_embedder_registry(
460    config: &RuntimeConfig,
461) -> (crate::embedder_registry::EmbedderRegistry, Arc<str>) {
462    use crate::embedder_registry::{EmbedderRegistry, LatticeEmbedderProvider};
463    let mut registry = EmbedderRegistry::new();
464    for model in configured_embedding_models(config) {
465        registry.register(LatticeEmbedderProvider::new(model));
466    }
467    let default_embedder_name = config
468        .embedding_model
469        .map(|model| Arc::<str>::from(model.to_string()))
470        .unwrap_or_else(|| Arc::<str>::from(""));
471    (registry, default_embedder_name)
472}
473
474fn configured_embedding_models(config: &RuntimeConfig) -> Vec<EmbeddingModel> {
475    let mut models = Vec::new();
476    if let Some(model) = config.embedding_model {
477        models.push(model);
478    }
479    models.extend(config.additional_embedding_models.iter().copied());
480    models.sort_by_key(|model| model.to_string());
481    models.dedup();
482    models
483}
484
485pub(crate) fn register_configured_embedding_models(
486    backend: &StorageBackend,
487    config: &RuntimeConfig,
488) -> RuntimeResult<()> {
489    for model in configured_embedding_models(config) {
490        backend.register_embedding_model(
491            &model.to_string(),
492            model.model_id(),
493            model.key_version(),
494            model.dimensions() as u32,
495        )?;
496    }
497    Ok(())
498}
499
500/// Build a `RuntimeConfig` from a parsed `KhiveConfig`.
501///
502/// For each `[[engines]]` entry:
503/// - The engine flagged `default = true` becomes `RuntimeConfig::embedding_model`.
504/// - All other engines become `RuntimeConfig::additional_embedding_models`.
505///
506/// Model name validity is checked here: any engine whose `model` field cannot
507/// be parsed via `parse_embedding_model_alias` is skipped with a warning.
508///
509/// If `khive_cfg.engines` is empty, the returned `RuntimeConfig` uses the
510/// env-var-derived defaults from `RuntimeConfig::default()`.
511///
512/// When both a config file and `KHIVE_EMBEDDING_MODEL` env var are present,
513/// the caller is responsible for emitting a warning that env vars are overridden.
514/// This function purely converts `KhiveConfig` to `RuntimeConfig` fields.
515pub fn runtime_config_from_khive_config(
516    khive_cfg: &crate::engine_config::KhiveConfig,
517    base: RuntimeConfig,
518) -> RuntimeConfig {
519    // `[actor] id` never becomes the storage namespace (writes always pin to
520    // `local`); it only widens the read visible-set below.
521    let default_namespace = base.default_namespace.clone();
522
523    // base.brain_profile must carry only the explicit CLI tier, never an env
524    // value: env sits below toml in precedence and is applied later by the MCP resolver.
525    let brain_profile = base.brain_profile.clone().or_else(|| {
526        khive_cfg
527            .runtime
528            .brain_profile
529            .clone()
530            .filter(|s| !s.trim().is_empty())
531    });
532
533    let visible_namespaces: Vec<Namespace> = khive_cfg
534        .actor
535        .visible_namespaces
536        .as_deref()
537        .unwrap_or_default()
538        .iter()
539        .filter_map(|s| match Namespace::parse(s) {
540            Ok(ns) => Some(ns),
541            Err(e) => {
542                tracing::warn!(ns = %s, error = %e, "actor.visible_namespaces: invalid namespace; skipped");
543                None
544            }
545        })
546        .collect();
547
548    // Fold actor.id's namespace into visible_namespaces so default reads widen
549    // to {local} ∪ {actor namespace}; skipped when it parses to `local` (would
550    // duplicate the primary namespace already minted) or is already present.
551    let visible_namespaces = if let Some(id) = khive_cfg.actor.id.as_deref() {
552        match Namespace::parse(id) {
553            Ok(actor_ns) if actor_ns != Namespace::local() => {
554                let mut v = visible_namespaces;
555                if !v.contains(&actor_ns) {
556                    v.push(actor_ns);
557                }
558                v
559            }
560            _ => visible_namespaces,
561        }
562    } else {
563        visible_namespaces
564    };
565
566    // KhiveConfig::validate() guarantees these are valid Namespace strings, so
567    // parse failures here are unreachable for validated configs; filter_map+warn
568    // guards against a validation bug panicking instead.
569    let allowed_outbound_namespaces: Vec<Namespace> = khive_cfg
570        .actor
571        .allowed_outbound_namespaces
572        .iter()
573        .filter_map(|s| match Namespace::parse(s) {
574            Ok(ns) => Some(ns),
575            Err(e) => {
576                tracing::warn!(ns = %s, error = %e, "actor.allowed_outbound_namespaces: invalid namespace; skipped");
577                None
578            }
579        })
580        .collect();
581
582    // Precedence: TOML `[actor] id` > `base.actor_id` (env/CLI-resolved) >
583    // anonymous. Falls back to `base.actor_id` rather than `None` when
584    // `[actor] id` is absent: otherwise an env-resolved actor like
585    // `KHIVE_ACTOR` is silently dropped whenever a project config exists
586    // without an `[actor]` block.
587    let actor_id = khive_cfg
588        .actor
589        .id
590        .clone()
591        .filter(|s| !s.trim().is_empty())
592        .or_else(|| base.actor_id.clone());
593
594    if khive_cfg.engines.is_empty() {
595        return RuntimeConfig {
596            default_namespace,
597            brain_profile,
598            visible_namespaces,
599            allowed_outbound_namespaces,
600            actor_id,
601            ..base
602        };
603    }
604
605    let mut embedding_model: Option<EmbeddingModel> = None;
606    let mut additional: Vec<EmbeddingModel> = Vec::new();
607
608    for engine in &khive_cfg.engines {
609        match parse_embedding_model_alias(&engine.model) {
610            Some(model) => {
611                if engine.default {
612                    embedding_model = Some(model);
613                } else {
614                    additional.push(model);
615                }
616            }
617            None => {
618                tracing::warn!(
619                    engine = %engine.name,
620                    model = %engine.model,
621                    "engine config: unknown model name; engine will be skipped"
622                );
623            }
624        }
625    }
626
627    RuntimeConfig {
628        embedding_model,
629        additional_embedding_models: additional,
630        default_namespace,
631        brain_profile,
632        visible_namespaces,
633        allowed_outbound_namespaces,
634        actor_id,
635        ..base
636    }
637}
638
639/// Parse a comma- or whitespace-separated list of embedding model names.
640fn parse_embedding_model_list(s: &str) -> Vec<EmbeddingModel> {
641    parse_pack_list(s)
642        .into_iter()
643        .filter_map(|raw| {
644            let parsed = parse_embedding_model_alias(&raw);
645            if parsed.is_none() && !raw.trim().is_empty() {
646                tracing::warn!(
647                    model = %raw,
648                    "KHIVE_ADDITIONAL_EMBEDDING_MODELS contains unknown model name; ignored. \
649                     Valid forms: short alias like 'paraphrase' or a fully-qualified key \
650                     from lattice_embed::EmbeddingModel::from_str."
651                );
652            }
653            parsed
654        })
655        .collect()
656}
657
658pub(crate) fn parse_embedding_model_alias(name: &str) -> Option<EmbeddingModel> {
659    let normalized = name.trim().to_ascii_lowercase().replace('_', "-");
660    match normalized.as_str() {
661        "paraphrase" => Some(EmbeddingModel::ParaphraseMultilingualMiniLmL12V2),
662        _ => normalized.parse().ok(),
663    }
664}
665
666#[cfg(test)]
667mod resolve_db_anchor_tests {
668    use super::resolve_db_anchor;
669
670    #[test]
671    fn memory_sentinel_maps_to_none() {
672        assert_eq!(resolve_db_anchor(Some(":memory:")), None);
673    }
674
675    #[test]
676    fn explicit_path_maps_to_some() {
677        assert_eq!(
678            resolve_db_anchor(Some("/tmp/khive-anchor-test.db")),
679            Some(std::path::PathBuf::from("/tmp/khive-anchor-test.db"))
680        );
681    }
682
683    #[test]
684    fn absent_maps_to_home_default() {
685        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
686        let expected = std::path::PathBuf::from(format!("{home}/.khive/khive.db"));
687        assert_eq!(resolve_db_anchor(None), Some(expected));
688    }
689}
690
691#[cfg(test)]
692mod assert_db_anchor_consistent_tests {
693    use super::{assert_db_anchor_consistent, resolve_db_anchor};
694
695    #[test]
696    fn diverging_db_path_is_rejected_naming_both_paths() {
697        let args_db = "/tmp/khive-anchor-guard-real.db";
698        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
699        let wrong = std::path::PathBuf::from("/tmp/khive-anchor-guard-wrong.db");
700
701        let err = assert_db_anchor_consistent(Some(wrong.as_path()), Some(args_db))
702            .expect_err("a resolved db_path diverging from the anchor must be rejected");
703
704        let msg = err.to_string();
705        assert!(
706            msg.contains(&wrong.display().to_string()),
707            "error must name the resolved (wrong) path: {msg}"
708        );
709        assert!(
710            msg.contains(&anchor.display().to_string()),
711            "error must name the canonical anchor path: {msg}"
712        );
713    }
714
715    #[test]
716    fn matching_explicit_db_path_passes() {
717        let args_db = "/tmp/khive-anchor-guard-consistent.db";
718        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
719        assert!(assert_db_anchor_consistent(Some(anchor.as_path()), Some(args_db)).is_ok());
720    }
721
722    #[test]
723    fn memory_sentinel_anchor_is_inert() {
724        // `resolve_db_anchor(":memory:")` yields `None` — there is no canonical
725        // path to assert against, so the guard passes regardless of what
726        // `resolved_db_path` happens to carry.
727        let bogus = std::path::PathBuf::from("/tmp/should-not-matter.db");
728        assert!(assert_db_anchor_consistent(Some(bogus.as_path()), Some(":memory:")).is_ok());
729        assert!(assert_db_anchor_consistent(None, Some(":memory:")).is_ok());
730    }
731
732    #[test]
733    fn normal_boot_with_db_unset_passes_silently() {
734        // Mirrors a normal boot with `--db` unset: `resolve_db_anchor(None)`
735        // always resolves to `Some(..)` (HOME-set or -unset both produce a
736        // concrete anchor), so a runtime whose resolved `db_path` matches
737        // passes silently.
738        let anchor = resolve_db_anchor(None);
739        assert!(assert_db_anchor_consistent(anchor.as_deref(), None).is_ok());
740    }
741}
742
743#[cfg(test)]
744mod resolve_project_actor_id_tests {
745    use super::resolve_project_actor_id;
746
747    fn write_toml(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
748        let path = dir.path().join("config.toml");
749        std::fs::write(&path, body).expect("write config.toml");
750        path
751    }
752
753    #[test]
754    fn extracts_non_empty_actor_id_from_explicit_path() {
755        let dir = tempfile::tempdir().expect("tempdir");
756        let path = write_toml(&dir, "[actor]\nid = \"lambda:explicit-actor\"\n");
757
758        assert_eq!(
759            resolve_project_actor_id(Some(&path)).expect("no error"),
760            Some("lambda:explicit-actor".to_string())
761        );
762    }
763
764    #[test]
765    fn returns_none_for_missing_explicit_path() {
766        let missing = std::path::PathBuf::from("/nonexistent/khive-project-actor-test/config.toml");
767        assert_eq!(
768            resolve_project_actor_id(Some(&missing)).expect("no error"),
769            None,
770            "a nonexistent explicit path must resolve to None, not an error"
771        );
772    }
773
774    #[test]
775    fn propagates_load_error_for_invalid_actor_id() {
776        // `KhiveConfig::load`'s `validate()` rejects an empty `[actor] id` before
777        // the emptiness filter in `resolve_project_actor_id` ever sees it; this
778        // asserts the error surfaces rather than being swallowed into `Ok(None)`.
779        let dir = tempfile::tempdir().expect("tempdir");
780        let path = write_toml(&dir, "[actor]\nid = \"\"\n");
781
782        let err = resolve_project_actor_id(Some(&path)).expect_err("invalid actor.id must error");
783        assert!(
784            matches!(
785                err,
786                crate::engine_config::ConfigError::InvalidActorId { .. }
787            ),
788            "expected InvalidActorId, got {err:?}"
789        );
790    }
791
792    #[test]
793    fn returns_none_when_config_has_no_actor_section() {
794        let dir = tempfile::tempdir().expect("tempdir");
795        let path = write_toml(
796            &dir,
797            "[[engines]]\nname = \"primary\"\nmodel = \"bge-small-en-v1.5\"\ndefault = true\n",
798        );
799
800        assert_eq!(
801            resolve_project_actor_id(Some(&path)).expect("no error"),
802            None,
803            "a config file with no [actor] section must resolve to None"
804        );
805    }
806}
807
808#[cfg(test)]
809mod no_embeddings_tests {
810    use super::*;
811    use serial_test::serial;
812
813    #[test]
814    fn no_embeddings_clears_both_fields() {
815        let config = RuntimeConfig::no_embeddings();
816        assert_eq!(config.embedding_model, None);
817        assert!(config.additional_embedding_models.is_empty());
818        assert!(
819            configured_embedding_models(&config).is_empty(),
820            "no_embeddings() must yield zero configured embedders"
821        );
822    }
823
824    #[test]
825    #[serial]
826    fn no_embeddings_ignores_additional_env_override() {
827        // no_embeddings() is an unconditional opt-out: even if the caller's
828        // environment sets KHIVE_ADDITIONAL_EMBEDDING_MODELS, the resulting
829        // config must still report zero embedders.
830        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
831        let config = RuntimeConfig::no_embeddings();
832        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
833
834        assert!(config.additional_embedding_models.is_empty());
835        assert!(configured_embedding_models(&config).is_empty());
836    }
837
838    #[test]
839    #[serial]
840    fn default_still_seeds_additional_models_when_env_unset() {
841        // `Default` must keep computing `embedding_model` and
842        // `additional_embedding_models` independently; `no_embeddings()` is a
843        // separate opt-out constructor, not a change to `Default`'s seeding.
844        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
845        let config = RuntimeConfig::default();
846
847        assert_eq!(
848            config.additional_embedding_models,
849            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
850        );
851
852        // Overriding only `embedding_model` via struct-update syntax does not
853        // clear `additional_embedding_models`.
854        let buggy_form = RuntimeConfig {
855            embedding_model: None,
856            ..RuntimeConfig::default()
857        };
858        assert!(
859            !buggy_form.additional_embedding_models.is_empty(),
860            "Default's independent-field seeding must remain unchanged; \
861             no_embeddings() is the fix, not a change to Default"
862        );
863    }
864}