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