Skip to main content

khive_runtime/
runtime.rs

1//! KhiveRuntime — composable handle to all storage capabilities.
2//!
3//! `RuntimeConfig`, `BackendId`, `NamespaceToken`, and embedding model helpers
4//! live in `super::config` and are re-exported from here.
5
6use std::sync::{Arc, RwLock};
7
8use khive_db::StorageBackend;
9#[cfg(test)]
10use khive_gate::AllowAllGate;
11use khive_gate::GateRequest;
12use khive_storage::{EntityStore, Event, EventStore, GraphStore, NoteStore, SqlAccess};
13use khive_types::{EdgeEndpointRule, EventKind, Namespace, SubstrateKind};
14use lattice_embed::{EmbeddingModel, EmbeddingService};
15
16use crate::config::{
17    build_embedder_registry, parse_embedding_model_alias, register_configured_embedding_models,
18    sanitize_key, vec_model_key,
19};
20use crate::error::{RuntimeError, RuntimeResult};
21
22/// Callback type for pack-installed entity-type validators.
23///
24/// Receives `(kind, entity_type)` and returns the normalised type string,
25/// or `RuntimeError::InvalidInput` if the type is not registered for that kind.
26/// When `entity_type` is `None`, the implementation must return `Ok(None)`.
27pub type EntityTypeValidatorFn =
28    Arc<dyn Fn(&str, Option<&str>) -> Result<Option<String>, RuntimeError> + Send + Sync>;
29
30/// Callback type for a pack-installed note-mutation hook.
31///
32/// Invoked by `update_note` (when the note's text/embedding actually
33/// changed) and `delete_note` (soft or hard) with `(note_kind, note_id)`,
34/// after the mutation has been durably applied. Returns a boxed future so
35/// the hook can await async cache-invalidation work (e.g.
36/// `khive-pack-memory`'s ANN warm-cache generation bump) without
37/// `khive-runtime` depending on any pack crate: dependencies point the
38/// other way, so the runtime exposes an extension point and the pack
39/// installs into it, same shape as `EntityTypeValidatorFn`, just async.
40pub type NoteMutationHookFn = Arc<
41    dyn Fn(String, uuid::Uuid) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
42        + Send
43        + Sync,
44>;
45
46pub use crate::config::{
47    assert_captured_db_anchor_consistent, assert_db_anchor_consistent, expand_tilde,
48    parse_pack_list, resolve_db_anchor, resolve_project_actor_id, runtime_config_from_khive_config,
49    BackendId, NamespaceToken, RuntimeConfig,
50};
51
52// ---- KhiveRuntime ----
53
54/// Composable runtime handle used by the MCP server.
55///
56/// Wraps a `StorageBackend` and provides namespace-scoped accessor methods
57/// for each storage capability, plus a lazily-loaded embedder.
58#[derive(Clone)]
59pub struct KhiveRuntime {
60    backend: Arc<StorageBackend>,
61    /// When `Some`, holds the main backend so that `core()` can return a
62    /// main-bound runtime handle without constructing a new connection.
63    /// `None` when this runtime is already bound to the main backend.
64    core_backend: Option<Arc<StorageBackend>>,
65    config: RuntimeConfig,
66    /// Pack-extensible embedder registry.
67    ///
68    /// Shared across clones via `Arc<RwLock<_>>` so that
69    /// [`register_embedder`](Self::register_embedder) after clone is visible
70    /// to all handles. Built-in lattice models are pre-registered during
71    /// construction; packs may add more via [`PackRuntime::register_embedders`].
72    embedder_registry: Arc<std::sync::RwLock<crate::embedder_registry::EmbedderRegistry>>,
73    default_embedder_name: Arc<str>,
74    /// Pack-extensible edge endpoint rules. Shared across clones
75    /// via `Arc<RwLock<_>>`; installed once by the transport after the
76    /// `VerbRegistry` is built. Empty until installed
77    edge_rules: Arc<RwLock<Vec<EdgeEndpointRule>>>,
78    /// Pack-aggregated valid entity and note kind strings.
79    ///
80    /// Installed by the transport layer after building the `VerbRegistry`.
81    /// When non-empty, `create_entity`, `create_note_inner`, and `import_kg`
82    /// reject kinds not in these sets. When empty (no packs loaded, e.g.
83    /// bare runtime in unit tests), kind validation is skipped — the pack
84    /// handler layer is the primary enforcement point.
85    valid_entity_kinds: Arc<RwLock<Vec<String>>>,
86    valid_note_kinds: Arc<RwLock<Vec<String>>>,
87    /// Pack-installed entity-type validator.
88    ///
89    /// When `Some`, `create_many` calls this function to validate and normalise
90    /// each `(kind, entity_type)` pair before writing. When `None` (bare runtime
91    /// without packs), entity-type validation is skipped — the pack handler layer
92    /// is the primary enforcement point, same as for `valid_entity_kinds`.
93    entity_type_validator: Arc<RwLock<Option<EntityTypeValidatorFn>>>,
94    /// Pack-installed note-mutation hook.
95    ///
96    /// When `Some`, `update_note` (on text change) and `delete_note` (soft
97    /// or hard) call this after the mutation is durably applied, so a pack
98    /// that caches derived state keyed by note content (e.g. `khive-pack-memory`'s
99    /// warm ANN index) can invalidate/advance its own generation counter even
100    /// when the mutation arrived through a different pack's verb (e.g. KG's
101    /// `update`/`delete` on a `kind="memory"` note) that has no dependency on
102    /// the reacting pack. `None` when no pack installs one (bare runtime, or
103    /// no pack cares about note-mutation notifications) — the call becomes a
104    /// no-op check of an `Option`.
105    note_mutation_hook: Arc<RwLock<Option<NoteMutationHookFn>>>,
106    /// The config-resolved `BlobStore` (ADR-111 Amendment 2), installed by
107    /// the boot path (`khive-mcp`'s single- and multi-backend startup paths)
108    /// via [`install_blob_store`](Self::install_blob_store) once `khive.toml`'s
109    /// `[storage.blob]` selection has been resolved through
110    /// `khive_runtime::resolve_blob_store`. `None` until installed — every
111    /// constructor here defaults it unset rather than eagerly resolving a
112    /// filesystem default, because many callers (unit tests, `memory()`) use
113    /// an in-memory backend with no blob root configured at all.
114    blob_store: Arc<RwLock<Option<Arc<dyn khive_storage::BlobStore>>>>,
115}
116
117impl KhiveRuntime {
118    /// Create a new runtime with the given config.
119    ///
120    /// The config's `db_path` is used to open or create the SQLite backend.
121    /// For the preferred boot path in multi-backend deployments, use
122    /// [`from_backend`](Self::from_backend) instead.
123    pub fn new(config: RuntimeConfig) -> RuntimeResult<Self> {
124        let backend = match &config.db_path {
125            Some(path) => {
126                if let Some(parent) = path.parent() {
127                    std::fs::create_dir_all(parent).ok();
128                }
129                StorageBackend::sqlite(path)?
130            }
131            None => StorageBackend::memory()?,
132        };
133        // Migrations must run before any pack handler touches the DB; idempotent;
134        // failure aborts construction with a clear error.
135        {
136            let mut writer = backend.pool().try_writer()?;
137            khive_db::run_migrations(writer.conn_mut())?;
138        }
139        register_configured_embedding_models(&backend, &config)?;
140        let (registry, default_embedder_name) = build_embedder_registry(&config);
141        Ok(Self {
142            backend: Arc::new(backend),
143            core_backend: None,
144            config,
145            embedder_registry: Arc::new(std::sync::RwLock::new(registry)),
146            default_embedder_name,
147            edge_rules: Arc::new(RwLock::new(Vec::new())),
148            valid_entity_kinds: Arc::new(RwLock::new(Vec::new())),
149            valid_note_kinds: Arc::new(RwLock::new(Vec::new())),
150            entity_type_validator: Arc::new(RwLock::new(None)),
151            note_mutation_hook: Arc::new(RwLock::new(None)),
152            blob_store: Arc::new(RwLock::new(None)),
153        })
154    }
155
156    /// Open a runtime for read-only inspection (no model registration, no DB creation).
157    ///
158    /// Runs migrations (idempotent) but skips `register_configured_embedding_models`,
159    /// so `engine list` / `engine status` cannot mutate the registry as a side effect.
160    /// Returns `None` when `db_path` is `None` and the default DB does not exist.
161    pub fn new_readonly(config: RuntimeConfig) -> RuntimeResult<Self> {
162        let backend = match &config.db_path {
163            Some(path) => StorageBackend::sqlite(path)?,
164            None => StorageBackend::memory()?,
165        };
166        {
167            let mut writer = backend.pool().try_writer()?;
168            khive_db::run_migrations(writer.conn_mut())?;
169        }
170        let (registry, default_embedder_name) = build_embedder_registry(&config);
171        Ok(Self {
172            backend: Arc::new(backend),
173            core_backend: None,
174            config,
175            embedder_registry: Arc::new(std::sync::RwLock::new(registry)),
176            default_embedder_name,
177            edge_rules: Arc::new(RwLock::new(Vec::new())),
178            valid_entity_kinds: Arc::new(RwLock::new(Vec::new())),
179            valid_note_kinds: Arc::new(RwLock::new(Vec::new())),
180            entity_type_validator: Arc::new(RwLock::new(None)),
181            note_mutation_hook: Arc::new(RwLock::new(None)),
182            blob_store: Arc::new(RwLock::new(None)),
183        })
184    }
185
186    /// Construct a runtime from an already-opened backend.
187    ///
188    /// This is the preferred constructor for multi-backend deployments. The caller
189    /// (boot path in `kkernel` or `khive-mcp`) opens each backend from `khive.toml`,
190    /// then constructs a `KhiveRuntime` per pack using this method.
191    ///
192    /// The returned runtime has `db_path = None` and `embedding_model = None`; all
193    /// storage access is through the provided `backend`. Set `backend_id` and
194    /// `default_namespace` via the config builder pattern if non-defaults are needed.
195    pub fn from_backend(backend: Arc<StorageBackend>, config: RuntimeConfig) -> Self {
196        if let Err(err) = register_configured_embedding_models(&backend, &config) {
197            tracing::warn!(error = %err, "failed to register configured embedding models");
198        }
199        let (registry, default_embedder_name) = build_embedder_registry(&config);
200        Self {
201            backend,
202            core_backend: None,
203            config,
204            embedder_registry: Arc::new(std::sync::RwLock::new(registry)),
205            default_embedder_name,
206            edge_rules: Arc::new(RwLock::new(Vec::new())),
207            valid_entity_kinds: Arc::new(RwLock::new(Vec::new())),
208            valid_note_kinds: Arc::new(RwLock::new(Vec::new())),
209            entity_type_validator: Arc::new(RwLock::new(None)),
210            note_mutation_hook: Arc::new(RwLock::new(None)),
211            blob_store: Arc::new(RwLock::new(None)),
212        }
213    }
214
215    /// Wire this runtime as a secondary-backend runtime pointing at `core`.
216    ///
217    /// After this call, `self.core()` returns a handle to `core` rather than
218    /// cloning `self`. The caller (the boot path, not pack code) is responsible
219    /// for passing the correct main backend.
220    ///
221    /// Panics in debug builds if `self.config.backend_id == BackendId::MAIN`,
222    /// because the main runtime does not need a core pointer.
223    pub fn with_core_backend(mut self, core: Arc<StorageBackend>) -> Self {
224        debug_assert_ne!(
225            self.config.backend_id.as_str(),
226            BackendId::MAIN,
227            "with_core_backend must not be called on the main runtime"
228        );
229        self.core_backend = Some(core);
230        self
231    }
232
233    /// Return a runtime handle bound to the main (shared-graph) backend.
234    ///
235    /// When `self` is already the main runtime (`core_backend` is `None`),
236    /// this returns a clone of `self` — no new backend reference is acquired.
237    ///
238    /// When `self` is a secondary-backend runtime (`core_backend` is `Some`),
239    /// this returns a new `KhiveRuntime` backed by the main
240    /// `Arc<StorageBackend>` and sharing all registry state (`embedder_registry`,
241    /// `edge_rules`, `valid_entity_kinds`, `valid_note_kinds`,
242    /// `entity_type_validator`, `note_mutation_hook`) with `self`.
243    /// No database I/O occurs; no embedding models are reloaded.
244    ///
245    /// Use `core()` for notes and entities that must reside in the shared graph
246    /// so that `memory.recall`, cross-pack search, and `annotates` edges work.
247    /// Use `self` (or `self.sql()`) for pack-auxiliary bulk tables.
248    ///
249    /// Handlers that call `core()` more than once per request or loop should bind
250    /// `let core = self.core();` once and reuse it, since each call clones
251    /// `RuntimeConfig` (a heap-allocated struct containing `Vec<String>` fields).
252    pub fn core(&self) -> KhiveRuntime {
253        match &self.core_backend {
254            None => self.clone(),
255            Some(main_arc) => {
256                let mut core_config = self.config.clone();
257                core_config.backend_id = BackendId::main();
258                KhiveRuntime {
259                    backend: main_arc.clone(),
260                    core_backend: None,
261                    config: core_config,
262                    embedder_registry: self.embedder_registry.clone(),
263                    default_embedder_name: self.default_embedder_name.clone(),
264                    edge_rules: self.edge_rules.clone(),
265                    valid_entity_kinds: self.valid_entity_kinds.clone(),
266                    valid_note_kinds: self.valid_note_kinds.clone(),
267                    entity_type_validator: self.entity_type_validator.clone(),
268                    note_mutation_hook: self.note_mutation_hook.clone(),
269                    blob_store: self.blob_store.clone(),
270                }
271            }
272        }
273    }
274
275    /// Create an in-memory runtime (for tests and ephemeral use).
276    pub fn memory() -> RuntimeResult<Self> {
277        Self::new(RuntimeConfig {
278            db_path: None,
279            packs: vec!["kg".to_string()],
280            brain_profile: None,
281            actor_id: None,
282            ..RuntimeConfig::no_embeddings()
283        })
284    }
285
286    /// Return the [`BackendId`] for this runtime's backend.
287    ///
288    /// Used by `SubstrateCoordinator` in `kkernel`
289    /// to identify which backend owns a given node, and to detect cross-backend merges.
290    pub fn backend_id(&self) -> &BackendId {
291        &self.config.backend_id
292    }
293
294    /// Return the extra-visible namespaces assembled at config load.
295    ///
296    /// OSS dispatch uses this set to widen the default multi-record read scope
297    /// to `['local'] ∪ visible_namespaces`. Writes are unchanged: always
298    /// pinned to `'local'`. This set is also available as gate/cloud policy
299    /// input.
300    pub fn visible_namespaces(&self) -> &[Namespace] {
301        &self.config.visible_namespaces
302    }
303
304    /// Return a reference to the runtime config.
305    pub fn config(&self) -> &RuntimeConfig {
306        &self.config
307    }
308
309    /// Return a reference to the underlying storage backend.
310    pub fn backend(&self) -> &StorageBackend {
311        &self.backend
312    }
313
314    /// Return the directory containing the backend's database file, or `None`
315    /// for an in-memory backend.
316    pub fn backend_data_dir(&self) -> Option<std::path::PathBuf> {
317        self.backend.data_dir()
318    }
319
320    /// Root directory for this database's ANN segment tree (`<db-file>.ann/`
321    /// beside the file), or `None` for an in-memory backend. Scoped to the
322    /// database file itself so two databases sharing a parent directory can
323    /// never adopt each other's segments.
324    pub fn backend_ann_root(&self) -> Option<std::path::PathBuf> {
325        self.backend.ann_root()
326    }
327
328    /// WAL/checkpoint diagnostics (ADR-091 operator surface): build identity,
329    /// checkpoint counters, a PASSIVE checkpoint probe, WAL file size, and
330    /// WAL-pin census. Not write-free: the PASSIVE probe may backfill WAL
331    /// frames into the database (normal checkpoint I/O). It never changes
332    /// logical state, escalates to TRUNCATE, creates a missing database file,
333    /// or deletes sidecar evidence — see `khive_db::diagnostics` for the
334    /// narrowings that make those claims hold.
335    ///
336    /// Always targets the *main* backend via [`Self::core`], regardless of
337    /// which backend this runtime handle is bound to, so a report never
338    /// describes a database this handle is not the canonical owner of.
339    pub async fn db_diagnostics(&self) -> RuntimeResult<khive_db::diagnostics::DbDiagnostics> {
340        let pool = self.core().backend.pool_arc();
341        let interval = khive_db::CheckpointConfig::from_env().interval;
342        let build_hash = crate::build_info::BUILD_INFO
343            .is_stamped()
344            .then_some(crate::build_info::BUILD_INFO.source_revision);
345        let build =
346            khive_db::diagnostics::BuildIdentity::from_env(env!("CARGO_PKG_VERSION"), build_hash);
347
348        tokio::task::spawn_blocking(move || khive_db::diagnostics::collect(&pool, build, interval))
349            .await
350            .map_err(|e| {
351                RuntimeError::Internal(format!("db_diagnostics: spawn_blocking join: {e}"))
352            })
353    }
354
355    // ---- Store accessors (token-scoped) ----
356
357    /// Get an EntityStore scoped to the token's namespace.
358    pub fn entities(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn EntityStore>> {
359        Ok(self
360            .backend
361            .entities_for_namespace(token.namespace().as_str())?)
362    }
363
364    /// Get a GraphStore scoped to the token's namespace.
365    pub fn graph(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn GraphStore>> {
366        Ok(self
367            .backend
368            .graph_for_namespace(token.namespace().as_str())?)
369    }
370
371    /// Get a NoteStore scoped to the token's namespace.
372    pub fn notes(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn NoteStore>> {
373        Ok(self
374            .backend
375            .notes_for_namespace(token.namespace().as_str())?)
376    }
377
378    /// Get an EventStore scoped to the token's namespace.
379    pub fn events(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn EventStore>> {
380        Ok(self
381            .backend
382            .events_for_namespace(token.namespace().as_str())?)
383    }
384
385    /// Get the raw SQL access capability (for ad-hoc queries).
386    pub fn sql(&self) -> Arc<dyn SqlAccess> {
387        self.backend.sql()
388    }
389
390    /// Get a VectorStore for the configured embedding model, scoped to the token's namespace.
391    ///
392    /// Returns `Unconfigured("embedding_model")` if no model is set.
393    pub fn vectors(
394        &self,
395        token: &NamespaceToken,
396    ) -> RuntimeResult<Arc<dyn khive_storage::VectorStore>> {
397        let model = self.resolve_embedding_model(None)?;
398        self.vectors_for_embedding_model(token, model)
399    }
400
401    /// Get a VectorStore for a specific named embedding model, scoped to the token's namespace.
402    ///
403    /// Accepts both built-in lattice model names/aliases and custom provider names
404    /// registered via [`register_embedder`](Self::register_embedder). Lattice names
405    /// are routed through the enum-backed path; custom provider names use the
406    /// provider's declared `dimensions()` directly so that the vector store key
407    /// is consistent with how vectors were written during `remember`/`recall`.
408    pub fn vectors_for_model(
409        &self,
410        token: &NamespaceToken,
411        model_name: &str,
412    ) -> RuntimeResult<Arc<dyn khive_storage::VectorStore>> {
413        if let Some(model) = parse_embedding_model_alias(model_name) {
414            // Only proceed via the lattice path if this model is actually in the
415            // registry; otherwise fall through to the custom-provider path.
416            let key = model.to_string();
417            let in_registry = self
418                .embedder_registry
419                .read()
420                .map(|reg| reg.contains(&key))
421                .unwrap_or(false);
422            if in_registry {
423                return self.vectors_for_embedding_model(token, model);
424            }
425        }
426        let dims = {
427            let registry = self.embedder_registry.read().map_err(|_| {
428                crate::RuntimeError::Internal("embedder registry lock poisoned".into())
429            })?;
430            registry
431                .get_provider(model_name)
432                .map(|p| p.dimensions())
433                .ok_or_else(|| crate::RuntimeError::UnknownModel(model_name.to_string()))?
434        };
435        let model_key = sanitize_key(model_name);
436        Ok(self.backend.vectors_for_namespace(
437            &model_key,
438            model_name,
439            dims,
440            token.namespace().as_str(),
441        )?)
442    }
443
444    /// Output dimensions for a named embedding model, resolved from the
445    /// embedder registry alone — no storage access. Mirrors
446    /// [`vectors_for_model`](Self::vectors_for_model)'s resolution order:
447    /// lattice aliases route through the enum when registered, otherwise the
448    /// custom provider's declared `dimensions()`. `None` when no such model
449    /// is registered.
450    pub fn embedder_dimensions(&self, model_name: &str) -> Option<usize> {
451        if let Some(model) = parse_embedding_model_alias(model_name) {
452            let key = model.to_string();
453            let in_registry = self
454                .embedder_registry
455                .read()
456                .map(|reg| reg.contains(&key))
457                .unwrap_or(false);
458            if in_registry {
459                return Some(model.dimensions());
460            }
461        }
462        self.embedder_registry
463            .read()
464            .ok()?
465            .get_provider(model_name)
466            .map(|p| p.dimensions())
467    }
468
469    fn vectors_for_embedding_model(
470        &self,
471        token: &NamespaceToken,
472        model: EmbeddingModel,
473    ) -> RuntimeResult<Arc<dyn khive_storage::VectorStore>> {
474        Ok(self.backend.vectors_for_namespace(
475            &vec_model_key(model),
476            &model.to_string(),
477            model.dimensions(),
478            token.namespace().as_str(),
479        )?)
480    }
481
482    /// Get a TextSearch index for the entity corpus (single shared table).
483    pub fn text(
484        &self,
485        token: &NamespaceToken,
486    ) -> RuntimeResult<Arc<dyn khive_storage::TextSearch>> {
487        let _ = token;
488        Ok(self.backend.text("entities")?)
489    }
490
491    /// Get a TextSearch index for the notes corpus (single shared table).
492    pub fn text_for_notes(
493        &self,
494        token: &NamespaceToken,
495    ) -> RuntimeResult<Arc<dyn khive_storage::TextSearch>> {
496        let _ = token;
497        Ok(self.backend.text("notes")?)
498    }
499
500    /// Mint an authorization token for the given namespace.
501    ///
502    /// Consults the configured [`crate::Gate`] before minting. With the default
503    /// `AllowAllGate` this always succeeds. When a real policy-backed gate is
504    /// installed, this method enforces it and returns `PermissionDenied` on
505    /// denial.
506    ///
507    /// The returned token's read visibility set defaults to `[ns]` — identical
508    /// to the pre-visibility-set behaviour. Use [`Self::authorize_with_visibility`]
509    /// to mint a token that can read additional namespaces.
510    ///
511    /// When `actor_id` is configured in `RuntimeConfig`, the token carries that
512    /// actor label so that `comm.inbox` filters by `to_actor`. When
513    /// unconfigured, the token carries `ActorRef::anonymous()` and inbox falls
514    /// back to party-line behavior.
515    pub fn authorize(&self, ns: Namespace) -> RuntimeResult<NamespaceToken> {
516        let actor = crate::actor_identity::resolve_actor(self.config.actor_id.as_deref());
517        let req = GateRequest::new(
518            actor.clone(),
519            ns.clone(),
520            "authorize",
521            serde_json::Value::Null,
522        );
523        match self.config.gate.check(&req) {
524            Ok(ref decision) if decision.is_allow() => {
525                if let khive_gate::GateDecision::Allow { ref obligations } = decision {
526                    if !obligations.is_empty() {
527                        tracing::debug!(
528                            namespace = %ns.as_str(),
529                            "authorize: obligations={:?}",
530                            obligations
531                        );
532                    }
533                }
534                Ok(NamespaceToken::mint_authorized(ns, actor))
535            }
536            Ok(khive_gate::GateDecision::Deny { reason }) => {
537                Err(crate::RuntimeError::PermissionDenied {
538                    verb: "authorize".to_string(),
539                    reason,
540                })
541            }
542            Ok(_) => Err(crate::RuntimeError::PermissionDenied {
543                verb: "authorize".to_string(),
544                reason: "gate denied".to_string(),
545            }),
546            Err(e) => Err(crate::RuntimeError::Internal(format!("gate error: {e}"))),
547        }
548    }
549
550    /// Mint an authorization token with an explicit read-visibility set.
551    ///
552    /// `primary` is the **write namespace** — all records created via the
553    /// returned token land there. `extra_visible` lists additional namespaces
554    /// the token may read. The primary is always included in the visible set
555    /// regardless of `extra_visible`.
556    ///
557    /// Usage (lambda:leo reading both leo and khive namespaces):
558    /// ```rust,ignore
559    /// let tok = rt.authorize_with_visibility(
560    ///     Namespace::parse("lambda:leo").unwrap(),
561    ///     vec![Namespace::parse("lambda:khive").unwrap()],
562    /// )?;
563    /// ```
564    pub fn authorize_with_visibility(
565        &self,
566        primary: Namespace,
567        extra_visible: Vec<Namespace>,
568    ) -> RuntimeResult<NamespaceToken> {
569        let actor = crate::actor_identity::resolve_actor(self.config.actor_id.as_deref());
570        let req = GateRequest::new(
571            actor.clone(),
572            primary.clone(),
573            "authorize",
574            serde_json::Value::Null,
575        );
576        match self.config.gate.check(&req) {
577            Ok(ref decision) if decision.is_allow() => {
578                if let khive_gate::GateDecision::Allow { ref obligations } = decision {
579                    if !obligations.is_empty() {
580                        tracing::debug!(
581                            namespace = %primary.as_str(),
582                            "authorize_with_visibility: obligations={:?}",
583                            obligations
584                        );
585                    }
586                }
587                Ok(NamespaceToken::mint_with_visibility(
588                    primary,
589                    extra_visible,
590                    actor,
591                ))
592            }
593            Ok(khive_gate::GateDecision::Deny { reason }) => {
594                Err(crate::RuntimeError::PermissionDenied {
595                    verb: "authorize".to_string(),
596                    reason,
597                })
598            }
599            Ok(_) => Err(crate::RuntimeError::PermissionDenied {
600                verb: "authorize".to_string(),
601                reason: "gate denied".to_string(),
602            }),
603            Err(e) => Err(crate::RuntimeError::Internal(format!("gate error: {e}"))),
604        }
605    }
606
607    /// Install the pack-aggregated edge endpoint rules.
608    ///
609    /// Called by the transport layer after the `VerbRegistry` is built so
610    /// that runtime-layer edge validation can consult pack rules. Idempotent:
611    /// later calls overwrite the previous rule set.
612    pub fn install_edge_rules(&self, rules: Vec<EdgeEndpointRule>) {
613        if let Ok(mut guard) = self.edge_rules.write() {
614            *guard = rules;
615        }
616    }
617
618    /// Install the config-resolved `BlobStore` (ADR-111 Amendment 2).
619    ///
620    /// Called by the boot path (`khive-mcp`'s single- and multi-backend
621    /// startup paths, `crates/khive-mcp/src/serve.rs`) once
622    /// `khive_runtime::resolve_blob_store` has selected the backend
623    /// `khive.toml`'s `[storage.blob]` section requests. Idempotent: a later
624    /// call overwrites the previous handle.
625    pub fn install_blob_store(&self, store: Arc<dyn khive_storage::BlobStore>) {
626        if let Ok(mut guard) = self.blob_store.write() {
627            *guard = Some(store);
628        }
629    }
630
631    /// Return the installed `BlobStore`, if the boot path resolved and
632    /// installed one. `None` when no `[storage.blob]` selection was ever
633    /// installed — e.g. a bare/test runtime constructed without going
634    /// through the `khive-mcp` boot path.
635    pub fn blob_store(&self) -> Option<Arc<dyn khive_storage::BlobStore>> {
636        self.blob_store.read().ok().and_then(|guard| guard.clone())
637    }
638
639    /// Install the pack-aggregated valid entity and note kinds.
640    ///
641    /// Called by the transport layer after the `VerbRegistry` is built so that
642    /// runtime-layer entity/note creation and import validate kind strings against
643    /// the merged pack vocabulary. Idempotent: later calls overwrite previous sets.
644    ///
645    /// When no kinds are installed (empty lists), kind validation is skipped at
646    /// the runtime layer. The pack handler layer remains the primary enforcement
647    /// point; this provides defense-in-depth for direct Rust callers and import.
648    pub fn install_kind_registry(&self, entity_kinds: Vec<String>, note_kinds: Vec<String>) {
649        if let Ok(mut guard) = self.valid_entity_kinds.write() {
650            *guard = entity_kinds;
651        }
652        if let Ok(mut guard) = self.valid_note_kinds.write() {
653            *guard = note_kinds;
654        }
655    }
656
657    /// Validate that `kind` is a pack-registered entity kind.
658    ///
659    /// Returns `Ok(())` when no kinds are installed (bare runtime without packs).
660    /// Returns `InvalidInput` when kinds are installed and `kind` is not among them.
661    pub(crate) fn validate_entity_kind(&self, kind: &str) -> crate::RuntimeResult<()> {
662        let guard = self.valid_entity_kinds.read().map_err(|_| {
663            crate::RuntimeError::Internal("entity kind registry lock poisoned".into())
664        })?;
665        if guard.is_empty() {
666            return Ok(());
667        }
668        if guard.iter().any(|k| k == kind) {
669            Ok(())
670        } else {
671            Err(crate::RuntimeError::InvalidInput(format!(
672                "unknown entity kind {kind:?}; valid: {}",
673                guard.join(", ")
674            )))
675        }
676    }
677
678    /// Validate that `kind` is a pack-registered note kind.
679    ///
680    /// Returns `Ok(())` when no kinds are installed (bare runtime without packs).
681    /// Returns `InvalidInput` when kinds are installed and `kind` is not among them.
682    pub(crate) fn validate_note_kind(&self, kind: &str) -> crate::RuntimeResult<()> {
683        let guard = self.valid_note_kinds.read().map_err(|_| {
684            crate::RuntimeError::Internal("note kind registry lock poisoned".into())
685        })?;
686        if guard.is_empty() {
687            return Ok(());
688        }
689        if guard.iter().any(|k| k == kind) {
690            Ok(())
691        } else {
692            Err(crate::RuntimeError::InvalidInput(format!(
693                "unknown note kind {kind:?}; valid: {}",
694                guard.join(", ")
695            )))
696        }
697    }
698
699    /// Install a pack-supplied entity-type validator.
700    ///
701    /// Called by the `KgPack` during registration so that `create_many` can validate
702    /// `entity_type` values at the runtime layer, closing the hole where direct Rust
703    /// callers bypass the handler-layer `validate_entity_type` check.
704    ///
705    /// The callback receives `(kind, entity_type)` and returns the normalised type
706    /// string, or `RuntimeError::InvalidInput` if the type is not registered for that
707    /// kind. Passing `entity_type = None` must return `Ok(None)`.
708    pub fn install_entity_type_validator(&self, f: EntityTypeValidatorFn) {
709        if let Ok(mut guard) = self.entity_type_validator.write() {
710            *guard = Some(f);
711        }
712    }
713
714    /// Validate and normalise `entity_type` through the pack-installed validator.
715    ///
716    /// Returns `Ok(entity_type)` when no validator is installed (bare runtime).
717    /// Returns `InvalidInput` when a validator is installed and rejects the type.
718    pub(crate) fn validate_entity_type_for_kind(
719        &self,
720        kind: &str,
721        entity_type: Option<&str>,
722    ) -> crate::RuntimeResult<Option<String>> {
723        let guard = self.entity_type_validator.read().map_err(|_| {
724            crate::RuntimeError::Internal("entity type validator lock poisoned".into())
725        })?;
726        match guard.as_ref() {
727            None => Ok(entity_type.map(str::to_string)),
728            Some(validate) => validate(kind, entity_type),
729        }
730    }
731
732    /// Install a pack-owned note-mutation hook.
733    ///
734    /// Overwrites any previously-installed hook, same single-slot semantics
735    /// as [`install_entity_type_validator`](Self::install_entity_type_validator).
736    /// In practice only one pack (`khive-pack-memory`) installs one today;
737    /// if a second pack ever needs this, the slot should be widened to a
738    /// `Vec` at that point rather than silently overwritten.
739    pub fn install_note_mutation_hook(&self, f: NoteMutationHookFn) {
740        if let Ok(mut guard) = self.note_mutation_hook.write() {
741            *guard = Some(f);
742        }
743    }
744
745    /// Invoke the pack-installed note-mutation hook, if any.
746    ///
747    /// `kind` is the note's `kind` string (e.g. `"memory"`); `id` is the
748    /// note's UUID. No-op when no hook is installed (bare runtime, or no
749    /// pack cares). Errors inside the hook are the hook's own concern to
750    /// handle/log — this call site cannot propagate a failure without
751    /// changing `update_note`/`delete_note`'s already-committed success
752    /// return value.
753    pub(crate) async fn fire_note_mutation_hook(&self, kind: &str, id: uuid::Uuid) {
754        let hook = self
755            .note_mutation_hook
756            .read()
757            .ok()
758            .and_then(|guard| guard.clone());
759        if let Some(hook) = hook {
760            hook(kind.to_string(), id).await;
761        }
762    }
763
764    /// Snapshot of currently-installed pack edge rules.
765    ///
766    /// This is the same composed rule set `validate_edge_relation_endpoints`
767    /// consults via `pack_rule_allows` when accepting/rejecting an edge. Public
768    /// so pack-layer error-hint code (e.g. `khive-pack-kg`'s
769    /// `valid_relations_for_entity_pair`) can derive hints from the exact
770    /// source the validator uses, rather than maintaining a separate
771    /// hand-authored table that can drift out of sync.
772    pub fn pack_edge_rules(&self) -> Vec<EdgeEndpointRule> {
773        self.edge_rules
774            .read()
775            .map(|g| g.clone())
776            .unwrap_or_default()
777    }
778
779    /// Borrow the installed pack edge rules for a synchronous calculation.
780    pub(crate) fn with_pack_edge_rules<T>(&self, f: impl FnOnce(&[EdgeEndpointRule]) -> T) -> T {
781        match self.edge_rules.read() {
782            Ok(rules) => f(&rules),
783            Err(_) => f(&[]),
784        }
785    }
786
787    /// Return the name of the default embedding model (empty string if none configured).
788    pub fn default_embedder_name(&self) -> &str {
789        self.default_embedder_name.as_ref()
790    }
791
792    /// Resolve a model name (or `None` for the default) to an `EmbeddingModel`.
793    ///
794    /// Returns `UnknownModel` if the name is not in the registry, or
795    /// `Unconfigured` if `None` is passed and no default model is set.
796    pub fn resolve_embedding_model(&self, name: Option<&str>) -> RuntimeResult<EmbeddingModel> {
797        let model = match name {
798            Some(raw) => parse_embedding_model_alias(raw)
799                .ok_or_else(|| crate::RuntimeError::UnknownModel(raw.to_string()))?,
800            None => self
801                .config
802                .embedding_model
803                .ok_or_else(|| crate::RuntimeError::Unconfigured("embedding_model".into()))?,
804        };
805        let key = model.to_string();
806        let contains = self
807            .embedder_registry
808            .read()
809            .map(|reg| reg.contains(&key))
810            .unwrap_or(false);
811        if contains {
812            Ok(model)
813        } else {
814            Err(crate::RuntimeError::UnknownModel(
815                name.unwrap_or_else(|| self.default_embedder_name())
816                    .to_string(),
817            ))
818        }
819    }
820
821    /// Names of all registered embedding models in this runtime.
822    ///
823    /// Includes both built-in lattice models and any custom embedders
824    /// registered by packs via [`register_embedder`](Self::register_embedder).
825    /// Useful for operations that must touch every model's storage (e.g.,
826    /// scoped vector deletion on note delete). The default model is included.
827    pub fn registered_embedding_model_names(&self) -> Vec<String> {
828        self.embedder_registry
829            .read()
830            .map(|reg| reg.names())
831            .unwrap_or_default()
832    }
833
834    /// Get the lazily-initialized embedding service for the named model.
835    ///
836    /// Accepts both built-in lattice model names (e.g. `"all-minilm-l6-v2"`,
837    /// `"paraphrase"`) and custom provider names registered via
838    /// [`register_embedder`](Self::register_embedder).
839    ///
840    /// For lattice model names, aliases (e.g. `"paraphrase"`) are resolved to
841    /// their canonical key before looking up the registry. For custom providers
842    /// the name must match exactly as supplied during registration.
843    ///
844    /// First call for any name loads the underlying service (cold start cost);
845    /// subsequent calls are cheap (registry caches the `Arc`).
846    pub async fn embedder(&self, name: &str) -> RuntimeResult<Arc<dyn EmbeddingService>> {
847        self.embedder_inner(name, None).await
848    }
849
850    pub(crate) async fn embedder_with_token(
851        &self,
852        token: &NamespaceToken,
853        name: &str,
854    ) -> RuntimeResult<Arc<dyn EmbeddingService>> {
855        self.embedder_inner(name, Some(token)).await
856    }
857
858    async fn embedder_inner(
859        &self,
860        name: &str,
861        token: Option<&NamespaceToken>,
862    ) -> RuntimeResult<Arc<dyn EmbeddingService>> {
863        // Fall back to the literal name (not the alias table) so custom
864        // providers registered with non-lattice names stay reachable.
865        let canonical_key = match parse_embedding_model_alias(name) {
866            Some(model) => model.to_string(),
867            None => name.to_owned(),
868        };
869        // Clone the entry so we don't hold the RwLockGuard across the
870        // async OnceCell initialisation (Send bound).
871        let entry = {
872            let registry = self.embedder_registry.read().map_err(|_| {
873                crate::RuntimeError::Internal("embedder registry lock poisoned".into())
874            })?;
875            registry
876                .get_entry(&canonical_key)
877                .ok_or_else(|| crate::RuntimeError::UnknownModel(name.to_string()))?
878        };
879        let (service, init_duration_us) = entry.resolve().await?;
880        if let Some(duration_us) = init_duration_us {
881            if let Some(token) = token {
882                self.emit_embedder_initialized(token, &canonical_key, duration_us)
883                    .await;
884            } else if let Ok(token) = self.authorize(self.config.default_namespace.clone()) {
885                self.emit_embedder_initialized(&token, &canonical_key, duration_us)
886                    .await;
887            }
888        }
889        Ok(service)
890    }
891
892    async fn emit_embedder_initialized(
893        &self,
894        token: &NamespaceToken,
895        model_name: &str,
896        duration_us: i64,
897    ) {
898        let Ok(store) = self.events(token) else {
899            return;
900        };
901        let event = Event::new(
902            token.namespace().as_str(),
903            "embedder.init",
904            EventKind::EmbedderInitialized,
905            SubstrateKind::Event,
906            format!("{}:{}", token.actor().kind, token.actor().id),
907        )
908        .with_payload(serde_json::json!({
909            "model_name": model_name,
910            "duration_us": duration_us,
911        }))
912        .with_duration_us(duration_us);
913        if let Err(err) = store.append_event(event).await {
914            tracing::warn!(error = %err, model_name, "embedder initialization event append failed");
915        }
916    }
917
918    /// Register a custom embedding provider with this runtime.
919    ///
920    /// The provider is added to the shared [`EmbedderRegistry`] so all clones
921    /// of this runtime see the new provider immediately. If a provider with the
922    /// same name already exists it is replaced (last-writer wins — see
923    /// [`crate::EmbedderRegistry::register`] for the rationale).
924    ///
925    /// Packs should call this from [`crate::PackRuntime::register_embedders`] (the
926    /// hook is invoked by the transport during pack initialisation, before the
927    /// first verb dispatch).
928    ///
929    /// [`EmbedderRegistry`]: crate::embedder_registry::EmbedderRegistry
930    pub fn register_embedder(
931        &self,
932        provider: impl crate::embedder_registry::EmbedderProvider + 'static,
933    ) {
934        if let Ok(mut registry) = self.embedder_registry.write() {
935            registry.register(provider);
936        } else {
937            tracing::warn!(
938                "embedder registry lock poisoned — embedder {} not registered",
939                std::any::type_name::<dyn crate::embedder_registry::EmbedderProvider>()
940            );
941        }
942    }
943
944    /// List registered embedding models via `SqlAccess`, routing through the
945    /// existing connection pool rather than opening a fresh `Connection` per call.
946    ///
947    /// Optionally filter by `engine_name`. Returns an empty vec when the
948    /// `_embedding_models` table does not yet exist (e.g. no migrations have run
949    /// or no models have been registered). All other SQL errors are propagated.
950    pub async fn list_embedding_models(
951        &self,
952        engine_filter: Option<&str>,
953    ) -> RuntimeResult<Vec<khive_db::EmbeddingModelRegistryRecord>> {
954        use khive_storage::{SqlStatement, SqlValue};
955
956        let (sql_text, params) = if let Some(engine) = engine_filter {
957            (
958                "SELECT engine_name, model_id, key_version, dim, status, \
959                 activated_at, superseded_at \
960                 FROM _embedding_models WHERE engine_name = ?1 \
961                 ORDER BY engine_name, activated_at IS NULL, activated_at"
962                    .to_string(),
963                vec![SqlValue::Text(engine.to_string())],
964            )
965        } else {
966            (
967                "SELECT engine_name, model_id, key_version, dim, status, \
968                 activated_at, superseded_at \
969                 FROM _embedding_models \
970                 ORDER BY engine_name, activated_at IS NULL, activated_at"
971                    .to_string(),
972                vec![],
973            )
974        };
975
976        let stmt = SqlStatement {
977            sql: sql_text,
978            params,
979            label: Some("list_embedding_models".into()),
980        };
981
982        let mut reader = self
983            .sql()
984            .reader()
985            .await
986            .map_err(crate::RuntimeError::Storage)?;
987
988        let rows = match reader.query_all(stmt).await {
989            Ok(rows) => rows,
990            Err(e) if e.to_string().contains("no such table: _embedding_models") => {
991                return Ok(Vec::new())
992            }
993            Err(e) => return Err(crate::RuntimeError::Storage(e)),
994        };
995
996        let mut records = Vec::with_capacity(rows.len());
997        for row in rows {
998            macro_rules! required_text {
999                ($col:expr) => {
1000                    match row.get($col) {
1001                        Some(SqlValue::Text(s)) => s.clone(),
1002                        other => {
1003                            tracing::warn!(column = $col, value = ?other, "skipping registry row: unexpected type");
1004                            continue;
1005                        }
1006                    }
1007                };
1008            }
1009            let engine_name = required_text!("engine_name");
1010            let model_id = required_text!("model_id");
1011            let key_version = required_text!("key_version");
1012            let dimensions = match row.get("dim") {
1013                Some(SqlValue::Integer(n)) => match u32::try_from(*n) {
1014                    Ok(d) => d,
1015                    Err(_) => {
1016                        tracing::warn!(dim = n, "skipping registry row: dim out of u32 range");
1017                        continue;
1018                    }
1019                },
1020                other => {
1021                    tracing::warn!(column = "dim", value = ?other, "skipping registry row: unexpected type");
1022                    continue;
1023                }
1024            };
1025            let status = required_text!("status");
1026            let activated_at = match row.get("activated_at") {
1027                Some(SqlValue::Integer(n)) => Some(*n),
1028                _ => None,
1029            };
1030            let superseded_at = match row.get("superseded_at") {
1031                Some(SqlValue::Integer(n)) => Some(*n),
1032                _ => None,
1033            };
1034            records.push(khive_db::EmbeddingModelRegistryRecord {
1035                engine_name,
1036                model_id,
1037                key_version,
1038                dimensions,
1039                status,
1040                activated_at,
1041                superseded_at,
1042            });
1043        }
1044
1045        Ok(records)
1046    }
1047}
1048
1049// INLINE TEST JUSTIFICATION: tests here cover KhiveRuntime construction helpers
1050// (in-memory backend wiring, NamespaceToken::for_namespace) that are
1051// pub(crate)-only and cannot be called from the integration test crate.
1052#[cfg(test)]
1053mod tests {
1054    use super::*;
1055    use khive_gate::GateRef;
1056    use serial_test::serial;
1057
1058    #[test]
1059    fn memory_runtime_creates_successfully() {
1060        let rt = KhiveRuntime::memory().expect("memory runtime should create");
1061        assert!(rt.config().db_path.is_none());
1062    }
1063
1064    #[test]
1065    fn backend_data_dir_returns_none_for_memory_backend() {
1066        let rt = KhiveRuntime::memory().expect("memory runtime");
1067        assert!(rt.backend_data_dir().is_none());
1068    }
1069
1070    #[test]
1071    fn backend_data_dir_returns_parent_dir_for_file_backend() {
1072        let dir = tempfile::tempdir().unwrap();
1073        let path = dir.path().join("test.db");
1074        let config = RuntimeConfig {
1075            git_write: Default::default(),
1076            db_path: Some(path),
1077            default_namespace: Namespace::local(),
1078            embedding_model: None,
1079            additional_embedding_models: vec![],
1080            gate: Arc::new(AllowAllGate),
1081            packs: vec!["kg".to_string()],
1082            backend_id: BackendId::main(),
1083            brain_profile: None,
1084            visible_namespaces: vec![],
1085            allowed_outbound_namespaces: vec![],
1086            actor_id: None,
1087        };
1088        let rt = KhiveRuntime::new(config).expect("file runtime");
1089        let data_dir = rt
1090            .backend_data_dir()
1091            .expect("file backend must return Some");
1092        assert_eq!(data_dir, dir.path());
1093    }
1094
1095    #[test]
1096    fn backend_data_dir_returns_none_for_from_backend_with_memory() {
1097        let backend = Arc::new(StorageBackend::memory().expect("memory backend"));
1098        let config = RuntimeConfig {
1099            git_write: Default::default(),
1100            db_path: None,
1101            default_namespace: Namespace::local(),
1102            embedding_model: None,
1103            additional_embedding_models: vec![],
1104            gate: Arc::new(AllowAllGate),
1105            packs: vec!["kg".to_string()],
1106            backend_id: BackendId::main(),
1107            brain_profile: None,
1108            visible_namespaces: vec![],
1109            allowed_outbound_namespaces: vec![],
1110            actor_id: None,
1111        };
1112        let rt = KhiveRuntime::from_backend(backend, config);
1113        assert!(rt.backend_data_dir().is_none());
1114    }
1115
1116    #[test]
1117    fn file_runtime_creates_successfully() {
1118        let dir = tempfile::tempdir().unwrap();
1119        let path = dir.path().join("test.db");
1120        let config = RuntimeConfig {
1121            git_write: Default::default(),
1122            db_path: Some(path.clone()),
1123            default_namespace: Namespace::parse("test").unwrap(),
1124            embedding_model: None,
1125            additional_embedding_models: vec![],
1126            gate: Arc::new(AllowAllGate),
1127            packs: vec!["kg".to_string()],
1128            backend_id: BackendId::main(),
1129            brain_profile: None,
1130            visible_namespaces: vec![],
1131            allowed_outbound_namespaces: vec![],
1132            actor_id: None,
1133        };
1134        let rt = KhiveRuntime::new(config).expect("file runtime should create");
1135        assert!(path.exists());
1136        assert_eq!(rt.config().default_namespace.as_str(), "test");
1137    }
1138
1139    /// A `~/`-prefixed `--db`/`KHIVE_DB` override must resolve, boot, and
1140    /// fingerprint identically to the equivalent absolute path. Before this
1141    /// fix, `resolve_db_anchor` left a leading `~` unexpanded in
1142    /// `RuntimeConfig.db_path`, so single-backend boot (`KhiveRuntime::new`)
1143    /// opened a literal `./~/...` file under the process cwd while
1144    /// `compute_config_id` (which canonicalizes/expands separately) still
1145    /// fingerprinted the real `$HOME` path — two processes pointed at the
1146    /// same logical database could open different files yet share a
1147    /// `config_id`, letting daemon dispatch route requests to the wrong one.
1148    #[test]
1149    #[serial]
1150    fn tilde_prefixed_db_override_resolves_and_boots_like_the_absolute_equivalent() {
1151        let original_home = std::env::var_os("HOME");
1152        let original_cwd = std::env::current_dir().expect("read cwd");
1153        let home_dir = tempfile::tempdir().expect("home tempdir");
1154        let work_dir = tempfile::tempdir().expect("work tempdir");
1155        std::env::set_var("HOME", home_dir.path());
1156        std::env::set_current_dir(work_dir.path()).expect("chdir into isolated work dir");
1157
1158        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1159            let tilde_anchor = crate::config::resolve_db_anchor(Some("~/data.db"))
1160                .expect("an explicit path always anchors");
1161            let expected = home_dir.path().join("data.db");
1162            assert_eq!(
1163                tilde_anchor, expected,
1164                "resolve_db_anchor must expand a leading ~ to $HOME before it ever \
1165                 reaches RuntimeConfig.db_path"
1166            );
1167
1168            let absolute_anchor = crate::config::resolve_db_anchor(Some(
1169                expected.to_str().expect("utf8 tempdir path"),
1170            ))
1171            .expect("an explicit path always anchors");
1172            assert_eq!(
1173                tilde_anchor, absolute_anchor,
1174                "a ~-prefixed override and its equivalent absolute path must resolve to \
1175                 the identical anchor"
1176            );
1177
1178            let make_config = |db_path: std::path::PathBuf| RuntimeConfig {
1179                git_write: Default::default(),
1180                db_path: Some(db_path),
1181                default_namespace: Namespace::local(),
1182                embedding_model: None,
1183                additional_embedding_models: vec![],
1184                gate: Arc::new(AllowAllGate),
1185                packs: vec!["kg".to_string()],
1186                backend_id: BackendId::main(),
1187                brain_profile: None,
1188                visible_namespaces: vec![],
1189                allowed_outbound_namespaces: vec![],
1190                actor_id: None,
1191            };
1192
1193            let tilde_cfg = make_config(tilde_anchor.clone());
1194
1195            let rt = KhiveRuntime::new(tilde_cfg).expect("boot must open the expanded path");
1196            assert_eq!(
1197                rt.backend_data_dir().expect("file backend"),
1198                home_dir.path(),
1199                "single-backend boot must open the file under the expanded $HOME \
1200                 directory, not a literal ~ path relative to cwd"
1201            );
1202            assert!(
1203                expected.exists(),
1204                "the database file must be created at the expanded $HOME path"
1205            );
1206            assert!(
1207                !work_dir.path().join("~").exists(),
1208                "boot must never create a literal '~' directory under the process cwd"
1209            );
1210        }));
1211
1212        match &original_home {
1213            Some(h) => std::env::set_var("HOME", h),
1214            None => std::env::remove_var("HOME"),
1215        }
1216        let _ = std::env::set_current_dir(&original_cwd);
1217        outcome.expect("test body panicked");
1218    }
1219
1220    #[test]
1221    fn from_backend_uses_provided_backend() {
1222        let backend = Arc::new(StorageBackend::memory().expect("memory backend"));
1223        let config = RuntimeConfig {
1224            git_write: Default::default(),
1225            db_path: None,
1226            default_namespace: Namespace::local(),
1227            embedding_model: None,
1228            additional_embedding_models: vec![],
1229            gate: Arc::new(AllowAllGate),
1230            packs: vec!["kg".to_string()],
1231            backend_id: BackendId::new("lore"),
1232            brain_profile: None,
1233            visible_namespaces: vec![],
1234            allowed_outbound_namespaces: vec![],
1235            actor_id: None,
1236        };
1237        let rt = KhiveRuntime::from_backend(backend, config);
1238        assert_eq!(rt.backend_id().as_str(), "lore");
1239        assert!(rt.config().db_path.is_none());
1240    }
1241
1242    #[test]
1243    fn backend_id_defaults_to_main() {
1244        let rt = KhiveRuntime::memory().unwrap();
1245        assert_eq!(rt.backend_id().as_str(), BackendId::MAIN);
1246    }
1247
1248    #[test]
1249    fn store_accessors_return_ok() {
1250        let rt = KhiveRuntime::memory().unwrap();
1251        let tok = NamespaceToken::local();
1252        assert!(rt.entities(&tok).is_ok());
1253        assert!(rt.graph(&tok).is_ok());
1254        assert!(rt.notes(&tok).is_ok());
1255        assert!(rt.events(&tok).is_ok());
1256    }
1257
1258    #[test]
1259    fn vectors_returns_unconfigured_without_model() {
1260        let rt = KhiveRuntime::memory().unwrap();
1261        let tok = NamespaceToken::local();
1262        match rt.vectors(&tok) {
1263            Err(crate::RuntimeError::Unconfigured(s)) => assert_eq!(s, "embedding_model"),
1264            Err(other) => panic!("expected Unconfigured, got {:?}", other),
1265            Ok(_) => panic!("expected Err, got Ok"),
1266        }
1267    }
1268
1269    #[test]
1270    fn vec_model_key_sanitizes_dots_and_dashes() {
1271        assert_eq!(
1272            vec_model_key(EmbeddingModel::BgeSmallEnV15),
1273            "bge_small_en_v1_5"
1274        );
1275        assert_eq!(
1276            vec_model_key(EmbeddingModel::BgeBaseEnV15),
1277            "bge_base_en_v1_5"
1278        );
1279        assert_eq!(
1280            vec_model_key(EmbeddingModel::AllMiniLmL6V2),
1281            "all_minilm_l6_v2"
1282        );
1283    }
1284
1285    #[test]
1286    fn default_config_uses_allow_all_gate() {
1287        let cfg = RuntimeConfig::default();
1288        assert_eq!(cfg.default_namespace.as_str(), "local");
1289        let _: GateRef = cfg.gate.clone();
1290    }
1291
1292    #[test]
1293    fn parse_pack_list_handles_comma_and_whitespace() {
1294        assert_eq!(parse_pack_list("kg"), vec!["kg".to_string()]);
1295        assert_eq!(
1296            parse_pack_list("kg,gtd"),
1297            vec!["kg".to_string(), "gtd".to_string()]
1298        );
1299        assert_eq!(
1300            parse_pack_list("  kg ,  gtd  "),
1301            vec!["kg".to_string(), "gtd".to_string()]
1302        );
1303        assert_eq!(
1304            parse_pack_list("kg gtd"),
1305            vec!["kg".to_string(), "gtd".to_string()]
1306        );
1307        assert_eq!(parse_pack_list(",,"), Vec::<String>::new());
1308        assert_eq!(parse_pack_list(""), Vec::<String>::new());
1309    }
1310
1311    #[test]
1312    fn default_config_packs_loads_production_set() {
1313        let prior = std::env::var("KHIVE_PACKS").ok();
1314        // SAFETY: test function runs single-threaded; no other threads read or write KHIVE_PACKS.
1315        unsafe {
1316            std::env::remove_var("KHIVE_PACKS");
1317        }
1318        // The default distribution loads all production packs.
1319        let cfg = RuntimeConfig::default();
1320        assert_eq!(cfg.packs, RuntimeConfig::built_in_packs());
1321        assert!(cfg.packs.contains(&"kg".to_string()));
1322        assert!(cfg.packs.contains(&"gtd".to_string()));
1323        assert!(cfg.packs.contains(&"memory".to_string()));
1324        assert!(cfg.packs.contains(&"brain".to_string()));
1325        assert!(cfg.packs.contains(&"comm".to_string()));
1326        assert!(cfg.packs.contains(&"schedule".to_string()));
1327        assert!(cfg.packs.contains(&"knowledge".to_string()));
1328        // session loads by default so its background mirror warm-hook runs in
1329        // production; its handlers are all operator-only subhandlers (0 wire verbs).
1330        assert!(cfg.packs.contains(&"session".to_string()));
1331        assert!(cfg.packs.contains(&"git".to_string()));
1332        assert!(cfg.packs.contains(&"code".to_string()));
1333        assert!(cfg.packs.contains(&"workspace".to_string()));
1334        // blob loads by default; a normal file-backed boot installs a
1335        // default FsBlobStore beside the database file with no config
1336        // needed, so its verbs are live in default deployments too (only an
1337        // in-memory backend leaves them unconfigured).
1338        assert!(cfg.packs.contains(&"blob".to_string()));
1339        assert_eq!(cfg.packs.len(), 12);
1340        if let Some(v) = prior {
1341            // SAFETY: single-threaded test cleanup; restores KHIVE_PACKS to its prior value.
1342            unsafe {
1343                std::env::set_var("KHIVE_PACKS", v);
1344            }
1345        }
1346    }
1347
1348    #[test]
1349    fn default_config_uses_minilm_when_env_unset() {
1350        let prior = std::env::var("KHIVE_EMBEDDING_MODEL").ok();
1351        // SAFETY: tests are serial by default for env mutation here; if other tests
1352        // mutate this var, mark them with the same scope.
1353        unsafe {
1354            std::env::remove_var("KHIVE_EMBEDDING_MODEL");
1355        }
1356        let cfg = RuntimeConfig::default();
1357        assert_eq!(cfg.embedding_model, Some(EmbeddingModel::AllMiniLmL6V2));
1358        if let Some(v) = prior {
1359            // SAFETY: single-threaded test cleanup; restores KHIVE_EMBEDDING_MODEL to its prior value.
1360            unsafe {
1361                std::env::set_var("KHIVE_EMBEDDING_MODEL", v);
1362            }
1363        }
1364    }
1365
1366    // ---- Actor config tests ----
1367
1368    use crate::engine_config::{ActorConfig, KhiveConfig};
1369
1370    fn khive_cfg_with_actor(id: &str) -> KhiveConfig {
1371        KhiveConfig {
1372            engines: vec![],
1373            actor: ActorConfig {
1374                id: Some(id.to_string()),
1375                display_name: None,
1376                ..Default::default()
1377            },
1378            ..KhiveConfig::default()
1379        }
1380    }
1381
1382    #[test]
1383    fn runtime_config_from_khive_config_actor_id_does_not_override_default_namespace() {
1384        // `[actor] id` must not set `default_namespace`: writes stay pinned to
1385        // `local`. A non-`'local'` actor.id is folded into the default read
1386        // visible-set, but that does not change default_namespace. This test
1387        // asserts the write-routing invariant only.
1388        let base = RuntimeConfig {
1389            git_write: Default::default(),
1390            db_path: None,
1391            default_namespace: Namespace::local(),
1392            embedding_model: None,
1393            additional_embedding_models: vec![],
1394            gate: Arc::new(AllowAllGate),
1395            packs: vec!["kg".to_string()],
1396            backend_id: BackendId::main(),
1397            brain_profile: None,
1398            visible_namespaces: vec![],
1399            allowed_outbound_namespaces: vec![],
1400            actor_id: None,
1401        };
1402        let cfg = khive_cfg_with_actor("lambda:khive");
1403        let result = runtime_config_from_khive_config(&cfg, base);
1404        assert_eq!(
1405            result.default_namespace.as_str(),
1406            "local",
1407            "actor.id must not become default_namespace (ADR-007 Rev 4 Rule 0); writes pin to local"
1408        );
1409    }
1410
1411    #[test]
1412    fn runtime_config_from_khive_config_empty_actor_id_keeps_base_namespace() {
1413        let base = RuntimeConfig {
1414            git_write: Default::default(),
1415            db_path: None,
1416            default_namespace: Namespace::parse("lambda:base").unwrap(),
1417            embedding_model: None,
1418            additional_embedding_models: vec![],
1419            gate: Arc::new(AllowAllGate),
1420            packs: vec!["kg".to_string()],
1421            backend_id: BackendId::main(),
1422            brain_profile: None,
1423            visible_namespaces: vec![],
1424            allowed_outbound_namespaces: vec![],
1425            actor_id: None,
1426        };
1427        let cfg = KhiveConfig {
1428            engines: vec![],
1429            actor: ActorConfig {
1430                id: Some(String::new()),
1431                display_name: None,
1432                ..Default::default()
1433            },
1434            ..KhiveConfig::default()
1435        };
1436        let result = runtime_config_from_khive_config(&cfg, base);
1437        assert_eq!(
1438            result.default_namespace.as_str(),
1439            "lambda:base",
1440            "empty actor.id must not override base namespace"
1441        );
1442    }
1443
1444    #[test]
1445    fn runtime_config_from_khive_config_absent_actor_id_keeps_base_namespace() {
1446        let base = RuntimeConfig {
1447            git_write: Default::default(),
1448            db_path: None,
1449            default_namespace: Namespace::parse("lambda:base").unwrap(),
1450            embedding_model: None,
1451            additional_embedding_models: vec![],
1452            gate: Arc::new(AllowAllGate),
1453            packs: vec!["kg".to_string()],
1454            backend_id: BackendId::main(),
1455            brain_profile: None,
1456            visible_namespaces: vec![],
1457            allowed_outbound_namespaces: vec![],
1458            actor_id: None,
1459        };
1460        let cfg = KhiveConfig::default(); // no actor.id
1461        let result = runtime_config_from_khive_config(&cfg, base);
1462        assert_eq!(
1463            result.default_namespace.as_str(),
1464            "lambda:base",
1465            "absent actor.id must not override base namespace"
1466        );
1467    }
1468
1469    #[test]
1470    fn runtime_config_from_khive_config_actor_id_with_engines() {
1471        let base = RuntimeConfig {
1472            git_write: Default::default(),
1473            db_path: None,
1474            default_namespace: Namespace::local(),
1475            embedding_model: None,
1476            additional_embedding_models: vec![],
1477            gate: Arc::new(AllowAllGate),
1478            packs: vec!["kg".to_string()],
1479            backend_id: BackendId::main(),
1480            brain_profile: None,
1481            visible_namespaces: vec![],
1482            allowed_outbound_namespaces: vec![],
1483            actor_id: None,
1484        };
1485        let cfg = KhiveConfig {
1486            engines: vec![crate::engine_config::EngineConfig {
1487                name: "default".to_string(),
1488                model: "all-minilm-l6-v2".to_string(),
1489                default: true,
1490                fusion_weight: None,
1491                dims: None,
1492            }],
1493            actor: ActorConfig {
1494                id: Some("lambda:test".to_string()),
1495                display_name: None,
1496                ..Default::default()
1497            },
1498            ..KhiveConfig::default()
1499        };
1500        let result = runtime_config_from_khive_config(&cfg, base);
1501        assert_eq!(
1502            result.default_namespace.as_str(),
1503            "local",
1504            "actor.id must not override default_namespace (ADR-007 Rev 4 Rule 0); \
1505             writes pin to local; engine config is still applied"
1506        );
1507        assert!(result.embedding_model.is_some());
1508    }
1509
1510    // ---- base.actor_id (env-resolved actor) preservation tests ----
1511    //
1512    // Regression coverage: a project config found without an `[actor] id` used
1513    // to silently drop `base.actor_id` (e.g. the value `RuntimeConfig::default()`
1514    // read from `KHIVE_ACTOR`) because both return arms spread an unconditional
1515    // `actor_id: None` over `..base`. The fix falls back to `base.actor_id`
1516    // when the TOML supplies no `[actor] id`, in both arms.
1517
1518    #[test]
1519    #[serial]
1520    fn runtime_config_from_khive_config_engines_present_preserves_env_actor_when_toml_has_none() {
1521        let prior = std::env::var("KHIVE_ACTOR").ok();
1522        // SAFETY: test is #[serial]; no other test in this crate reads/writes KHIVE_ACTOR.
1523        unsafe {
1524            std::env::set_var("KHIVE_ACTOR", "lambda:test-env-actor");
1525        }
1526        let base = RuntimeConfig::default();
1527        assert_eq!(base.actor_id.as_deref(), Some("lambda:test-env-actor"));
1528
1529        let cfg = KhiveConfig {
1530            engines: vec![crate::engine_config::EngineConfig {
1531                name: "default".to_string(),
1532                model: "all-minilm-l6-v2".to_string(),
1533                default: true,
1534                fusion_weight: None,
1535                dims: None,
1536            }],
1537            actor: ActorConfig::default(), // no [actor] id
1538            ..KhiveConfig::default()
1539        };
1540        let result = runtime_config_from_khive_config(&cfg, base);
1541        assert_eq!(
1542            result.actor_id.as_deref(),
1543            Some("lambda:test-env-actor"),
1544            "engines-present arm must preserve base.actor_id (env actor) when TOML has no [actor] id"
1545        );
1546
1547        // SAFETY: restores prior KHIVE_ACTOR value (test cleanup).
1548        unsafe {
1549            match prior {
1550                Some(v) => std::env::set_var("KHIVE_ACTOR", v),
1551                None => std::env::remove_var("KHIVE_ACTOR"),
1552            }
1553        }
1554    }
1555
1556    #[test]
1557    #[serial]
1558    fn runtime_config_from_khive_config_engines_empty_preserves_env_actor_when_toml_has_none() {
1559        let prior = std::env::var("KHIVE_ACTOR").ok();
1560        // SAFETY: test is #[serial]; no other test in this crate reads/writes KHIVE_ACTOR.
1561        unsafe {
1562            std::env::set_var("KHIVE_ACTOR", "lambda:test-env-actor");
1563        }
1564        let base = RuntimeConfig::default();
1565        assert_eq!(base.actor_id.as_deref(), Some("lambda:test-env-actor"));
1566
1567        let cfg = KhiveConfig {
1568            engines: vec![],
1569            actor: ActorConfig::default(), // no [actor] id
1570            ..KhiveConfig::default()
1571        };
1572        let result = runtime_config_from_khive_config(&cfg, base);
1573        assert_eq!(
1574            result.actor_id.as_deref(),
1575            Some("lambda:test-env-actor"),
1576            "engines-empty early-return arm must preserve base.actor_id (env actor) when TOML has no [actor] id"
1577        );
1578
1579        // SAFETY: restores prior KHIVE_ACTOR value (test cleanup).
1580        unsafe {
1581            match prior {
1582                Some(v) => std::env::set_var("KHIVE_ACTOR", v),
1583                None => std::env::remove_var("KHIVE_ACTOR"),
1584            }
1585        }
1586    }
1587
1588    #[test]
1589    #[serial]
1590    fn runtime_config_from_khive_config_toml_actor_wins_over_env_actor() {
1591        let prior = std::env::var("KHIVE_ACTOR").ok();
1592        // SAFETY: test is #[serial]; no other test in this crate reads/writes KHIVE_ACTOR.
1593        unsafe {
1594            std::env::set_var("KHIVE_ACTOR", "lambda:test-env-actor");
1595        }
1596        let base = RuntimeConfig::default();
1597        assert_eq!(base.actor_id.as_deref(), Some("lambda:test-env-actor"));
1598
1599        let cfg = khive_cfg_with_actor("lambda:toml-actor");
1600        let result = runtime_config_from_khive_config(&cfg, base);
1601        assert_eq!(
1602            result.actor_id.as_deref(),
1603            Some("lambda:toml-actor"),
1604            "TOML [actor] id must win over the env-resolved base.actor_id"
1605        );
1606
1607        // SAFETY: restores prior KHIVE_ACTOR value (test cleanup).
1608        unsafe {
1609            match prior {
1610                Some(v) => std::env::set_var("KHIVE_ACTOR", v),
1611                None => std::env::remove_var("KHIVE_ACTOR"),
1612            }
1613        }
1614    }
1615
1616    // ---- list_embedding_models tests ----
1617
1618    // ---- core_backend accessor tests ----
1619
1620    /// Create a migrated in-memory backend (for tests that need raw Arc<StorageBackend>).
1621    fn migrated_memory_backend() -> Arc<StorageBackend> {
1622        let backend = StorageBackend::memory().expect("memory backend");
1623        {
1624            let mut writer = backend.pool().try_writer().expect("writer");
1625            khive_db::run_migrations(writer.conn_mut()).expect("migrations");
1626        }
1627        Arc::new(backend)
1628    }
1629
1630    fn secondary_config() -> RuntimeConfig {
1631        RuntimeConfig {
1632            git_write: Default::default(),
1633            db_path: None,
1634            default_namespace: Namespace::local(),
1635            embedding_model: None,
1636            additional_embedding_models: vec![],
1637            gate: Arc::new(AllowAllGate),
1638            packs: vec!["kg".to_string()],
1639            backend_id: BackendId::new("lore"),
1640            brain_profile: None,
1641            visible_namespaces: vec![],
1642            allowed_outbound_namespaces: vec![],
1643            actor_id: None,
1644        }
1645    }
1646
1647    #[test]
1648    fn core_on_main_runtime_returns_same_backend_id() {
1649        // For a main-bound runtime, core() must return a clone with backend_id == "main".
1650        let rt = KhiveRuntime::memory().unwrap();
1651        assert_eq!(rt.backend_id().as_str(), BackendId::MAIN);
1652        let core_rt = rt.core();
1653        assert_eq!(core_rt.backend_id().as_str(), BackendId::MAIN);
1654    }
1655
1656    #[tokio::test]
1657    async fn core_on_main_runtime_round_trips_note() {
1658        // core() on a main-bound runtime (core_backend = None) returns self.clone(),
1659        // so a note written through core() is readable through the original runtime.
1660        let rt = KhiveRuntime::memory().unwrap();
1661        let tok = NamespaceToken::local();
1662
1663        let note = rt
1664            .core()
1665            .create_note(
1666                &tok,
1667                "observation",
1668                None,
1669                "adr073-main-round-trip",
1670                None,
1671                None,
1672                vec![],
1673            )
1674            .await
1675            .expect("create_note via core()");
1676
1677        let found = rt
1678            .notes(&tok)
1679            .expect("notes store")
1680            .get_note(note.id)
1681            .await
1682            .expect("get_note");
1683
1684        assert!(
1685            found.is_some(),
1686            "note written via core() must be visible through original rt"
1687        );
1688    }
1689
1690    /// Proves note→main and aux→secondary writes are each isolated.
1691    ///
1692    /// Backend A = main; backend B = secondary.
1693    /// rt_secondary is bound to B with core_backend = Some(A).
1694    ///
1695    /// Direction 1 (note → main):
1696    ///   rt_secondary.core().create_note(...) must land in A (visible from rt_main)
1697    ///   and NOT in B (not visible from rt_secondary).
1698    ///
1699    /// Direction 2 (aux → secondary):
1700    ///   A raw SQL write via rt_secondary.sql() lands in B only; A is untouched.
1701    #[tokio::test]
1702    async fn cross_backend_split_note_to_main_aux_to_secondary() {
1703        use khive_storage::{SqlStatement, SqlValue};
1704
1705        let main_arc = migrated_memory_backend();
1706        let secondary_arc = migrated_memory_backend();
1707
1708        let main_config = RuntimeConfig {
1709            git_write: Default::default(),
1710            db_path: None,
1711            default_namespace: Namespace::local(),
1712            embedding_model: None,
1713            additional_embedding_models: vec![],
1714            gate: Arc::new(AllowAllGate),
1715            packs: vec!["kg".to_string()],
1716            backend_id: BackendId::main(),
1717            brain_profile: None,
1718            visible_namespaces: vec![],
1719            allowed_outbound_namespaces: vec![],
1720            actor_id: None,
1721        };
1722
1723        let rt_main = KhiveRuntime::from_backend(main_arc.clone(), main_config);
1724        let rt_secondary = KhiveRuntime::from_backend(secondary_arc, secondary_config())
1725            .with_core_backend(main_arc.clone());
1726
1727        let tok = NamespaceToken::local();
1728
1729        // ── Direction 1: note must land in A (main), not in B (secondary) ──
1730
1731        let note = rt_secondary
1732            .core()
1733            .create_note(
1734                &tok,
1735                "observation",
1736                None,
1737                "adr073-split-test",
1738                None,
1739                None,
1740                vec![],
1741            )
1742            .await
1743            .expect("create_note via core()");
1744        let note_id = note.id;
1745
1746        // Visible from main (A).
1747        let in_main = rt_main
1748            .notes(&tok)
1749            .expect("main notes store")
1750            .get_note(note_id)
1751            .await
1752            .expect("get_note from main");
1753        assert!(
1754            in_main.is_some(),
1755            "note written via core() must appear in main backend A"
1756        );
1757
1758        // Not visible from secondary (B).
1759        let in_secondary = rt_secondary
1760            .notes(&tok)
1761            .expect("secondary notes store")
1762            .get_note(note_id)
1763            .await
1764            .expect("get_note from secondary");
1765        assert!(
1766            in_secondary.is_none(),
1767            "note written to main via core() must NOT appear in secondary backend B"
1768        );
1769
1770        // ── Direction 2: aux write via rt_secondary.sql() lands in B, not A ──
1771
1772        {
1773            let mut writer = rt_secondary.sql().writer().await.expect("secondary writer");
1774            writer
1775                .execute(SqlStatement {
1776                    sql: "CREATE TABLE IF NOT EXISTS _test_adr073_aux \
1777                          (marker TEXT PRIMARY KEY)"
1778                        .into(),
1779                    params: vec![],
1780                    label: None,
1781                })
1782                .await
1783                .expect("create aux table in B");
1784            writer
1785                .execute(SqlStatement {
1786                    sql: "INSERT INTO _test_adr073_aux VALUES (?1)".into(),
1787                    params: vec![SqlValue::Text("b-side-sentinel".into())],
1788                    label: None,
1789                })
1790                .await
1791                .expect("insert into aux table in B");
1792        }
1793
1794        // Row is present in B.
1795        let mut reader_b = rt_secondary.sql().reader().await.expect("secondary reader");
1796        let rows_b = reader_b
1797            .query_all(SqlStatement {
1798                sql: "SELECT marker FROM _test_adr073_aux".into(),
1799                params: vec![],
1800                label: None,
1801            })
1802            .await
1803            .expect("select from B");
1804        assert_eq!(rows_b.len(), 1, "aux row must exist in B");
1805        match rows_b[0].get("marker") {
1806            Some(SqlValue::Text(s)) => {
1807                assert_eq!(s, "b-side-sentinel", "sentinel value must match")
1808            }
1809            other => panic!("expected Text('b-side-sentinel'), got {other:?}"),
1810        }
1811
1812        // Row is absent from A (table does not exist there).
1813        let mut reader_a = rt_main.sql().reader().await.expect("main reader");
1814        let result_a = reader_a
1815            .query_all(SqlStatement {
1816                sql: "SELECT marker FROM _test_adr073_aux".into(),
1817                params: vec![],
1818                label: None,
1819            })
1820            .await;
1821        // A does not have this table → must error or return no rows.
1822        match result_a {
1823            Err(e) => assert!(
1824                e.to_string().contains("no such table"),
1825                "expected 'no such table' error from A, got: {e}"
1826            ),
1827            Ok(rows) => assert!(
1828                rows.is_empty(),
1829                "aux table must not have rows in A, got {} rows",
1830                rows.len()
1831            ),
1832        }
1833    }
1834
1835    #[test]
1836    fn constructors_leave_core_backend_none_by_behavior() {
1837        // core() on any standard constructor returns a clone with same backend_id —
1838        // proof that core_backend = None (returns self.clone(), not a different backend).
1839        let rt_mem = KhiveRuntime::memory().unwrap();
1840        assert_eq!(rt_mem.core().backend_id().as_str(), BackendId::MAIN);
1841
1842        let backend = migrated_memory_backend();
1843        let rt_from = KhiveRuntime::from_backend(
1844            backend,
1845            RuntimeConfig {
1846                git_write: Default::default(),
1847                db_path: None,
1848                default_namespace: Namespace::local(),
1849                embedding_model: None,
1850                additional_embedding_models: vec![],
1851                gate: Arc::new(AllowAllGate),
1852                packs: vec!["kg".to_string()],
1853                backend_id: BackendId::new("lore"),
1854                brain_profile: None,
1855                visible_namespaces: vec![],
1856                allowed_outbound_namespaces: vec![],
1857                actor_id: None,
1858            },
1859        );
1860        // from_backend with backend_id="lore" and no core_backend: core() returns
1861        // self.clone() which has backend_id="lore" (not "main").
1862        assert_eq!(rt_from.core().backend_id().as_str(), "lore");
1863    }
1864
1865    #[test]
1866    fn with_core_backend_sets_core_then_core_returns_main_id() {
1867        // After wiring, core() must return a runtime with backend_id == "main".
1868        let main_arc = migrated_memory_backend();
1869        let secondary_arc = migrated_memory_backend();
1870
1871        let rt_secondary = KhiveRuntime::from_backend(secondary_arc, secondary_config())
1872            .with_core_backend(main_arc);
1873
1874        assert_eq!(rt_secondary.backend_id().as_str(), "lore");
1875        assert_eq!(
1876            rt_secondary.core().backend_id().as_str(),
1877            BackendId::MAIN,
1878            "core() on a secondary runtime must return a main-bound handle"
1879        );
1880    }
1881
1882    #[tokio::test]
1883    async fn list_embedding_models_returns_empty_when_table_absent() {
1884        // A brand-new in-memory runtime has migrations applied, so _embedding_models
1885        // IS created. But with no rows inserted, the result must be empty.
1886        let rt = KhiveRuntime::memory().expect("memory runtime");
1887        let records = rt
1888            .list_embedding_models(None)
1889            .await
1890            .expect("list ok on empty table");
1891        assert!(records.is_empty());
1892    }
1893
1894    #[tokio::test]
1895    async fn list_embedding_models_returns_row_after_insert() {
1896        use khive_storage::{SqlStatement, SqlValue};
1897
1898        let rt = KhiveRuntime::memory().expect("memory runtime");
1899        let sql = rt.sql();
1900
1901        let now = 1_000_000i64;
1902        let id = uuid::Uuid::new_v4();
1903        let canonical_key = b"test_engine:test-model-v1:v1:384".to_vec();
1904
1905        let mut writer = sql.writer().await.expect("writer");
1906        writer
1907            .execute(SqlStatement {
1908                sql: "INSERT INTO _embedding_models \
1909                      (id, engine_name, model_id, key_version, dim, output_dim, status, \
1910                       activated_at, superseded_at, superseded_by, canonical_key, created_at) \
1911                      VALUES (?1, ?2, ?3, ?4, ?5, NULL, ?6, ?7, NULL, NULL, ?8, ?9)"
1912                    .into(),
1913                params: vec![
1914                    SqlValue::Blob(id.as_bytes().to_vec()),
1915                    SqlValue::Text("test_engine".into()),
1916                    SqlValue::Text("test-model-v1".into()),
1917                    SqlValue::Text("v1".into()),
1918                    SqlValue::Integer(384),
1919                    SqlValue::Text("active".into()),
1920                    SqlValue::Integer(now),
1921                    SqlValue::Blob(canonical_key),
1922                    SqlValue::Integer(now),
1923                ],
1924                label: None,
1925            })
1926            .await
1927            .expect("insert row");
1928        drop(writer);
1929
1930        let records = rt.list_embedding_models(None).await.expect("list ok");
1931        assert_eq!(records.len(), 1);
1932        assert_eq!(records[0].engine_name, "test_engine");
1933        assert_eq!(records[0].model_id, "test-model-v1");
1934        assert_eq!(records[0].key_version, "v1");
1935        assert_eq!(records[0].dimensions, 384);
1936        assert_eq!(records[0].status, "active");
1937
1938        // engine filter — match
1939        let filtered = rt
1940            .list_embedding_models(Some("test_engine"))
1941            .await
1942            .expect("filter ok");
1943        assert_eq!(filtered.len(), 1);
1944
1945        // engine filter — no match
1946        let no_match = rt
1947            .list_embedding_models(Some("other_engine"))
1948            .await
1949            .expect("no-match ok");
1950        assert!(no_match.is_empty());
1951    }
1952}