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::collections::HashMap;
7use std::sync::{Arc, OnceLock, RwLock};
8
9use khive_db::StorageBackend;
10#[cfg(test)]
11use khive_gate::AllowAllGate;
12use khive_gate::GateRequest;
13use khive_storage::types::{SqlStatement, SqlValue};
14use khive_storage::{
15    AttachmentStore, EntityStore, Event, EventStore, GraphStore, NoteStore, SqlAccess, VectorStore,
16};
17use khive_types::{EdgeEndpointRule, EventKind, Namespace, SubstrateKind};
18use lattice_embed::{EmbeddingModel, EmbeddingService};
19
20use crate::config::{
21    build_embedder_registry, parse_embedding_model_alias, register_configured_embedding_models,
22    sanitize_key, vec_model_key,
23};
24use crate::error::{RuntimeError, RuntimeResult};
25
26/// Callback type for pack-installed entity-type validators.
27///
28/// Receives `(kind, entity_type)` and returns the normalised type string,
29/// or `RuntimeError::InvalidInput` if the type is not registered for that kind.
30/// When `entity_type` is `None`, the implementation must return `Ok(None)`.
31pub type EntityTypeValidatorFn =
32    Arc<dyn Fn(&str, Option<&str>) -> Result<Option<String>, RuntimeError> + Send + Sync>;
33
34/// Callback type for a pack-installed note-mutation hook.
35///
36/// Invoked by `update_note` (when the note's text/embedding actually
37/// changed) and `delete_note` (soft or hard) with `(note_kind, note_id)`,
38/// after the mutation has been durably applied. Returns a boxed future so
39/// the hook can await async cache-invalidation work (e.g.
40/// `khive-pack-memory`'s ANN warm-cache generation bump) without
41/// `khive-runtime` depending on any pack crate: dependencies point the
42/// other way, so the runtime exposes an extension point and the pack
43/// installs into it, same shape as `EntityTypeValidatorFn`, just async.
44pub type NoteMutationHookFn = Arc<
45    dyn Fn(String, uuid::Uuid) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
46        + Send
47        + Sync,
48>;
49
50/// Callback type for a pack-installed note-write validator.
51///
52/// The pack that owns a note kind carrying derivable identity installs one so
53/// that the identity is a function of the authorization token rather than of
54/// caller input, on every write path including direct callers that bypass the
55/// handler layer — same rationale as [`EntityTypeValidatorFn`], which exists
56/// for exactly that reason on the entity side.
57///
58/// Kinds the installing pack does not own must be returned unchanged: the slot
59/// is single-occupancy (like `note_mutation_hook`), so a validator that
60/// rewrote foreign kinds would silently govern every other pack's notes.
61pub type NoteWriteValidatorFn = Arc<
62    dyn Fn(&str, &str, Option<serde_json::Value>) -> Result<Option<serde_json::Value>, RuntimeError>
63        + Send
64        + Sync,
65>;
66
67/// Immutable identity for a non-text vector store owned by a pack consumer.
68///
69/// This does not register an [`crate::EmbedderProvider`]. It gives a pack that
70/// performs its own governed inference a narrow path to a namespace-scoped
71/// Khive vector table while keeping model-key and dimension validation at the
72/// runtime boundary.
73#[derive(Clone, Debug, Eq, PartialEq)]
74pub struct NamedVectorIdentity {
75    model_key: String,
76    model_name: String,
77    dimensions: usize,
78}
79
80impl NamedVectorIdentity {
81    const MAX_MODEL_KEY_BYTES: usize = 128;
82    const MAX_MODEL_NAME_BYTES: usize = 512;
83
84    /// Validate and construct a named vector identity.
85    pub fn new(
86        model_key: impl Into<String>,
87        model_name: impl Into<String>,
88        dimensions: usize,
89    ) -> RuntimeResult<Self> {
90        let model_key = model_key.into();
91        let model_name = model_name.into();
92        if model_key.is_empty()
93            || model_key.len() > Self::MAX_MODEL_KEY_BYTES
94            || !model_key
95                .chars()
96                .all(|c| c.is_ascii_alphanumeric() || c == '_')
97        {
98            return Err(RuntimeError::InvalidInput(format!(
99                "named vector model_key must be 1..={} bytes of ASCII alphanumeric/underscore",
100                Self::MAX_MODEL_KEY_BYTES
101            )));
102        }
103        if model_name.trim().is_empty()
104            || model_name.trim() != model_name
105            || model_name.len() > Self::MAX_MODEL_NAME_BYTES
106        {
107            return Err(RuntimeError::InvalidInput(format!(
108                "named vector model_name must be 1..={} bytes with no surrounding whitespace",
109                Self::MAX_MODEL_NAME_BYTES
110            )));
111        }
112        if !(1..=8192).contains(&dimensions) {
113            return Err(RuntimeError::InvalidInput(format!(
114                "named vector dimensions must be in 1..=8192, got {dimensions}"
115            )));
116        }
117        Ok(Self {
118            model_key,
119            model_name,
120            dimensions,
121        })
122    }
123
124    pub fn model_key(&self) -> &str {
125        &self.model_key
126    }
127
128    pub fn model_name(&self) -> &str {
129        &self.model_name
130    }
131
132    pub fn dimensions(&self) -> usize {
133        self.dimensions
134    }
135}
136
137pub use crate::config::{
138    assert_captured_db_anchor_consistent, assert_db_anchor_consistent, expand_tilde,
139    parse_pack_list, resolve_db_anchor, resolve_project_actor_id, runtime_config_from_khive_config,
140    BackendId, NamespaceToken, RuntimeConfig,
141};
142
143// ---- KhiveRuntime ----
144
145/// Composable runtime handle used by the MCP server.
146///
147/// Wraps a `StorageBackend` and provides namespace-scoped accessor methods
148/// for each storage capability, plus a lazily-loaded embedder.
149#[derive(Clone)]
150pub struct KhiveRuntime {
151    backend: Arc<StorageBackend>,
152    /// When `Some`, holds the main backend so that `core()` can return a
153    /// main-bound runtime handle without constructing a new connection.
154    /// `None` when this runtime is already bound to the main backend.
155    core_backend: Option<Arc<StorageBackend>>,
156    config: RuntimeConfig,
157    /// ADR-118 exact-leg policy, sampled once at runtime construction.
158    /// Request-time memory/knowledge serving must never re-read the process
159    /// environment because tests and embedded runtimes share one process.
160    ann_fresh_tail_enabled: bool,
161    /// Pack-extensible embedder registry.
162    ///
163    /// Shared across clones via `Arc<RwLock<_>>` so that
164    /// [`register_embedder`](Self::register_embedder) after clone is visible
165    /// to all handles. Built-in lattice models are pre-registered during
166    /// construction; packs may add more via [`PackRuntime::register_embedders`].
167    embedder_registry: Arc<std::sync::RwLock<crate::embedder_registry::EmbedderRegistry>>,
168    default_embedder_name: Arc<str>,
169    /// Pack-extensible edge endpoint rules. Shared across clones
170    /// via `Arc<RwLock<_>>`; installed once by the transport after the
171    /// `VerbRegistry` is built. Empty until installed
172    edge_rules: Arc<RwLock<Vec<EdgeEndpointRule>>>,
173    /// Pack-aggregated valid entity and note kind strings.
174    ///
175    /// Installed by the transport layer after building the `VerbRegistry`.
176    /// When non-empty, `create_entity`, `create_note_inner`, and `import_kg`
177    /// reject kinds not in these sets. When empty (no packs loaded, e.g.
178    /// bare runtime in unit tests), kind validation is skipped — the pack
179    /// handler layer is the primary enforcement point.
180    valid_entity_kinds: Arc<RwLock<Vec<String>>>,
181    valid_note_kinds: Arc<RwLock<Vec<String>>>,
182    /// Pack-installed entity-type validator.
183    ///
184    /// When `Some`, `create_many` calls this function to validate and normalise
185    /// each `(kind, entity_type)` pair before writing. When `None` (bare runtime
186    /// without packs), entity-type validation is skipped — the pack handler layer
187    /// is the primary enforcement point, same as for `valid_entity_kinds`.
188    entity_type_validator: Arc<RwLock<Option<EntityTypeValidatorFn>>>,
189    /// Pack-installed note-mutation hook.
190    ///
191    /// When `Some`, `update_note` (on text change) and `delete_note` (soft
192    /// or hard) call this after the mutation is durably applied, so a pack
193    /// that caches derived state keyed by note content (e.g. `khive-pack-memory`'s
194    /// warm ANN index) can invalidate/advance its own generation counter even
195    /// when the mutation arrived through a different pack's verb (e.g. KG's
196    /// `update`/`delete` on a `kind="memory"` note) that has no dependency on
197    /// the reacting pack. `None` when no pack installs one (bare runtime, or
198    /// no pack cares about note-mutation notifications) — the call becomes a
199    /// no-op check of an `Option`.
200    note_mutation_hook: Arc<RwLock<Option<NoteMutationHookFn>>>,
201    /// Pack-installed note-write validator.
202    ///
203    /// When `Some`, every runtime note-materialisation site that accepts
204    /// caller-supplied `properties` routes them through this function before
205    /// the `Note` is built, so a pack-owned identity property is derived from
206    /// the authorization token instead of trusted from caller input. `None`
207    /// on a bare runtime (no packs) — the properties pass through unchanged.
208    note_write_validator: Arc<RwLock<Option<NoteWriteValidatorFn>>>,
209    /// Pack-owned note kinds — every note kind declared by a pack other than
210    /// the generic-CRUD pack, installed by the transport from the registry
211    /// (see `VerbRegistry::pack_owned_note_kinds`). Records of these kinds are
212    /// maintained by their owning pack's own verbs, so `update`'s `properties`
213    /// patch is refused on them at the runtime layer and their owned identity
214    /// properties survive a `merge` unchanged. Empty until installed (bare
215    /// runtime), which leaves both rules inert.
216    pack_owned_note_kinds: Arc<RwLock<Vec<String>>>,
217    /// The immutable runtime-owned store/hydration pair (ADR-160 D3).
218    ///
219    /// Boot resolves one store and constructs exactly one shared hydrator,
220    /// then installs that same `Arc` on every runtime handle. The one-shot
221    /// slot rejects replacement so pack runtimes cannot silently split the
222    /// aggregate byte budget after startup. Bare runtimes leave it unset.
223    blob_hydrator: Arc<OnceLock<Arc<crate::blob::BlobHydrator>>>,
224    /// Pack-registered custom fusion executors (ADR-012), keyed by the name
225    /// carried in `FusionStrategy::Custom { name, .. }`.
226    ///
227    /// Unlike `entity_type_validator`/`note_mutation_hook` (single-occupancy —
228    /// one pack owns the slot), multiple packs each register their own named
229    /// strategy under this shared map, so it is keyed rather than a bare
230    /// `Option`. Empty until a pack calls
231    /// [`register_fusion_strategy`](Self::register_fusion_strategy); an
232    /// unregistered `Custom` name at dispatch time is
233    /// `RuntimeError::UnknownFusionStrategy`, never a silent fallback.
234    fusion_executors: Arc<RwLock<HashMap<String, Arc<dyn crate::fusion::FusionExecutor>>>>,
235}
236
237impl KhiveRuntime {
238    /// Create a new runtime with the given config.
239    ///
240    /// The config's `db_path` is used to open or create the SQLite backend.
241    /// This direct constructor is intended for fresh/current single-backend
242    /// databases and tests. Production and multi-backend hosts must use the
243    /// async khive-mcp/kkernel builders so secondary inventory and any
244    /// application-assisted V21 cutover complete before serving. The
245    /// [`from_backend`](Self::from_backend) seam is likewise only for an
246    /// already-prepared backend.
247    pub fn new(config: RuntimeConfig) -> RuntimeResult<Self> {
248        let backend = match &config.db_path {
249            Some(path) => {
250                if let Some(parent) = path.parent() {
251                    std::fs::create_dir_all(parent).ok();
252                }
253                StorageBackend::sqlite(path)?
254            }
255            None => StorageBackend::memory()?,
256        };
257        // Writable backends migrate before handlers touch the DB. A detected
258        // read-only snapshot is validated at the current schema version without
259        // attempting migration DDL.
260        let schema_version = backend.prepare_core_schema()?;
261        if schema_version < khive_db::migrations::ATTACHMENT_CUTOVER_VERSION {
262            return Err(khive_db::SqliteError::InvalidData(
263                "database requires the host application-assisted V21 attachment cutover; \
264                 start through khive-mcp/kkernel boot instead of constructing KhiveRuntime \
265                 directly"
266                    .into(),
267            )
268            .into());
269        }
270        if !backend.is_read_only() {
271            register_configured_embedding_models(&backend, &config)?;
272        }
273        Ok(Self::assemble_from_backend(Arc::new(backend), config))
274    }
275
276    /// Open a runtime for read-only inspection (no model registration, no DB creation).
277    ///
278    /// File-backed databases are opened with SQLite read-only/query-only flags
279    /// and must already be at this build's current schema version. No migrations
280    /// or configured-model registration writes are attempted. A `None` path
281    /// retains the historical ephemeral in-memory behavior for tests.
282    pub fn new_readonly(config: RuntimeConfig) -> RuntimeResult<Self> {
283        let backend = match &config.db_path {
284            Some(path) => StorageBackend::sqlite_read_only(path)?,
285            None => StorageBackend::memory()?,
286        };
287        backend.prepare_core_schema()?;
288        Ok(Self::assemble_from_backend(Arc::new(backend), config))
289    }
290
291    /// Construct a runtime from an already-opened backend.
292    ///
293    /// This is a low-level, infallible assembly seam for already-prepared
294    /// multi-backend deployments. It does not inspect or migrate the V21
295    /// attachment-cutover state. Production hosts must first run the async
296    /// kkernel/khive-mcp coordinator and must not expose a server over a
297    /// pending or incomplete backend. Prefer [`Self::from_prepared_backend`]
298    /// when constructing one fallible host runtime.
299    ///
300    /// The returned runtime has `db_path = None` and `embedding_model = None`; all
301    /// storage access is through the provided `backend`. Set `backend_id` and
302    /// `default_namespace` via the config builder pattern if non-defaults are needed.
303    pub fn from_backend(backend: Arc<StorageBackend>, config: RuntimeConfig) -> Self {
304        if !backend.is_read_only() {
305            if let Err(err) = register_configured_embedding_models(&backend, &config) {
306                tracing::warn!(error = %err, "failed to register configured embedding models");
307            }
308        }
309        Self::assemble_from_backend(backend, config)
310    }
311
312    /// Construct a single-backend runtime after a host boot coordinator has
313    /// completed schema preparation and any application-assisted cutover.
314    ///
315    /// Unlike [`Self::from_backend`], configured embedding-model registration
316    /// is fallible here, preserving [`Self::new`]'s single-backend startup
317    /// semantics. This method never runs migrations itself.
318    pub fn from_prepared_backend(
319        backend: Arc<StorageBackend>,
320        config: RuntimeConfig,
321    ) -> RuntimeResult<Self> {
322        if backend.attachment_cutover_status()?
323            != khive_db::migrations::AttachmentCutoverStatus::Complete
324        {
325            return Err(khive_db::SqliteError::InvalidData(
326                "from_prepared_backend requires a complete V21 attachment cutover".into(),
327            )
328            .into());
329        }
330        if !backend.is_read_only() {
331            register_configured_embedding_models(&backend, &config)?;
332        }
333        Ok(Self::assemble_from_backend(backend, config))
334    }
335
336    fn assemble_from_backend(backend: Arc<StorageBackend>, config: RuntimeConfig) -> Self {
337        let ann_fresh_tail_enabled = crate::config::ann_fresh_tail_enabled_from_env();
338        let (registry, default_embedder_name) = build_embedder_registry(&config);
339        Self {
340            backend,
341            core_backend: None,
342            config,
343            ann_fresh_tail_enabled,
344            embedder_registry: Arc::new(std::sync::RwLock::new(registry)),
345            default_embedder_name,
346            edge_rules: Arc::new(RwLock::new(Vec::new())),
347            valid_entity_kinds: Arc::new(RwLock::new(Vec::new())),
348            valid_note_kinds: Arc::new(RwLock::new(Vec::new())),
349            entity_type_validator: Arc::new(RwLock::new(None)),
350            note_mutation_hook: Arc::new(RwLock::new(None)),
351            note_write_validator: Arc::new(RwLock::new(None)),
352            pack_owned_note_kinds: Arc::new(RwLock::new(Vec::new())),
353            blob_hydrator: Arc::new(OnceLock::new()),
354            fusion_executors: Arc::new(RwLock::new(HashMap::new())),
355        }
356    }
357
358    /// Wire this runtime as a secondary-backend runtime pointing at `core`.
359    ///
360    /// After this call, `self.core()` returns a handle to `core` rather than
361    /// cloning `self`. The caller (the boot path, not pack code) is responsible
362    /// for passing the correct main backend.
363    ///
364    /// Panics in debug builds if `self.config.backend_id == BackendId::MAIN`,
365    /// because the main runtime does not need a core pointer.
366    pub fn with_core_backend(mut self, core: Arc<StorageBackend>) -> Self {
367        debug_assert_ne!(
368            self.config.backend_id.as_str(),
369            BackendId::MAIN,
370            "with_core_backend must not be called on the main runtime"
371        );
372        self.core_backend = Some(core);
373        self
374    }
375
376    /// Return a runtime handle bound to the main (shared-graph) backend.
377    ///
378    /// When `self` is already the main runtime (`core_backend` is `None`),
379    /// this returns a clone of `self` — no new backend reference is acquired.
380    ///
381    /// When `self` is a secondary-backend runtime (`core_backend` is `Some`),
382    /// this returns a new `KhiveRuntime` backed by the main
383    /// `Arc<StorageBackend>` and sharing all registry state (`embedder_registry`,
384    /// `edge_rules`, `valid_entity_kinds`, `valid_note_kinds`,
385    /// `entity_type_validator`, `note_mutation_hook`) with `self`.
386    /// No database I/O occurs; no embedding models are reloaded.
387    ///
388    /// Use `core()` for notes and entities that must reside in the shared graph
389    /// so that `memory.recall`, cross-pack search, and `annotates` edges work.
390    /// Use `self` (or `self.sql()`) for pack-auxiliary bulk tables.
391    ///
392    /// Handlers that call `core()` more than once per request or loop should bind
393    /// `let core = self.core();` once and reuse it, since each call clones
394    /// `RuntimeConfig` (a heap-allocated struct containing `Vec<String>` fields).
395    pub fn core(&self) -> KhiveRuntime {
396        match &self.core_backend {
397            None => self.clone(),
398            Some(main_arc) => {
399                let mut core_config = self.config.clone();
400                core_config.backend_id = BackendId::main();
401                KhiveRuntime {
402                    backend: main_arc.clone(),
403                    core_backend: None,
404                    config: core_config,
405                    ann_fresh_tail_enabled: self.ann_fresh_tail_enabled,
406                    embedder_registry: self.embedder_registry.clone(),
407                    default_embedder_name: self.default_embedder_name.clone(),
408                    edge_rules: self.edge_rules.clone(),
409                    valid_entity_kinds: self.valid_entity_kinds.clone(),
410                    valid_note_kinds: self.valid_note_kinds.clone(),
411                    entity_type_validator: self.entity_type_validator.clone(),
412                    note_mutation_hook: self.note_mutation_hook.clone(),
413                    note_write_validator: self.note_write_validator.clone(),
414                    pack_owned_note_kinds: self.pack_owned_note_kinds.clone(),
415                    blob_hydrator: self.blob_hydrator.clone(),
416                    fusion_executors: self.fusion_executors.clone(),
417                }
418            }
419        }
420    }
421
422    /// Create an in-memory runtime (for tests and ephemeral use).
423    pub fn memory() -> RuntimeResult<Self> {
424        Self::new(RuntimeConfig {
425            db_path: None,
426            packs: vec!["kg".to_string()],
427            brain_profile: None,
428            actor_id: None,
429            ..RuntimeConfig::no_embeddings()
430        })
431    }
432
433    /// Return the [`BackendId`] for this runtime's backend.
434    ///
435    /// Used by `SubstrateCoordinator` in `kkernel`
436    /// to identify which backend owns a given node, and to detect cross-backend merges.
437    pub fn backend_id(&self) -> &BackendId {
438        &self.config.backend_id
439    }
440
441    /// Return the extra-visible namespaces assembled at config load.
442    ///
443    /// OSS dispatch uses this set to widen the default multi-record read scope
444    /// to `['local'] ∪ visible_namespaces`. Writes are unchanged: always
445    /// pinned to `'local'`. This set is also available as gate/cloud policy
446    /// input.
447    pub fn visible_namespaces(&self) -> &[Namespace] {
448        &self.config.visible_namespaces
449    }
450
451    /// Return a reference to the runtime config.
452    pub fn config(&self) -> &RuntimeConfig {
453        &self.config
454    }
455
456    /// Return the immutable ADR-118 fresh-tail serving policy captured when
457    /// this runtime was constructed.
458    pub fn ann_fresh_tail_enabled(&self) -> bool {
459        self.ann_fresh_tail_enabled
460    }
461
462    /// Override ADR-118's fresh-tail serving policy for this runtime instance.
463    ///
464    /// This is primarily useful for embedded runtimes and deterministic tests:
465    /// it avoids mutating process-global environment state. Clones and `core()`
466    /// handles preserve the chosen value.
467    pub fn with_ann_fresh_tail_enabled(mut self, enabled: bool) -> Self {
468        self.ann_fresh_tail_enabled = enabled;
469        self
470    }
471
472    /// Return a reference to the underlying storage backend.
473    ///
474    /// This is an embedder/infrastructure surface (connection pools, schema
475    /// plans, diagnostics). Stores obtained from it are NOT wrapped by the
476    /// message-evidence policy that [`Self::notes`] enforces: an embedder
477    /// holding the backend already holds root-equivalent access to the
478    /// database file, so the policy boundary sits at the typed accessors
479    /// pack code uses, not here. Pack code must not take note stores from
480    /// this surface.
481    pub fn backend(&self) -> &StorageBackend {
482        &self.backend
483    }
484
485    /// Whether this runtime's bound backend is explicitly or filesystem-mode
486    /// detected read-only.
487    pub fn is_read_only(&self) -> bool {
488        self.backend.is_read_only()
489    }
490
491    /// Return the directory containing the backend's database file, or `None`
492    /// for an in-memory backend.
493    pub fn backend_data_dir(&self) -> Option<std::path::PathBuf> {
494        self.backend.data_dir()
495    }
496
497    /// Root directory for this database's ANN segment tree (`<db-file>.ann/`
498    /// beside the file), or `None` for an in-memory backend. Scoped to the
499    /// database file itself so two databases sharing a parent directory can
500    /// never adopt each other's segments.
501    pub fn backend_ann_root(&self) -> Option<std::path::PathBuf> {
502        self.backend.ann_root()
503    }
504
505    /// Writer-contention, graph-edge integrity, and WAL/checkpoint diagnostics
506    /// (ADR-091/ADR-135 operator surface): pooled writer and audit-failure
507    /// counters, build identity, duplicate edge-ID and list-ledger counts,
508    /// checkpoint counters, a PASSIVE checkpoint probe, WAL file size, and
509    /// explicitly qualified WAL-pin census. Not write-free: the
510    /// PASSIVE probe may backfill WAL frames into the database (normal
511    /// checkpoint I/O). It never changes logical state, escalates to TRUNCATE,
512    /// creates a missing database file, or deletes sidecar evidence — see
513    /// `khive_db::diagnostics` for the narrowings that make those claims hold.
514    ///
515    /// Always targets the *main* backend via [`Self::core`], regardless of
516    /// which backend this runtime handle is bound to, so a report never
517    /// describes a database this handle is not the canonical owner of.
518    pub async fn db_diagnostics(&self) -> RuntimeResult<khive_db::diagnostics::DbDiagnostics> {
519        // No `VerbRegistry` handle is reachable from a bare `KhiveRuntime`
520        // (the audit-batch seam is owned by whichever registry was built
521        // over this runtime's `EventStore`, not by the runtime itself), so
522        // the batch-health fields report unavailable with a reason here.
523        // Callers that hold the registry — e.g. the `db_diagnostics` verb
524        // handler — use `Self::db_diagnostics_with_audit_metrics` with
525        // `VerbRegistry::audit_batch_metrics()` instead.
526        self.db_diagnostics_with_audit_metrics(None).await
527    }
528
529    /// As [`Self::db_diagnostics`], but with the caller supplying the
530    /// ADR-133 audit-batch health counters from whichever `VerbRegistry`
531    /// owns the seam over this runtime's `EventStore` (typically
532    /// `VerbRegistry::audit_batch_metrics()`). `None` behaves identically to
533    /// [`Self::db_diagnostics`].
534    pub async fn db_diagnostics_with_audit_metrics(
535        &self,
536        runtime_audit_batch_metrics: Option<khive_db::diagnostics::RuntimeAuditBatchMetrics>,
537    ) -> RuntimeResult<khive_db::diagnostics::DbDiagnostics> {
538        let pool = self.core().backend.pool_arc();
539        let interval = khive_db::CheckpointConfig::from_env().interval;
540        let build_hash = crate::build_info::BUILD_INFO
541            .is_stamped()
542            .then_some(crate::build_info::BUILD_INFO.source_revision);
543        let build =
544            khive_db::diagnostics::BuildIdentity::from_env(env!("CARGO_PKG_VERSION"), build_hash);
545
546        khive_db::diagnostics::collect_with_runtime_audit_metrics_interruptibly(
547            pool,
548            build,
549            interval,
550            crate::pack::audit_append_failure_count(),
551            runtime_audit_batch_metrics,
552        )
553        .await
554        .map_err(RuntimeError::from)
555    }
556
557    // ---- Store accessors (token-scoped) ----
558
559    /// Get an EntityStore scoped to the token's namespace.
560    pub fn entities(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn EntityStore>> {
561        Ok(self
562            .backend
563            .entities_for_namespace(token.namespace().as_str())?)
564    }
565
566    /// Get a GraphStore scoped to the token's namespace.
567    pub fn graph(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn GraphStore>> {
568        Ok(self
569            .backend
570            .graph_for_namespace(token.namespace().as_str())?)
571    }
572
573    /// Get a NoteStore scoped to the token's namespace.
574    ///
575    /// Wrapped in `note_store_guard::PolicyEnforcingNoteStore`, which
576    /// refuses any insert/upsert of a `kind = "message"` note carrying
577    /// `quarantined` / `channel_kind` / `channel_slug` — the transport-owned
578    /// evidence `comm.health` trusts at face value — and refuses patching
579    /// those keys through the property-mutation seams on any note kind, so
580    /// the guard cannot be sidestepped by inserting a clean message note and
581    /// patching the evidence onto it afterward. The trusted channel-ingest
582    /// path does not go through this accessor; see
583    /// `Self::raw_notes` and [`Self::try_create_note_as_trusted_ingest`].
584    pub fn notes(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn NoteStore>> {
585        Ok(crate::note_store_guard::PolicyEnforcingNoteStore::wrap(
586            self.raw_notes(token)?,
587        ))
588    }
589
590    /// Get the unwrapped, policy-free NoteStore scoped to the token's namespace.
591    ///
592    /// Bypasses `note_store_guard::PolicyEnforcingNoteStore`. Callers
593    /// within this crate that have already enforced the reserved-transport-
594    /// property policy themselves (namely `try_create_note_impl`, which
595    /// applies it conditionally based on whether the caller presented a
596    /// [`crate::pack::ChannelIngestCapability`]) use this to reach storage
597    /// directly rather than run a redundant, less-informed check. Not exposed
598    /// outside this crate — every other caller must use [`Self::notes`].
599    pub(crate) fn raw_notes(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn NoteStore>> {
600        Ok(self
601            .backend
602            .notes_for_namespace(token.namespace().as_str())?)
603    }
604
605    /// Return the role-keyed attachment substrate on the canonical main backend.
606    ///
607    /// Attachment rows are the process-shared BlobStore's sole SQL liveness
608    /// authority. A runtime bound directly to a secondary pack backend must call
609    /// [`Self::core`] first; accepting a secondary mutation here would create a
610    /// reference that the main-database GC sweep cannot see or fence.
611    pub fn attachments(&self) -> RuntimeResult<Arc<dyn AttachmentStore>> {
612        if self.config.backend_id.as_str() != BackendId::MAIN {
613            return Err(RuntimeError::InvalidInput(format!(
614                "attachments are owned by the canonical main backend; runtime backend {:?} must route through KhiveRuntime::core()",
615                self.config.backend_id.as_str()
616            )));
617        }
618        Ok(self.backend.attachments()?)
619    }
620
621    /// Get an EventStore scoped to the token's namespace.
622    ///
623    /// When the events-daemon split (ADR-170) is configured, the store routes
624    /// by append class: the ADR-133 idempotent audit-batch lane — the
625    /// measured bulk of event write volume — persists to the events database
626    /// (forwarded over the events daemon socket in daemon deployments, or
627    /// opened directly in embedded/one-shot contexts), while plain appends
628    /// stay on this runtime's backend, keeping every raw-SQL consumer of the
629    /// legacy `events` table (schedule provenance, kg projection guards,
630    /// GraphQuery's substrate union) correct by construction. Reads merge
631    /// both stores. Unconfigured runtimes (tests, in-memory) keep the legacy
632    /// main-store behavior.
633    pub fn events(&self, token: &NamespaceToken) -> RuntimeResult<Arc<dyn EventStore>> {
634        let legacy = self
635            .backend
636            .events_for_namespace(token.namespace().as_str())?;
637        match &self.config.events_split {
638            None => Ok(legacy),
639            Some(split) => {
640                // Read-only is decided before the transport question: a
641                // read-only runtime must neither create nor schema-initialize
642                // an events database, and it must not forward writes to the
643                // events daemon either — a socket in the config describes the
644                // deployment, not this process's authority. Serve merged
645                // reads from a read-only open of the sidecar when it exists
646                // (the storage-layer read-only binding refuses any write that
647                // slips through), and the legacy store alone otherwise: no
648                // sidecar on disk means no lane rows exist, so minting the
649                // file just to read nothing from it would be a write in
650                // disguise.
651                if self.backend.is_read_only() {
652                    if !split.db_path.exists() {
653                        return Ok(legacy);
654                    }
655                    let lane = crate::events_split::direct_backend_read_only_for(&split.db_path)?
656                        .events_for_namespace(token.namespace().as_str())?;
657                    return Ok(Arc::new(crate::events_split::SplitEventStore::new(
658                        legacy, lane,
659                    )));
660                }
661                let lane: Arc<dyn EventStore> = match &split.socket_path {
662                    #[cfg(unix)]
663                    Some(socket) => {
664                        let client = crate::events_split::client_for(socket)?;
665                        Arc::new(crate::events_split::ForwardingEventStore::new(
666                            token.namespace().as_str(),
667                            client,
668                        ))
669                    }
670                    #[cfg(not(unix))]
671                    Some(_socket) => {
672                        return Err(RuntimeError::InvalidInput(
673                            "events-daemon socket forwarding requires a Unix platform; \
674                             configure the events split in direct mode here"
675                                .to_string(),
676                        ));
677                    }
678                    None => crate::events_split::direct_backend_for(&split.db_path)?
679                        .events_for_namespace(token.namespace().as_str())?,
680                };
681                Ok(Arc::new(crate::events_split::SplitEventStore::new(
682                    legacy, lane,
683                )))
684            }
685        }
686    }
687
688    /// Get the raw SQL access capability (for ad-hoc queries).
689    pub fn sql(&self) -> Arc<dyn SqlAccess> {
690        self.backend.sql()
691    }
692
693    /// SQL access to the events-split sidecar database for read purposes,
694    /// when the split (ADR-170) is configured and the sidecar exists on
695    /// disk. `None` means every event row lives in the legacy `events`
696    /// table, so a raw-SQL consumer needs no second lookup. Consumers that
697    /// resolve an event by id or hex prefix against `self.sql()` must also
698    /// consult this store on a miss: the audit-batch lane's rows live only
699    /// in the sidecar.
700    ///
701    /// A writable runtime opens the sidecar through the ordinary writable
702    /// binding: WAL supports one-writer-many-readers, and the read-only
703    /// binding's frozen-snapshot guard refuses any sidecar with a live
704    /// writer's `-shm` beside it — exactly the live-deployment case these
705    /// reads exist for. A read-only runtime keeps the read-only open (it
706    /// must neither create nor schema-initialize a sidecar), which serves
707    /// genuinely frozen snapshots and refuses live ones, matching the
708    /// read-only arm of `events()`. Never creates a sidecar as a side
709    /// effect of a read.
710    pub fn events_sidecar_sql_read_only(&self) -> RuntimeResult<Option<Arc<dyn SqlAccess>>> {
711        match &self.config.events_split {
712            None => Ok(None),
713            Some(split) => {
714                if !split.db_path.exists() {
715                    return Ok(None);
716                }
717                let backend = if self.backend.is_read_only() {
718                    crate::events_split::direct_backend_read_only_for(&split.db_path)?
719                } else {
720                    crate::events_split::direct_backend_for(&split.db_path)?
721                };
722                Ok(Some(backend.sql()))
723            }
724        }
725    }
726
727    /// Get a VectorStore for the configured embedding model, scoped to the token's namespace.
728    ///
729    /// Returns `Unconfigured("embedding_model")` if no model is set.
730    pub fn vectors(
731        &self,
732        token: &NamespaceToken,
733    ) -> RuntimeResult<Arc<dyn khive_storage::VectorStore>> {
734        let model = self.resolve_embedding_model(None)?;
735        self.vectors_for_embedding_model(token, model)
736    }
737
738    /// Get a VectorStore for a specific named embedding model, scoped to the token's namespace.
739    ///
740    /// Accepts both built-in lattice model names/aliases and custom provider names
741    /// registered via [`register_embedder`](Self::register_embedder). Lattice names
742    /// are routed through the enum-backed path; custom provider names use the
743    /// provider's declared `dimensions()` directly so that the vector store key
744    /// is consistent with how vectors were written during `remember`/`recall`.
745    pub fn vectors_for_model(
746        &self,
747        token: &NamespaceToken,
748        model_name: &str,
749    ) -> RuntimeResult<Arc<dyn khive_storage::VectorStore>> {
750        if let Some(model) = parse_embedding_model_alias(model_name) {
751            // Only proceed via the lattice path if this model is actually in the
752            // registry; otherwise fall through to the custom-provider path.
753            let key = model.to_string();
754            let in_registry = self
755                .embedder_registry
756                .read()
757                .map(|reg| reg.contains(&key))
758                .unwrap_or(false);
759            if in_registry {
760                return self.vectors_for_embedding_model(token, model);
761            }
762        }
763        let dims = {
764            let registry = self.embedder_registry.read().map_err(|_| {
765                crate::RuntimeError::Internal("embedder registry lock poisoned".into())
766            })?;
767            registry
768                .get_provider(model_name)
769                .map(|p| p.dimensions())
770                .ok_or_else(|| crate::RuntimeError::UnknownModel(model_name.to_string()))?
771        };
772        let model_key = sanitize_key(model_name);
773        Ok(self.backend.vectors_for_namespace(
774            &model_key,
775            model_name,
776            dims,
777            token.namespace().as_str(),
778        )?)
779    }
780
781    /// Get a namespace-scoped vector store for a pack-owned immutable identity.
782    ///
783    /// The table key is syntactically validated by [`NamedVectorIdentity`]. This
784    /// accessor additionally verifies the table's actual sqlite-vec dimension
785    /// declaration and every persisted `embedding_model` value before returning
786    /// the store, so reusing one key for incompatible descriptor geometry or
787    /// semantics fails before a caller can replace rows.
788    pub async fn vectors_for_named_identity(
789        &self,
790        token: &NamespaceToken,
791        identity: &NamedVectorIdentity,
792    ) -> RuntimeResult<Arc<dyn VectorStore>> {
793        let store = self.backend.vectors_for_namespace(
794            identity.model_key(),
795            identity.model_name(),
796            identity.dimensions(),
797            token.namespace().as_str(),
798        )?;
799
800        let table = format!("vec_{}", identity.model_key());
801        let mut reader = self.sql().reader().await?;
802        let dimension_row = reader
803            .query_row(SqlStatement {
804                sql: "SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?1".to_string(),
805                params: vec![SqlValue::Text(table.clone())],
806                label: Some("runtime_named_vector_dimension".to_string()),
807            })
808            .await?
809            .ok_or_else(|| {
810                RuntimeError::Internal(format!(
811                    "named vector table {table} has no sqlite_schema declaration"
812                ))
813            })?;
814        let table_ddl = match dimension_row.get("sql") {
815            Some(SqlValue::Text(value)) => value,
816            other => {
817                return Err(RuntimeError::Internal(format!(
818                    "named vector table {table} returned invalid schema metadata: {other:?}"
819                )))
820            }
821        };
822        let declared_dimensions = vector_dimensions_from_ddl(table_ddl).ok_or_else(|| {
823            RuntimeError::Internal(format!(
824                "named vector table {table} has no parseable embedding dimension"
825            ))
826        })?;
827        if declared_dimensions != identity.dimensions() {
828            return Err(RuntimeError::InvalidInput(format!(
829                "named vector model_key {:?} is already bound to {declared_dimensions} dimensions, expected {}",
830                identity.model_key(),
831                identity.dimensions()
832            )));
833        }
834
835        let stored_models = reader
836            .query_all(SqlStatement {
837                sql: format!(
838                    "SELECT DISTINCT embedding_model FROM {table} ORDER BY embedding_model LIMIT 2"
839                ),
840                params: vec![],
841                label: Some("runtime_named_vector_model_identity".to_string()),
842            })
843            .await?;
844        for row in stored_models {
845            let stored = match row.get("embedding_model") {
846                Some(SqlValue::Text(value)) => value,
847                other => {
848                    return Err(RuntimeError::Internal(format!(
849                        "named vector table {table} returned invalid model identity metadata: {other:?}"
850                    )))
851                }
852            };
853            if stored != identity.model_name() {
854                return Err(RuntimeError::InvalidInput(format!(
855                    "named vector model_key {:?} already contains model {stored:?}, cannot bind it to {:?}",
856                    identity.model_key(),
857                    identity.model_name()
858                )));
859            }
860        }
861
862        self.backend
863            .register_embedding_model(
864                identity.model_key(),
865                identity.model_name(),
866                identity.model_key(),
867                identity.dimensions() as u32,
868            )
869            .map_err(|error| {
870                if matches!(
871                    &error,
872                    khive_db::SqliteError::Rusqlite(rusqlite::Error::SqliteFailure(code, _))
873                        if code.code == rusqlite::ErrorCode::ConstraintViolation
874                ) {
875                    RuntimeError::InvalidInput(format!(
876                        "named vector model_key {:?} is already bound to a different active model identity",
877                        identity.model_key()
878                    ))
879                } else {
880                    RuntimeError::Sqlite(error)
881                }
882            })?;
883
884        Ok(store)
885    }
886
887    /// Output dimensions for a named embedding model, resolved from the
888    /// embedder registry alone — no storage access. Mirrors
889    /// [`vectors_for_model`](Self::vectors_for_model)'s resolution order:
890    /// lattice aliases route through the enum when registered, otherwise the
891    /// custom provider's declared `dimensions()`. `None` when no such model
892    /// is registered.
893    pub fn embedder_dimensions(&self, model_name: &str) -> Option<usize> {
894        if let Some(model) = parse_embedding_model_alias(model_name) {
895            let key = model.to_string();
896            let in_registry = self
897                .embedder_registry
898                .read()
899                .map(|reg| reg.contains(&key))
900                .unwrap_or(false);
901            if in_registry {
902                return Some(model.dimensions());
903            }
904        }
905        self.embedder_registry
906            .read()
907            .ok()?
908            .get_provider(model_name)
909            .map(|p| p.dimensions())
910    }
911
912    fn vectors_for_embedding_model(
913        &self,
914        token: &NamespaceToken,
915        model: EmbeddingModel,
916    ) -> RuntimeResult<Arc<dyn khive_storage::VectorStore>> {
917        Ok(self.backend.vectors_for_namespace(
918            &vec_model_key(model),
919            &model.to_string(),
920            model.dimensions(),
921            token.namespace().as_str(),
922        )?)
923    }
924
925    /// Get a TextSearch index for the entity corpus (single shared table).
926    pub fn text(
927        &self,
928        token: &NamespaceToken,
929    ) -> RuntimeResult<Arc<dyn khive_storage::TextSearch>> {
930        let _ = token;
931        Ok(self.backend.text("entities")?)
932    }
933
934    /// Get a TextSearch index for the notes corpus (single shared table).
935    pub fn text_for_notes(
936        &self,
937        token: &NamespaceToken,
938    ) -> RuntimeResult<Arc<dyn khive_storage::TextSearch>> {
939        let _ = token;
940        Ok(self.backend.text("notes")?)
941    }
942
943    /// Mint an authorization token for the given namespace.
944    ///
945    /// Consults the configured [`crate::Gate`] before minting. With the default
946    /// `AllowAllGate` this always succeeds. When a real policy-backed gate is
947    /// installed, this method enforces it and returns `PermissionDenied` on
948    /// denial.
949    ///
950    /// The returned token's read visibility set defaults to `[ns]` — identical
951    /// to the pre-visibility-set behaviour. Use [`Self::authorize_with_visibility`]
952    /// to mint a token that can read additional namespaces.
953    ///
954    /// When `actor_id` is configured in `RuntimeConfig`, the token carries that
955    /// actor label so that `comm.inbox` filters by `to_actor`. When
956    /// unconfigured, the token carries `ActorRef::anonymous()` and inbox falls
957    /// back to party-line behavior.
958    pub fn authorize(&self, ns: Namespace) -> RuntimeResult<NamespaceToken> {
959        let actor = crate::actor_identity::resolve_actor(self.config.actor_id.as_deref());
960        let req = GateRequest::new(
961            actor.clone(),
962            ns.clone(),
963            "authorize",
964            serde_json::Value::Null,
965        );
966        match self.config.gate.check(&req) {
967            Ok(ref decision) if decision.is_allow() => {
968                if let khive_gate::GateDecision::Allow { ref obligations } = decision {
969                    if !obligations.is_empty() {
970                        tracing::debug!(
971                            namespace = %ns.as_str(),
972                            "authorize: obligations={:?}",
973                            obligations
974                        );
975                    }
976                }
977                Ok(NamespaceToken::mint_authorized(ns, actor))
978            }
979            Ok(khive_gate::GateDecision::Deny { reason }) => {
980                Err(crate::RuntimeError::PermissionDenied {
981                    verb: "authorize".to_string(),
982                    reason,
983                })
984            }
985            Ok(_) => Err(crate::RuntimeError::PermissionDenied {
986                verb: "authorize".to_string(),
987                reason: "gate denied".to_string(),
988            }),
989            Err(e) => {
990                tracing::warn!(
991                    namespace = %ns.as_str(),
992                    error = %crate::secret_gate::bounded_masked_log_text(&e.to_string()),
993                    "authorize: gate check failed (fail-closed)"
994                );
995                Err(crate::RuntimeError::Internal(format!(
996                    "gate error: {}",
997                    e.wire_reason()
998                )))
999            }
1000        }
1001    }
1002
1003    /// Mint an authorization token with an explicit read-visibility set.
1004    ///
1005    /// `primary` is the **write namespace** — all records created via the
1006    /// returned token land there. `extra_visible` lists additional namespaces
1007    /// the token may read. The primary is always included in the visible set
1008    /// regardless of `extra_visible`.
1009    ///
1010    /// Usage (lambda:leo reading both leo and khive namespaces):
1011    /// ```rust,ignore
1012    /// let tok = rt.authorize_with_visibility(
1013    ///     Namespace::parse("lambda:leo").unwrap(),
1014    ///     vec![Namespace::parse("lambda:khive").unwrap()],
1015    /// )?;
1016    /// ```
1017    pub fn authorize_with_visibility(
1018        &self,
1019        primary: Namespace,
1020        extra_visible: Vec<Namespace>,
1021    ) -> RuntimeResult<NamespaceToken> {
1022        let actor = crate::actor_identity::resolve_actor(self.config.actor_id.as_deref());
1023        let req = GateRequest::new(
1024            actor.clone(),
1025            primary.clone(),
1026            "authorize",
1027            serde_json::Value::Null,
1028        );
1029        match self.config.gate.check(&req) {
1030            Ok(ref decision) if decision.is_allow() => {
1031                if let khive_gate::GateDecision::Allow { ref obligations } = decision {
1032                    if !obligations.is_empty() {
1033                        tracing::debug!(
1034                            namespace = %primary.as_str(),
1035                            "authorize_with_visibility: obligations={:?}",
1036                            obligations
1037                        );
1038                    }
1039                }
1040                // The primary check authorizes writes to `primary` only. Each
1041                // extra namespace grants read visibility, so each one takes
1042                // its own gate check before it may enter the minted set — a
1043                // token must never carry visibility the gate was not asked
1044                // about. Any deny or gate error refuses the whole mint,
1045                // naming the offending namespace (fail-closed).
1046                for extra in &extra_visible {
1047                    let extra_req = GateRequest::new(
1048                        actor.clone(),
1049                        extra.clone(),
1050                        "authorize",
1051                        serde_json::Value::Null,
1052                    );
1053                    match self.config.gate.check(&extra_req) {
1054                        Ok(ref extra_decision) if extra_decision.is_allow() => {}
1055                        Ok(khive_gate::GateDecision::Deny { reason }) => {
1056                            return Err(crate::RuntimeError::PermissionDenied {
1057                                verb: "authorize".to_string(),
1058                                reason: format!(
1059                                    "visibility namespace {:?} denied: {reason}",
1060                                    extra.as_str()
1061                                ),
1062                            });
1063                        }
1064                        Ok(_) => {
1065                            return Err(crate::RuntimeError::PermissionDenied {
1066                                verb: "authorize".to_string(),
1067                                reason: format!(
1068                                    "visibility namespace {:?} denied by gate",
1069                                    extra.as_str()
1070                                ),
1071                            });
1072                        }
1073                        Err(e) => {
1074                            tracing::warn!(
1075                                namespace = %extra.as_str(),
1076                                error = %crate::secret_gate::bounded_masked_log_text(&e.to_string()),
1077                                "authorize_with_visibility: extra-namespace gate check failed (fail-closed)"
1078                            );
1079                            return Err(crate::RuntimeError::Internal(format!(
1080                                "gate error: {}",
1081                                e.wire_reason()
1082                            )));
1083                        }
1084                    }
1085                }
1086                Ok(NamespaceToken::mint_with_visibility(
1087                    primary,
1088                    extra_visible,
1089                    actor,
1090                ))
1091            }
1092            Ok(khive_gate::GateDecision::Deny { reason }) => {
1093                Err(crate::RuntimeError::PermissionDenied {
1094                    verb: "authorize".to_string(),
1095                    reason,
1096                })
1097            }
1098            Ok(_) => Err(crate::RuntimeError::PermissionDenied {
1099                verb: "authorize".to_string(),
1100                reason: "gate denied".to_string(),
1101            }),
1102            Err(e) => {
1103                tracing::warn!(
1104                    namespace = %primary.as_str(),
1105                    error = %crate::secret_gate::bounded_masked_log_text(&e.to_string()),
1106                    "authorize_with_visibility: gate check failed (fail-closed)"
1107                );
1108                Err(crate::RuntimeError::Internal(format!(
1109                    "gate error: {}",
1110                    e.wire_reason()
1111                )))
1112            }
1113        }
1114    }
1115
1116    /// Install the pack-aggregated edge endpoint rules.
1117    ///
1118    /// Called by the transport layer after the `VerbRegistry` is built so
1119    /// that runtime-layer edge validation can consult pack rules. Idempotent:
1120    /// later calls overwrite the previous rule set.
1121    pub fn install_edge_rules(&self, rules: Vec<EdgeEndpointRule>) {
1122        if let Ok(mut guard) = self.edge_rules.write() {
1123            *guard = rules;
1124        }
1125    }
1126
1127    /// Install an already-paired blob hydrator into this runtime.
1128    ///
1129    /// Reinstalling the exact same `Arc` is idempotent. A different pair is
1130    /// rejected: replacing it would split or reset the aggregate admission
1131    /// budget while requests may still hold leases.
1132    pub fn install_blob_hydrator(
1133        &self,
1134        hydrator: Arc<crate::blob::BlobHydrator>,
1135    ) -> RuntimeResult<()> {
1136        if hydrator.budget_bytes() != self.config.blob_hydration_bytes {
1137            return Err(RuntimeError::InvalidInput(format!(
1138                "blob hydrator budget {} does not match this runtime's resolved budget {}",
1139                hydrator.budget_bytes(),
1140                self.config.blob_hydration_bytes
1141            )));
1142        }
1143        // The mode gate must sit on THIS seam, not only on `install_blob_store`:
1144        // `BlobHydrator::new` is public, so without it a caller pairs a writable
1145        // store, installs it here, and `blob_store()` hands mutating pack paths
1146        // a writable store on a runtime whose declared mode is read-only.
1147        // Boot paths installing one hydrator across handles of MIXED modes —
1148        // where the blob pack's own backend mode, not each receiving
1149        // handle's, governs mutability — go through
1150        // [`Self::install_shared_blob_hydrator`] instead.
1151        if self.is_read_only() && !hydrator.enforces_read_only() {
1152            return Err(RuntimeError::InvalidInput(
1153                "this runtime is read-only: install the raw store with install_blob_store, \
1154                 which wraps it so every physical mutator refuses"
1155                    .to_string(),
1156            ));
1157        }
1158        self.install_blob_hydrator_slot(hydrator)
1159    }
1160
1161    /// Install a boot-shared hydrator whose mutability is governed by the
1162    /// blob runtime's own mode, not this handle's domain-store mode.
1163    ///
1164    /// ADR-160 D3 installs one hydrator `Arc` on every runtime handle a boot
1165    /// produces, and the documented multi-backend matrix includes a writable
1166    /// blob secondary beside a read-only main: there the shared hydrator is
1167    /// legitimately writable on a read-only domain handle. The mode decision
1168    /// must therefore already be encoded in the hydrator, and it must have
1169    /// been DERIVED, not declared: only hydrators built through
1170    /// [`crate::BlobHydrator::resolve_for_governing_backend`] — whose mode
1171    /// comes from the governing backend's own access mode — are accepted
1172    /// here. A hand-paired hydrator (`BlobHydrator::new` / `for_mode`) is
1173    /// refused so a safe downstream caller cannot use this seam to put a
1174    /// writable store on a read-only runtime; such callers use
1175    /// [`Self::install_blob_hydrator`], which holds hydrator mode against
1176    /// this runtime's own.
1177    ///
1178    /// This gate is a wrong-wiring guard, not an in-process sandbox: which
1179    /// backend governs is the boot host's topology assertion, and a caller
1180    /// who deliberately selects an unrelated writable backend as governing
1181    /// is outside what any runtime seam can enforce (see the trust-model
1182    /// note on [`crate::BlobHydrator::resolve_for_governing_backend`]).
1183    pub fn install_shared_blob_hydrator(
1184        &self,
1185        hydrator: Arc<crate::blob::BlobHydrator>,
1186    ) -> RuntimeResult<()> {
1187        if !hydrator.is_governed() {
1188            return Err(RuntimeError::InvalidInput(
1189                "the shared install seam accepts only hydrators whose mode was derived from a \
1190                 governing backend (BlobHydrator::resolve_for_governing_backend); use \
1191                 install_blob_hydrator for a hand-paired hydrator"
1192                    .to_string(),
1193            ));
1194        }
1195        if hydrator.budget_bytes() != self.config.blob_hydration_bytes {
1196            return Err(RuntimeError::InvalidInput(format!(
1197                "blob hydrator budget {} does not match this runtime's resolved budget {}",
1198                hydrator.budget_bytes(),
1199                self.config.blob_hydration_bytes
1200            )));
1201        }
1202        self.install_blob_hydrator_slot(hydrator)
1203    }
1204
1205    /// Whether `candidate` is the same pairing as the installed `current`:
1206    /// the exact `Arc`, or a distinct hydrator allocation over the same raw
1207    /// store with the same budget and mode. The latter arises when two
1208    /// concurrent first installs each construct a hydrator from one raw
1209    /// store — the `OnceLock` loser must read as idempotent, not as a
1210    /// conflicting install.
1211    fn is_same_blob_pairing(
1212        current: &Arc<crate::blob::BlobHydrator>,
1213        candidate: &Arc<crate::blob::BlobHydrator>,
1214    ) -> bool {
1215        Arc::ptr_eq(current, candidate)
1216            || (Arc::ptr_eq(&current.raw_store(), &candidate.raw_store())
1217                && current.budget_bytes() == candidate.budget_bytes()
1218                && current.enforces_read_only() == candidate.enforces_read_only())
1219    }
1220
1221    /// One-shot slot semantics shared by both install seams: first install
1222    /// wins, an equivalent pairing is idempotent, a different pairing is
1223    /// refused (replacing it would split or reset the aggregate admission
1224    /// budget while requests may still hold leases).
1225    fn install_blob_hydrator_slot(
1226        &self,
1227        hydrator: Arc<crate::blob::BlobHydrator>,
1228    ) -> RuntimeResult<()> {
1229        if let Some(current) = self.blob_hydrator.get() {
1230            return if Self::is_same_blob_pairing(current, &hydrator) {
1231                Ok(())
1232            } else {
1233                Err(RuntimeError::InvalidInput(
1234                    "a different blob hydrator is already installed".to_string(),
1235                ))
1236            };
1237        }
1238
1239        match self.blob_hydrator.set(hydrator) {
1240            Ok(()) => Ok(()),
1241            Err(candidate) => {
1242                let current = self.blob_hydrator.get().ok_or_else(|| {
1243                    RuntimeError::Internal(
1244                        "blob hydrator install raced without a visible winner".to_string(),
1245                    )
1246                })?;
1247                if Self::is_same_blob_pairing(current, &candidate) {
1248                    Ok(())
1249                } else {
1250                    Err(RuntimeError::InvalidInput(
1251                        "a different blob hydrator is already installed".to_string(),
1252                    ))
1253                }
1254            }
1255        }
1256    }
1257
1258    /// Pair and install a store using this runtime's resolved hydration budget.
1259    ///
1260    /// Boot paths that own multiple runtimes should instead construct one
1261    /// [`crate::BlobHydrator`] and call [`Self::install_blob_hydrator`] with
1262    /// the same `Arc` on every handle.
1263    pub fn install_blob_store(
1264        &self,
1265        store: Arc<dyn khive_storage::BlobStore>,
1266    ) -> RuntimeResult<()> {
1267        if let Some(current) = self.blob_hydrator.get() {
1268            // Reinstalling the same raw store is idempotent in BOTH modes:
1269            // on a read-only runtime the installed hydrator wraps the raw
1270            // store, so identity is checked against the raw handle the
1271            // hydrator remembers, not only the (possibly wrapped) paired one.
1272            let current_store = current.store();
1273            if Arc::ptr_eq(&current_store, &store) || Arc::ptr_eq(&current.raw_store(), &store) {
1274                return Ok(());
1275            }
1276        }
1277        // A read-only runtime holds its mode at this seam, not only during
1278        // boot resolution: an arbitrary store installed after launch is
1279        // wrapped so every physical mutator refuses while the bounded read
1280        // surface stays available. Without this, post-boot installation is a
1281        // writable bypass of the runtime's declared mode.
1282        let hydrator = if self.is_read_only() {
1283            crate::blob::BlobHydrator::new_read_only(store, self.config.blob_hydration_bytes)?
1284        } else {
1285            crate::blob::BlobHydrator::new(store, self.config.blob_hydration_bytes)?
1286        };
1287        self.install_blob_hydrator(Arc::new(hydrator))
1288    }
1289
1290    /// Return the installed shared blob hydrator, if boot configured one.
1291    pub fn blob_hydrator(&self) -> Option<Arc<crate::blob::BlobHydrator>> {
1292        self.blob_hydrator.get().cloned()
1293    }
1294
1295    /// Return the installed `BlobStore`, if the boot path resolved and
1296    /// installed one. `None` when no `[storage.blob]` selection was ever
1297    /// installed — e.g. a bare/test runtime constructed without going
1298    /// through the `khive-mcp` boot path.
1299    pub fn blob_store(&self) -> Option<Arc<dyn khive_storage::BlobStore>> {
1300        self.blob_hydrator.get().map(|hydrator| hydrator.store())
1301    }
1302
1303    /// Install the pack-aggregated valid entity and note kinds.
1304    ///
1305    /// Called by the transport layer after the `VerbRegistry` is built so that
1306    /// runtime-layer entity/note creation and import validate kind strings against
1307    /// the merged pack vocabulary. Idempotent: later calls overwrite previous sets.
1308    ///
1309    /// When no kinds are installed (empty lists), kind validation is skipped at
1310    /// the runtime layer. The pack handler layer remains the primary enforcement
1311    /// point; this provides defense-in-depth for direct Rust callers and import.
1312    pub fn install_kind_registry(&self, entity_kinds: Vec<String>, note_kinds: Vec<String>) {
1313        if let Ok(mut guard) = self.valid_entity_kinds.write() {
1314            *guard = entity_kinds;
1315        }
1316        if let Ok(mut guard) = self.valid_note_kinds.write() {
1317            *guard = note_kinds;
1318        }
1319    }
1320
1321    /// Install the pack-owned note kinds aggregated from the pack registry.
1322    ///
1323    /// Called by the transport after the `VerbRegistry` is built, same timing
1324    /// as [`install_kind_registry`](Self::install_kind_registry).
1325    pub fn install_pack_owned_note_kinds(&self, kinds: Vec<String>) {
1326        if let Ok(mut guard) = self.pack_owned_note_kinds.write() {
1327            *guard = kinds;
1328        }
1329    }
1330
1331    /// Whether `kind` is a note kind owned by a pack (see
1332    /// [`install_pack_owned_note_kinds`](Self::install_pack_owned_note_kinds)).
1333    ///
1334    /// Always `false` before the transport installs the list — a bare runtime
1335    /// has no packs, so no kind is pack-owned there.
1336    pub fn is_pack_owned_note_kind(&self, kind: &str) -> bool {
1337        self.pack_owned_note_kinds
1338            .read()
1339            .map(|g| g.iter().any(|k| k == kind))
1340            .unwrap_or(false)
1341    }
1342
1343    /// Validate that `kind` is a pack-registered entity kind.
1344    ///
1345    /// Returns `Ok(())` when no kinds are installed (bare runtime without packs).
1346    /// Returns `InvalidInput` when kinds are installed and `kind` is not among them.
1347    pub(crate) fn validate_entity_kind(&self, kind: &str) -> crate::RuntimeResult<()> {
1348        let guard = self.valid_entity_kinds.read().map_err(|_| {
1349            crate::RuntimeError::Internal("entity kind registry lock poisoned".into())
1350        })?;
1351        if guard.is_empty() {
1352            return Ok(());
1353        }
1354        if guard.iter().any(|k| k == kind) {
1355            Ok(())
1356        } else {
1357            Err(crate::RuntimeError::InvalidInput(format!(
1358                "unknown entity kind {kind:?}; valid: {}",
1359                guard.join(", ")
1360            )))
1361        }
1362    }
1363
1364    /// Validate that `kind` is a pack-registered note kind.
1365    ///
1366    /// Returns `Ok(())` when no kinds are installed (bare runtime without packs).
1367    /// Returns `InvalidInput` when kinds are installed and `kind` is not among them.
1368    pub(crate) fn validate_note_kind(&self, kind: &str) -> crate::RuntimeResult<()> {
1369        let guard = self.valid_note_kinds.read().map_err(|_| {
1370            crate::RuntimeError::Internal("note kind registry lock poisoned".into())
1371        })?;
1372        if guard.is_empty() {
1373            return Ok(());
1374        }
1375        if guard.iter().any(|k| k == kind) {
1376            Ok(())
1377        } else {
1378            Err(crate::RuntimeError::InvalidInput(format!(
1379                "unknown note kind {kind:?}; valid: {}",
1380                guard.join(", ")
1381            )))
1382        }
1383    }
1384
1385    /// Install a pack-supplied entity-type validator.
1386    ///
1387    /// Called by the `KgPack` during registration so that `create_many` can validate
1388    /// `entity_type` values at the runtime layer, closing the hole where direct Rust
1389    /// callers bypass the handler-layer `validate_entity_type` check.
1390    ///
1391    /// The callback receives `(kind, entity_type)` and returns the normalised type
1392    /// string, or `RuntimeError::InvalidInput` if the type is not registered for that
1393    /// kind. Passing `entity_type = None` must return `Ok(None)`.
1394    pub fn install_entity_type_validator(&self, f: EntityTypeValidatorFn) {
1395        if let Ok(mut guard) = self.entity_type_validator.write() {
1396            *guard = Some(f);
1397        }
1398    }
1399
1400    /// Validate and normalise `entity_type` through the pack-installed validator.
1401    ///
1402    /// Returns `Ok(entity_type)` when no validator is installed (bare runtime).
1403    /// Returns `InvalidInput` when a validator is installed and rejects the type.
1404    pub(crate) fn validate_entity_type_for_kind(
1405        &self,
1406        kind: &str,
1407        entity_type: Option<&str>,
1408    ) -> crate::RuntimeResult<Option<String>> {
1409        let guard = self.entity_type_validator.read().map_err(|_| {
1410            crate::RuntimeError::Internal("entity type validator lock poisoned".into())
1411        })?;
1412        match guard.as_ref() {
1413            None => Ok(entity_type.map(str::to_string)),
1414            Some(validate) => validate(kind, entity_type),
1415        }
1416    }
1417
1418    /// Install a pack-owned note-mutation hook.
1419    ///
1420    /// Overwrites any previously-installed hook, same single-slot semantics
1421    /// as [`install_entity_type_validator`](Self::install_entity_type_validator).
1422    /// In practice only one pack (`khive-pack-memory`) installs one today;
1423    /// if a second pack ever needs this, the slot should be widened to a
1424    /// `Vec` at that point rather than silently overwritten.
1425    pub fn install_note_mutation_hook(&self, f: NoteMutationHookFn) {
1426        if let Ok(mut guard) = self.note_mutation_hook.write() {
1427            *guard = Some(f);
1428        }
1429    }
1430
1431    /// Install a pack-owned note-write validator.
1432    ///
1433    /// Called during pack registration (`PackRuntime::register_note_write_validator`)
1434    /// so that the covered note-write sites carrying caller-supplied
1435    /// `properties` derive the owning pack's identity properties from the
1436    /// authorization token, closing the gap where a direct Rust caller, the
1437    /// generic `create` verb, or the proposal-apply path (which dispatches no
1438    /// pack hooks) writes them unchecked. Single-slot semantics, same as
1439    /// [`install_note_mutation_hook`](Self::install_note_mutation_hook): a
1440    /// second installing pack overwrites the first, so a validator must return
1441    /// kinds it does not own unchanged.
1442    ///
1443    /// Covered sites — each calls `derive_note_write_properties`
1444    /// before the write: `create_note_inner` (`operations.rs`, the generic
1445    /// `create` verb funnel and every other public `create_note*` variant),
1446    /// `atomic_prepare::prepare_add_note` (the proposal-apply add-note path),
1447    /// and `atomic_message::create_notes_atomic_with_report` (the atomic
1448    /// multi-note writer).
1449    ///
1450    /// NOT covered by this validator: `try_create_note` (`operations.rs`).
1451    /// `try_create_note` is deliberately excluded — its only caller path is
1452    /// `comm.ingest`, where `properties.from_actor` is the external transport
1453    /// sender named by the `from` parameter, not the authenticated caller,
1454    /// and where transport-owned quarantine/channel properties are
1455    /// legitimately established. Running the generic validator there would
1456    /// stamp every inbound message as the ingesting daemon and reject the
1457    /// evidence the trusted ingest handler just derived. `try_create_note`
1458    /// instead runs its own narrower reserved-transport-property check
1459    /// inline (`operations.rs`'s `try_create_note_impl`), which allows the
1460    /// three `message`-kind transport properties only when called through
1461    /// [`Self::try_create_note_as_trusted_ingest`] with a
1462    /// [`crate::pack::ChannelIngestCapability`].
1463    ///
1464    /// The `NoteStore` returned by [`notes`](Self::notes) is covered by a
1465    /// different, narrower mechanism: it is wrapped in
1466    /// `note_store_guard::PolicyEnforcingNoteStore`, which refuses
1467    /// `upsert_note` / `upsert_notes` / `try_insert_note` /
1468    /// `replace_note_if_unchanged` calls that would write a `kind = "message"`
1469    /// note carrying `quarantined` / `channel_kind` / `channel_slug`, and
1470    /// refuses `set_note_property` / `try_patch_note_property` /
1471    /// `patch_note_property_atomic` / `update_note_properties` calls that
1472    /// would patch any of those keys onto any note — unconditionally, since
1473    /// that public accessor has no way to see a trust decision. `try_create_note_impl` itself reaches storage through
1474    /// `Self::raw_notes`, the unwrapped accessor, so its own inline check
1475    /// (which can legitimately allow those properties for trusted ingest)
1476    /// is not double-enforced or contradicted by the wrapper.
1477    /// Register a pack-defined custom fusion strategy under `name` (ADR-012).
1478    ///
1479    /// Unlike `install_entity_type_validator`/`install_note_mutation_hook`,
1480    /// this slot is keyed rather than single-occupancy: multiple packs each
1481    /// register their own named strategy, and a second registration under an
1482    /// already-used `name` replaces the first. Looked up by
1483    /// `FusionStrategy::Custom { name, .. }` at the hybrid-search dispatch
1484    /// boundary in `crate::fusion`; an unregistered name fails closed with
1485    /// `RuntimeError::UnknownFusionStrategy` rather than silently falling
1486    /// back to RRF.
1487    pub fn register_fusion_strategy(
1488        &self,
1489        name: impl Into<String>,
1490        executor: Arc<dyn crate::fusion::FusionExecutor>,
1491    ) {
1492        if let Ok(mut guard) = self.fusion_executors.write() {
1493            guard.insert(name.into(), executor);
1494        }
1495    }
1496
1497    /// Resolve a registered custom fusion executor by name.
1498    ///
1499    /// Returns `RuntimeError::UnknownFusionStrategy` when no pack has
1500    /// registered `name` — callers must invoke this before any
1501    /// empty-input/zero-limit short circuit so a misconfigured name errors
1502    /// on every call, including zero-result ones.
1503    pub(crate) fn fusion_executor(
1504        &self,
1505        name: &str,
1506    ) -> RuntimeResult<Arc<dyn crate::fusion::FusionExecutor>> {
1507        let guard = self
1508            .fusion_executors
1509            .read()
1510            .map_err(|_| RuntimeError::Internal("fusion executor registry lock poisoned".into()))?;
1511        guard
1512            .get(name)
1513            .cloned()
1514            .ok_or_else(|| RuntimeError::UnknownFusionStrategy(name.to_string()))
1515    }
1516
1517    pub fn install_note_write_validator(&self, f: NoteWriteValidatorFn) {
1518        if let Ok(mut guard) = self.note_write_validator.write() {
1519            *guard = Some(f);
1520        }
1521    }
1522
1523    /// Whether a note-write validator is installed on this runtime.
1524    ///
1525    /// Exists so a transport's own tests can assert, per boot path, that the
1526    /// documented startup sequence actually filled the slot. A missing install
1527    /// fails open and silently — an empty slot passes caller-supplied
1528    /// properties straight through, which no write site can distinguish from a
1529    /// validator that approved them — so occupancy is asserted, never assumed.
1530    pub fn has_note_write_validator(&self) -> bool {
1531        self.note_write_validator
1532            .read()
1533            .map(|g| g.is_some())
1534            .unwrap_or(false)
1535    }
1536
1537    /// Run caller-supplied note `properties` through the installed note-write
1538    /// validator, returning the properties to store.
1539    ///
1540    /// Returns them unchanged when no validator is installed (bare runtime).
1541    pub(crate) fn derive_note_write_properties(
1542        &self,
1543        kind: &str,
1544        token: &NamespaceToken,
1545        properties: Option<serde_json::Value>,
1546    ) -> RuntimeResult<Option<serde_json::Value>> {
1547        let validator = self
1548            .note_write_validator
1549            .read()
1550            .map_err(|_| RuntimeError::Internal("note write validator lock poisoned".into()))?
1551            .clone();
1552        match validator {
1553            None => Ok(properties),
1554            Some(validate) => validate(kind, &token.actor().id, properties),
1555        }
1556    }
1557
1558    /// Invoke the pack-installed note-mutation hook, if any.
1559    ///
1560    /// `kind` is the note's `kind` string (e.g. `"memory"`); `id` is the
1561    /// note's UUID. No-op when no hook is installed (bare runtime, or no
1562    /// pack cares). Errors inside the hook are the hook's own concern to
1563    /// handle/log — this call site cannot propagate a failure without
1564    /// changing `update_note`/`delete_note`'s already-committed success
1565    /// return value.
1566    pub(crate) async fn fire_note_mutation_hook(&self, kind: &str, id: uuid::Uuid) {
1567        let hook = self
1568            .note_mutation_hook
1569            .read()
1570            .ok()
1571            .and_then(|guard| guard.clone());
1572        if let Some(hook) = hook {
1573            hook(kind.to_string(), id).await;
1574        }
1575    }
1576
1577    /// Snapshot of currently-installed pack edge rules.
1578    ///
1579    /// This is the same composed rule set `validate_edge_relation_endpoints`
1580    /// consults via `pack_rule_allows` when accepting/rejecting an edge. Public
1581    /// so pack-layer error-hint code (e.g. `khive-pack-kg`'s
1582    /// `valid_relations_for_entity_pair`) can derive hints from the exact
1583    /// source the validator uses, rather than maintaining a separate
1584    /// hand-authored table that can drift out of sync.
1585    pub fn pack_edge_rules(&self) -> Vec<EdgeEndpointRule> {
1586        self.edge_rules
1587            .read()
1588            .map(|g| g.clone())
1589            .unwrap_or_default()
1590    }
1591
1592    /// Borrow the installed pack edge rules for a synchronous calculation.
1593    pub(crate) fn with_pack_edge_rules<T>(&self, f: impl FnOnce(&[EdgeEndpointRule]) -> T) -> T {
1594        match self.edge_rules.read() {
1595            Ok(rules) => f(&rules),
1596            Err(_) => f(&[]),
1597        }
1598    }
1599
1600    /// Return the name of the default embedding model (empty string if none configured).
1601    pub fn default_embedder_name(&self) -> &str {
1602        self.default_embedder_name.as_ref()
1603    }
1604
1605    /// Resolve a model name (or `None` for the default) to an `EmbeddingModel`.
1606    ///
1607    /// Returns `UnknownModel` if the name is not in the registry, or
1608    /// `Unconfigured` if `None` is passed and no default model is set.
1609    pub fn resolve_embedding_model(&self, name: Option<&str>) -> RuntimeResult<EmbeddingModel> {
1610        let model = match name {
1611            Some(raw) => parse_embedding_model_alias(raw)
1612                .ok_or_else(|| crate::RuntimeError::UnknownModel(raw.to_string()))?,
1613            None => self
1614                .config
1615                .embedding_model
1616                .ok_or_else(|| crate::RuntimeError::Unconfigured("embedding_model".into()))?,
1617        };
1618        let key = model.to_string();
1619        let contains = self
1620            .embedder_registry
1621            .read()
1622            .map(|reg| reg.contains(&key))
1623            .unwrap_or(false);
1624        if contains {
1625            Ok(model)
1626        } else {
1627            Err(crate::RuntimeError::UnknownModel(
1628                name.unwrap_or_else(|| self.default_embedder_name())
1629                    .to_string(),
1630            ))
1631        }
1632    }
1633
1634    /// Names of all registered embedding models in this runtime.
1635    ///
1636    /// Includes both built-in lattice models and any custom embedders
1637    /// registered by packs via [`register_embedder`](Self::register_embedder).
1638    /// Useful for operations that must touch every model's storage (e.g.,
1639    /// scoped vector deletion on note delete). The default model is included.
1640    pub fn registered_embedding_model_names(&self) -> Vec<String> {
1641        self.embedder_registry
1642            .read()
1643            .map(|reg| reg.names())
1644            .unwrap_or_default()
1645    }
1646
1647    /// Get the lazily-initialized embedding service for the named model.
1648    ///
1649    /// Accepts both built-in lattice model names (e.g. `"all-minilm-l6-v2"`,
1650    /// `"paraphrase"`) and custom provider names registered via
1651    /// [`register_embedder`](Self::register_embedder).
1652    ///
1653    /// For lattice model names, aliases (e.g. `"paraphrase"`) are resolved to
1654    /// their canonical key before looking up the registry. For custom providers
1655    /// the name must match exactly as supplied during registration.
1656    ///
1657    /// First call for any name loads the underlying service (cold start cost);
1658    /// subsequent calls are cheap (registry caches the `Arc`).
1659    pub async fn embedder(&self, name: &str) -> RuntimeResult<Arc<dyn EmbeddingService>> {
1660        self.embedder_inner(name, None).await
1661    }
1662
1663    pub(crate) async fn embedder_with_token(
1664        &self,
1665        token: &NamespaceToken,
1666        name: &str,
1667    ) -> RuntimeResult<Arc<dyn EmbeddingService>> {
1668        self.embedder_inner(name, Some(token)).await
1669    }
1670
1671    async fn embedder_inner(
1672        &self,
1673        name: &str,
1674        token: Option<&NamespaceToken>,
1675    ) -> RuntimeResult<Arc<dyn EmbeddingService>> {
1676        // Fall back to the literal name (not the alias table) so custom
1677        // providers registered with non-lattice names stay reachable.
1678        let canonical_key = match parse_embedding_model_alias(name) {
1679            Some(model) => model.to_string(),
1680            None => name.to_owned(),
1681        };
1682        // Clone the entry so we don't hold the RwLockGuard across the
1683        // async OnceCell initialisation (Send bound).
1684        let entry = {
1685            let registry = self.embedder_registry.read().map_err(|_| {
1686                crate::RuntimeError::Internal("embedder registry lock poisoned".into())
1687            })?;
1688            registry
1689                .get_entry(&canonical_key)
1690                .ok_or_else(|| crate::RuntimeError::UnknownModel(name.to_string()))?
1691        };
1692        let (service, init_duration_us) = entry.resolve().await?;
1693        if let Some(duration_us) = init_duration_us {
1694            if let Some(token) = token {
1695                self.emit_embedder_initialized(token, &canonical_key, duration_us)
1696                    .await;
1697            } else if let Ok(token) = self.authorize(self.config.default_namespace.clone()) {
1698                self.emit_embedder_initialized(&token, &canonical_key, duration_us)
1699                    .await;
1700            }
1701        }
1702        Ok(service)
1703    }
1704
1705    async fn emit_embedder_initialized(
1706        &self,
1707        token: &NamespaceToken,
1708        model_name: &str,
1709        duration_us: i64,
1710    ) {
1711        // Lazy embedder construction can happen during daemon warm or an
1712        // assertive request. A snapshot has no durable audit sink, so do not
1713        // resolve an EventStore merely to attempt a known-rejected append.
1714        if self.is_read_only() {
1715            return;
1716        }
1717        let Ok(store) = self.events(token) else {
1718            return;
1719        };
1720        let event = Event::new(
1721            token.namespace().as_str(),
1722            "embedder.init",
1723            EventKind::EmbedderInitialized,
1724            SubstrateKind::Event,
1725            format!("{}:{}", token.actor().kind, token.actor().id),
1726        )
1727        .with_payload(serde_json::json!({
1728            "model_name": model_name,
1729            "duration_us": duration_us,
1730        }))
1731        .with_duration_us(duration_us);
1732        if let Err(err) = store.append_event(event).await {
1733            tracing::warn!(error = %err, model_name, "embedder initialization event append failed");
1734        }
1735    }
1736
1737    /// Register a custom embedding provider with this runtime.
1738    ///
1739    /// The provider is added to the shared [`EmbedderRegistry`] so all clones
1740    /// of this runtime see the new provider immediately. If a provider with the
1741    /// same name already exists it is replaced (last-writer wins — see
1742    /// [`crate::EmbedderRegistry::register`] for the rationale).
1743    ///
1744    /// Packs should call this from [`crate::PackRuntime::register_embedders`] (the
1745    /// hook is invoked by the transport during pack initialisation, before the
1746    /// first verb dispatch).
1747    ///
1748    /// [`EmbedderRegistry`]: crate::embedder_registry::EmbedderRegistry
1749    pub fn register_embedder(
1750        &self,
1751        provider: impl crate::embedder_registry::EmbedderProvider + 'static,
1752    ) {
1753        if let Ok(mut registry) = self.embedder_registry.write() {
1754            registry.register(provider);
1755        } else {
1756            tracing::warn!(
1757                "embedder registry lock poisoned — embedder {} not registered",
1758                std::any::type_name::<dyn crate::embedder_registry::EmbedderProvider>()
1759            );
1760        }
1761    }
1762
1763    /// List registered embedding models via `SqlAccess`, routing through the
1764    /// existing connection pool rather than opening a fresh `Connection` per call.
1765    ///
1766    /// Optionally filter by `engine_name`. Returns an empty vec when the
1767    /// `_embedding_models` table does not yet exist (e.g. no migrations have run
1768    /// or no models have been registered). All other SQL errors are propagated.
1769    pub async fn list_embedding_models(
1770        &self,
1771        engine_filter: Option<&str>,
1772    ) -> RuntimeResult<Vec<khive_db::EmbeddingModelRegistryRecord>> {
1773        use khive_storage::{SqlStatement, SqlValue};
1774
1775        let (sql_text, params) = if let Some(engine) = engine_filter {
1776            (
1777                "SELECT engine_name, model_id, key_version, dim, status, \
1778                 activated_at, superseded_at \
1779                 FROM _embedding_models WHERE engine_name = ?1 \
1780                 ORDER BY engine_name, activated_at IS NULL, activated_at"
1781                    .to_string(),
1782                vec![SqlValue::Text(engine.to_string())],
1783            )
1784        } else {
1785            (
1786                "SELECT engine_name, model_id, key_version, dim, status, \
1787                 activated_at, superseded_at \
1788                 FROM _embedding_models \
1789                 ORDER BY engine_name, activated_at IS NULL, activated_at"
1790                    .to_string(),
1791                vec![],
1792            )
1793        };
1794
1795        let stmt = SqlStatement {
1796            sql: sql_text,
1797            params,
1798            label: Some("list_embedding_models".into()),
1799        };
1800
1801        let mut reader = self
1802            .sql()
1803            .reader()
1804            .await
1805            .map_err(crate::RuntimeError::Storage)?;
1806
1807        let rows = match reader.query_all(stmt).await {
1808            Ok(rows) => rows,
1809            Err(e) if e.to_string().contains("no such table: _embedding_models") => {
1810                return Ok(Vec::new())
1811            }
1812            Err(e) => return Err(crate::RuntimeError::Storage(e)),
1813        };
1814
1815        let mut records = Vec::with_capacity(rows.len());
1816        for row in rows {
1817            macro_rules! required_text {
1818                ($col:expr) => {
1819                    match row.get($col) {
1820                        Some(SqlValue::Text(s)) => s.clone(),
1821                        other => {
1822                            tracing::warn!(column = $col, value = ?other, "skipping registry row: unexpected type");
1823                            continue;
1824                        }
1825                    }
1826                };
1827            }
1828            let engine_name = required_text!("engine_name");
1829            let model_id = required_text!("model_id");
1830            let key_version = required_text!("key_version");
1831            let dimensions = match row.get("dim") {
1832                Some(SqlValue::Integer(n)) => match u32::try_from(*n) {
1833                    Ok(d) => d,
1834                    Err(_) => {
1835                        tracing::warn!(dim = n, "skipping registry row: dim out of u32 range");
1836                        continue;
1837                    }
1838                },
1839                other => {
1840                    tracing::warn!(column = "dim", value = ?other, "skipping registry row: unexpected type");
1841                    continue;
1842                }
1843            };
1844            let status = required_text!("status");
1845            let activated_at = match row.get("activated_at") {
1846                Some(SqlValue::Integer(n)) => Some(*n),
1847                _ => None,
1848            };
1849            let superseded_at = match row.get("superseded_at") {
1850                Some(SqlValue::Integer(n)) => Some(*n),
1851                _ => None,
1852            };
1853            records.push(khive_db::EmbeddingModelRegistryRecord {
1854                engine_name,
1855                model_id,
1856                key_version,
1857                dimensions,
1858                status,
1859                activated_at,
1860                superseded_at,
1861            });
1862        }
1863
1864        Ok(records)
1865    }
1866}
1867
1868fn vector_dimensions_from_ddl(ddl: &str) -> Option<usize> {
1869    let lower = ddl.to_ascii_lowercase();
1870    let suffix = lower.split_once("embedding float[")?.1;
1871    let dimension = suffix.split_once(']')?.0;
1872    if dimension.is_empty() || !dimension.bytes().all(|byte| byte.is_ascii_digit()) {
1873        return None;
1874    }
1875    dimension.parse().ok()
1876}
1877
1878// INLINE TEST JUSTIFICATION: tests here cover KhiveRuntime construction helpers
1879// (in-memory backend wiring, NamespaceToken::for_namespace) that are
1880// pub(crate)-only and cannot be called from the integration test crate.
1881#[cfg(test)]
1882mod tests {
1883    use super::*;
1884    use khive_gate::GateRef;
1885    use serial_test::serial;
1886
1887    fn test_blob_hydrator() -> (tempfile::TempDir, Arc<crate::BlobHydrator>) {
1888        let root = tempfile::tempdir().expect("blob root");
1889        let store = Arc::new(
1890            khive_db::stores::blob::FsBlobStore::new(root.path().to_path_buf(), 0)
1891                .expect("fs blob store"),
1892        );
1893        let hydrator = Arc::new(
1894            crate::BlobHydrator::new(store, crate::DEFAULT_BLOB_HYDRATION_BYTES)
1895                .expect("blob hydrator"),
1896        );
1897        (root, hydrator)
1898    }
1899
1900    #[test]
1901    fn memory_runtime_creates_successfully() {
1902        let rt = KhiveRuntime::memory().expect("memory runtime should create");
1903        assert!(rt.config().db_path.is_none());
1904    }
1905
1906    #[test]
1907    fn installed_blob_hydrator_is_shared_by_clone_and_core_handles() {
1908        let main_backend = Arc::new(StorageBackend::memory().expect("main backend"));
1909        let pack_backend = Arc::new(StorageBackend::memory().expect("pack backend"));
1910        let mut config = RuntimeConfig::no_embeddings();
1911        config.backend_id = BackendId::new("assets");
1912        let runtime = KhiveRuntime::from_backend(pack_backend, config)
1913            .with_core_backend(Arc::clone(&main_backend));
1914        let (_root, hydrator) = test_blob_hydrator();
1915
1916        runtime
1917            .install_blob_hydrator(Arc::clone(&hydrator))
1918            .expect("first install");
1919
1920        for handle in [runtime.clone(), runtime.core()] {
1921            let installed = handle.blob_hydrator().expect("installed hydrator");
1922            assert!(Arc::ptr_eq(&installed, &hydrator));
1923        }
1924    }
1925
1926    #[test]
1927    fn blob_hydrator_install_is_idempotent_but_rejects_replacement() {
1928        let runtime = KhiveRuntime::memory().expect("runtime");
1929        let (_first_root, first) = test_blob_hydrator();
1930        let (_second_root, second) = test_blob_hydrator();
1931
1932        runtime
1933            .install_blob_hydrator(Arc::clone(&first))
1934            .expect("first install");
1935        runtime
1936            .install_blob_hydrator(Arc::clone(&first))
1937            .expect("same Arc reinstall is idempotent");
1938
1939        let error = runtime
1940            .install_blob_hydrator(second)
1941            .expect_err("a different hydrator must not replace the installed pair");
1942        assert!(error.to_string().contains("already installed"));
1943        assert!(Arc::ptr_eq(
1944            &runtime.blob_hydrator().expect("original remains"),
1945            &first
1946        ));
1947    }
1948
1949    #[test]
1950    fn blob_hydrator_install_rejects_a_budget_that_disagrees_with_runtime_identity() {
1951        let runtime = KhiveRuntime::memory().expect("runtime");
1952        let root = tempfile::tempdir().expect("blob root");
1953        let store = Arc::new(
1954            khive_db::stores::blob::FsBlobStore::new(root.path().to_path_buf(), 0)
1955                .expect("fs blob store"),
1956        );
1957        let mismatched = Arc::new(
1958            crate::BlobHydrator::new(store, khive_storage::MAX_BLOB_WHOLE_BYTES)
1959                .expect("minimum blob budget"),
1960        );
1961
1962        let error = runtime
1963            .install_blob_hydrator(mismatched)
1964            .expect_err("live admission must match the construction-baked config identity");
1965        assert!(matches!(error, RuntimeError::InvalidInput(_)));
1966        assert!(runtime.blob_hydrator().is_none());
1967    }
1968
1969    #[test]
1970    fn fresh_tail_policy_is_instance_scoped_and_clone_stable() {
1971        let enabled = KhiveRuntime::memory()
1972            .expect("enabled memory runtime")
1973            .with_ann_fresh_tail_enabled(true);
1974        let disabled = KhiveRuntime::memory()
1975            .expect("disabled memory runtime")
1976            .with_ann_fresh_tail_enabled(false);
1977
1978        assert!(enabled.ann_fresh_tail_enabled());
1979        assert!(enabled.clone().ann_fresh_tail_enabled());
1980        assert!(!disabled.ann_fresh_tail_enabled());
1981        assert!(!disabled.clone().ann_fresh_tail_enabled());
1982    }
1983
1984    #[tokio::test]
1985    async fn runtime_db_diagnostics_supplies_both_contention_counter_sources() {
1986        let rt = KhiveRuntime::memory().expect("memory runtime should create");
1987
1988        let report = rt.db_diagnostics().await.expect("diagnostics succeed");
1989
1990        assert!(
1991            report.writer_contention.writer_acquisitions >= 1,
1992            "runtime construction runs migrations through the finite-wait pooled writer"
1993        );
1994        assert_eq!(
1995            report.writer_contention.writer_acquisitions,
1996            report
1997                .writer_contention
1998                .pooled_writer_acquisitions
1999                .saturating_add(report.writer_contention.standalone_writer_acquisitions)
2000                .saturating_add(report.writer_contention.writer_task_acquisitions),
2001            "the public aggregate must equal the class-specific snapshot"
2002        );
2003        assert!(
2004            report.writer_contention.audit_append_failures.is_some(),
2005            "the runtime path must supply its process-wide swallowed-audit counter"
2006        );
2007        assert!(report
2008            .writer_contention
2009            .audit_append_failures_unavailable_reason
2010            .is_none());
2011    }
2012
2013    #[test]
2014    fn backend_data_dir_returns_none_for_memory_backend() {
2015        let rt = KhiveRuntime::memory().expect("memory runtime");
2016        assert!(rt.backend_data_dir().is_none());
2017    }
2018
2019    #[test]
2020    fn backend_data_dir_returns_parent_dir_for_file_backend() {
2021        let dir = tempfile::tempdir().unwrap();
2022        let path = dir.path().join("test.db");
2023        let config = RuntimeConfig {
2024            git_write: Default::default(),
2025            display_timezone: chrono_tz::Tz::UTC,
2026            events_split: None,
2027            db_path: Some(path),
2028            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2029            default_namespace: Namespace::local(),
2030            embedding_model: None,
2031            additional_embedding_models: vec![],
2032            gate: Arc::new(AllowAllGate),
2033            packs: vec!["kg".to_string()],
2034            backend_id: BackendId::main(),
2035            brain_profile: None,
2036            visible_namespaces: vec![],
2037            allowed_outbound_namespaces: vec![],
2038            actor_id: None,
2039        };
2040        let rt = KhiveRuntime::new(config).expect("file runtime");
2041        let data_dir = rt
2042            .backend_data_dir()
2043            .expect("file backend must return Some");
2044        assert_eq!(data_dir, dir.path());
2045    }
2046
2047    /// A sidecar-only event must resolve through the public hex-prefix path:
2048    /// the main-store scan cannot see lane rows, so `resolve_prefix_inner`
2049    /// carries a sidecar arm. The pre-insert assert is the control — the
2050    /// prefix misses until the lane row exists, so a pass cannot come from
2051    /// the legacy scan.
2052    #[tokio::test]
2053    async fn resolve_prefix_finds_sidecar_only_event() {
2054        let dir = tempfile::tempdir().unwrap();
2055        let sidecar_path = dir.path().join("main.db.events.db");
2056        let config = RuntimeConfig {
2057            git_write: Default::default(),
2058            display_timezone: chrono_tz::Tz::UTC,
2059            events_split: Some(crate::events_split::EventsSplitConfig {
2060                db_path: sidecar_path.clone(),
2061                socket_path: None,
2062            }),
2063            db_path: Some(dir.path().join("main.db")),
2064            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2065            default_namespace: Namespace::local(),
2066            embedding_model: None,
2067            additional_embedding_models: vec![],
2068            gate: Arc::new(AllowAllGate),
2069            packs: vec!["kg".to_string()],
2070            backend_id: BackendId::main(),
2071            brain_profile: None,
2072            visible_namespaces: vec![],
2073            allowed_outbound_namespaces: vec![],
2074            actor_id: None,
2075        };
2076        let rt = KhiveRuntime::new(config).expect("file runtime");
2077
2078        let event = khive_storage::Event::new(
2079            "local",
2080            "memory.recall",
2081            khive_types::EventKind::RecallExecuted,
2082            khive_types::SubstrateKind::Note,
2083            "agent:test",
2084        );
2085        let event_id = event.id;
2086        let prefix = event_id.to_string()[..8].to_string();
2087
2088        assert_eq!(
2089            rt.resolve_prefix_unfiltered(&prefix)
2090                .await
2091                .expect("pre-insert resolve"),
2092            None,
2093            "control: prefix must miss before the lane row exists"
2094        );
2095
2096        let lane = crate::events_split::direct_backend_for(&sidecar_path)
2097            .expect("lane backend")
2098            .events_for_namespace("local")
2099            .expect("lane store");
2100        lane.append_event(event).await.expect("lane append");
2101
2102        assert_eq!(
2103            rt.resolve_prefix_unfiltered(&prefix)
2104                .await
2105                .expect("post-insert resolve"),
2106            Some(event_id),
2107            "a sidecar-only event id must resolve by hex prefix"
2108        );
2109    }
2110
2111    #[test]
2112    fn backend_data_dir_returns_none_for_from_backend_with_memory() {
2113        let backend = Arc::new(StorageBackend::memory().expect("memory backend"));
2114        let config = RuntimeConfig {
2115            git_write: Default::default(),
2116            display_timezone: chrono_tz::Tz::UTC,
2117            events_split: None,
2118            db_path: None,
2119            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2120            default_namespace: Namespace::local(),
2121            embedding_model: None,
2122            additional_embedding_models: vec![],
2123            gate: Arc::new(AllowAllGate),
2124            packs: vec!["kg".to_string()],
2125            backend_id: BackendId::main(),
2126            brain_profile: None,
2127            visible_namespaces: vec![],
2128            allowed_outbound_namespaces: vec![],
2129            actor_id: None,
2130        };
2131        let rt = KhiveRuntime::from_backend(backend, config);
2132        assert!(rt.backend_data_dir().is_none());
2133    }
2134
2135    #[test]
2136    fn file_runtime_creates_successfully() {
2137        let dir = tempfile::tempdir().unwrap();
2138        let path = dir.path().join("test.db");
2139        let config = RuntimeConfig {
2140            git_write: Default::default(),
2141            display_timezone: chrono_tz::Tz::UTC,
2142            events_split: None,
2143            db_path: Some(path.clone()),
2144            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2145            default_namespace: Namespace::parse("test").unwrap(),
2146            embedding_model: None,
2147            additional_embedding_models: vec![],
2148            gate: Arc::new(AllowAllGate),
2149            packs: vec!["kg".to_string()],
2150            backend_id: BackendId::main(),
2151            brain_profile: None,
2152            visible_namespaces: vec![],
2153            allowed_outbound_namespaces: vec![],
2154            actor_id: None,
2155        };
2156        let rt = KhiveRuntime::new(config).expect("file runtime should create");
2157        assert!(path.exists());
2158        assert_eq!(rt.config().default_namespace.as_str(), "test");
2159    }
2160
2161    #[cfg(unix)]
2162    #[tokio::test]
2163    async fn normal_boot_detects_read_only_snapshot_and_skips_model_registration() {
2164        use std::os::unix::fs::PermissionsExt;
2165
2166        let dir = tempfile::tempdir().unwrap();
2167        let path = dir.path().join("read_only_runtime.db");
2168        let base = RuntimeConfig {
2169            git_write: Default::default(),
2170            display_timezone: chrono_tz::Tz::UTC,
2171            events_split: None,
2172            db_path: Some(path.clone()),
2173            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2174            default_namespace: Namespace::local(),
2175            embedding_model: None,
2176            additional_embedding_models: vec![],
2177            gate: Arc::new(AllowAllGate),
2178            packs: vec!["kg".to_string()],
2179            backend_id: BackendId::main(),
2180            brain_profile: None,
2181            visible_namespaces: vec![],
2182            allowed_outbound_namespaces: vec![],
2183            actor_id: None,
2184        };
2185        {
2186            let writable = KhiveRuntime::new(base.clone()).expect("create migrated snapshot");
2187            assert!(writable
2188                .list_embedding_models(None)
2189                .await
2190                .expect("registry query")
2191                .is_empty());
2192        }
2193
2194        let mut permissions = std::fs::metadata(&path).unwrap().permissions();
2195        permissions.set_mode(0o444);
2196        std::fs::set_permissions(&path, permissions).unwrap();
2197        // A lingering writable `-shm` from the writable fixture's asynchronous
2198        // connection close is rejected by read-only admission as potentially
2199        // live; freeze any sidecars into the documented frozen-snapshot form.
2200        for suffix in ["-wal", "-shm"] {
2201            let mut name = path.file_name().expect("db file name").to_os_string();
2202            name.push(suffix);
2203            let sidecar = path.parent().expect("db parent dir").join(name);
2204            if sidecar.exists() {
2205                let mut sidecar_permissions = std::fs::metadata(&sidecar)
2206                    .expect("sidecar metadata")
2207                    .permissions();
2208                sidecar_permissions.set_mode(0o444);
2209                std::fs::set_permissions(&sidecar, sidecar_permissions).expect("freeze sidecar");
2210            }
2211        }
2212
2213        let read_only_config = RuntimeConfig {
2214            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
2215            ..base
2216        };
2217        let runtime = KhiveRuntime::new(read_only_config)
2218            .expect("read-only boot must validate instead of migrating/registering");
2219        assert!(runtime.is_read_only());
2220        assert_eq!(
2221            runtime.backend().pool().writer_acquisition_snapshot(),
2222            khive_db::pool::WriterAcquisitionSnapshot::default(),
2223            "the construction-inclusive acquisition baseline must stay at zero"
2224        );
2225        assert!(
2226            runtime
2227                .list_embedding_models(None)
2228                .await
2229                .expect("read-only registry query")
2230                .is_empty(),
2231            "configured models must remain in-memory only during read-only boot"
2232        );
2233    }
2234
2235    #[test]
2236    fn explicit_readonly_constructor_uses_read_only_pool_even_on_writable_file_mode() {
2237        let dir = tempfile::tempdir().unwrap();
2238        let path = dir.path().join("explicit_read_only_runtime.db");
2239        let config = RuntimeConfig {
2240            git_write: Default::default(),
2241            display_timezone: chrono_tz::Tz::UTC,
2242            events_split: None,
2243            db_path: Some(path.clone()),
2244            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2245            default_namespace: Namespace::local(),
2246            embedding_model: None,
2247            additional_embedding_models: vec![],
2248            gate: Arc::new(AllowAllGate),
2249            packs: vec!["kg".to_string()],
2250            backend_id: BackendId::main(),
2251            brain_profile: None,
2252            visible_namespaces: vec![],
2253            allowed_outbound_namespaces: vec![],
2254            actor_id: None,
2255        };
2256        KhiveRuntime::new(config.clone()).expect("create migrated database");
2257        #[cfg(unix)]
2258        {
2259            use std::os::unix::fs::PermissionsExt;
2260            for suffix in ["-wal", "-shm"] {
2261                let mut name = path.file_name().expect("db file name").to_os_string();
2262                name.push(suffix);
2263                let sidecar = path.parent().expect("db parent dir").join(name);
2264                if sidecar.exists() {
2265                    let mut permissions = std::fs::metadata(&sidecar)
2266                        .expect("sidecar metadata")
2267                        .permissions();
2268                    permissions.set_mode(0o444);
2269                    std::fs::set_permissions(&sidecar, permissions).expect("freeze sidecar");
2270                }
2271            }
2272        }
2273
2274        let runtime = KhiveRuntime::new_readonly(config).expect("explicit read-only boot");
2275        assert!(runtime.is_read_only());
2276        assert_eq!(
2277            runtime.backend().pool().writer_acquisition_snapshot(),
2278            khive_db::pool::WriterAcquisitionSnapshot::default(),
2279            "explicit read-only construction must validate through a reader without ever \
2280             acquiring the writer"
2281        );
2282    }
2283
2284    /// Denies exactly one namespace; every other request is allowed. Lets the
2285    /// tests below prove a refusal comes from the per-extra visibility check
2286    /// rather than from the primary authorization.
2287    #[derive(Debug)]
2288    struct DenyNamespaceGate {
2289        deny: &'static str,
2290    }
2291
2292    impl khive_gate::Gate for DenyNamespaceGate {
2293        fn check(
2294            &self,
2295            req: &khive_gate::GateRequest,
2296        ) -> Result<khive_gate::GateDecision, khive_gate::GateError> {
2297            if req.namespace.as_str() == self.deny {
2298                Ok(khive_gate::GateDecision::Deny {
2299                    reason: "namespace denied by policy".to_string(),
2300                })
2301            } else {
2302                Ok(khive_gate::GateDecision::allow())
2303            }
2304        }
2305    }
2306
2307    #[test]
2308    fn authorize_with_visibility_gate_checks_every_extra_namespace() {
2309        let config = RuntimeConfig {
2310            db_path: None,
2311            packs: vec!["kg".to_string()],
2312            brain_profile: None,
2313            actor_id: None,
2314            gate: Arc::new(DenyNamespaceGate {
2315                deny: "lambda:secret",
2316            }),
2317            ..RuntimeConfig::no_embeddings()
2318        };
2319        let rt = KhiveRuntime::new(config).expect("memory runtime");
2320        let primary = Namespace::parse("lambda:caller").expect("primary");
2321        let denied = Namespace::parse("lambda:secret").expect("denied");
2322        let allowed = Namespace::parse("lambda:open").expect("allowed");
2323
2324        // Control: the same mint without the denied namespace succeeds, so
2325        // the refusal below can only come from the per-extra check.
2326        rt.authorize_with_visibility(primary.clone(), vec![allowed.clone()])
2327            .expect("mint with only allowed extras");
2328
2329        let err = rt
2330            .authorize_with_visibility(primary, vec![allowed, denied])
2331            .expect_err("a denied extra namespace must refuse the whole mint");
2332        let msg = err.to_string();
2333        assert!(
2334            msg.contains("lambda:secret"),
2335            "refusal must name the offending namespace: {msg}"
2336        );
2337    }
2338
2339    /// Build a migrated database and reopen it read-only, returning the
2340    /// tempdir that keeps it alive alongside the runtime.
2341    fn make_read_only_runtime() -> (tempfile::TempDir, KhiveRuntime) {
2342        let dir = tempfile::tempdir().unwrap();
2343        let path = dir.path().join("read_only_blob_seam.db");
2344        let config = RuntimeConfig {
2345            git_write: Default::default(),
2346            display_timezone: chrono_tz::Tz::UTC,
2347            db_path: Some(path.clone()),
2348            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2349            default_namespace: Namespace::local(),
2350            embedding_model: None,
2351            additional_embedding_models: vec![],
2352            gate: Arc::new(AllowAllGate),
2353            packs: vec!["kg".to_string()],
2354            backend_id: BackendId::main(),
2355            brain_profile: None,
2356            visible_namespaces: vec![],
2357            allowed_outbound_namespaces: vec![],
2358            actor_id: None,
2359            events_split: None,
2360        };
2361        KhiveRuntime::new(config.clone()).expect("create migrated database");
2362        #[cfg(unix)]
2363        {
2364            use std::os::unix::fs::PermissionsExt;
2365            for suffix in ["-wal", "-shm"] {
2366                let mut name = path.file_name().expect("db file name").to_os_string();
2367                name.push(suffix);
2368                let sidecar = path.parent().expect("db parent dir").join(name);
2369                if sidecar.exists() {
2370                    let mut permissions = std::fs::metadata(&sidecar)
2371                        .expect("sidecar metadata")
2372                        .permissions();
2373                    permissions.set_mode(0o444);
2374                    std::fs::set_permissions(&sidecar, permissions).expect("freeze sidecar");
2375                }
2376            }
2377        }
2378        let runtime = KhiveRuntime::new_readonly(config).expect("read-only boot");
2379        assert!(runtime.is_read_only());
2380        (dir, runtime)
2381    }
2382
2383    #[tokio::test]
2384    async fn install_blob_store_on_read_only_runtime_refuses_mutators() {
2385        let (_dir, runtime) = make_read_only_runtime();
2386
2387        // Control: the raw store IS writable — seed an object through it —
2388        // so the refusal below can only come from the install-seam wrap.
2389        use khive_storage::BlobStore as _;
2390        let blob_root = tempfile::tempdir().unwrap();
2391        let writable = Arc::new(
2392            khive_db::stores::blob::FsBlobStore::new(blob_root.path().to_path_buf(), 0)
2393                .expect("fs blob store"),
2394        );
2395        let seeded = writable
2396            .put(b"seed".to_vec())
2397            .await
2398            .expect("seed put through the raw store");
2399        runtime
2400            .install_blob_store(writable.clone())
2401            .expect("read-only install wraps rather than refusing");
2402
2403        let installed = runtime.blob_store().expect("installed store");
2404        assert!(
2405            installed.exists(&seeded).await.expect("exists"),
2406            "bounded read surface must stay available"
2407        );
2408        let err = installed
2409            .put(b"post-boot".to_vec())
2410            .await
2411            .expect_err("put must refuse on a read-only runtime");
2412        assert!(
2413            err.to_string().contains("read-only"),
2414            "refusal must name the mode: {err}"
2415        );
2416
2417        // Reinstalling the SAME raw store stays idempotent even though the
2418        // installed hydrator holds a wrapper around it: identity is checked
2419        // against the raw handle the hydrator remembers.
2420        runtime
2421            .install_blob_store(writable.clone())
2422            .expect("reinstalling the same raw store must be idempotent");
2423
2424        // The hydrator seam holds the mode too: pairing a writable store
2425        // with `BlobHydrator::new` and installing it directly must refuse,
2426        // or it is a public bypass of everything above.
2427        let bypass_root = tempfile::tempdir().unwrap();
2428        let bypass_store = Arc::new(
2429            khive_db::stores::blob::FsBlobStore::new(bypass_root.path().to_path_buf(), 0)
2430                .expect("fs blob store"),
2431        );
2432        let writable_hydrator = Arc::new(
2433            crate::BlobHydrator::new(bypass_store, crate::DEFAULT_BLOB_HYDRATION_BYTES)
2434                .expect("construct writable hydrator"),
2435        );
2436        let err = runtime
2437            .install_blob_hydrator(writable_hydrator)
2438            .expect_err("a writable hydrator must be refused on a read-only runtime");
2439        assert!(
2440            err.to_string().contains("read-only"),
2441            "refusal must name the mode: {err}"
2442        );
2443    }
2444
2445    #[tokio::test]
2446    async fn mode_aware_hydrator_constructor_satisfies_read_only_install() {
2447        // The boot path constructs its hydrator with `for_mode` from the
2448        // blob runtime's configured mode; a read-only construction must pass
2449        // the read-only install gate, serve bounded reads, refuse mutation,
2450        // and treat a second hydrator allocation over the same raw store as
2451        // the same pairing (the concurrent-first-install loser shape).
2452        let (_dir, runtime) = make_read_only_runtime();
2453        let blob_root = tempfile::tempdir().unwrap();
2454        let raw = Arc::new(
2455            khive_db::stores::blob::FsBlobStore::new(blob_root.path().to_path_buf(), 0)
2456                .expect("fs blob store"),
2457        ) as Arc<dyn khive_storage::BlobStore>;
2458        let seeded = raw.put(b"seed".to_vec()).await.expect("seed put");
2459        let hydrator = Arc::new(
2460            crate::BlobHydrator::for_mode(
2461                Arc::clone(&raw),
2462                crate::DEFAULT_BLOB_HYDRATION_BYTES,
2463                true,
2464            )
2465            .expect("mode-aware read-only construction"),
2466        );
2467        runtime
2468            .install_blob_hydrator(hydrator)
2469            .expect("a for_mode(read_only) hydrator must pass the read-only gate");
2470        let installed = runtime.blob_store().expect("installed store");
2471        assert!(installed.exists(&seeded).await.expect("exists"));
2472        installed
2473            .put(b"post".to_vec())
2474            .await
2475            .expect_err("mutation must refuse through the wrapped store");
2476
2477        // A DISTINCT hydrator allocation over the same raw store, budget,
2478        // and mode is the same pairing: installing it must be idempotent,
2479        // not a conflicting-install error.
2480        let twin = Arc::new(
2481            crate::BlobHydrator::for_mode(
2482                Arc::clone(&raw),
2483                crate::DEFAULT_BLOB_HYDRATION_BYTES,
2484                true,
2485            )
2486            .expect("twin construction"),
2487        );
2488        runtime
2489            .install_blob_hydrator(twin)
2490            .expect("an equivalent pairing must read as idempotent");
2491    }
2492
2493    #[tokio::test]
2494    async fn shared_install_permits_governed_writable_hydrator_on_read_only_handle() {
2495        // The documented multi-backend matrix includes a writable blob
2496        // secondary beside a read-only main: boot installs ONE writable
2497        // hydrator on every handle, including read-only ones. The plain
2498        // seam must still refuse that pairing, and the shared seam accepts
2499        // it ONLY when the hydrator's mode was derived from a governing
2500        // backend — a hand-paired writable hydrator is refused too, so a
2501        // safe downstream caller cannot use the shared seam to defeat a
2502        // read-only handle's guarantee.
2503        let (_dir, runtime) = make_read_only_runtime();
2504        let blob_root = tempfile::tempdir().unwrap();
2505        let raw = Arc::new(
2506            khive_db::stores::blob::FsBlobStore::new(blob_root.path().to_path_buf(), 0)
2507                .expect("fs blob store"),
2508        ) as Arc<dyn khive_storage::BlobStore>;
2509        let hand_paired = Arc::new(
2510            crate::BlobHydrator::for_mode(raw, crate::DEFAULT_BLOB_HYDRATION_BYTES, false)
2511                .expect("writable construction"),
2512        );
2513        runtime
2514            .install_blob_hydrator(Arc::clone(&hand_paired))
2515            .expect_err("the plain seam must refuse a writable hydrator on a read-only handle");
2516        runtime
2517            .install_shared_blob_hydrator(hand_paired)
2518            .expect_err("the shared seam must refuse a hand-paired (ungoverned) hydrator");
2519
2520        // The sanctioned path: a WRITABLE governing backend (the blob pack's
2521        // backend in the mixed-mode topology) derives a governed writable
2522        // hydrator, and the shared seam installs it on the read-only handle.
2523        let governing = khive_db::StorageBackend::memory().expect("memory backend");
2524        let cfg = crate::KhiveConfig {
2525            storage: crate::engine_config::StorageSectionConfig {
2526                blob: Some(crate::engine_config::BlobConfig::Fs {
2527                    root: Some(blob_root.path().to_string_lossy().into_owned()),
2528                    floor_bytes: Some(0),
2529                }),
2530            },
2531            ..crate::KhiveConfig::default()
2532        };
2533        let governed = Arc::new(
2534            crate::BlobHydrator::resolve_for_governing_backend(
2535                &cfg,
2536                &governing,
2537                &governing,
2538                crate::DEFAULT_BLOB_HYDRATION_BYTES,
2539            )
2540            .expect("governed construction"),
2541        );
2542        runtime
2543            .install_shared_blob_hydrator(governed)
2544            .expect("the shared seam accepts a governed hydrator");
2545        let installed = runtime.blob_store().expect("installed store");
2546        let put = installed
2547            .put(b"shared-write".to_vec())
2548            .await
2549            .expect("the governed writable capability must actually mutate");
2550        assert!(installed.exists(&put).await.expect("exists"));
2551    }
2552
2553    /// A `~/`-prefixed `--db`/`KHIVE_DB` override must resolve, boot, and
2554    /// fingerprint identically to the equivalent absolute path. Before this
2555    /// fix, `resolve_db_anchor` left a leading `~` unexpanded in
2556    /// `RuntimeConfig.db_path`, so single-backend boot (`KhiveRuntime::new`)
2557    /// opened a literal `./~/...` file under the process cwd while
2558    /// `compute_config_id` (which canonicalizes/expands separately) still
2559    /// fingerprinted the real `$HOME` path — two processes pointed at the
2560    /// same logical database could open different files yet share a
2561    /// `config_id`, letting daemon dispatch route requests to the wrong one.
2562    #[test]
2563    #[serial]
2564    fn tilde_prefixed_db_override_resolves_and_boots_like_the_absolute_equivalent() {
2565        let original_home = std::env::var_os("HOME");
2566        let original_cwd = std::env::current_dir().expect("read cwd");
2567        let home_dir = tempfile::tempdir().expect("home tempdir");
2568        let work_dir = tempfile::tempdir().expect("work tempdir");
2569        std::env::set_var("HOME", home_dir.path());
2570        std::env::set_current_dir(work_dir.path()).expect("chdir into isolated work dir");
2571
2572        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2573            let tilde_anchor = crate::config::resolve_db_anchor(Some("~/data.db"))
2574                .expect("an explicit path always anchors");
2575            let expected = home_dir.path().join("data.db");
2576            assert_eq!(
2577                tilde_anchor, expected,
2578                "resolve_db_anchor must expand a leading ~ to $HOME before it ever \
2579                 reaches RuntimeConfig.db_path"
2580            );
2581
2582            let absolute_anchor = crate::config::resolve_db_anchor(Some(
2583                expected.to_str().expect("utf8 tempdir path"),
2584            ))
2585            .expect("an explicit path always anchors");
2586            assert_eq!(
2587                tilde_anchor, absolute_anchor,
2588                "a ~-prefixed override and its equivalent absolute path must resolve to \
2589                 the identical anchor"
2590            );
2591
2592            let make_config = |db_path: std::path::PathBuf| RuntimeConfig {
2593                git_write: Default::default(),
2594                display_timezone: chrono_tz::Tz::UTC,
2595                events_split: None,
2596                db_path: Some(db_path),
2597                blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2598                default_namespace: Namespace::local(),
2599                embedding_model: None,
2600                additional_embedding_models: vec![],
2601                gate: Arc::new(AllowAllGate),
2602                packs: vec!["kg".to_string()],
2603                backend_id: BackendId::main(),
2604                brain_profile: None,
2605                visible_namespaces: vec![],
2606                allowed_outbound_namespaces: vec![],
2607                actor_id: None,
2608            };
2609
2610            let tilde_cfg = make_config(tilde_anchor.clone());
2611
2612            let rt = KhiveRuntime::new(tilde_cfg).expect("boot must open the expanded path");
2613            assert_eq!(
2614                rt.backend_data_dir().expect("file backend"),
2615                home_dir.path(),
2616                "single-backend boot must open the file under the expanded $HOME \
2617                 directory, not a literal ~ path relative to cwd"
2618            );
2619            assert!(
2620                expected.exists(),
2621                "the database file must be created at the expanded $HOME path"
2622            );
2623            assert!(
2624                !work_dir.path().join("~").exists(),
2625                "boot must never create a literal '~' directory under the process cwd"
2626            );
2627        }));
2628
2629        match &original_home {
2630            Some(h) => std::env::set_var("HOME", h),
2631            None => std::env::remove_var("HOME"),
2632        }
2633        let _ = std::env::set_current_dir(&original_cwd);
2634        outcome.expect("test body panicked");
2635    }
2636
2637    #[test]
2638    fn from_backend_uses_provided_backend() {
2639        let backend = Arc::new(StorageBackend::memory().expect("memory backend"));
2640        let config = RuntimeConfig {
2641            git_write: Default::default(),
2642            display_timezone: chrono_tz::Tz::UTC,
2643            events_split: None,
2644            db_path: None,
2645            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2646            default_namespace: Namespace::local(),
2647            embedding_model: None,
2648            additional_embedding_models: vec![],
2649            gate: Arc::new(AllowAllGate),
2650            packs: vec!["kg".to_string()],
2651            backend_id: BackendId::new("lore"),
2652            brain_profile: None,
2653            visible_namespaces: vec![],
2654            allowed_outbound_namespaces: vec![],
2655            actor_id: None,
2656        };
2657        let rt = KhiveRuntime::from_backend(backend, config);
2658        assert_eq!(rt.backend_id().as_str(), "lore");
2659        assert!(rt.config().db_path.is_none());
2660    }
2661
2662    #[test]
2663    fn backend_id_defaults_to_main() {
2664        let rt = KhiveRuntime::memory().unwrap();
2665        assert_eq!(rt.backend_id().as_str(), BackendId::MAIN);
2666    }
2667
2668    #[test]
2669    fn store_accessors_return_ok() {
2670        let rt = KhiveRuntime::memory().unwrap();
2671        let tok = NamespaceToken::local();
2672        assert!(rt.entities(&tok).is_ok());
2673        assert!(rt.graph(&tok).is_ok());
2674        assert!(rt.notes(&tok).is_ok());
2675        assert!(rt.events(&tok).is_ok());
2676    }
2677
2678    #[test]
2679    fn vectors_returns_unconfigured_without_model() {
2680        let rt = KhiveRuntime::memory().unwrap();
2681        let tok = NamespaceToken::local();
2682        match rt.vectors(&tok) {
2683            Err(crate::RuntimeError::Unconfigured(s)) => assert_eq!(s, "embedding_model"),
2684            Err(other) => panic!("expected Unconfigured, got {:?}", other),
2685            Ok(_) => panic!("expected Err, got Ok"),
2686        }
2687    }
2688
2689    #[test]
2690    fn vec_model_key_sanitizes_dots_and_dashes() {
2691        assert_eq!(
2692            vec_model_key(EmbeddingModel::BgeSmallEnV15),
2693            "bge_small_en_v1_5"
2694        );
2695        assert_eq!(
2696            vec_model_key(EmbeddingModel::BgeBaseEnV15),
2697            "bge_base_en_v1_5"
2698        );
2699        assert_eq!(
2700            vec_model_key(EmbeddingModel::AllMiniLmL6V2),
2701            "all_minilm_l6_v2"
2702        );
2703    }
2704
2705    #[test]
2706    fn default_config_uses_allow_all_gate() {
2707        let cfg = RuntimeConfig::default();
2708        assert_eq!(cfg.default_namespace.as_str(), "local");
2709        let _: GateRef = cfg.gate.clone();
2710    }
2711
2712    #[test]
2713    fn parse_pack_list_handles_comma_and_whitespace() {
2714        assert_eq!(parse_pack_list("kg"), vec!["kg".to_string()]);
2715        assert_eq!(
2716            parse_pack_list("kg,gtd"),
2717            vec!["kg".to_string(), "gtd".to_string()]
2718        );
2719        assert_eq!(
2720            parse_pack_list("  kg ,  gtd  "),
2721            vec!["kg".to_string(), "gtd".to_string()]
2722        );
2723        assert_eq!(
2724            parse_pack_list("kg gtd"),
2725            vec!["kg".to_string(), "gtd".to_string()]
2726        );
2727        assert_eq!(parse_pack_list(",,"), Vec::<String>::new());
2728        assert_eq!(parse_pack_list(""), Vec::<String>::new());
2729    }
2730
2731    #[test]
2732    fn default_config_packs_loads_production_set() {
2733        let prior = std::env::var("KHIVE_PACKS").ok();
2734        // SAFETY: test function runs single-threaded; no other threads read or write KHIVE_PACKS.
2735        unsafe {
2736            std::env::remove_var("KHIVE_PACKS");
2737        }
2738        // The default distribution loads all production packs.
2739        let cfg = RuntimeConfig::default();
2740        assert_eq!(cfg.packs, RuntimeConfig::built_in_packs());
2741        assert!(cfg.packs.contains(&"kg".to_string()));
2742        assert!(cfg.packs.contains(&"gtd".to_string()));
2743        assert!(cfg.packs.contains(&"memory".to_string()));
2744        assert!(cfg.packs.contains(&"brain".to_string()));
2745        assert!(cfg.packs.contains(&"comm".to_string()));
2746        assert!(cfg.packs.contains(&"schedule".to_string()));
2747        assert!(cfg.packs.contains(&"knowledge".to_string()));
2748        // session loads by default so its background mirror warm-hook runs in
2749        // production; its handlers are all operator-only subhandlers (0 wire verbs).
2750        assert!(cfg.packs.contains(&"session".to_string()));
2751        assert!(cfg.packs.contains(&"git".to_string()));
2752        assert!(cfg.packs.contains(&"code".to_string()));
2753        assert!(cfg.packs.contains(&"workspace".to_string()));
2754        // blob loads by default; a normal file-backed boot installs a
2755        // default FsBlobStore beside the database file with no config
2756        // needed, so its verbs are live in default deployments too (only an
2757        // in-memory backend leaves them unconfigured).
2758        assert!(cfg.packs.contains(&"blob".to_string()));
2759        assert_eq!(cfg.packs.len(), 12);
2760        if let Some(v) = prior {
2761            // SAFETY: single-threaded test cleanup; restores KHIVE_PACKS to its prior value.
2762            unsafe {
2763                std::env::set_var("KHIVE_PACKS", v);
2764            }
2765        }
2766    }
2767
2768    #[test]
2769    fn default_config_uses_minilm_when_env_unset() {
2770        let prior = std::env::var("KHIVE_EMBEDDING_MODEL").ok();
2771        // SAFETY: tests are serial by default for env mutation here; if other tests
2772        // mutate this var, mark them with the same scope.
2773        unsafe {
2774            std::env::remove_var("KHIVE_EMBEDDING_MODEL");
2775        }
2776        let cfg = RuntimeConfig::default();
2777        assert_eq!(cfg.embedding_model, Some(EmbeddingModel::AllMiniLmL6V2));
2778        if let Some(v) = prior {
2779            // SAFETY: single-threaded test cleanup; restores KHIVE_EMBEDDING_MODEL to its prior value.
2780            unsafe {
2781                std::env::set_var("KHIVE_EMBEDDING_MODEL", v);
2782            }
2783        }
2784    }
2785
2786    // ---- Actor config tests ----
2787
2788    use crate::engine_config::{ActorConfig, KhiveConfig};
2789
2790    fn khive_cfg_with_actor(id: &str) -> KhiveConfig {
2791        KhiveConfig {
2792            engines: vec![],
2793            actor: ActorConfig {
2794                id: Some(id.to_string()),
2795                display_name: None,
2796                ..Default::default()
2797            },
2798            ..KhiveConfig::default()
2799        }
2800    }
2801
2802    #[test]
2803    fn runtime_config_from_khive_config_actor_id_does_not_override_default_namespace() {
2804        // `[actor] id` must not set `default_namespace`: writes stay pinned to
2805        // `local`. A non-`'local'` actor.id is folded into the default read
2806        // visible-set, but that does not change default_namespace. This test
2807        // asserts the write-routing invariant only.
2808        let base = RuntimeConfig {
2809            git_write: Default::default(),
2810            display_timezone: chrono_tz::Tz::UTC,
2811            events_split: None,
2812            db_path: None,
2813            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2814            default_namespace: Namespace::local(),
2815            embedding_model: None,
2816            additional_embedding_models: vec![],
2817            gate: Arc::new(AllowAllGate),
2818            packs: vec!["kg".to_string()],
2819            backend_id: BackendId::main(),
2820            brain_profile: None,
2821            visible_namespaces: vec![],
2822            allowed_outbound_namespaces: vec![],
2823            actor_id: None,
2824        };
2825        let cfg = khive_cfg_with_actor("lambda:khive");
2826        let result = runtime_config_from_khive_config(&cfg, base);
2827        assert_eq!(
2828            result.default_namespace.as_str(),
2829            "local",
2830            "actor.id must not become default_namespace (ADR-007 Rev 4 Rule 0); writes pin to local"
2831        );
2832    }
2833
2834    #[test]
2835    fn runtime_config_from_khive_config_empty_actor_id_keeps_base_namespace() {
2836        let base = RuntimeConfig {
2837            git_write: Default::default(),
2838            display_timezone: chrono_tz::Tz::UTC,
2839            events_split: None,
2840            db_path: None,
2841            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2842            default_namespace: Namespace::parse("lambda:base").unwrap(),
2843            embedding_model: None,
2844            additional_embedding_models: vec![],
2845            gate: Arc::new(AllowAllGate),
2846            packs: vec!["kg".to_string()],
2847            backend_id: BackendId::main(),
2848            brain_profile: None,
2849            visible_namespaces: vec![],
2850            allowed_outbound_namespaces: vec![],
2851            actor_id: None,
2852        };
2853        let cfg = KhiveConfig {
2854            engines: vec![],
2855            actor: ActorConfig {
2856                id: Some(String::new()),
2857                display_name: None,
2858                ..Default::default()
2859            },
2860            ..KhiveConfig::default()
2861        };
2862        let result = runtime_config_from_khive_config(&cfg, base);
2863        assert_eq!(
2864            result.default_namespace.as_str(),
2865            "lambda:base",
2866            "empty actor.id must not override base namespace"
2867        );
2868    }
2869
2870    #[test]
2871    fn runtime_config_from_khive_config_absent_actor_id_keeps_base_namespace() {
2872        let base = RuntimeConfig {
2873            git_write: Default::default(),
2874            display_timezone: chrono_tz::Tz::UTC,
2875            events_split: None,
2876            db_path: None,
2877            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2878            default_namespace: Namespace::parse("lambda:base").unwrap(),
2879            embedding_model: None,
2880            additional_embedding_models: vec![],
2881            gate: Arc::new(AllowAllGate),
2882            packs: vec!["kg".to_string()],
2883            backend_id: BackendId::main(),
2884            brain_profile: None,
2885            visible_namespaces: vec![],
2886            allowed_outbound_namespaces: vec![],
2887            actor_id: None,
2888        };
2889        let cfg = KhiveConfig::default(); // no actor.id
2890        let result = runtime_config_from_khive_config(&cfg, base);
2891        assert_eq!(
2892            result.default_namespace.as_str(),
2893            "lambda:base",
2894            "absent actor.id must not override base namespace"
2895        );
2896    }
2897
2898    #[test]
2899    fn runtime_config_from_khive_config_actor_id_with_engines() {
2900        let base = RuntimeConfig {
2901            git_write: Default::default(),
2902            display_timezone: chrono_tz::Tz::UTC,
2903            events_split: None,
2904            db_path: None,
2905            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2906            default_namespace: Namespace::local(),
2907            embedding_model: None,
2908            additional_embedding_models: vec![],
2909            gate: Arc::new(AllowAllGate),
2910            packs: vec!["kg".to_string()],
2911            backend_id: BackendId::main(),
2912            brain_profile: None,
2913            visible_namespaces: vec![],
2914            allowed_outbound_namespaces: vec![],
2915            actor_id: None,
2916        };
2917        let cfg = KhiveConfig {
2918            engines: vec![crate::engine_config::EngineConfig {
2919                name: "default".to_string(),
2920                model: "all-minilm-l6-v2".to_string(),
2921                default: true,
2922                fusion_weight: None,
2923                dims: None,
2924            }],
2925            actor: ActorConfig {
2926                id: Some("lambda:test".to_string()),
2927                display_name: None,
2928                ..Default::default()
2929            },
2930            ..KhiveConfig::default()
2931        };
2932        let result = runtime_config_from_khive_config(&cfg, base);
2933        assert_eq!(
2934            result.default_namespace.as_str(),
2935            "local",
2936            "actor.id must not override default_namespace (ADR-007 Rev 4 Rule 0); \
2937             writes pin to local; engine config is still applied"
2938        );
2939        assert!(result.embedding_model.is_some());
2940    }
2941
2942    // ---- [display] timezone (ADR-169) wiring tests ----
2943
2944    #[test]
2945    fn runtime_config_from_khive_config_display_timezone_overrides_base() {
2946        let base = RuntimeConfig {
2947            git_write: Default::default(),
2948            display_timezone: chrono_tz::Tz::UTC,
2949            events_split: None,
2950            db_path: None,
2951            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2952            default_namespace: Namespace::local(),
2953            embedding_model: None,
2954            additional_embedding_models: vec![],
2955            gate: Arc::new(AllowAllGate),
2956            packs: vec!["kg".to_string()],
2957            backend_id: BackendId::main(),
2958            brain_profile: None,
2959            visible_namespaces: vec![],
2960            allowed_outbound_namespaces: vec![],
2961            actor_id: None,
2962        };
2963        let cfg = KhiveConfig {
2964            display: crate::engine_config::DisplaySectionConfig {
2965                timezone: Some("America/New_York".to_string()),
2966            },
2967            ..KhiveConfig::default()
2968        };
2969        let result = runtime_config_from_khive_config(&cfg, base);
2970        assert_eq!(
2971            result.display_timezone,
2972            "America/New_York".parse::<chrono_tz::Tz>().unwrap(),
2973            "[display] timezone in khive.toml must override base.display_timezone"
2974        );
2975    }
2976
2977    #[test]
2978    fn runtime_config_from_khive_config_absent_display_timezone_keeps_base() {
2979        let base = RuntimeConfig {
2980            git_write: Default::default(),
2981            display_timezone: "Asia/Tokyo".parse().unwrap(),
2982            events_split: None,
2983            db_path: None,
2984            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
2985            default_namespace: Namespace::local(),
2986            embedding_model: None,
2987            additional_embedding_models: vec![],
2988            gate: Arc::new(AllowAllGate),
2989            packs: vec!["kg".to_string()],
2990            backend_id: BackendId::main(),
2991            brain_profile: None,
2992            visible_namespaces: vec![],
2993            allowed_outbound_namespaces: vec![],
2994            actor_id: None,
2995        };
2996        let cfg = KhiveConfig::default(); // no [display] section
2997        let result = runtime_config_from_khive_config(&cfg, base);
2998        assert_eq!(
2999            result.display_timezone,
3000            "Asia/Tokyo".parse::<chrono_tz::Tz>().unwrap(),
3001            "absent [display] timezone must preserve base.display_timezone unchanged"
3002        );
3003    }
3004
3005    // ---- base.actor_id (env-resolved actor) preservation tests ----
3006    //
3007    // Regression coverage: a project config found without an `[actor] id` used
3008    // to silently drop `base.actor_id` (e.g. the value `RuntimeConfig::default()`
3009    // read from `KHIVE_ACTOR`) because both return arms spread an unconditional
3010    // `actor_id: None` over `..base`. The fix falls back to `base.actor_id`
3011    // when the TOML supplies no `[actor] id`, in both arms.
3012
3013    #[test]
3014    #[serial]
3015    fn runtime_config_from_khive_config_engines_present_preserves_env_actor_when_toml_has_none() {
3016        let prior = std::env::var("KHIVE_ACTOR").ok();
3017        // SAFETY: test is #[serial]; no other test in this crate reads/writes KHIVE_ACTOR.
3018        unsafe {
3019            std::env::set_var("KHIVE_ACTOR", "lambda:test-env-actor");
3020        }
3021        let base = RuntimeConfig::default();
3022        assert_eq!(base.actor_id.as_deref(), Some("lambda:test-env-actor"));
3023
3024        let cfg = KhiveConfig {
3025            engines: vec![crate::engine_config::EngineConfig {
3026                name: "default".to_string(),
3027                model: "all-minilm-l6-v2".to_string(),
3028                default: true,
3029                fusion_weight: None,
3030                dims: None,
3031            }],
3032            actor: ActorConfig::default(), // no [actor] id
3033            ..KhiveConfig::default()
3034        };
3035        let result = runtime_config_from_khive_config(&cfg, base);
3036        assert_eq!(
3037            result.actor_id.as_deref(),
3038            Some("lambda:test-env-actor"),
3039            "engines-present arm must preserve base.actor_id (env actor) when TOML has no [actor] id"
3040        );
3041
3042        // SAFETY: restores prior KHIVE_ACTOR value (test cleanup).
3043        unsafe {
3044            match prior {
3045                Some(v) => std::env::set_var("KHIVE_ACTOR", v),
3046                None => std::env::remove_var("KHIVE_ACTOR"),
3047            }
3048        }
3049    }
3050
3051    #[test]
3052    #[serial]
3053    fn runtime_config_from_khive_config_engines_empty_preserves_env_actor_when_toml_has_none() {
3054        let prior = std::env::var("KHIVE_ACTOR").ok();
3055        // SAFETY: test is #[serial]; no other test in this crate reads/writes KHIVE_ACTOR.
3056        unsafe {
3057            std::env::set_var("KHIVE_ACTOR", "lambda:test-env-actor");
3058        }
3059        let base = RuntimeConfig::default();
3060        assert_eq!(base.actor_id.as_deref(), Some("lambda:test-env-actor"));
3061
3062        let cfg = KhiveConfig {
3063            engines: vec![],
3064            actor: ActorConfig::default(), // no [actor] id
3065            ..KhiveConfig::default()
3066        };
3067        let result = runtime_config_from_khive_config(&cfg, base);
3068        assert_eq!(
3069            result.actor_id.as_deref(),
3070            Some("lambda:test-env-actor"),
3071            "engines-empty early-return arm must preserve base.actor_id (env actor) when TOML has no [actor] id"
3072        );
3073
3074        // SAFETY: restores prior KHIVE_ACTOR value (test cleanup).
3075        unsafe {
3076            match prior {
3077                Some(v) => std::env::set_var("KHIVE_ACTOR", v),
3078                None => std::env::remove_var("KHIVE_ACTOR"),
3079            }
3080        }
3081    }
3082
3083    #[test]
3084    #[serial]
3085    fn runtime_config_from_khive_config_toml_actor_wins_over_env_actor() {
3086        let prior = std::env::var("KHIVE_ACTOR").ok();
3087        // SAFETY: test is #[serial]; no other test in this crate reads/writes KHIVE_ACTOR.
3088        unsafe {
3089            std::env::set_var("KHIVE_ACTOR", "lambda:test-env-actor");
3090        }
3091        let base = RuntimeConfig::default();
3092        assert_eq!(base.actor_id.as_deref(), Some("lambda:test-env-actor"));
3093
3094        let cfg = khive_cfg_with_actor("lambda:toml-actor");
3095        let result = runtime_config_from_khive_config(&cfg, base);
3096        assert_eq!(
3097            result.actor_id.as_deref(),
3098            Some("lambda:toml-actor"),
3099            "TOML [actor] id must win over the env-resolved base.actor_id"
3100        );
3101
3102        // SAFETY: restores prior KHIVE_ACTOR value (test cleanup).
3103        unsafe {
3104            match prior {
3105                Some(v) => std::env::set_var("KHIVE_ACTOR", v),
3106                None => std::env::remove_var("KHIVE_ACTOR"),
3107            }
3108        }
3109    }
3110
3111    // ---- list_embedding_models tests ----
3112
3113    // ---- core_backend accessor tests ----
3114
3115    /// Create a migrated in-memory backend (for tests that need raw Arc<StorageBackend>).
3116    fn migrated_memory_backend() -> Arc<StorageBackend> {
3117        let backend = StorageBackend::memory().expect("memory backend");
3118        {
3119            let mut writer = backend.pool().try_writer().expect("writer");
3120            khive_db::run_migrations(writer.conn_mut()).expect("migrations");
3121        }
3122        Arc::new(backend)
3123    }
3124
3125    fn secondary_config() -> RuntimeConfig {
3126        RuntimeConfig {
3127            git_write: Default::default(),
3128            display_timezone: chrono_tz::Tz::UTC,
3129            events_split: None,
3130            db_path: None,
3131            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
3132            default_namespace: Namespace::local(),
3133            embedding_model: None,
3134            additional_embedding_models: vec![],
3135            gate: Arc::new(AllowAllGate),
3136            packs: vec!["kg".to_string()],
3137            backend_id: BackendId::new("lore"),
3138            brain_profile: None,
3139            visible_namespaces: vec![],
3140            allowed_outbound_namespaces: vec![],
3141            actor_id: None,
3142        }
3143    }
3144
3145    #[test]
3146    fn core_on_main_runtime_returns_same_backend_id() {
3147        // For a main-bound runtime, core() must return a clone with backend_id == "main".
3148        let rt = KhiveRuntime::memory().unwrap();
3149        assert_eq!(rt.backend_id().as_str(), BackendId::MAIN);
3150        let core_rt = rt.core();
3151        assert_eq!(core_rt.backend_id().as_str(), BackendId::MAIN);
3152    }
3153
3154    #[tokio::test]
3155    async fn core_on_main_runtime_round_trips_note() {
3156        // core() on a main-bound runtime (core_backend = None) returns self.clone(),
3157        // so a note written through core() is readable through the original runtime.
3158        let rt = KhiveRuntime::memory().unwrap();
3159        let tok = NamespaceToken::local();
3160
3161        let note = rt
3162            .core()
3163            .create_note(
3164                &tok,
3165                "observation",
3166                None,
3167                "adr073-main-round-trip",
3168                None,
3169                None,
3170                vec![],
3171            )
3172            .await
3173            .expect("create_note via core()");
3174
3175        let found = rt
3176            .notes(&tok)
3177            .expect("notes store")
3178            .get_note(note.id)
3179            .await
3180            .expect("get_note");
3181
3182        assert!(
3183            found.is_some(),
3184            "note written via core() must be visible through original rt"
3185        );
3186    }
3187
3188    /// Proves note→main and aux→secondary writes are each isolated.
3189    ///
3190    /// Backend A = main; backend B = secondary.
3191    /// rt_secondary is bound to B with core_backend = Some(A).
3192    ///
3193    /// Direction 1 (note → main):
3194    ///   rt_secondary.core().create_note(...) must land in A (visible from rt_main)
3195    ///   and NOT in B (not visible from rt_secondary).
3196    ///
3197    /// Direction 2 (aux → secondary):
3198    ///   A raw SQL write via rt_secondary.sql() lands in B only; A is untouched.
3199    #[tokio::test]
3200    async fn cross_backend_split_note_to_main_aux_to_secondary() {
3201        use khive_storage::{SqlStatement, SqlValue};
3202
3203        let main_arc = migrated_memory_backend();
3204        let secondary_arc = migrated_memory_backend();
3205
3206        let main_config = RuntimeConfig {
3207            git_write: Default::default(),
3208            display_timezone: chrono_tz::Tz::UTC,
3209            events_split: None,
3210            db_path: None,
3211            blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
3212            default_namespace: Namespace::local(),
3213            embedding_model: None,
3214            additional_embedding_models: vec![],
3215            gate: Arc::new(AllowAllGate),
3216            packs: vec!["kg".to_string()],
3217            backend_id: BackendId::main(),
3218            brain_profile: None,
3219            visible_namespaces: vec![],
3220            allowed_outbound_namespaces: vec![],
3221            actor_id: None,
3222        };
3223
3224        let rt_main = KhiveRuntime::from_backend(main_arc.clone(), main_config);
3225        let rt_secondary = KhiveRuntime::from_backend(secondary_arc, secondary_config())
3226            .with_core_backend(main_arc.clone());
3227
3228        let tok = NamespaceToken::local();
3229
3230        // ── Direction 1: note must land in A (main), not in B (secondary) ──
3231
3232        let note = rt_secondary
3233            .core()
3234            .create_note(
3235                &tok,
3236                "observation",
3237                None,
3238                "adr073-split-test",
3239                None,
3240                None,
3241                vec![],
3242            )
3243            .await
3244            .expect("create_note via core()");
3245        let note_id = note.id;
3246
3247        // Visible from main (A).
3248        let in_main = rt_main
3249            .notes(&tok)
3250            .expect("main notes store")
3251            .get_note(note_id)
3252            .await
3253            .expect("get_note from main");
3254        assert!(
3255            in_main.is_some(),
3256            "note written via core() must appear in main backend A"
3257        );
3258
3259        // Not visible from secondary (B).
3260        let in_secondary = rt_secondary
3261            .notes(&tok)
3262            .expect("secondary notes store")
3263            .get_note(note_id)
3264            .await
3265            .expect("get_note from secondary");
3266        assert!(
3267            in_secondary.is_none(),
3268            "note written to main via core() must NOT appear in secondary backend B"
3269        );
3270
3271        // ── Direction 2: aux write via rt_secondary.sql() lands in B, not A ──
3272
3273        {
3274            let mut writer = rt_secondary.sql().writer().await.expect("secondary writer");
3275            writer
3276                .execute(SqlStatement {
3277                    sql: "CREATE TABLE IF NOT EXISTS _test_adr073_aux \
3278                          (marker TEXT PRIMARY KEY)"
3279                        .into(),
3280                    params: vec![],
3281                    label: None,
3282                })
3283                .await
3284                .expect("create aux table in B");
3285            writer
3286                .execute(SqlStatement {
3287                    sql: "INSERT INTO _test_adr073_aux VALUES (?1)".into(),
3288                    params: vec![SqlValue::Text("b-side-sentinel".into())],
3289                    label: None,
3290                })
3291                .await
3292                .expect("insert into aux table in B");
3293        }
3294
3295        // Row is present in B.
3296        let mut reader_b = rt_secondary.sql().reader().await.expect("secondary reader");
3297        let rows_b = reader_b
3298            .query_all(SqlStatement {
3299                sql: "SELECT marker FROM _test_adr073_aux".into(),
3300                params: vec![],
3301                label: None,
3302            })
3303            .await
3304            .expect("select from B");
3305        assert_eq!(rows_b.len(), 1, "aux row must exist in B");
3306        match rows_b[0].get("marker") {
3307            Some(SqlValue::Text(s)) => {
3308                assert_eq!(s, "b-side-sentinel", "sentinel value must match")
3309            }
3310            other => panic!("expected Text('b-side-sentinel'), got {other:?}"),
3311        }
3312
3313        // Row is absent from A (table does not exist there).
3314        let mut reader_a = rt_main.sql().reader().await.expect("main reader");
3315        let result_a = reader_a
3316            .query_all(SqlStatement {
3317                sql: "SELECT marker FROM _test_adr073_aux".into(),
3318                params: vec![],
3319                label: None,
3320            })
3321            .await;
3322        // A does not have this table → must error or return no rows.
3323        match result_a {
3324            Err(e) => assert!(
3325                e.to_string().contains("no such table"),
3326                "expected 'no such table' error from A, got: {e}"
3327            ),
3328            Ok(rows) => assert!(
3329                rows.is_empty(),
3330                "aux table must not have rows in A, got {} rows",
3331                rows.len()
3332            ),
3333        }
3334    }
3335
3336    #[test]
3337    fn constructors_leave_core_backend_none_by_behavior() {
3338        // core() on any standard constructor returns a clone with same backend_id —
3339        // proof that core_backend = None (returns self.clone(), not a different backend).
3340        let rt_mem = KhiveRuntime::memory().unwrap();
3341        assert_eq!(rt_mem.core().backend_id().as_str(), BackendId::MAIN);
3342
3343        let backend = migrated_memory_backend();
3344        let rt_from = KhiveRuntime::from_backend(
3345            backend,
3346            RuntimeConfig {
3347                git_write: Default::default(),
3348                display_timezone: chrono_tz::Tz::UTC,
3349                events_split: None,
3350                db_path: None,
3351                blob_hydration_bytes: crate::DEFAULT_BLOB_HYDRATION_BYTES,
3352                default_namespace: Namespace::local(),
3353                embedding_model: None,
3354                additional_embedding_models: vec![],
3355                gate: Arc::new(AllowAllGate),
3356                packs: vec!["kg".to_string()],
3357                backend_id: BackendId::new("lore"),
3358                brain_profile: None,
3359                visible_namespaces: vec![],
3360                allowed_outbound_namespaces: vec![],
3361                actor_id: None,
3362            },
3363        );
3364        // from_backend with backend_id="lore" and no core_backend: core() returns
3365        // self.clone() which has backend_id="lore" (not "main").
3366        assert_eq!(rt_from.core().backend_id().as_str(), "lore");
3367    }
3368
3369    #[test]
3370    fn with_core_backend_sets_core_then_core_returns_main_id() {
3371        // After wiring, core() must return a runtime with backend_id == "main".
3372        let main_arc = migrated_memory_backend();
3373        let secondary_arc = migrated_memory_backend();
3374
3375        let rt_secondary = KhiveRuntime::from_backend(secondary_arc, secondary_config())
3376            .with_core_backend(main_arc);
3377
3378        assert_eq!(rt_secondary.backend_id().as_str(), "lore");
3379        assert_eq!(
3380            rt_secondary.core().backend_id().as_str(),
3381            BackendId::MAIN,
3382            "core() on a secondary runtime must return a main-bound handle"
3383        );
3384    }
3385
3386    #[test]
3387    fn attachment_store_rejects_secondary_handle_and_accepts_its_core_projection() {
3388        let main_arc = migrated_memory_backend();
3389        let secondary_arc = migrated_memory_backend();
3390        let rt_secondary = KhiveRuntime::from_backend(secondary_arc, secondary_config())
3391            .with_core_backend(main_arc);
3392
3393        let error = match rt_secondary.attachments() {
3394            Ok(_) => panic!("a secondary runtime must not expose attachment mutation"),
3395            Err(error) => error,
3396        };
3397        assert!(matches!(error, RuntimeError::InvalidInput(_)));
3398        assert!(
3399            error.to_string().contains("canonical main backend"),
3400            "secondary refusal must explain the liveness authority: {error}"
3401        );
3402        rt_secondary
3403            .core()
3404            .attachments()
3405            .expect("core projection must expose the main attachment store");
3406    }
3407
3408    #[tokio::test]
3409    async fn record_plus_attachment_publication_rejects_a_secondary_runtime() {
3410        use khive_storage::{BlobStore as _, NewAttachment};
3411
3412        let main_arc = migrated_memory_backend();
3413        let secondary_arc = migrated_memory_backend();
3414        let rt_secondary =
3415            KhiveRuntime::from_backend(Arc::clone(&secondary_arc), secondary_config())
3416                .with_core_backend(Arc::clone(&main_arc));
3417        let blob_root = tempfile::tempdir().expect("blob root");
3418        let blob_store = Arc::new(
3419            khive_db::stores::blob::FsBlobStore::new(blob_root.path().to_path_buf(), 0)
3420                .expect("blob store"),
3421        );
3422        let content_ref = blob_store.put(b"secondary-ref".to_vec()).await.unwrap();
3423        rt_secondary
3424            .install_blob_store(blob_store.clone())
3425            .expect("shared blob store");
3426        let token = rt_secondary.authorize(Namespace::local()).unwrap();
3427
3428        let error = rt_secondary
3429            .create_entity_with_attachments(
3430                &token,
3431                "artifact",
3432                Some("visual_asset"),
3433                "must route through core",
3434                None,
3435                None,
3436                vec![],
3437                vec![NewAttachment {
3438                    role: "content".to_string(),
3439                    content_ref: content_ref.clone(),
3440                    media_type: None,
3441                    size_bytes: Some(13),
3442                }],
3443            )
3444            .await
3445            .expect_err("secondary attachment publication must fail closed");
3446        assert!(error.to_string().contains("canonical main backend"));
3447        assert!(rt_secondary
3448            .list_entities(&token, None, None, 10, 0)
3449            .await
3450            .unwrap()
3451            .is_empty());
3452        assert!(rt_secondary
3453            .core()
3454            .list_entities(&token, None, None, 10, 0)
3455            .await
3456            .unwrap()
3457            .is_empty());
3458        assert!(
3459            blob_store.exists(&content_ref).await.unwrap(),
3460            "refusal must not mutate the already-published object"
3461        );
3462    }
3463
3464    #[tokio::test]
3465    async fn list_embedding_models_returns_empty_when_table_absent() {
3466        // A brand-new in-memory runtime has migrations applied, so _embedding_models
3467        // IS created. But with no rows inserted, the result must be empty.
3468        let rt = KhiveRuntime::memory().expect("memory runtime");
3469        let records = rt
3470            .list_embedding_models(None)
3471            .await
3472            .expect("list ok on empty table");
3473        assert!(records.is_empty());
3474    }
3475
3476    #[tokio::test]
3477    async fn list_embedding_models_returns_row_after_insert() {
3478        use khive_storage::{SqlStatement, SqlValue};
3479
3480        let rt = KhiveRuntime::memory().expect("memory runtime");
3481        let sql = rt.sql();
3482
3483        let now = 1_000_000i64;
3484        let id = uuid::Uuid::new_v4();
3485        let canonical_key = b"test_engine:test-model-v1:v1:384".to_vec();
3486
3487        let mut writer = sql.writer().await.expect("writer");
3488        writer
3489            .execute(SqlStatement {
3490                sql: "INSERT INTO _embedding_models \
3491                      (id, engine_name, model_id, key_version, dim, output_dim, status, \
3492                       activated_at, superseded_at, superseded_by, canonical_key, created_at) \
3493                      VALUES (?1, ?2, ?3, ?4, ?5, NULL, ?6, ?7, NULL, NULL, ?8, ?9)"
3494                    .into(),
3495                params: vec![
3496                    SqlValue::Blob(id.as_bytes().to_vec()),
3497                    SqlValue::Text("test_engine".into()),
3498                    SqlValue::Text("test-model-v1".into()),
3499                    SqlValue::Text("v1".into()),
3500                    SqlValue::Integer(384),
3501                    SqlValue::Text("active".into()),
3502                    SqlValue::Integer(now),
3503                    SqlValue::Blob(canonical_key),
3504                    SqlValue::Integer(now),
3505                ],
3506                label: None,
3507            })
3508            .await
3509            .expect("insert row");
3510        drop(writer);
3511
3512        let records = rt.list_embedding_models(None).await.expect("list ok");
3513        assert_eq!(records.len(), 1);
3514        assert_eq!(records[0].engine_name, "test_engine");
3515        assert_eq!(records[0].model_id, "test-model-v1");
3516        assert_eq!(records[0].key_version, "v1");
3517        assert_eq!(records[0].dimensions, 384);
3518        assert_eq!(records[0].status, "active");
3519
3520        // engine filter — match
3521        let filtered = rt
3522            .list_embedding_models(Some("test_engine"))
3523            .await
3524            .expect("filter ok");
3525        assert_eq!(filtered.len(), 1);
3526
3527        // engine filter — no match
3528        let no_match = rt
3529            .list_embedding_models(Some("other_engine"))
3530            .await
3531            .expect("no-match ok");
3532        assert!(no_match.is_empty());
3533    }
3534
3535    #[test]
3536    fn named_vector_identity_rejects_ambiguous_or_unsafe_values() {
3537        assert!(NamedVectorIdentity::new("", "model", 4).is_err());
3538        assert!(NamedVectorIdentity::new("bad-key", "model", 4).is_err());
3539        assert!(NamedVectorIdentity::new("valid_key", " model", 4).is_err());
3540        assert!(NamedVectorIdentity::new("valid_key", "model", 0).is_err());
3541        assert!(NamedVectorIdentity::new("valid_key", "model", 8193).is_err());
3542        assert!(NamedVectorIdentity::new("k".repeat(128), "m".repeat(512), 4).is_ok());
3543        assert!(NamedVectorIdentity::new("k".repeat(129), "model", 4).is_err());
3544        assert!(NamedVectorIdentity::new("valid_key", "m".repeat(513), 4).is_err());
3545        assert_eq!(
3546            NamedVectorIdentity::new("valid_key", "model", 4)
3547                .expect("valid identity")
3548                .dimensions(),
3549            4
3550        );
3551    }
3552
3553    #[tokio::test]
3554    async fn named_vector_store_rejects_dimension_or_model_key_rebinding() {
3555        let rt = KhiveRuntime::memory().expect("memory runtime");
3556        let token = rt.authorize(Namespace::local()).expect("authorize");
3557        let original = NamedVectorIdentity::new("visual_contract", "model-a", 4).unwrap();
3558        rt.vectors_for_named_identity(&token, &original)
3559            .await
3560            .expect("create named vector store");
3561        let registered = rt
3562            .list_embedding_models(Some("visual_contract"))
3563            .await
3564            .expect("list model registry");
3565        assert!(registered.iter().any(|record| {
3566            record.model_id == "model-a"
3567                && record.key_version == "visual_contract"
3568                && record.dimensions == 4
3569        }));
3570        let wrong_dimensions = NamedVectorIdentity::new("visual_contract", "model-a", 5).unwrap();
3571        let Err(dimension_error) = rt
3572            .vectors_for_named_identity(&token, &wrong_dimensions)
3573            .await
3574        else {
3575            panic!("same key cannot change dimensions");
3576        };
3577        assert!(dimension_error.to_string().contains("dimensions"));
3578
3579        let wrong_model = NamedVectorIdentity::new("visual_contract", "model-b", 4).unwrap();
3580        let Err(model_error) = rt.vectors_for_named_identity(&token, &wrong_model).await else {
3581            panic!("same key cannot change model identity");
3582        };
3583        assert!(model_error.to_string().contains("already bound"));
3584    }
3585
3586    #[tokio::test]
3587    async fn concurrent_named_vector_first_bind_has_one_immutable_winner() {
3588        let rt = KhiveRuntime::memory().expect("memory runtime");
3589        let token = rt.authorize(Namespace::local()).expect("authorize");
3590        let first = NamedVectorIdentity::new("visual_race", "model-a", 4).unwrap();
3591        let second = NamedVectorIdentity::new("visual_race", "model-b", 4).unwrap();
3592
3593        let (first_result, second_result) = tokio::join!(
3594            rt.vectors_for_named_identity(&token, &first),
3595            rt.vectors_for_named_identity(&token, &second),
3596        );
3597        assert_ne!(
3598            first_result.is_ok(),
3599            second_result.is_ok(),
3600            "the active engine_name uniqueness rule must select exactly one first binding"
3601        );
3602
3603        let (winner, loser) = if first_result.is_ok() {
3604            (&first, &second)
3605        } else {
3606            (&second, &first)
3607        };
3608        rt.vectors_for_named_identity(&token, winner)
3609            .await
3610            .expect("winning identity remains idempotent");
3611        let error = match rt.vectors_for_named_identity(&token, loser).await {
3612            Ok(_) => panic!("losing identity cannot rebind the empty table"),
3613            Err(error) => error,
3614        };
3615        assert!(error.to_string().contains("already bound"));
3616
3617        let registered = rt
3618            .list_embedding_models(Some("visual_race"))
3619            .await
3620            .expect("list race registry");
3621        assert_eq!(registered.len(), 1);
3622        assert_eq!(registered[0].model_id, winner.model_name());
3623    }
3624
3625    #[tokio::test]
3626    async fn named_vector_registry_keeps_immutable_revisions_active_together() {
3627        let rt = KhiveRuntime::memory().expect("memory runtime");
3628        let token = rt.authorize(Namespace::local()).expect("authorize");
3629        let first = NamedVectorIdentity::new("visual_revision_a", "visual-model", 4).unwrap();
3630        let second = NamedVectorIdentity::new("visual_revision_b", "visual-model", 4).unwrap();
3631
3632        rt.vectors_for_named_identity(&token, &first)
3633            .await
3634            .expect("open first immutable space");
3635        rt.vectors_for_named_identity(&token, &second)
3636            .await
3637            .expect("open second immutable space");
3638
3639        let registered = rt.list_embedding_models(None).await.expect("list registry");
3640        assert!(registered.iter().any(|record| {
3641            record.engine_name == "visual_revision_a"
3642                && record.model_id == "visual-model"
3643                && record.key_version == "visual_revision_a"
3644                && record.status == "active"
3645        }));
3646        assert!(registered.iter().any(|record| {
3647            record.engine_name == "visual_revision_b"
3648                && record.model_id == "visual-model"
3649                && record.key_version == "visual_revision_b"
3650                && record.status == "active"
3651        }));
3652    }
3653}