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` field remains for backward compatibility and as input to the
213/// supported async khive-mcp/kkernel host builders. Direct backend assembly is
214/// reserved for an already-coordinated database; use
215/// [`crate::KhiveRuntime::from_prepared_backend`] when that precondition has
216/// been established. `embedding_model` remains as the primary-model config
217/// shorthand beside the provider registry.
218#[derive(Clone, Debug)]
219pub struct RuntimeConfig {
220 /// Path to the SQLite database file. `None` = in-memory (tests).
221 ///
222 /// Production boot passes this value to the async khive-mcp/kkernel host
223 /// builders, which coordinate V21 before constructing runtimes. Tests and
224 /// already-current single-backend callers may still use it directly.
225 pub db_path: Option<std::path::PathBuf>,
226 /// Namespace used when no explicit namespace is provided.
227 pub default_namespace: Namespace,
228 /// Local embedding model. `None` alone does not disable embedding: setting
229 /// only this field to `None` while `additional_embedding_models` is
230 /// non-empty still registers those models. Both `embedding_model` and
231 /// `additional_embedding_models` must be empty to disable built-in
232 /// embedding model registration, at which point `hybrid_search` falls back
233 /// to text-only. Use [`RuntimeConfig::no_embeddings`] to clear both fields
234 /// together — it is the canonical constructor for this. Custom embedder
235 /// providers registered later by packs are not affected by this field.
236 ///
237 /// Deprecated: embedding engines move to a per-pack `EmbedderRegistry`.
238 /// This field persists for backward compatibility until the embedder registry
239 /// is fully plumbed.
240 pub embedding_model: Option<EmbeddingModel>,
241 /// Additional embedding models to make available by request name.
242 ///
243 /// `embedding_model` remains the default used by existing `embed()` and
244 /// `embed_batch()` callers. This list adds non-default models that can be
245 /// selected with `embedder(name)`, `embed_with_model(...)`, memory
246 /// `remember.embedding_model`, and memory `recall.embedding_model`.
247 pub additional_embedding_models: Vec<EmbeddingModel>,
248 /// Authorization gate consulted before each verb dispatch.
249 /// Default: `AllowAllGate` (permissive). For production policy enforcement,
250 /// plug in a Rego- or capability-witness-backed impl.
251 pub gate: GateRef,
252 /// Names of packs the transport layer should register into the VerbRegistry.
253 /// The transport layer (e.g. `khive-mcp`) reads this list and instantiates
254 /// the matching concrete pack types. Unknown names are reported as errors
255 /// by the transport, not silently ignored.
256 /// Defaults to the shipped production set returned by
257 /// [`RuntimeConfig::built_in_packs`].
258 pub packs: Vec<String>,
259 /// Resolved aggregate admission budget for resident digest-verified blob
260 /// buffers (ADR-160 D3), in raw bytes.
261 ///
262 /// `[runtime].blob_hydration_bytes` may raise or lower the built-in 256 MiB
263 /// value, but config validation guarantees enough room for one maximum-size
264 /// whole-blob read.
265 pub blob_hydration_bytes: u64,
266 /// Identifies this runtime's backend in a multi-backend deployment.
267 ///
268 /// Set by the boot path when constructing per-pack runtimes from `khive.toml`.
269 /// Single-backend deployments use the default `BackendId::MAIN`.
270 pub backend_id: BackendId,
271 /// Brain profile to use for `memory.feedback` / `knowledge.feedback` and
272 /// recall-time score boosting (ADR-035 §Brain profile configuration).
273 ///
274 /// Resolution order (highest to lowest, ADR-035): CLI flag, then
275 /// `runtime.brain_profile` in project/global `khive.toml`, then the
276 /// `KHIVE_BRAIN_PROFILE` env var as fallback default. Callers must keep
277 /// env OUT of the base config they pass in (see `khive-mcp` serve.rs).
278 /// 1. `--brain-profile` CLI flag (explicit only)
279 /// 2. Namespace-bound profile resolved via `brain.resolve` at feedback time
280 /// 3. Pack-local global tuning prior (default fallback)
281 pub brain_profile: Option<String>,
282 /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
283 ///
284 /// OSS dispatch widens the DEFAULT multi-record read scope to
285 /// `['local'] ∪ visible_namespaces`. Writes remain pinned to `'local'`.
286 /// An explicit `namespace=` request param is a precise single-namespace
287 /// escape and is not widened. Populated from `actor.visible_namespaces`
288 /// in `khive.toml`.
289 pub visible_namespaces: Vec<Namespace>,
290 /// Namespaces this actor's comm.send/reply may deliver messages INTO
291 /// (outbound, sender-side). Populated from `actor.allowed_outbound_namespaces`
292 /// in `khive.toml`. Empty by default — cross-namespace delivery denied
293 /// unless explicitly declared. The comm handler uses an ordinary
294 /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
295 /// the token itself is NOT type-enforced write-only. The recipient-side
296 /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
297 /// a future cloud-path authorization ADR (not yet written).
298 pub allowed_outbound_namespaces: Vec<Namespace>,
299 /// Configured actor identity label (ADR-057). Populated from `[actor] id` in
300 /// `khive.toml`. When `Some`, `authorize()` mints tokens carrying this actor
301 /// label so that `comm.inbox` filters by `to_actor` instead of falling back to
302 /// the party-line "local" behavior. When `None` (default), tokens carry
303 /// `ActorRef::anonymous()` and inbox is scoped to party-line messages —
304 /// those addressed to `"local"` or carrying no `to_actor` stamp.
305 pub actor_id: Option<String>,
306 /// Resolved `[git_write]` policy allowlist (ADR-108 Amendment), populated
307 /// from `khive.toml`'s `[[git_write.allowed]]` entries by
308 /// [`runtime_config_from_khive_config`]. Threaded through so
309 /// `khive-pack-git`'s write-verb handlers read an already-resolved policy
310 /// instead of re-running config discovery (which would ignore an
311 /// explicit `--config` path not also exported as `KHIVE_CONFIG`).
312 pub git_write: crate::engine_config::GitWriteSectionConfig,
313 /// Resolved rendering timezone (ADR-169), consumed today by date-only
314 /// `parse_due` anchoring. Populated from `[display] timezone` in
315 /// `khive.toml` by [`runtime_config_from_khive_config`]; when absent,
316 /// resolves once to the host's local IANA zone (falling back to UTC when
317 /// the host zone cannot be determined) via [`resolve_default_display_timezone`].
318 pub display_timezone: chrono_tz::Tz,
319 /// Events-daemon split (ADR-170). `None` = legacy behavior: events persist
320 /// in the main store. `Some` routes event persistence to the events database —
321 /// forwarded over the events daemon socket in daemon deployments, opened
322 /// directly in embedded/one-shot contexts. Populated by the transport
323 /// hosts (khive-mcp serve, kkernel exec); tests and in-memory runtimes
324 /// leave it `None`.
325 pub events_split: Option<crate::events_split::EventsSplitConfig>,
326}
327
328/// Parse a comma- or whitespace-separated pack list from a single string.
329///
330/// Empty entries are dropped, surrounding whitespace is trimmed.
331pub fn parse_pack_list(s: &str) -> Vec<String> {
332 s.split(|c: char| c == ',' || c.is_whitespace())
333 .map(str::trim)
334 .filter(|s| !s.is_empty())
335 .map(str::to_owned)
336 .collect()
337}
338
339/// Interpret the construction-time `KHIVE_ANN_FRESH_TAIL` value.
340///
341/// Preserve the escape hatch's existing semantics while moving its read out of
342/// request serving: only `0` disables; unset and every other value enable.
343fn ann_fresh_tail_enabled_from_value(value: Option<&str>) -> bool {
344 value != Some("0")
345}
346
347/// Sample ADR-118's fresh-tail escape hatch for runtime construction.
348///
349/// Callers must retain the returned value for the runtime's lifetime instead
350/// of re-reading the environment on a serving path. Only the exact value `0`
351/// disables; unset and every other value enable.
352pub fn ann_fresh_tail_enabled_from_env() -> bool {
353 let value = std::env::var("KHIVE_ANN_FRESH_TAIL").ok();
354 ann_fresh_tail_enabled_from_value(value.as_deref())
355}
356
357/// Resolve the host's local IANA zone name once, for [`RuntimeConfig`]'s
358/// default `display_timezone` (ADR-169). Falls back to UTC when the host
359/// zone cannot be determined (e.g. `TZ`/`/etc/localtime` unreadable) or does
360/// not parse as a known `chrono_tz::Tz` — this must never panic or block
361/// construction of a default `RuntimeConfig`.
362pub fn resolve_default_display_timezone() -> chrono_tz::Tz {
363 iana_time_zone::get_timezone()
364 .ok()
365 .and_then(|name| name.parse::<chrono_tz::Tz>().ok())
366 .unwrap_or(chrono_tz::Tz::UTC)
367}
368
369impl Default for RuntimeConfig {
370 fn default() -> Self {
371 let db_path = std::env::var("HOME")
372 .ok()
373 .map(|h| std::path::PathBuf::from(h).join(".khive/khive.db"));
374 let embedding_model = std::env::var("KHIVE_EMBEDDING_MODEL")
375 .ok()
376 .and_then(|s| s.parse().ok())
377 .or(Some(EmbeddingModel::AllMiniLmL6V2));
378 // Ships single-engine. A second engine is embedded on every write and
379 // searched on every read, which is cost a deployment should opt into
380 // rather than inherit: set KHIVE_ADDITIONAL_EMBEDDING_MODELS to add one.
381 let additional_embedding_models = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
382 .ok()
383 .map(|s| parse_embedding_model_list(&s))
384 .unwrap_or_default();
385 let packs = std::env::var("KHIVE_PACKS")
386 .ok()
387 .map(|s| parse_pack_list(&s))
388 .filter(|v| !v.is_empty())
389 .unwrap_or_else(Self::built_in_packs);
390 let brain_profile = std::env::var("KHIVE_BRAIN_PROFILE")
391 .ok()
392 .filter(|s| !s.trim().is_empty());
393 let actor_id = std::env::var("KHIVE_ACTOR")
394 .ok()
395 .filter(|s| !s.trim().is_empty());
396 Self {
397 db_path,
398 default_namespace: Namespace::local(),
399 embedding_model,
400 additional_embedding_models,
401 gate: Arc::new(AllowAllGate),
402 packs,
403 blob_hydration_bytes: crate::blob::DEFAULT_BLOB_HYDRATION_BYTES,
404 backend_id: BackendId::main(),
405 brain_profile,
406 visible_namespaces: vec![],
407 allowed_outbound_namespaces: vec![],
408 actor_id,
409 git_write: crate::engine_config::GitWriteSectionConfig::default(),
410 display_timezone: resolve_default_display_timezone(),
411 events_split: None,
412 }
413 }
414}
415
416impl RuntimeConfig {
417 /// Return the shipped pack set used when no CLI, environment, or
418 /// configuration-file selection is present.
419 pub fn built_in_packs() -> Vec<String> {
420 [
421 "kg",
422 "gtd",
423 "memory",
424 "brain",
425 "comm",
426 "schedule",
427 "knowledge",
428 "session",
429 "git",
430 "code",
431 "workspace",
432 "blob",
433 ]
434 .into_iter()
435 .map(String::from)
436 .collect()
437 }
438
439 /// Build a `RuntimeConfig` with embedding disabled entirely.
440 ///
441 /// `embedding_model` and `additional_embedding_models` are computed
442 /// independently inside [`Default::default`], so `RuntimeConfig {
443 /// embedding_model: None, ..RuntimeConfig::default() }` does NOT produce a
444 /// model-less runtime: `additional_embedding_models` still carries its
445 /// env-driven fallback seed, and the note-write path fans out embedding to
446 /// every registered model regardless of `embedding_model`: so the first
447 /// `memory.remember` on a machine without local model files hard-fails
448 /// instead of degrading to FTS-only.
449 ///
450 /// This constructor clears both fields together and ignores
451 /// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` unconditionally: the caller wants
452 /// zero embedders, not "zero unless the environment disagrees". Use it on
453 /// model-less machines (CI runners, fresh installs without local model
454 /// files) instead of the two-field struct-update form.
455 pub fn no_embeddings() -> Self {
456 Self {
457 embedding_model: None,
458 additional_embedding_models: Vec::new(),
459 ..Self::default()
460 }
461 }
462}
463
464/// Expand a leading `~` to `$HOME` in a path.
465///
466/// This is the single shared expansion point for every `RuntimeConfig.db_path`
467/// construction site (CLI `--db`, `KHIVE_DB`, declared `[[backends]].path`).
468/// [`resolve_db_anchor`] calls it so a `~`-prefixed override is expanded once,
469/// at resolution, before the path ever reaches boot (single- or multi-backend),
470/// `compute_config_id` fingerprinting, or the `--db` override equivalence
471/// guard — those consumers then agree on one expanded path instead of a raw
472/// `~` diverging from its already-expanded equivalent.
473pub fn expand_tilde(path: &std::path::Path) -> std::path::PathBuf {
474 let s = path.to_string_lossy();
475 if let Some(rest) = s.strip_prefix("~/") {
476 let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
477 std::path::PathBuf::from(format!("{home}/{rest}"))
478 } else if s == "~" {
479 let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
480 std::path::PathBuf::from(home)
481 } else {
482 path.to_path_buf()
483 }
484}
485
486/// Resolve the `--db`/`KHIVE_DB` value into the anchor path used for tier-3
487/// project-local `.khive/config.toml` discovery, mirroring the precedence
488/// `kkernel mcp` and `kkernel exec` use to open the database itself:
489/// `:memory:` has no file to anchor on (`None`); an explicit path anchors on
490/// that path (with a leading `~` expanded via [`expand_tilde`]); an unset
491/// value falls back to `$HOME/.khive/khive.db`, or `./.khive/khive.db` when
492/// `HOME` is unset.
493///
494/// Always resolves to a concrete anchor (unlike a 2-arm "override the
495/// default?" resolver): when `HOME` is unset this falls back to
496/// `./.khive/khive.db` rather than `None`, deliberately diverging from
497/// `RuntimeConfig::default()`: a caller anchoring config discovery needs a
498/// concrete directory to search even without `HOME`.
499pub fn resolve_db_anchor(db: Option<&str>) -> Option<std::path::PathBuf> {
500 match db {
501 Some(":memory:") => None,
502 Some(path) => Some(expand_tilde(std::path::Path::new(path))),
503 None => {
504 let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
505 Some(std::path::PathBuf::from(format!("{home}/.khive/khive.db")))
506 }
507 }
508}
509
510/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
511/// process's `config_id`: agrees with what [`resolve_db_anchor`] derives from
512/// the same raw `--db`/`KHIVE_DB` input.
513///
514/// This compatibility entry point preserves the raw-string API. Construction
515/// paths that already captured the anchor should call
516/// [`assert_captured_db_anchor_consistent`] so they do not re-read mutable
517/// process environment.
518pub fn assert_db_anchor_consistent(
519 resolved_db_path: Option<&std::path::Path>,
520 args_db: Option<&str>,
521) -> anyhow::Result<()> {
522 let db_anchor = resolve_db_anchor(args_db);
523 assert_captured_db_anchor_consistent(resolved_db_path, db_anchor.as_deref())
524}
525
526/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
527/// process's `config_id`: agrees with the database anchor captured from the
528/// same `--db`/`KHIVE_DB` input at the construction boundary.
529///
530/// Guards against a construction path recomputing `db_path` independently of
531/// `resolve_db_anchor`: left unchecked, that would silently desync `config_id`
532/// from a daemon or peer sharing the same database instead of failing loud.
533/// The caller passes the captured anchor so validation never re-reads mutable
534/// process environment. Inert (`Ok(())`) when the anchor itself is `None` (the
535/// `:memory:` sentinel) since there is nothing to compare against.
536pub fn assert_captured_db_anchor_consistent(
537 resolved_db_path: Option<&std::path::Path>,
538 db_anchor: Option<&std::path::Path>,
539) -> anyhow::Result<()> {
540 let Some(anchor) = db_anchor else {
541 return Ok(());
542 };
543 if resolved_db_path != Some(anchor) {
544 anyhow::bail!(
545 "db-path resolution drift at server construction: resolved db_path {:?} \
546 does not match the canonical anchor {:?} computed by resolve_db_anchor \
547 from the same --db input; this construction path likely recomputed the \
548 db path independently instead of routing through the shared resolver, \
549 which would desynchronize config_id from other processes sharing the \
550 same database",
551 resolved_db_path,
552 anchor
553 );
554 }
555 Ok(())
556}
557
558/// Resolve the per-connection attribution actor from the project/cwd-anchored
559/// config tier, independently of the database-anchored config load that
560/// governs `config_id`.
561///
562/// The database-anchored config load keeps `config_id` coherent between a
563/// short-lived client and a long-running daemon sharing one database, but
564/// when many per-project connections share one database under a single
565/// `HOME` (the daemon-multiplexed fleet case), that shared config carries no
566/// `[actor]` block, so every connection's write-stamp attribution collapses
567/// to the default identity.
568///
569/// This performs a separate, cwd-anchored lookup (`db_path: None`) and reads
570/// only `[actor].id`: it must not perturb `config_id` or `default_namespace`,
571/// which remain governed exclusively by the database-anchored load.
572///
573/// `config_path` is the same explicit `--config`/`KHIVE_CONFIG` override the
574/// caller's database-anchored load receives, so an explicit override wins
575/// here too.
576///
577/// Returns `Ok(None)` when no project-anchored config exists, or it exists
578/// but carries no non-empty `[actor].id`: callers fall through to their own
579/// env/anonymous tiers in that case. A `config_path` naming a file that does
580/// not exist is a loud error (`ExplicitConfigMissing`), matching the
581/// database-anchored load's explicit-tier contract (ADR-035) — in production
582/// that load errors first, so this lookup only ever sees an existing file.
583pub fn resolve_project_actor_id(
584 config_path: Option<&std::path::Path>,
585) -> Result<Option<String>, crate::engine_config::ConfigError> {
586 let khive_cfg = crate::engine_config::KhiveConfig::load_with_home_fallback(config_path, None)?;
587 Ok(khive_cfg
588 .and_then(|cfg| cfg.actor.id)
589 .filter(|s| !s.trim().is_empty()))
590}
591
592// ---- Embedding model helpers ----
593
594/// Sanitize an embedding model name into a valid SQL table suffix.
595/// e.g. `bge-small-en-v1.5` -> `bge_small_en_v1_5`
596pub(crate) fn vec_model_key(model: EmbeddingModel) -> String {
597 sanitize_key(&model.to_string())
598}
599
600pub(crate) fn sanitize_key(s: &str) -> String {
601 s.chars()
602 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
603 .collect()
604}
605
606pub(crate) fn build_embedder_registry(
607 config: &RuntimeConfig,
608) -> (crate::embedder_registry::EmbedderRegistry, Arc<str>) {
609 use crate::embedder_registry::{EmbedderRegistry, LatticeEmbedderProvider};
610 let mut registry = EmbedderRegistry::new();
611 for model in configured_embedding_models(config) {
612 registry.register(LatticeEmbedderProvider::new(model));
613 }
614 let default_embedder_name = config
615 .embedding_model
616 .map(|model| Arc::<str>::from(model.to_string()))
617 .unwrap_or_else(|| Arc::<str>::from(""));
618 (registry, default_embedder_name)
619}
620
621fn configured_embedding_models(config: &RuntimeConfig) -> Vec<EmbeddingModel> {
622 let mut models: Vec<EmbeddingModel> = Vec::new();
623 if let Some(model) = config.embedding_model {
624 models.push(model);
625 }
626 for model in config.additional_embedding_models.iter().copied() {
627 if !models.contains(&model) {
628 models.push(model);
629 }
630 }
631 models
632}
633
634pub(crate) fn register_configured_embedding_models(
635 backend: &StorageBackend,
636 config: &RuntimeConfig,
637) -> RuntimeResult<()> {
638 for model in configured_embedding_models(config) {
639 backend.register_embedding_model(
640 &model.to_string(),
641 model.model_id(),
642 model.key_version(),
643 model.dimensions() as u32,
644 )?;
645 }
646 Ok(())
647}
648
649/// Build a `RuntimeConfig` from a parsed `KhiveConfig`.
650///
651/// For each `[[engines]]` entry:
652/// - The engine flagged `default = true` becomes `RuntimeConfig::embedding_model`.
653/// - All other engines become `RuntimeConfig::additional_embedding_models`.
654///
655/// Model name validity is checked here: any engine whose `model` field cannot
656/// be parsed via `parse_embedding_model_alias` is skipped with a warning.
657///
658/// If `khive_cfg.engines` is empty, the returned `RuntimeConfig` uses the
659/// env-var-derived defaults from `RuntimeConfig::default()`.
660///
661/// When both a config file and `KHIVE_EMBEDDING_MODEL` env var are present,
662/// the caller is responsible for emitting a warning that env vars are overridden.
663/// This function purely converts `KhiveConfig` to `RuntimeConfig` fields.
664pub fn runtime_config_from_khive_config(
665 khive_cfg: &crate::engine_config::KhiveConfig,
666 base: RuntimeConfig,
667) -> RuntimeConfig {
668 // `[actor] id` never becomes the storage namespace (writes always pin to
669 // `local`); it only widens the read visible-set below.
670 let default_namespace = base.default_namespace.clone();
671
672 // base.brain_profile must carry only the explicit CLI tier, never an env
673 // value: env sits below toml in precedence and is applied later by the MCP resolver.
674 let brain_profile = base.brain_profile.clone().or_else(|| {
675 khive_cfg
676 .runtime
677 .brain_profile
678 .clone()
679 .filter(|s| !s.trim().is_empty())
680 });
681
682 let visible_namespaces: Vec<Namespace> = khive_cfg
683 .actor
684 .visible_namespaces
685 .as_deref()
686 .unwrap_or_default()
687 .iter()
688 .filter_map(|s| match Namespace::parse(s) {
689 Ok(ns) => Some(ns),
690 Err(e) => {
691 tracing::warn!(ns = %s, error = %e, "actor.visible_namespaces: invalid namespace; skipped");
692 None
693 }
694 })
695 .collect();
696
697 // Fold actor.id's namespace into visible_namespaces so default reads widen
698 // to {local} ∪ {actor namespace}; skipped when it parses to `local` (would
699 // duplicate the primary namespace already minted) or is already present.
700 let visible_namespaces = if let Some(id) = khive_cfg.actor.id.as_deref() {
701 match Namespace::parse(id) {
702 Ok(actor_ns) if actor_ns != Namespace::local() => {
703 let mut v = visible_namespaces;
704 if !v.contains(&actor_ns) {
705 v.push(actor_ns);
706 }
707 v
708 }
709 _ => visible_namespaces,
710 }
711 } else {
712 visible_namespaces
713 };
714
715 // KhiveConfig::validate() guarantees these are valid Namespace strings, so
716 // parse failures here are unreachable for validated configs; filter_map+warn
717 // guards against a validation bug panicking instead.
718 let allowed_outbound_namespaces: Vec<Namespace> = khive_cfg
719 .actor
720 .allowed_outbound_namespaces
721 .iter()
722 .filter_map(|s| match Namespace::parse(s) {
723 Ok(ns) => Some(ns),
724 Err(e) => {
725 tracing::warn!(ns = %s, error = %e, "actor.allowed_outbound_namespaces: invalid namespace; skipped");
726 None
727 }
728 })
729 .collect();
730
731 // Precedence: TOML `[actor] id` > `base.actor_id` (env/CLI-resolved) >
732 // anonymous. Falls back to `base.actor_id` rather than `None` when
733 // `[actor] id` is absent: otherwise an env-resolved actor like
734 // `KHIVE_ACTOR` is silently dropped whenever a project config exists
735 // without an `[actor]` block.
736 let actor_id = khive_cfg
737 .actor
738 .id
739 .clone()
740 .filter(|s| !s.trim().is_empty())
741 .or_else(|| base.actor_id.clone());
742
743 let git_write = khive_cfg.git_write.clone();
744 let blob_hydration_bytes = khive_cfg
745 .runtime
746 .blob_hydration_bytes
747 .unwrap_or(base.blob_hydration_bytes);
748
749 // KhiveConfig::validate() guarantees a present timezone parses as a valid
750 // chrono_tz::Tz, so the fallback to base.display_timezone below is only
751 // reachable for an unvalidated caller-constructed KhiveConfig, not a
752 // config loaded via KhiveConfig::load.
753 let display_timezone = khive_cfg
754 .display
755 .timezone
756 .as_deref()
757 .and_then(|s| s.parse::<chrono_tz::Tz>().ok())
758 .unwrap_or(base.display_timezone);
759
760 if khive_cfg.engines.is_empty() {
761 return RuntimeConfig {
762 default_namespace,
763 brain_profile,
764 visible_namespaces,
765 allowed_outbound_namespaces,
766 actor_id,
767 git_write,
768 blob_hydration_bytes,
769 display_timezone,
770 ..base
771 };
772 }
773
774 let mut embedding_model: Option<EmbeddingModel> = None;
775 let mut additional: Vec<EmbeddingModel> = Vec::new();
776
777 for engine in &khive_cfg.engines {
778 match parse_embedding_model_alias(&engine.model) {
779 Some(model) => {
780 if engine.default {
781 embedding_model = Some(model);
782 } else {
783 additional.push(model);
784 }
785 }
786 None => {
787 tracing::warn!(
788 engine = %engine.name,
789 model = %engine.model,
790 "engine config: unknown model name; engine will be skipped"
791 );
792 }
793 }
794 }
795
796 RuntimeConfig {
797 embedding_model,
798 additional_embedding_models: additional,
799 default_namespace,
800 brain_profile,
801 visible_namespaces,
802 allowed_outbound_namespaces,
803 actor_id,
804 git_write,
805 blob_hydration_bytes,
806 display_timezone,
807 ..base
808 }
809}
810
811#[cfg(test)]
812mod display_timezone_tests {
813 use super::resolve_default_display_timezone;
814
815 // The host's actual zone is environment-dependent (CI runners are
816 // typically UTC), so this only asserts the resolver always produces some
817 // valid, non-panicking Tz — never that it matches a specific zone.
818 #[test]
819 fn resolve_default_display_timezone_never_panics() {
820 let _tz = resolve_default_display_timezone();
821 }
822}
823
824/// Parse a comma- or whitespace-separated list of embedding model names.
825fn parse_embedding_model_list(s: &str) -> Vec<EmbeddingModel> {
826 parse_pack_list(s)
827 .into_iter()
828 .filter_map(|raw| {
829 let parsed = parse_embedding_model_alias(&raw);
830 if parsed.is_none() && !raw.trim().is_empty() {
831 tracing::warn!(
832 model = %raw,
833 "KHIVE_ADDITIONAL_EMBEDDING_MODELS contains unknown model name; ignored. \
834 Valid forms: short alias like 'paraphrase' or a fully-qualified key \
835 from lattice_embed::EmbeddingModel::from_str."
836 );
837 }
838 parsed
839 })
840 .collect()
841}
842
843pub(crate) fn parse_embedding_model_alias(name: &str) -> Option<EmbeddingModel> {
844 let normalized = name.trim().to_ascii_lowercase().replace('_', "-");
845 match normalized.as_str() {
846 "paraphrase" => Some(EmbeddingModel::ParaphraseMultilingualMiniLmL12V2),
847 _ => normalized.parse().ok(),
848 }
849}
850
851#[cfg(test)]
852mod resolve_db_anchor_tests {
853 use super::resolve_db_anchor;
854
855 #[test]
856 fn memory_sentinel_maps_to_none() {
857 assert_eq!(resolve_db_anchor(Some(":memory:")), None);
858 }
859
860 #[test]
861 fn explicit_path_maps_to_some() {
862 assert_eq!(
863 resolve_db_anchor(Some("/tmp/khive-anchor-test.db")),
864 Some(std::path::PathBuf::from("/tmp/khive-anchor-test.db"))
865 );
866 }
867
868 #[test]
869 fn absent_maps_to_home_default() {
870 let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
871 let expected = std::path::PathBuf::from(format!("{home}/.khive/khive.db"));
872 assert_eq!(resolve_db_anchor(None), Some(expected));
873 }
874}
875
876#[cfg(test)]
877mod assert_db_anchor_consistent_tests {
878 use super::{assert_captured_db_anchor_consistent, resolve_db_anchor};
879 use crate::assert_db_anchor_consistent;
880
881 #[test]
882 fn diverging_db_path_is_rejected_naming_both_paths() {
883 let args_db = "/tmp/khive-anchor-guard-real.db";
884 let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
885 let wrong = std::path::PathBuf::from("/tmp/khive-anchor-guard-wrong.db");
886
887 let err =
888 assert_captured_db_anchor_consistent(Some(wrong.as_path()), Some(anchor.as_path()))
889 .expect_err("a resolved db_path diverging from the anchor must be rejected");
890
891 let msg = err.to_string();
892 assert!(
893 msg.contains(&wrong.display().to_string()),
894 "error must name the resolved (wrong) path: {msg}"
895 );
896 assert!(
897 msg.contains(&anchor.display().to_string()),
898 "error must name the canonical anchor path: {msg}"
899 );
900 }
901
902 #[test]
903 fn matching_explicit_db_path_passes() {
904 let args_db = "/tmp/khive-anchor-guard-consistent.db";
905 let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
906 assert!(assert_captured_db_anchor_consistent(
907 Some(anchor.as_path()),
908 Some(anchor.as_path())
909 )
910 .is_ok());
911 }
912
913 #[test]
914 fn memory_sentinel_anchor_is_inert() {
915 // `resolve_db_anchor(":memory:")` yields `None` — there is no canonical
916 // path to assert against, so the guard passes regardless of what
917 // `resolved_db_path` happens to carry.
918 let bogus = std::path::PathBuf::from("/tmp/should-not-matter.db");
919 assert!(assert_captured_db_anchor_consistent(Some(bogus.as_path()), None).is_ok());
920 assert!(assert_captured_db_anchor_consistent(None, None).is_ok());
921 }
922
923 #[test]
924 fn normal_boot_with_db_unset_passes_silently() {
925 // Mirrors a normal boot with `--db` unset: `resolve_db_anchor(None)`
926 // always resolves to `Some(..)` (HOME-set or -unset both produce a
927 // concrete anchor), so a runtime whose resolved `db_path` matches
928 // passes silently.
929 let anchor = resolve_db_anchor(None);
930 assert!(assert_captured_db_anchor_consistent(anchor.as_deref(), anchor.as_deref()).is_ok());
931 }
932
933 #[test]
934 fn public_compatibility_wrapper_accepts_path_and_memory_sentinel() {
935 let args_db = "/tmp/khive-anchor-guard-public-api.db";
936 let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
937 assert!(assert_db_anchor_consistent(Some(anchor.as_path()), Some(args_db)).is_ok());
938
939 let unrelated = std::path::Path::new("/tmp/khive-anchor-guard-unrelated.db");
940 assert!(assert_db_anchor_consistent(Some(unrelated), Some(":memory:")).is_ok());
941 }
942}
943
944#[cfg(test)]
945mod resolve_project_actor_id_tests {
946 use super::resolve_project_actor_id;
947
948 fn write_toml(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
949 let path = dir.path().join("config.toml");
950 std::fs::write(&path, body).expect("write config.toml");
951 path
952 }
953
954 #[test]
955 fn extracts_non_empty_actor_id_from_explicit_path() {
956 let dir = tempfile::tempdir().expect("tempdir");
957 let path = write_toml(&dir, "[actor]\nid = \"lambda:explicit-actor\"\n");
958
959 assert_eq!(
960 resolve_project_actor_id(Some(&path)).expect("no error"),
961 Some("lambda:explicit-actor".to_string())
962 );
963 }
964
965 #[test]
966 fn missing_explicit_path_fails_loud() {
967 // The explicit tier is enforced inside the loader
968 // (`KhiveConfig::load_with_home_fallback_and_source` returns
969 // `ExplicitConfigMissing`): a nonexistent explicit path is an error,
970 // never a silent `None` (ADR-035).
971 let missing = std::path::PathBuf::from("/nonexistent/khive-project-actor-test/config.toml");
972 let err = resolve_project_actor_id(Some(&missing))
973 .expect_err("a missing explicit path must fail loud");
974 assert!(
975 matches!(
976 err,
977 crate::engine_config::ConfigError::ExplicitConfigMissing { .. }
978 ),
979 "expected ExplicitConfigMissing, got {err:?}"
980 );
981 }
982
983 #[test]
984 fn propagates_load_error_for_invalid_actor_id() {
985 // `KhiveConfig::load`'s `validate()` rejects an empty `[actor] id` before
986 // the emptiness filter in `resolve_project_actor_id` ever sees it; this
987 // asserts the error surfaces rather than being swallowed into `Ok(None)`.
988 let dir = tempfile::tempdir().expect("tempdir");
989 let path = write_toml(&dir, "[actor]\nid = \"\"\n");
990
991 let err = resolve_project_actor_id(Some(&path)).expect_err("invalid actor.id must error");
992 let root = match &err {
993 crate::engine_config::ConfigError::InFile { source, .. } => source.as_ref(),
994 other => other,
995 };
996 assert!(
997 matches!(
998 root,
999 crate::engine_config::ConfigError::InvalidActorId { .. }
1000 ),
1001 "expected InvalidActorId, got {err:?}"
1002 );
1003 }
1004
1005 #[test]
1006 fn returns_none_when_config_has_no_actor_section() {
1007 let dir = tempfile::tempdir().expect("tempdir");
1008 let path = write_toml(
1009 &dir,
1010 "[[engines]]\nname = \"primary\"\nmodel = \"bge-small-en-v1.5\"\ndefault = true\n",
1011 );
1012
1013 assert_eq!(
1014 resolve_project_actor_id(Some(&path)).expect("no error"),
1015 None,
1016 "a config file with no [actor] section must resolve to None"
1017 );
1018 }
1019}
1020
1021#[cfg(test)]
1022mod no_embeddings_tests {
1023 use super::*;
1024 use serial_test::serial;
1025
1026 #[test]
1027 fn no_embeddings_clears_both_fields() {
1028 let config = RuntimeConfig::no_embeddings();
1029 assert_eq!(config.embedding_model, None);
1030 assert!(config.additional_embedding_models.is_empty());
1031 assert!(
1032 configured_embedding_models(&config).is_empty(),
1033 "no_embeddings() must yield zero configured embedders"
1034 );
1035 }
1036
1037 #[test]
1038 fn blob_hydration_default_is_four_portable_whole_objects() {
1039 assert_eq!(
1040 RuntimeConfig::default().blob_hydration_bytes,
1041 4 * khive_storage::MAX_BLOB_WHOLE_BYTES
1042 );
1043 }
1044
1045 #[test]
1046 #[serial]
1047 fn no_embeddings_ignores_additional_env_override() {
1048 // no_embeddings() is an unconditional opt-out: even if the caller's
1049 // environment sets KHIVE_ADDITIONAL_EMBEDDING_MODELS, the resulting
1050 // config must still report zero embedders.
1051 std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1052 let config = RuntimeConfig::no_embeddings();
1053 std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1054
1055 assert!(config.additional_embedding_models.is_empty());
1056 assert!(configured_embedding_models(&config).is_empty());
1057 }
1058
1059 #[test]
1060 #[serial]
1061 fn default_computes_additional_models_independently_of_no_embeddings() {
1062 // `Default` must keep computing `embedding_model` and
1063 // `additional_embedding_models` independently; `no_embeddings()` is a
1064 // separate opt-out constructor, not a change to `Default`'s seeding.
1065 // The env var is SET here rather than cleared: since Default now ships
1066 // no secondary engine, an unset env would make Default and
1067 // no_embeddings() indistinguishable and the test would stop
1068 // discriminating the thing it exists to discriminate.
1069 std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1070 let config = RuntimeConfig::default();
1071 let buggy_form = RuntimeConfig {
1072 embedding_model: None,
1073 ..RuntimeConfig::default()
1074 };
1075 std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1076
1077 assert_eq!(
1078 config.additional_embedding_models,
1079 vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1080 );
1081
1082 // Overriding only `embedding_model` via struct-update syntax does not
1083 // clear `additional_embedding_models`.
1084 assert!(
1085 !buggy_form.additional_embedding_models.is_empty(),
1086 "Default's independent-field seeding must remain unchanged; \
1087 no_embeddings() is the fix, not a change to Default"
1088 );
1089 }
1090
1091 #[test]
1092 #[serial]
1093 fn default_ships_a_single_engine_when_env_unset() {
1094 // A secondary engine is embedded on every write and searched on every
1095 // read. That cost is opted into, not inherited.
1096 std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1097 let config = RuntimeConfig::default();
1098
1099 assert!(
1100 config.additional_embedding_models.is_empty(),
1101 "shipped default must register one engine; a second is opt-in via \
1102 KHIVE_ADDITIONAL_EMBEDDING_MODELS"
1103 );
1104 assert_eq!(
1105 configured_embedding_models(&config),
1106 vec![EmbeddingModel::AllMiniLmL6V2]
1107 );
1108 }
1109}
1110
1111#[cfg(test)]
1112mod ann_fresh_tail_config_tests {
1113 use super::ann_fresh_tail_enabled_from_value;
1114
1115 #[test]
1116 fn only_exact_zero_disables_fresh_tail() {
1117 assert!(ann_fresh_tail_enabled_from_value(None));
1118 assert!(!ann_fresh_tail_enabled_from_value(Some("0")));
1119 assert!(ann_fresh_tail_enabled_from_value(Some("1")));
1120 assert!(ann_fresh_tail_enabled_from_value(Some("false")));
1121 assert!(ann_fresh_tail_enabled_from_value(Some(" 0")));
1122 }
1123}
1124
1125#[cfg(test)]
1126mod configured_embedding_models_order_tests {
1127 use super::*;
1128
1129 /// Issue #1115: the configured engine list must preserve declaration
1130 /// order (primary first, then `additional_embedding_models` in order)
1131 /// instead of alphabetizing — any consumer that treats the list as
1132 /// ordered (e.g. recall fan-out) otherwise gets the wrong primary.
1133 #[test]
1134 fn preserves_primary_first_then_additional_in_declared_order() {
1135 let config = RuntimeConfig {
1136 embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1137 additional_embedding_models: vec![
1138 EmbeddingModel::Qwen3Embedding4B,
1139 EmbeddingModel::BgeSmallEnV15,
1140 ],
1141 ..RuntimeConfig::default()
1142 };
1143
1144 assert_eq!(
1145 configured_embedding_models(&config),
1146 vec![
1147 EmbeddingModel::AllMiniLmL6V2,
1148 EmbeddingModel::Qwen3Embedding4B,
1149 EmbeddingModel::BgeSmallEnV15,
1150 ],
1151 "order must be primary-first, then additional models as declared, \
1152 not alphabetized"
1153 );
1154 }
1155
1156 /// A model repeated in both `embedding_model` and `additional_embedding_models`
1157 /// must be deduped to a single entry, keeping its first (primary) position.
1158 #[test]
1159 fn dedupes_model_shared_between_primary_and_additional() {
1160 let config = RuntimeConfig {
1161 embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1162 additional_embedding_models: vec![
1163 EmbeddingModel::AllMiniLmL6V2,
1164 EmbeddingModel::BgeSmallEnV15,
1165 ],
1166 ..RuntimeConfig::default()
1167 };
1168
1169 assert_eq!(
1170 configured_embedding_models(&config),
1171 vec![EmbeddingModel::AllMiniLmL6V2, EmbeddingModel::BgeSmallEnV15],
1172 "the shared model must appear once, in its primary position"
1173 );
1174 }
1175}