Skip to main content

khive_runtime/
config.rs

1//! RuntimeConfig, BackendId, NamespaceToken, and embedding model helpers.
2
3use std::sync::Arc;
4
5use khive_db::StorageBackend;
6pub use khive_db::WalCeilingSource;
7use khive_gate::{ActorRef, AllowAllGate, GateRef};
8use khive_types::Namespace;
9use lattice_embed::EmbeddingModel;
10
11use crate::error::RuntimeResult;
12
13// ---- BackendId ----
14
15/// Identifies a named backend in a multi-backend deployment.
16///
17/// The `main` backend is the default single-backend name. Multi-backend deployments
18/// assign each `[[backends]]` entry a distinct `BackendId`. The
19/// `SubstrateCoordinator` in `kkernel`
20/// uses `BackendId` for node-to-backend resolution and cross-backend edge routing.
21///
22/// A single-backend `KhiveRuntime` always has the `main` backend id by default.
23/// The boot path in `kkernel` or `khive-mcp` sets the id via `RuntimeConfig::backend_id`
24/// when constructing per-pack runtimes.
25#[derive(Clone, Debug, PartialEq, Eq, Hash)]
26pub struct BackendId(String);
27
28/// Validation error returned when a backend identifier is rejected.
29#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
30pub enum BackendIdError {
31    /// The supplied identifier was empty or contained only whitespace.
32    #[error("backend id must not be empty or whitespace-only")]
33    Empty,
34}
35
36impl BackendId {
37    /// The default single-backend name.
38    pub const MAIN: &'static str = "main";
39
40    /// Parse a nonempty backend identifier.
41    pub fn parse(name: impl Into<String>) -> Result<Self, BackendIdError> {
42        let name = name.into();
43        if name.trim().is_empty() {
44            return Err(BackendIdError::Empty);
45        }
46        Ok(Self(name))
47    }
48
49    /// The default `main` backend id.
50    pub fn main() -> Self {
51        Self(Self::MAIN.to_string())
52    }
53
54    /// Return the backend name as a `&str`.
55    pub fn as_str(&self) -> &str {
56        &self.0
57    }
58}
59
60impl TryFrom<String> for BackendId {
61    type Error = BackendIdError;
62
63    fn try_from(value: String) -> Result<Self, Self::Error> {
64        Self::parse(value)
65    }
66}
67
68impl TryFrom<&str> for BackendId {
69    type Error = BackendIdError;
70
71    fn try_from(value: &str) -> Result<Self, Self::Error> {
72        Self::parse(value)
73    }
74}
75
76impl std::str::FromStr for BackendId {
77    type Err = BackendIdError;
78
79    fn from_str(value: &str) -> Result<Self, Self::Err> {
80        Self::parse(value)
81    }
82}
83
84impl std::fmt::Display for BackendId {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.write_str(&self.0)
87    }
88}
89
90#[cfg(test)]
91mod backend_id_tests {
92    use super::BackendId;
93
94    #[test]
95    fn empty_and_whitespace_only_backend_ids_are_rejected() {
96        for invalid in ["", " ", "\t\n"] {
97            assert!(
98                BackendId::parse(invalid).is_err(),
99                "backend id {invalid:?} must be rejected"
100            );
101        }
102    }
103
104    #[test]
105    fn nonempty_backend_id_round_trips() {
106        let id = BackendId::parse("archive").expect("valid backend id");
107        assert_eq!(id.as_str(), "archive");
108        assert_eq!(id.to_string(), "archive");
109    }
110}
111
112// ---- Sealed token ----
113
114mod private {
115    #[derive(Clone, Debug)]
116    pub(crate) struct Sealed;
117}
118
119/// Authorization proof that a caller is permitted to access a specific namespace.
120///
121/// Created by [`crate::VerbRegistry::dispatch`] after the gate approves the request.
122/// The sealed inner field prevents external code from constructing a token
123/// without going through the authorization path.
124///
125/// The `namespace` field is the **write namespace**: all records created via
126/// this token land in that namespace. `visible` is the **read visibility set**:
127/// list/search/get operations will return records from any namespace in this
128/// set. The write namespace is always a member of the visible set.
129///
130/// Single-namespace behaviour (backward-compatible default): `visible` contains
131/// exactly `[namespace]` — identical to the old strict-equality checks.
132#[derive(Clone, Debug)]
133pub struct NamespaceToken {
134    namespace: Namespace,
135    gate_namespace: Namespace,
136    gate_explicit_namespace: Option<String>,
137    request_id: Option<u64>,
138    visible: Vec<Namespace>,
139    actor: ActorRef,
140    process_ref: Option<String>,
141    /// Namespaces the caller declared it owns (`[actor] owned_namespaces`).
142    /// Read only through [`NamespaceToken::owns`]; it never widens visibility.
143    owned: Vec<Namespace>,
144    _sealed: private::Sealed,
145}
146
147impl NamespaceToken {
148    /// Mint an authorized token with an extended visibility set.
149    ///
150    /// `extra_visible` lists namespaces beyond the primary that the token may
151    /// read. The primary namespace is always included in the visible set
152    /// regardless of what `extra_visible` contains. Duplicates are removed.
153    pub(crate) fn mint_with_visibility(
154        namespace: Namespace,
155        extra_visible: Vec<Namespace>,
156        actor: ActorRef,
157    ) -> Self {
158        let mut visible = vec![namespace.clone()];
159        for ns in extra_visible {
160            if !visible.contains(&ns) {
161                visible.push(ns);
162            }
163        }
164        debug_assert!(!visible.is_empty(), "visible set must be non-empty");
165        Self {
166            gate_namespace: namespace.clone(),
167            gate_explicit_namespace: None,
168            request_id: None,
169            namespace,
170            visible,
171            actor,
172            process_ref: None,
173            owned: Vec::new(),
174            _sealed: private::Sealed,
175        }
176    }
177
178    /// Mint an authorized token. Only callable from within `khive-runtime`.
179    ///
180    /// The visible set defaults to `[namespace]` — backward-compatible with
181    /// single-namespace enforcement.
182    pub(crate) fn mint_authorized(namespace: Namespace, actor: ActorRef) -> Self {
183        Self::mint_with_visibility(namespace, vec![], actor)
184    }
185
186    /// Convenience constructor for the local namespace with an anonymous actor.
187    ///
188    /// Only callable from within `khive-runtime`. External callers must use
189    /// [`KhiveRuntime::authorize`] to mint tokens.
190    // Used only in #[cfg(test)] blocks within this crate's src/ files.
191    #[allow(dead_code)]
192    pub(crate) fn local() -> Self {
193        Self::mint_authorized(Namespace::local(), ActorRef::anonymous())
194    }
195
196    /// Convenience constructor for a specific namespace with an anonymous actor.
197    ///
198    /// Only callable from within `khive-runtime`. External callers must use
199    /// [`KhiveRuntime::authorize`] to mint tokens.
200    // Used only in #[cfg(test)] blocks within this crate's src/ files.
201    #[allow(dead_code)]
202    pub(crate) fn for_namespace(ns: Namespace) -> Self {
203        Self::mint_authorized(ns, ActorRef::anonymous())
204    }
205
206    /// Return the write namespace this token authorises.
207    ///
208    /// All records created via this token land in this namespace.
209    pub fn namespace(&self) -> &Namespace {
210        &self.namespace
211    }
212
213    /// Return the namespace used by the originating dispatch's Gate check.
214    /// It can differ from the primary storage namespace on an implicit request.
215    /// Tokens minted directly, or reminted by `with_namespace`, use their primary.
216    pub fn gate_namespace(&self) -> &Namespace {
217        &self.gate_namespace
218    }
219
220    pub(crate) fn with_gate_namespace(mut self, namespace: Namespace) -> Self {
221        self.gate_namespace = namespace;
222        self
223    }
224
225    /// The exact submitted namespace argument, if the caller supplied one.
226    /// Pack handlers normally receive params after dispatch strips this key.
227    pub(crate) fn gate_explicit_namespace(&self) -> Option<&str> {
228        self.gate_explicit_namespace.as_deref()
229    }
230
231    pub(crate) fn with_gate_explicit_namespace(mut self, namespace: Option<String>) -> Self {
232        self.gate_explicit_namespace = namespace;
233        self
234    }
235
236    /// Correlates handler-internal Gate consultations with their dispatch audit.
237    pub(crate) fn request_id(&self) -> Option<u64> {
238        self.request_id
239    }
240
241    pub(crate) fn with_request_id(mut self, request_id: Option<u64>) -> Self {
242        self.request_id = request_id;
243        self
244    }
245
246    /// Return the read-visibility set.
247    ///
248    /// List, search, and get operations must accept records whose namespace is
249    /// a member of this set. The write namespace is always included.
250    pub fn visible_namespaces(&self) -> &[Namespace] {
251        &self.visible
252    }
253
254    /// Return a deduplicated list of visible namespace strings (borrowed).
255    ///
256    /// Convenience for passing directly to storage layer filters.
257    pub fn visible_namespace_strs(&self) -> Vec<&str> {
258        self.visible.iter().map(|ns| ns.as_str()).collect()
259    }
260
261    /// Return the actor reference embedded in this token.
262    pub fn actor(&self) -> &ActorRef {
263        &self.actor
264    }
265
266    /// Return the originating process's opaque attribution reference, when set.
267    ///
268    /// This is request metadata only. It never participates in gate checks,
269    /// namespace visibility, or actor identity.
270    pub fn process_ref(&self) -> Option<&str> {
271        self.process_ref.as_deref()
272    }
273
274    pub(crate) fn with_process_ref(mut self, process_ref: Option<String>) -> Self {
275        self.process_ref = process_ref;
276        self
277    }
278
279    /// Return whether the caller declared that it owns `namespace`.
280    ///
281    /// The declaration is the `[actor] owned_namespaces` list carried on the
282    /// caller's identity. It is consulted by the `memory.apply_batch` old-row
283    /// namespace check alone: ownership grants no write into the namespace and
284    /// widens no read.
285    pub fn owns(&self, namespace: &str) -> bool {
286        self.owned.iter().any(|owned| owned.as_str() == namespace)
287    }
288
289    /// The caller's declared owned namespaces, for carrying the declaration
290    /// onto a re-minted token or a nested dispatch identity.
291    pub(crate) fn owned_namespaces(&self) -> &[Namespace] {
292        &self.owned
293    }
294
295    pub(crate) fn with_owned_namespaces(mut self, owned: Vec<Namespace>) -> Self {
296        self.owned = owned;
297        self
298    }
299
300    /// Return a new token with the same actor but a different namespace.
301    /// The Gate namespace metadata is reset to the new primary namespace.
302    ///
303    /// The visible set is replaced with `[ns]`: this is a full read+write token
304    /// for `ns`, not a type-enforced write-only or append-only capability. It is
305    /// a capability-transfer primitive, not a policy gate: callers must enforce
306    /// any ACL check before calling this and use the minted token only within
307    /// the intended narrow scope (e.g. a single `create_note` call). A future
308    /// security model should replace this pattern with a type-enforced
309    /// append-only capability that goes through the Gate.
310    ///
311    /// The owned-namespace declaration describes the caller, not the target
312    /// namespace, so it is kept on the new token.
313    pub fn with_namespace(&self, ns: Namespace) -> Self {
314        Self::mint_authorized(ns, self.actor.clone())
315            .with_process_ref(self.process_ref.clone())
316            .with_owned_namespaces(self.owned.clone())
317    }
318}
319
320/// Read the optional request-origin process reference without normalization.
321///
322/// A non-Unicode environment value cannot be represented in JSON and is
323/// treated as absent after emitting a warning that does not expose its bytes.
324pub fn process_ref_from_env() -> Option<String> {
325    match std::env::var("KHIVE_PROCESS_REF") {
326        Ok(value) => Some(value),
327        Err(std::env::VarError::NotPresent) => None,
328        Err(std::env::VarError::NotUnicode(_)) => {
329            tracing::warn!(
330                "KHIVE_PROCESS_REF is not valid Unicode and cannot be represented in request metadata"
331            );
332            None
333        }
334    }
335}
336
337// ---- RuntimeConfig ----
338
339/// Runtime configuration.
340///
341/// The `db_path` field remains for backward compatibility and as input to the
342/// supported async khive-mcp/kkernel host builders. Direct backend assembly is
343/// reserved for an already-coordinated database; use
344/// [`crate::KhiveRuntime::from_prepared_backend`] when that precondition has
345/// been established. `engines` is the ordered peer configuration; absent peers
346/// retain the legacy programmatic model shorthand until startup preparation.
347#[derive(Clone, Debug)]
348pub struct RuntimeConfig {
349    /// Maximum simultaneous background warm jobs in the host's shared domain.
350    /// Must be positive and fit Tokio's semaphore capacity.
351    pub warm_concurrency: usize,
352    /// Maximum simultaneous background maintenance jobs; interactive is unbounded.
353    pub maintenance_concurrency: usize,
354    /// Named custody references; secret material stays inside credential providers.
355    pub credentials: Vec<crate::credentials::CredentialConfig>,
356    /// Configured receipt key ring. Absence never generates a replacement key.
357    pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,
358
359    pub mounts: Vec<crate::mount_config::MountConfig>,
360
361    /// Opaque values retained from `[channel.*]` without interpretation.
362    pub channel: crate::channel_section::ChannelSectionConfig,
363    /// Host-supplied validators installed before pack registry construction.
364    pub channel_config_validators: crate::channel_section::ChannelConfigValidators,
365    /// Trusted host routes for custom communication address kinds. These
366    /// process-local callbacks must be installed in the dispatching host.
367    pub channel_send_routes: crate::channel_send::ChannelSendRoutes,
368
369    /// Path to the SQLite database file. `None` = in-memory (tests).
370    ///
371    /// Production boot passes this value to the async khive-mcp/kkernel host
372    /// builders, which coordinate V21 before constructing runtimes. Tests and
373    /// already-current single-backend callers may still use it directly.
374    pub db_path: Option<std::path::PathBuf>,
375    /// Canonicalization boundary for registered code-map database files.
376    pub code_map_root: Option<String>,
377    /// Operator-declared code maps loaded into the runtime registry at construction.
378    pub code_maps: Vec<crate::engine_config::CodeMapConfig>,
379    /// Declared SQLite backend paths protected from code-map registration.
380    pub code_map_protected_database_paths: Vec<std::path::PathBuf>,
381    /// The WAL ceiling applied to this runtime's implicit main backend.
382    /// Zero means disabled, including for a read-only backend that retains a
383    /// nonzero configured value only for operator reporting.
384    pub wal_ceiling_bytes: u64,
385    /// The configured value before read-only writer-policy suppression.
386    pub wal_ceiling_configured_bytes: u64,
387    /// Where the configured ceiling came from.
388    pub wal_ceiling_source: WalCeilingSource,
389    /// Construction-time snapshot of the environment fallback. The host uses
390    /// this same value to resolve every named backend before forwarding or
391    /// opening it, without rereading mutable process environment.
392    pub wal_ceiling_env_raw: Option<String>,
393    /// One snapshot for named backend resolution and daemon compatibility.
394    pub disk_guard_environment: khive_db::DiskGuardEnvironment,
395    /// Captured implicit-main policy, or an explicit caller-supplied policy.
396    pub disk_guard_config: Option<khive_db::EffectiveDiskGuardConfig>,
397    /// Directory for the SQLite volume lock files, captured with the rest of
398    /// boot configuration from [`crate::daemon::volume_lock_dir`]. `None` means
399    /// no directory could be resolved; every writable file-backed open then
400    /// fails with a configuration error naming `KHIVE_VOLUME_LOCK_DIR`.
401    pub volume_lock_dir: Option<std::path::PathBuf>,
402    /// Namespace used when no explicit namespace is provided.
403    pub default_namespace: Namespace,
404    /// Ordered participating engines. `Some`, including an empty list, is
405    /// authoritative; `None` converts the legacy model fields at startup.
406    pub engines: Option<Vec<crate::engine_config::EngineConfig>>,
407    /// Legacy local embedding model, used when `engines` is absent and otherwise
408    /// projected from its first peer at startup. `None` alone does not disable embedding: setting
409    /// only this field to `None` while `additional_embedding_models` is
410    /// non-empty still registers those models. Both `embedding_model` and
411    /// `additional_embedding_models` must be empty to disable built-in
412    /// embedding model registration, at which point `hybrid_search` falls back
413    /// to text-only. Use [`RuntimeConfig::no_embeddings`] to clear both fields
414    /// together — it is the canonical constructor for this. Custom embedder
415    /// providers registered later by packs are not affected by this field.
416    ///
417    /// Deprecated: embedding engines move to a per-pack `EmbedderRegistry`.
418    /// This field persists for backward compatibility until the embedder registry
419    /// is fully plumbed.
420    pub embedding_model: Option<EmbeddingModel>,
421    /// Legacy additional embedding models, used when `engines` is absent and
422    /// otherwise projected from its remaining peers at startup.
423    ///
424    /// `embedding_model` remains the default used by existing `embed()` and
425    /// `embed_batch()` callers. This list adds non-default models that can be
426    /// selected with `embedder(name)`, `embed_with_model(...)`, memory
427    /// `remember.embedding_model`, and memory `recall.embedding_model`.
428    pub additional_embedding_models: Vec<EmbeddingModel>,
429    /// Authorization gate consulted before each verb dispatch.
430    /// Default: `AllowAllGate` (permissive). For production policy enforcement,
431    /// plug in a Rego- or capability-witness-backed impl.
432    pub gate: GateRef,
433    /// Names of packs the transport layer should register into the VerbRegistry.
434    /// The transport layer (e.g. `khive-mcp`) reads this list and instantiates
435    /// the matching concrete pack types. Unknown names are reported as errors
436    /// by the transport, not silently ignored.
437    /// Defaults to the shipped production set returned by
438    /// [`RuntimeConfig::built_in_packs`].
439    pub packs: Vec<String>,
440    /// Resolved aggregate admission budget for resident digest-verified blob
441    /// buffers (ADR-160 D3), in raw bytes.
442    ///
443    /// `[runtime].blob_hydration_bytes` may raise or lower the built-in 256 MiB
444    /// value, but config validation guarantees enough room for one maximum-size
445    /// whole-blob read.
446    pub blob_hydration_bytes: u64,
447    /// Identifies this runtime's backend in a multi-backend deployment.
448    ///
449    /// Set by the boot path when constructing per-pack runtimes from `khive.toml`.
450    /// Single-backend deployments use the default `BackendId::MAIN`.
451    pub backend_id: BackendId,
452    /// Brain profile to use for `memory.feedback` / `knowledge.feedback` and
453    /// recall-time score boosting (ADR-035 §Brain profile configuration).
454    ///
455    /// Resolution order (highest to lowest, ADR-035): CLI flag, then
456    /// `runtime.brain_profile` in project/global `khive.toml`, then the
457    /// `KHIVE_BRAIN_PROFILE` env var as fallback default. Callers must keep
458    /// env OUT of the base config they pass in (see `khive-mcp` serve.rs).
459    /// 1. `--brain-profile` CLI flag (explicit only)
460    /// 2. Namespace-bound profile resolved via `brain.resolve` at feedback time
461    /// 3. Pack-local global tuning prior (default fallback)
462    pub brain_profile: Option<String>,
463    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
464    ///
465    /// OSS dispatch widens the DEFAULT multi-record read scope to
466    /// `['local'] ∪ visible_namespaces`. Writes remain pinned to `'local'`.
467    /// An explicit `namespace=` request param is a precise single-namespace
468    /// escape and is not widened. Populated from `actor.visible_namespaces`
469    /// in `khive.toml`.
470    pub visible_namespaces: Vec<Namespace>,
471    /// Namespaces this actor declared it owns (ADR-021 Delta 1). Populated from
472    /// `actor.owned_namespaces` in `khive.toml`. Empty by default. Ownership is
473    /// read by the `memory.apply_batch` old-row namespace check alone: it grants
474    /// no write into the namespace and widens no read, and it is NOT folded into
475    /// `visible_namespaces`.
476    pub owned_namespaces: Vec<Namespace>,
477    /// Namespaces this actor's comm.send/reply may deliver messages INTO
478    /// (outbound, sender-side). Populated from `actor.allowed_outbound_namespaces`
479    /// in `khive.toml`. Empty by default — cross-namespace delivery denied
480    /// unless explicitly declared. The comm handler uses an ordinary
481    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
482    /// the token itself is NOT type-enforced write-only. The recipient-side
483    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
484    /// a future cloud-path authorization ADR (not yet written).
485    pub allowed_outbound_namespaces: Vec<Namespace>,
486    /// Configured actor identity label (ADR-057). Populated from `[actor] id` in
487    /// `khive.toml`. When `Some`, `authorize()` mints tokens carrying this actor
488    /// label so that `comm.inbox` filters by `to_actor` instead of falling back to
489    /// the party-line "local" behavior. When `None` (default), tokens carry
490    /// `ActorRef::anonymous()` and inbox is scoped to party-line messages —
491    /// those addressed to `"local"` or carrying no `to_actor` stamp.
492    pub actor_id: Option<String>,
493    /// Strict attributed-actor mode requested by configuration: `[actor]
494    /// require_attributed = true` in the database-anchored or the project
495    /// config. The `KHIVE_REQUIRE_ATTRIBUTED_ACTOR=1` environment flag is read
496    /// separately by the enforcing seam; either one turns the refusal on.
497    pub require_attributed_actor: bool,
498    /// Resolved `[brain]` policy from the serving process's configuration.
499    pub brain: crate::engine_config::BrainSectionConfig,
500    /// Resolved `[git_write]` policy allowlist (ADR-108 Amendment), populated
501    /// from `khive.toml`'s `[[git_write.allowed]]` entries by
502    /// [`runtime_config_from_khive_config`]. Threaded through so
503    /// `khive-pack-git`'s write-verb handlers read an already-resolved policy
504    /// instead of re-running config discovery (which would ignore an
505    /// explicit `--config` path not also exported as `KHIVE_CONFIG`).
506    pub git_write: crate::engine_config::GitWriteSectionConfig,
507    /// Effective `[blob]` file-transfer opt-in, resolved with the exact environment
508    /// opt-in during construction and retained by the blob pack.
509    pub blob: crate::engine_config::BlobSectionConfig,
510    /// Resolved `[exec]` sandbox section (ADR-181), threaded through like
511    /// `git_write` so the exec pack reads an already-resolved config.
512    pub exec: crate::engine_config::ExecSectionConfig,
513    /// Resolved carrier and failure policy for telemetry emission.
514    pub telemetry: crate::telemetry_config::TelemetryConfig,
515    /// Resolved rendering timezone (ADR-169), consumed today by date-only
516    /// `parse_due` anchoring. Populated from `[display] timezone` in
517    /// `khive.toml` by [`runtime_config_from_khive_config`]; when absent,
518    /// resolves once to the host's local IANA zone (falling back to UTC when
519    /// the host zone cannot be determined) via [`resolve_default_display_timezone`].
520    pub display_timezone: chrono_tz::Tz,
521    /// Events-daemon split (ADR-170). `None` = legacy behavior: events persist
522    /// in the main store. `Some` routes event persistence to the events database —
523    /// forwarded over the events daemon socket in daemon deployments, opened
524    /// directly in embedded/one-shot contexts. Populated by the transport
525    /// hosts (khive-mcp serve, kkernel exec); tests and in-memory runtimes
526    /// leave it `None`.
527    pub events_split: Option<crate::events_split::EventsSplitConfig>,
528    /// Resolved `[web]` policy (ADR-175 Amendment 1), threaded through like
529    /// `exec`/`git_write` so `khive-pack-web` reads an already-resolved config.
530    pub web: crate::engine_config::WebSectionConfig,
531}
532
533/// Parse a comma- or whitespace-separated pack list from a single string.
534///
535/// Empty entries are dropped, surrounding whitespace is trimmed.
536pub fn parse_pack_list(s: &str) -> Vec<String> {
537    s.split(|c: char| c == ',' || c.is_whitespace())
538        .map(str::trim)
539        .filter(|s| !s.is_empty())
540        .map(str::to_owned)
541        .collect()
542}
543
544const ANN_REBUILD_THRESHOLD_DEFAULT: f64 = 0.20;
545
546/// Read the ANN tail-rebuild fraction on each invocation (ADR-079 Amendment 2).
547///
548/// ADR-079's `ann_rebuild_threshold` default rationale describes the raw-row
549/// policy, its workload assumptions and its coupled maintenance/visibility roles.
550///
551/// The exact environment value must parse as `f64` and lie in `(0, 1]`;
552/// unset, non-Unicode, malformed and out-of-range values use `0.20`.
553/// This reader deliberately does not trim or cache the value.
554pub fn ann_rebuild_threshold_from_env() -> f64 {
555    let value = khive_types::env::env_parse_or(
556        "KHIVE_ANN_REBUILD_THRESHOLD",
557        ANN_REBUILD_THRESHOLD_DEFAULT,
558    );
559    if value > 0.0 && value <= 1.0 {
560        value
561    } else {
562        ANN_REBUILD_THRESHOLD_DEFAULT
563    }
564}
565
566#[cfg(test)]
567#[path = "config/ann_rebuild_threshold_tests.rs"]
568mod ann_rebuild_threshold_tests;
569
570/// Interpret the construction-time `KHIVE_ANN_FRESH_TAIL` value.
571///
572/// Preserve the escape hatch's existing semantics while moving its read out of
573/// request serving: only `0` disables; unset and every other value enable.
574fn ann_fresh_tail_enabled_from_value(value: Option<&str>) -> bool {
575    value != Some("0")
576}
577
578/// Sample ADR-118's fresh-tail escape hatch for runtime construction.
579///
580/// Callers must retain the returned value for the runtime's lifetime instead
581/// of re-reading the environment on a serving path. Only the exact value `0`
582/// disables; unset and every other value enable.
583pub fn ann_fresh_tail_enabled_from_env() -> bool {
584    let value = std::env::var("KHIVE_ANN_FRESH_TAIL").ok();
585    ann_fresh_tail_enabled_from_value(value.as_deref())
586}
587
588/// Resolve the host's local IANA zone name once, for [`RuntimeConfig`]'s
589/// default `display_timezone` (ADR-169). Falls back to UTC when the host
590/// zone cannot be determined (e.g. `TZ`/`/etc/localtime` unreadable) or does
591/// not parse as a known `chrono_tz::Tz` — this must never panic or block
592/// construction of a default `RuntimeConfig`.
593pub fn resolve_default_display_timezone() -> chrono_tz::Tz {
594    iana_time_zone::get_timezone()
595        .ok()
596        .and_then(|name| name.parse::<chrono_tz::Tz>().ok())
597        .unwrap_or(chrono_tz::Tz::UTC)
598}
599
600impl Default for RuntimeConfig {
601    fn default() -> Self {
602        let db_path = std::env::var("HOME")
603            .ok()
604            .map(|h| std::path::PathBuf::from(h).join(".khive/khive.db"));
605        let embedding_model = Some(khive_types::env::env_parse_or(
606            "KHIVE_EMBEDDING_MODEL",
607            EmbeddingModel::AllMiniLmL6V2,
608        ));
609        // Ships single-engine. A second engine is embedded on every write and
610        // searched on every read, which is cost a deployment should opt into
611        // rather than inherit: set KHIVE_ADDITIONAL_EMBEDDING_MODELS to add one.
612        let additional_embedding_models = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
613            .ok()
614            .map(|s| parse_embedding_model_list(&s))
615            .unwrap_or_default();
616        let packs = std::env::var("KHIVE_PACKS")
617            .ok()
618            .map(|s| parse_pack_list(&s))
619            .filter(|v| !v.is_empty())
620            .unwrap_or_else(Self::built_in_packs);
621        let brain_profile = std::env::var("KHIVE_BRAIN_PROFILE")
622            .ok()
623            .filter(|s| !s.trim().is_empty());
624        let actor_id = std::env::var("KHIVE_ACTOR")
625            .ok()
626            .filter(|s| !s.trim().is_empty());
627        Self {
628            warm_concurrency: DEFAULT_WARM_CONCURRENCY,
629            maintenance_concurrency: DEFAULT_MAINTENANCE_CONCURRENCY,
630            credentials: Vec::new(),
631            visibility_receipts: None,
632            db_path,
633            code_map_root: None,
634            code_maps: Vec::new(),
635            code_map_protected_database_paths: Vec::new(),
636            wal_ceiling_bytes: 0,
637            wal_ceiling_configured_bytes: 0,
638            wal_ceiling_source: WalCeilingSource::Default,
639            wal_ceiling_env_raw: std::env::var_os("KHIVE_SQLITE_WAL_CEILING_BYTES")
640                .map(|value| value.to_string_lossy().into_owned()),
641            disk_guard_environment: khive_db::DiskGuardEnvironment::capture(),
642            disk_guard_config: None,
643            volume_lock_dir: crate::daemon::volume_lock_dir().ok(),
644            default_namespace: Namespace::local(),
645            engines: None,
646            embedding_model,
647            additional_embedding_models,
648            gate: Arc::new(AllowAllGate),
649            packs,
650            blob_hydration_bytes: crate::blob::DEFAULT_BLOB_HYDRATION_BYTES,
651            backend_id: BackendId::main(),
652            brain_profile,
653            visible_namespaces: vec![],
654            owned_namespaces: vec![],
655            allowed_outbound_namespaces: vec![],
656            actor_id,
657            require_attributed_actor: false,
658            brain: crate::engine_config::BrainSectionConfig::default(),
659            git_write: crate::engine_config::GitWriteSectionConfig::default(),
660            blob: crate::engine_config::BlobSectionConfig {
661                file_transfers: std::env::var("KHIVE_FILE_TRANSFERS")
662                    .map(|value| value == "1")
663                    .unwrap_or(false),
664            },
665            exec: crate::engine_config::ExecSectionConfig::default(),
666            telemetry: crate::telemetry_config::TelemetryConfig::default(),
667            mounts: Vec::new(),
668            channel: crate::channel_section::ChannelSectionConfig::default(),
669            channel_config_validators: crate::channel_section::ChannelConfigValidators::default(),
670            channel_send_routes: crate::channel_send::ChannelSendRoutes::default(),
671            display_timezone: resolve_default_display_timezone(),
672            events_split: None,
673            web: crate::engine_config::WebSectionConfig::default(),
674        }
675    }
676}
677
678impl RuntimeConfig {
679    /// Effective ordered peers with canonical built-in names, without binding
680    /// providers or mutating the configuration. Startup must still validate them.
681    pub fn configured_engines(&self) -> Vec<crate::engine_config::EngineConfig> {
682        match &self.engines {
683            Some(engines) => engines
684                .iter()
685                .cloned()
686                .map(|mut engine| {
687                    engine.name = crate::engine_config::canonical_engine_name(&engine.name);
688                    engine
689                })
690                .collect(),
691            None => configured_embedding_models(self)
692                .into_iter()
693                .map(|model| crate::engine_config::EngineConfig {
694                    name: model.to_string(),
695                    weight: 1.0,
696                    dims: None,
697                })
698                .collect(),
699        }
700    }
701
702    /// Validate and canonicalize ordered peers without resolving providers.
703    ///
704    /// Legacy programmatic model fields remain accepted when `engines` is
705    /// absent. Once prepared, those fields are projections of the peer list.
706    /// Hosts finalize provider binding after registering their custom providers.
707    pub fn prepare_engines(&mut self) -> RuntimeResult<()> {
708        let mut engines = self.configured_engines();
709        crate::engine_config::validate_peer_engines(self.engines.as_deref().unwrap_or(&engines))
710            .map_err(|error| crate::RuntimeError::InvalidInput(error.to_string()))?;
711
712        for engine in &mut engines {
713            engine.name = crate::engine_config::canonical_engine_name(&engine.name);
714        }
715        self.embedding_model = engines
716            .first()
717            .and_then(|engine| parse_embedding_model_alias(&engine.name));
718        self.additional_embedding_models = engines
719            .iter()
720            .skip(1)
721            .filter_map(|engine| parse_embedding_model_alias(&engine.name))
722            .collect();
723        self.engines = Some(engines);
724        Ok(())
725    }
726
727    /// Disable configured vector participation, including legacy model seeds.
728    pub fn disable_embedding_models(&mut self) {
729        self.engines = Some(Vec::new());
730        self.embedding_model = None;
731        self.additional_embedding_models.clear();
732    }
733
734    /// The WAL ceiling policy this config asks its implicit main backend to
735    /// open with. Preserves a configured ceiling for read-only reporting while
736    /// ensuring a directly constructed config cannot silently drop a nonzero
737    /// effective value: when the configured value is zero, the effective
738    /// `wal_ceiling_bytes` is used. Host openers validate the captured
739    /// environment through [`Self::resolve_wal_ceiling_policy`] first.
740    pub fn wal_ceiling_policy(&self) -> khive_db::WalCeilingPolicy {
741        khive_db::WalCeilingPolicy {
742            bytes: if self.wal_ceiling_configured_bytes == 0 {
743                self.wal_ceiling_bytes
744            } else {
745                self.wal_ceiling_configured_bytes
746            },
747            source: self.wal_ceiling_source,
748        }
749    }
750
751    /// Resolve the implicit backend against the config's captured environment,
752    /// retaining configured bytes separately from a read-only writer policy.
753    pub fn resolve_wal_ceiling_policy(
754        &mut self,
755        read_only: bool,
756    ) -> RuntimeResult<khive_db::WalCeilingPolicy> {
757        let policy = self.wal_ceiling_policy();
758        let backend_field = match self.wal_ceiling_source {
759            WalCeilingSource::BackendField => Some(policy.bytes),
760            WalCeilingSource::Environment if self.wal_ceiling_env_raw.is_some() => None,
761            _ if policy.bytes != 0 => Some(policy.bytes),
762            _ => None,
763        };
764        let kind = if self.db_path.is_some() {
765            crate::BackendKind::Sqlite
766        } else {
767            crate::BackendKind::Memory
768        };
769        let resolved = crate::resolve_wal_ceiling(
770            backend_field,
771            self.wal_ceiling_env_raw.as_deref(),
772            self.backend_id.as_str(),
773            kind,
774            true,
775            read_only,
776        )
777        .map_err(|error| khive_db::SqliteError::InvalidConfig(error.to_string()))?;
778        self.wal_ceiling_configured_bytes = resolved.configured_bytes;
779        self.wal_ceiling_bytes = resolved.effective_bytes;
780        self.wal_ceiling_source = resolved.source;
781        Ok(self.wal_ceiling_policy())
782    }
783
784    /// Resolve the implicit backend's disk reserve and guard deadline from the
785    /// config's captured environment, unless a caller already supplied a policy.
786    /// Read-only and in-memory backends have no writer to guard.
787    pub fn resolve_disk_guard_policy(
788        &mut self,
789        read_only: bool,
790    ) -> RuntimeResult<Option<khive_db::EffectiveDiskGuardConfig>> {
791        if self.db_path.is_none() {
792            if self
793                .disk_guard_config
794                .is_some_and(|policy| policy.reserve_bytes != 0)
795            {
796                return Err(khive_db::SqliteError::InvalidConfig(
797                    "nonzero disk_reserve_bytes requires a file-backed SQLite backend".into(),
798                )
799                .into());
800            }
801            return Ok(None);
802        }
803        if read_only {
804            return Ok(None);
805        }
806        let policy = match self.disk_guard_config {
807            Some(policy) => {
808                policy.validate()?;
809                policy
810            }
811            None => self.disk_guard_environment.resolve(None, None)?,
812        };
813        self.disk_guard_config = Some(policy);
814        Ok(Some(policy))
815    }
816
817    /// Pack-registry discovery has no file-backed writer to govern.
818    pub fn for_metadata_registry(mut self) -> Self {
819        self.db_path = None;
820        self.wal_ceiling_bytes = 0;
821        self.wal_ceiling_configured_bytes = 0;
822        self.wal_ceiling_source = WalCeilingSource::BackendField;
823        self.disk_guard_config = None;
824        self.disable_embedding_models();
825        self
826    }
827
828    /// Return the shipped pack set used when no CLI, environment, or
829    /// configuration-file selection is present.
830    pub fn built_in_packs() -> Vec<String> {
831        [
832            "kg",
833            "gtd",
834            "memory",
835            "brain",
836            "comm",
837            "schedule",
838            "knowledge",
839            "session",
840            "tool",
841            "exec",
842            "git",
843            "code",
844            "workspace",
845            "blob",
846        ]
847        .into_iter()
848        .map(String::from)
849        .collect()
850    }
851
852    /// Build a `RuntimeConfig` with embedding disabled entirely.
853    ///
854    /// `embedding_model` and `additional_embedding_models` are computed
855    /// independently inside [`Default::default`], so `RuntimeConfig {
856    /// embedding_model: None, ..RuntimeConfig::default() }` does NOT produce a
857    /// model-less runtime: `additional_embedding_models` still carries its
858    /// env-driven fallback seed, and the note-write path fans out embedding to
859    /// every registered model regardless of `embedding_model`: so the first
860    /// `memory.remember` on a machine without local model files hard-fails
861    /// instead of degrading to FTS-only.
862    ///
863    /// This constructor clears both fields together and ignores
864    /// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` unconditionally: the caller wants
865    /// zero embedders, not "zero unless the environment disagrees". Use it on
866    /// model-less machines (CI runners, fresh installs without local model
867    /// files) instead of the two-field struct-update form.
868    pub fn no_embeddings() -> Self {
869        Self {
870            embedding_model: None,
871            additional_embedding_models: Vec::new(),
872            ..Self::default()
873        }
874    }
875}
876
877/// Expand a leading `~` to `$HOME` in a path.
878///
879/// This is the single shared expansion point for every `RuntimeConfig.db_path`
880/// construction site (CLI `--db`, `KHIVE_DB`, declared `[[backends]].path`).
881/// [`resolve_db_anchor`] calls it so a `~`-prefixed override is expanded once,
882/// at resolution, before the path ever reaches boot (single- or multi-backend),
883/// `compute_config_id` fingerprinting, or the `--db` override equivalence
884/// guard — those consumers then agree on one expanded path instead of a raw
885/// `~` diverging from its already-expanded equivalent.
886pub fn expand_tilde(path: &std::path::Path) -> std::path::PathBuf {
887    let s = path.to_string_lossy();
888    if let Some(rest) = s.strip_prefix("~/") {
889        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
890        std::path::PathBuf::from(format!("{home}/{rest}"))
891    } else if s == "~" {
892        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
893        std::path::PathBuf::from(home)
894    } else {
895        path.to_path_buf()
896    }
897}
898
899/// Resolve the `--db`/`KHIVE_DB` value into the anchor path used for tier-3
900/// project-local `.khive/config.toml` discovery, mirroring the precedence
901/// `kkernel mcp` and `kkernel exec` use to open the database itself:
902/// `:memory:` has no file to anchor on (`None`); an explicit path anchors on
903/// that path (with a leading `~` expanded via [`expand_tilde`]); an unset
904/// value falls back to `$HOME/.khive/khive.db`, or `./.khive/khive.db` when
905/// `HOME` is unset.
906///
907/// Always resolves to a concrete anchor (unlike a 2-arm "override the
908/// default?" resolver): when `HOME` is unset this falls back to
909/// `./.khive/khive.db` rather than `None`, deliberately diverging from
910/// `RuntimeConfig::default()`: a caller anchoring config discovery needs a
911/// concrete directory to search even without `HOME`.
912pub fn resolve_db_anchor(db: Option<&str>) -> Option<std::path::PathBuf> {
913    match db {
914        Some(":memory:") => None,
915        Some(path) => Some(expand_tilde(std::path::Path::new(path))),
916        None => {
917            let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
918            Some(std::path::PathBuf::from(format!("{home}/.khive/khive.db")))
919        }
920    }
921}
922
923/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
924/// process's `config_id`: agrees with what [`resolve_db_anchor`] derives from
925/// the same raw `--db`/`KHIVE_DB` input.
926///
927/// This compatibility entry point preserves the raw-string API. Construction
928/// paths that already captured the anchor should call
929/// [`assert_captured_db_anchor_consistent`] so they do not re-read mutable
930/// process environment.
931pub fn assert_db_anchor_consistent(
932    resolved_db_path: Option<&std::path::Path>,
933    args_db: Option<&str>,
934) -> anyhow::Result<()> {
935    let db_anchor = resolve_db_anchor(args_db);
936    assert_captured_db_anchor_consistent(resolved_db_path, db_anchor.as_deref())
937}
938
939/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
940/// process's `config_id`: agrees with the database anchor captured from the
941/// same `--db`/`KHIVE_DB` input at the construction boundary.
942///
943/// Guards against a construction path recomputing `db_path` independently of
944/// `resolve_db_anchor`: left unchecked, that would silently desync `config_id`
945/// from a daemon or peer sharing the same database instead of failing loud.
946/// The caller passes the captured anchor so validation never re-reads mutable
947/// process environment. Inert (`Ok(())`) when the anchor itself is `None` (the
948/// `:memory:` sentinel) since there is nothing to compare against.
949pub fn assert_captured_db_anchor_consistent(
950    resolved_db_path: Option<&std::path::Path>,
951    db_anchor: Option<&std::path::Path>,
952) -> anyhow::Result<()> {
953    let Some(anchor) = db_anchor else {
954        return Ok(());
955    };
956    if resolved_db_path != Some(anchor) {
957        anyhow::bail!(
958            "db-path resolution drift at server construction: resolved db_path {:?} \
959             does not match the canonical anchor {:?} computed by resolve_db_anchor \
960             from the same --db input; this construction path likely recomputed the \
961             db path independently instead of routing through the shared resolver, \
962             which would desynchronize config_id from other processes sharing the \
963             same database",
964            resolved_db_path,
965            anchor
966        );
967    }
968    Ok(())
969}
970
971/// Resolve the per-connection attribution actor from the project/cwd-anchored
972/// config tier, independently of the database-anchored config load that
973/// governs `config_id`.
974///
975/// The database-anchored config load keeps `config_id` coherent between a
976/// short-lived client and a long-running daemon sharing one database, but
977/// when many per-project connections share one database under a single
978/// `HOME` (the daemon-multiplexed fleet case), that shared config carries no
979/// `[actor]` block, so every connection's write-stamp attribution collapses
980/// to the default identity.
981///
982/// This performs a separate, cwd-anchored lookup (`db_path: None`) and reads
983/// only `[actor].id`: it must not perturb `config_id` or `default_namespace`,
984/// which remain governed exclusively by the database-anchored load.
985///
986/// `config_path` is the same explicit `--config`/`KHIVE_CONFIG` override the
987/// caller's database-anchored load receives, so an explicit override wins
988/// here too.
989///
990/// Returns `Ok(None)` when no project-anchored config exists, or it exists
991/// but carries no non-empty `[actor].id`: callers fall through to their own
992/// env/anonymous tiers in that case. A `config_path` naming a file that does
993/// not exist is a loud error (`ExplicitConfigMissing`), matching the
994/// database-anchored load's explicit-tier contract (ADR-035) — in production
995/// that load errors first, so this lookup only ever sees an existing file.
996pub fn resolve_project_actor_id(
997    config_path: Option<&std::path::Path>,
998) -> Result<Option<String>, crate::engine_config::ConfigError> {
999    let khive_cfg = crate::engine_config::KhiveConfig::load_with_home_fallback(config_path, None)?;
1000    Ok(khive_cfg
1001        .and_then(|cfg| cfg.actor.id)
1002        .filter(|s| !s.trim().is_empty()))
1003}
1004
1005/// Read `[actor].require_attributed` from the explicit config, or with none from
1006/// every existing discovery tier (the one anchored at `db_path` included), ORed.
1007///
1008/// The database-anchored load already carries the key into
1009/// [`RuntimeConfig::require_attributed_actor`]; callers OR the two, so a request
1010/// for strict mode in any file holds and a higher-precedence file without the key
1011/// cannot shadow one that sets it. `Ok(false)` when no file sets it.
1012pub fn resolve_project_requires_attributed_actor(
1013    config_path: Option<&std::path::Path>,
1014    db_path: Option<&std::path::Path>,
1015) -> Result<bool, crate::engine_config::ConfigError> {
1016    crate::engine_config::KhiveConfig::require_attributed_in_any_tier(config_path, db_path)
1017}
1018
1019// ---- Embedding model helpers ----
1020
1021/// Sanitize an embedding model name into a valid SQL table suffix.
1022/// e.g. `bge-small-en-v1.5` -> `bge_small_en_v1_5`
1023#[cfg(test)]
1024pub(crate) fn vec_model_key(model: EmbeddingModel) -> String {
1025    sanitize_key(&model.to_string())
1026}
1027
1028/// Preserve ASCII letters and digits; replace every other Unicode character with `_`.
1029/// Used for model-name table suffixes; this mapping does not preserve uniqueness.
1030#[doc(hidden)]
1031pub fn sanitize_key(s: &str) -> String {
1032    s.chars()
1033        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
1034        .collect()
1035}
1036
1037pub(crate) fn build_embedder_registry(
1038    config: &RuntimeConfig,
1039) -> (crate::embedder_registry::EmbedderRegistry, Arc<str>) {
1040    use crate::embedder_registry::{EmbedderRegistry, LatticeEmbedderProvider};
1041    let mut registry = EmbedderRegistry::new();
1042    for model in configured_embedding_models(config) {
1043        registry.register_builtin(LatticeEmbedderProvider::new(model));
1044    }
1045    let default_embedder_name = config
1046        .configured_engines()
1047        .first()
1048        .map(|engine| Arc::<str>::from(engine.name.as_str()))
1049        .unwrap_or_else(|| Arc::<str>::from(""));
1050    (registry, default_embedder_name)
1051}
1052
1053fn configured_embedding_models(config: &RuntimeConfig) -> Vec<EmbeddingModel> {
1054    if let Some(engines) = &config.engines {
1055        return engines
1056            .iter()
1057            .filter_map(|engine| parse_embedding_model_alias(&engine.name))
1058            .collect();
1059    }
1060    let mut models: Vec<EmbeddingModel> = Vec::new();
1061    if let Some(model) = config.embedding_model {
1062        models.push(model);
1063    }
1064    for model in config.additional_embedding_models.iter().copied() {
1065        if !models.contains(&model) {
1066            models.push(model);
1067        }
1068    }
1069    models
1070}
1071
1072pub(crate) fn register_configured_embedding_models(
1073    backend: &StorageBackend,
1074    config: &RuntimeConfig,
1075) -> RuntimeResult<()> {
1076    for model in configured_embedding_models(config) {
1077        backend.register_embedding_model(
1078            &model.to_string(),
1079            model.model_id(),
1080            model.key_version(),
1081            model.dimensions() as u32,
1082        )?;
1083    }
1084    Ok(())
1085}
1086
1087/// Build a `RuntimeConfig` from a parsed `KhiveConfig`.
1088///
1089/// Declared engines preserve their order and dimension assertions. The first
1090/// peer is projected into the legacy single-model field when it is built-in;
1091/// hosts bind the complete list after provider registration, before serving.
1092/// An explicit empty list disables participation; an absent list preserves
1093/// the caller's base configuration, including environment-derived defaults.
1094/// Load file input with [`crate::KhiveConfig::load`] to preserve that distinction
1095/// and convert legacy declarations before calling this function.
1096///
1097/// When both a config file and `KHIVE_EMBEDDING_MODEL` env var are present,
1098/// the caller is responsible for emitting a warning that env vars are overridden.
1099/// This function purely converts `KhiveConfig` to `RuntimeConfig` fields.
1100pub fn runtime_config_from_khive_config(
1101    khive_cfg: &crate::engine_config::KhiveConfig,
1102    base: RuntimeConfig,
1103) -> RuntimeConfig {
1104    // `[actor] id` never becomes the storage namespace (writes always pin to
1105    // `local`); it only widens the read visible-set below.
1106    let default_namespace = base.default_namespace.clone();
1107    let mounts = khive_cfg.mounts.clone();
1108    let channel = khive_cfg.channel.clone();
1109    let credentials = khive_cfg.credentials.clone();
1110    let visibility_receipts = khive_cfg.visibility_receipts.clone();
1111    let code_map_root = khive_cfg.code_map_root.clone();
1112    let code_maps = khive_cfg.code_maps.clone();
1113    let code_map_protected_database_paths = khive_cfg
1114        .backends
1115        .iter()
1116        .filter(|backend| backend.kind == crate::engine_config::BackendKind::Sqlite)
1117        .filter_map(|backend| {
1118            backend
1119                .path
1120                .as_deref()
1121                .map(|path| expand_tilde(std::path::Path::new(path)))
1122        })
1123        .collect();
1124
1125    // base.brain_profile must carry only the explicit CLI tier, never an env
1126    // value: env sits below toml in precedence and is applied later by the MCP resolver.
1127    let brain_profile = base.brain_profile.clone().or_else(|| {
1128        khive_cfg
1129            .runtime
1130            .brain_profile
1131            .clone()
1132            .filter(|s| !s.trim().is_empty())
1133    });
1134
1135    let visible_namespaces: Vec<Namespace> = khive_cfg
1136        .actor
1137        .visible_namespaces
1138        .as_deref()
1139        .unwrap_or_default()
1140        .iter()
1141        .filter_map(|s| match Namespace::parse(s) {
1142            Ok(ns) => Some(ns),
1143            Err(e) => {
1144                tracing::warn!(ns = %s, error = %e, "actor.visible_namespaces: invalid namespace; skipped");
1145                None
1146            }
1147        })
1148        .collect();
1149
1150    // Fold actor.id's namespace into visible_namespaces so default reads widen
1151    // to {local} ∪ {actor namespace}; skipped when it parses to `local` (would
1152    // duplicate the primary namespace already minted) or is already present.
1153    let visible_namespaces = if let Some(id) = khive_cfg.actor.id.as_deref() {
1154        match Namespace::parse(id) {
1155            Ok(actor_ns) if actor_ns != Namespace::local() => {
1156                let mut v = visible_namespaces;
1157                if !v.contains(&actor_ns) {
1158                    v.push(actor_ns);
1159                }
1160                v
1161            }
1162            _ => visible_namespaces,
1163        }
1164    } else {
1165        visible_namespaces
1166    };
1167
1168    // `[actor] owned_namespaces` (ADR-021 Delta 1). KhiveConfig::validate()
1169    // guarantees every entry parses, so a parse failure here is unreachable for
1170    // a validated config; filter_map+warn guards against a validation bug
1171    // panicking instead. A dropped entry can only shrink what the actor owns.
1172    // The list is deliberately not folded into `visible_namespaces`.
1173    let owned_namespaces: Vec<Namespace> = khive_cfg
1174        .actor
1175        .owned_namespaces
1176        .iter()
1177        .filter_map(|s| match Namespace::parse(s) {
1178            Ok(ns) => Some(ns),
1179            Err(e) => {
1180                tracing::warn!(ns = %s, error = %e, "actor.owned_namespaces: invalid namespace; skipped");
1181                None
1182            }
1183        })
1184        .collect();
1185
1186    // KhiveConfig::validate() guarantees these are valid Namespace strings, so
1187    // parse failures here are unreachable for validated configs; filter_map+warn
1188    // guards against a validation bug panicking instead.
1189    let allowed_outbound_namespaces: Vec<Namespace> = khive_cfg
1190        .actor
1191        .allowed_outbound_namespaces
1192        .iter()
1193        .filter_map(|s| match Namespace::parse(s) {
1194            Ok(ns) => Some(ns),
1195            Err(e) => {
1196                tracing::warn!(ns = %s, error = %e, "actor.allowed_outbound_namespaces: invalid namespace; skipped");
1197                None
1198            }
1199        })
1200        .collect();
1201
1202    // Precedence: TOML `[actor] id` > `base.actor_id` (env/CLI-resolved) >
1203    // anonymous. Falls back to `base.actor_id` rather than `None` when
1204    // `[actor] id` is absent: otherwise an env-resolved actor like
1205    // `KHIVE_ACTOR` is silently dropped whenever a project config exists
1206    // without an `[actor]` block.
1207    let actor_id = khive_cfg
1208        .actor
1209        .id
1210        .clone()
1211        .filter(|s| !s.trim().is_empty())
1212        .or_else(|| base.actor_id.clone());
1213    let require_attributed_actor =
1214        khive_cfg.actor.require_attributed || base.require_attributed_actor;
1215
1216    let gate = khive_cfg
1217        .gate
1218        .as_ref()
1219        .map(|gate| {
1220            Arc::new(khive_gate::CallerEnrollmentGate::with_write_denials(
1221                gate.granted_actors.clone(),
1222                gate.grant_unattributed,
1223                gate.deny_writes_for.clone(),
1224            )) as GateRef
1225        })
1226        .unwrap_or_else(|| base.gate.clone());
1227    let gate = crate::mailbox_view::configured_mailbox_gate(&khive_cfg.actor, gate);
1228
1229    let brain = khive_cfg.brain.clone();
1230    let git_write = khive_cfg.git_write.clone();
1231    let blob = crate::engine_config::BlobSectionConfig {
1232        file_transfers: khive_cfg.blob.file_transfers || base.blob.file_transfers,
1233    };
1234    let exec = khive_cfg.exec.clone();
1235    let telemetry = khive_cfg.telemetry.clone();
1236    let web = khive_cfg.web.clone();
1237    let warm_concurrency = khive_cfg
1238        .runtime
1239        .warm_concurrency
1240        .unwrap_or(base.warm_concurrency);
1241    let maintenance_concurrency = khive_cfg
1242        .runtime
1243        .maintenance_concurrency
1244        .unwrap_or(base.maintenance_concurrency);
1245    let blob_hydration_bytes = khive_cfg
1246        .runtime
1247        .blob_hydration_bytes
1248        .unwrap_or(base.blob_hydration_bytes);
1249
1250    // KhiveConfig::validate() guarantees a present timezone parses as a valid
1251    // chrono_tz::Tz, so the fallback to base.display_timezone below is only
1252    // reachable for an unvalidated caller-constructed KhiveConfig, not a
1253    // config loaded via KhiveConfig::load.
1254    let display_timezone = khive_cfg
1255        .display
1256        .timezone
1257        .as_deref()
1258        .and_then(|s| s.parse::<chrono_tz::Tz>().ok())
1259        .unwrap_or(base.display_timezone);
1260
1261    if khive_cfg.engines.is_empty() && !khive_cfg.engines_declared {
1262        return RuntimeConfig {
1263            credentials,
1264            visibility_receipts,
1265            default_namespace,
1266            brain_profile,
1267            visible_namespaces,
1268            owned_namespaces,
1269            allowed_outbound_namespaces,
1270            actor_id,
1271            require_attributed_actor,
1272            gate,
1273            brain,
1274            git_write,
1275            blob,
1276            exec,
1277            telemetry,
1278            mounts,
1279            channel,
1280            code_map_root,
1281            code_maps,
1282            code_map_protected_database_paths,
1283            warm_concurrency,
1284            maintenance_concurrency,
1285            blob_hydration_bytes,
1286            display_timezone,
1287            web,
1288            ..base
1289        };
1290    }
1291
1292    let engines = khive_cfg.engines.clone();
1293    let embedding_model = engines
1294        .first()
1295        .and_then(|engine| parse_embedding_model_alias(&engine.name));
1296    let additional = engines
1297        .iter()
1298        .skip(1)
1299        .filter_map(|engine| parse_embedding_model_alias(&engine.name))
1300        .collect();
1301
1302    RuntimeConfig {
1303        credentials,
1304        visibility_receipts,
1305        engines: Some(engines),
1306        embedding_model,
1307        additional_embedding_models: additional,
1308        default_namespace,
1309        brain_profile,
1310        visible_namespaces,
1311        owned_namespaces,
1312        allowed_outbound_namespaces,
1313        actor_id,
1314        require_attributed_actor,
1315        gate,
1316        brain,
1317        git_write,
1318        blob,
1319        exec,
1320        telemetry,
1321        mounts,
1322        channel,
1323        code_map_root,
1324        code_maps,
1325        code_map_protected_database_paths,
1326        warm_concurrency,
1327        maintenance_concurrency,
1328        blob_hydration_bytes,
1329        display_timezone,
1330        web,
1331        ..base
1332    }
1333}
1334
1335#[cfg(test)]
1336mod display_timezone_tests {
1337    use super::resolve_default_display_timezone;
1338
1339    // The host's actual zone is environment-dependent (CI runners are
1340    // typically UTC), so this only asserts the resolver always produces some
1341    // valid, non-panicking Tz — never that it matches a specific zone.
1342    #[test]
1343    fn resolve_default_display_timezone_never_panics() {
1344        let _tz = resolve_default_display_timezone();
1345    }
1346}
1347
1348/// Parse a comma- or whitespace-separated list of embedding model names.
1349fn parse_embedding_model_list(s: &str) -> Vec<EmbeddingModel> {
1350    parse_pack_list(s)
1351        .into_iter()
1352        .filter_map(|raw| {
1353            let parsed = parse_embedding_model_alias(&raw);
1354            if parsed.is_none() && !raw.trim().is_empty() {
1355                tracing::warn!(
1356                    model = %raw,
1357                    "KHIVE_ADDITIONAL_EMBEDDING_MODELS contains unknown model name; ignored. \
1358                     Valid forms: short alias like 'paraphrase' or a fully-qualified key \
1359                     from lattice_embed::EmbeddingModel::from_str."
1360                );
1361            }
1362            parsed
1363        })
1364        .collect()
1365}
1366
1367pub(crate) fn parse_embedding_model_alias(name: &str) -> Option<EmbeddingModel> {
1368    let normalized = name.trim().to_ascii_lowercase().replace('_', "-");
1369    match normalized.as_str() {
1370        "paraphrase" => Some(EmbeddingModel::ParaphraseMultilingualMiniLmL12V2),
1371        _ => normalized.parse().ok(),
1372    }
1373}
1374
1375#[cfg(test)]
1376mod resolve_db_anchor_tests {
1377    use super::resolve_db_anchor;
1378
1379    #[test]
1380    fn memory_sentinel_maps_to_none() {
1381        assert_eq!(resolve_db_anchor(Some(":memory:")), None);
1382    }
1383
1384    #[test]
1385    fn explicit_path_maps_to_some() {
1386        assert_eq!(
1387            resolve_db_anchor(Some("/tmp/khive-anchor-test.db")),
1388            Some(std::path::PathBuf::from("/tmp/khive-anchor-test.db"))
1389        );
1390    }
1391
1392    #[test]
1393    fn absent_maps_to_home_default() {
1394        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
1395        let expected = std::path::PathBuf::from(format!("{home}/.khive/khive.db"));
1396        assert_eq!(resolve_db_anchor(None), Some(expected));
1397    }
1398}
1399
1400#[cfg(test)]
1401mod assert_db_anchor_consistent_tests {
1402    use super::{assert_captured_db_anchor_consistent, resolve_db_anchor};
1403    use crate::assert_db_anchor_consistent;
1404
1405    #[test]
1406    fn diverging_db_path_is_rejected_naming_both_paths() {
1407        let args_db = "/tmp/khive-anchor-guard-real.db";
1408        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1409        let wrong = std::path::PathBuf::from("/tmp/khive-anchor-guard-wrong.db");
1410
1411        let err =
1412            assert_captured_db_anchor_consistent(Some(wrong.as_path()), Some(anchor.as_path()))
1413                .expect_err("a resolved db_path diverging from the anchor must be rejected");
1414
1415        let msg = err.to_string();
1416        assert!(
1417            msg.contains(&wrong.display().to_string()),
1418            "error must name the resolved (wrong) path: {msg}"
1419        );
1420        assert!(
1421            msg.contains(&anchor.display().to_string()),
1422            "error must name the canonical anchor path: {msg}"
1423        );
1424    }
1425
1426    #[test]
1427    fn matching_explicit_db_path_passes() {
1428        let args_db = "/tmp/khive-anchor-guard-consistent.db";
1429        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1430        assert!(assert_captured_db_anchor_consistent(
1431            Some(anchor.as_path()),
1432            Some(anchor.as_path())
1433        )
1434        .is_ok());
1435    }
1436
1437    #[test]
1438    fn memory_sentinel_anchor_is_inert() {
1439        // `resolve_db_anchor(":memory:")` yields `None` — there is no canonical
1440        // path to assert against, so the guard passes regardless of what
1441        // `resolved_db_path` happens to carry.
1442        let bogus = std::path::PathBuf::from("/tmp/should-not-matter.db");
1443        assert!(assert_captured_db_anchor_consistent(Some(bogus.as_path()), None).is_ok());
1444        assert!(assert_captured_db_anchor_consistent(None, None).is_ok());
1445    }
1446
1447    #[test]
1448    fn normal_boot_with_db_unset_passes_silently() {
1449        // Mirrors a normal boot with `--db` unset: `resolve_db_anchor(None)`
1450        // always resolves to `Some(..)` (HOME-set or -unset both produce a
1451        // concrete anchor), so a runtime whose resolved `db_path` matches
1452        // passes silently.
1453        let anchor = resolve_db_anchor(None);
1454        assert!(assert_captured_db_anchor_consistent(anchor.as_deref(), anchor.as_deref()).is_ok());
1455    }
1456
1457    #[test]
1458    fn public_compatibility_wrapper_accepts_path_and_memory_sentinel() {
1459        let args_db = "/tmp/khive-anchor-guard-public-api.db";
1460        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
1461        assert!(assert_db_anchor_consistent(Some(anchor.as_path()), Some(args_db)).is_ok());
1462
1463        let unrelated = std::path::Path::new("/tmp/khive-anchor-guard-unrelated.db");
1464        assert!(assert_db_anchor_consistent(Some(unrelated), Some(":memory:")).is_ok());
1465    }
1466}
1467
1468#[cfg(test)]
1469mod resolve_project_actor_id_tests {
1470    use super::resolve_project_actor_id;
1471
1472    fn write_toml(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
1473        let path = dir.path().join("config.toml");
1474        std::fs::write(&path, body).expect("write config.toml");
1475        path
1476    }
1477
1478    #[test]
1479    fn extracts_non_empty_actor_id_from_explicit_path() {
1480        let dir = tempfile::tempdir().expect("tempdir");
1481        let path = write_toml(&dir, "[actor]\nid = \"lambda:explicit-actor\"\n");
1482
1483        assert_eq!(
1484            resolve_project_actor_id(Some(&path)).expect("no error"),
1485            Some("lambda:explicit-actor".to_string())
1486        );
1487    }
1488
1489    #[test]
1490    fn missing_explicit_path_fails_loud() {
1491        // The explicit tier is enforced inside the loader
1492        // (`KhiveConfig::load_with_home_fallback_and_source` returns
1493        // `ExplicitConfigMissing`): a nonexistent explicit path is an error,
1494        // never a silent `None` (ADR-035).
1495        let missing = std::path::PathBuf::from("/nonexistent/khive-project-actor-test/config.toml");
1496        let err = resolve_project_actor_id(Some(&missing))
1497            .expect_err("a missing explicit path must fail loud");
1498        assert!(
1499            matches!(
1500                err,
1501                crate::engine_config::ConfigError::ExplicitConfigMissing { .. }
1502            ),
1503            "expected ExplicitConfigMissing, got {err:?}"
1504        );
1505    }
1506
1507    #[test]
1508    fn propagates_load_error_for_invalid_actor_id() {
1509        // `KhiveConfig::load`'s `validate()` rejects an empty `[actor] id` before
1510        // the emptiness filter in `resolve_project_actor_id` ever sees it; this
1511        // asserts the error surfaces rather than being swallowed into `Ok(None)`.
1512        let dir = tempfile::tempdir().expect("tempdir");
1513        let path = write_toml(&dir, "[actor]\nid = \"\"\n");
1514
1515        let err = resolve_project_actor_id(Some(&path)).expect_err("invalid actor.id must error");
1516        let root = match &err {
1517            crate::engine_config::ConfigError::InFile { source, .. } => source.as_ref(),
1518            other => other,
1519        };
1520        assert!(
1521            matches!(
1522                root,
1523                crate::engine_config::ConfigError::InvalidActorId { .. }
1524            ),
1525            "expected InvalidActorId, got {err:?}"
1526        );
1527    }
1528
1529    #[test]
1530    fn returns_none_when_config_has_no_actor_section() {
1531        let dir = tempfile::tempdir().expect("tempdir");
1532        let path = write_toml(
1533            &dir,
1534            "[[engines]]\nname = \"primary\"\nmodel = \"bge-small-en-v1.5\"\ndefault = true\n",
1535        );
1536
1537        assert_eq!(
1538            resolve_project_actor_id(Some(&path)).expect("no error"),
1539            None,
1540            "a config file with no [actor] section must resolve to None"
1541        );
1542    }
1543}
1544
1545#[cfg(test)]
1546mod no_embeddings_tests {
1547    use super::*;
1548    use serial_test::serial;
1549
1550    #[test]
1551    fn default_embedding_model_environment_keeps_typed_fallbacks() {
1552        if crate::test_process::run_in_child() {
1553            return;
1554        }
1555        const PRIMARY: &str = "KHIVE_EMBEDDING_MODEL";
1556        const ADDITIONAL: &str = "KHIVE_ADDITIONAL_EMBEDDING_MODELS";
1557        assert_eq!(
1558            RuntimeConfig::default().embedding_model,
1559            Some(EmbeddingModel::AllMiniLmL6V2)
1560        );
1561        std::env::set_var(ADDITIONAL, "paraphrase-multilingual-minilm-l12-v2");
1562        for (value, expected) in [
1563            ("invalid", EmbeddingModel::AllMiniLmL6V2),
1564            ("", EmbeddingModel::AllMiniLmL6V2),
1565            ("bge-small-en-v1.5", EmbeddingModel::BgeSmallEnV15),
1566            (" BAAI/BGE_SMALL_EN_V1.5 ", EmbeddingModel::BgeSmallEnV15),
1567            ("all-minilm", EmbeddingModel::AllMiniLmL6V2),
1568        ] {
1569            std::env::set_var(PRIMARY, value);
1570            let config = RuntimeConfig::default();
1571            assert_eq!(config.embedding_model, Some(expected), "{value:?}");
1572            assert_eq!(
1573                config.additional_embedding_models,
1574                vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1575            );
1576        }
1577        #[cfg(unix)]
1578        {
1579            use std::os::unix::ffi::OsStrExt;
1580            std::env::set_var(PRIMARY, std::ffi::OsStr::from_bytes(b"\xff"));
1581            assert_eq!(
1582                RuntimeConfig::default().embedding_model,
1583                Some(EmbeddingModel::AllMiniLmL6V2)
1584            );
1585        }
1586        std::env::remove_var(PRIMARY);
1587        let config = RuntimeConfig::default();
1588        assert_eq!(config.embedding_model, Some(EmbeddingModel::AllMiniLmL6V2));
1589        assert_eq!(
1590            config.additional_embedding_models,
1591            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1592        );
1593        std::env::remove_var(ADDITIONAL);
1594    }
1595
1596    #[test]
1597    fn no_embeddings_clears_both_fields() {
1598        let config = RuntimeConfig::no_embeddings();
1599        assert_eq!(config.embedding_model, None);
1600        assert!(config.additional_embedding_models.is_empty());
1601        assert!(
1602            configured_embedding_models(&config).is_empty(),
1603            "no_embeddings() must yield zero configured embedders"
1604        );
1605    }
1606
1607    #[test]
1608    fn blob_hydration_default_is_four_portable_whole_objects() {
1609        assert_eq!(
1610            RuntimeConfig::default().blob_hydration_bytes,
1611            4 * khive_storage::MAX_BLOB_WHOLE_BYTES
1612        );
1613    }
1614
1615    #[test]
1616    #[serial]
1617    fn no_embeddings_ignores_additional_env_override() {
1618        // no_embeddings() is an unconditional opt-out: even if the caller's
1619        // environment sets KHIVE_ADDITIONAL_EMBEDDING_MODELS, the resulting
1620        // config must still report zero embedders.
1621        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1622        let config = RuntimeConfig::no_embeddings();
1623        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1624
1625        assert!(config.additional_embedding_models.is_empty());
1626        assert!(configured_embedding_models(&config).is_empty());
1627    }
1628
1629    #[test]
1630    #[serial]
1631    fn default_computes_additional_models_independently_of_no_embeddings() {
1632        // `Default` must keep computing `embedding_model` and
1633        // `additional_embedding_models` independently; `no_embeddings()` is a
1634        // separate opt-out constructor, not a change to `Default`'s seeding.
1635        // The env var is SET here rather than cleared: since Default now ships
1636        // no secondary engine, an unset env would make Default and
1637        // no_embeddings() indistinguishable and the test would stop
1638        // discriminating the thing it exists to discriminate.
1639        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
1640        let config = RuntimeConfig::default();
1641        let buggy_form = RuntimeConfig {
1642            embedding_model: None,
1643            ..RuntimeConfig::default()
1644        };
1645        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1646
1647        assert_eq!(
1648            config.additional_embedding_models,
1649            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
1650        );
1651
1652        // Overriding only `embedding_model` via struct-update syntax does not
1653        // clear `additional_embedding_models`.
1654        assert!(
1655            !buggy_form.additional_embedding_models.is_empty(),
1656            "Default's independent-field seeding must remain unchanged; \
1657             no_embeddings() is the fix, not a change to Default"
1658        );
1659    }
1660
1661    #[test]
1662    #[serial]
1663    fn default_ships_a_single_engine_when_env_unset() {
1664        // A secondary engine is embedded on every write and searched on every
1665        // read. That cost is opted into, not inherited.
1666        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
1667        let config = RuntimeConfig::default();
1668
1669        assert!(
1670            config.additional_embedding_models.is_empty(),
1671            "shipped default must register one engine; a second is opt-in via \
1672             KHIVE_ADDITIONAL_EMBEDDING_MODELS"
1673        );
1674        assert_eq!(
1675            configured_embedding_models(&config),
1676            vec![EmbeddingModel::AllMiniLmL6V2]
1677        );
1678    }
1679}
1680
1681#[cfg(test)]
1682mod ann_fresh_tail_config_tests {
1683    use super::ann_fresh_tail_enabled_from_value;
1684
1685    #[test]
1686    fn only_exact_zero_disables_fresh_tail() {
1687        assert!(ann_fresh_tail_enabled_from_value(None));
1688        assert!(!ann_fresh_tail_enabled_from_value(Some("0")));
1689        assert!(ann_fresh_tail_enabled_from_value(Some("1")));
1690        assert!(ann_fresh_tail_enabled_from_value(Some("false")));
1691        assert!(ann_fresh_tail_enabled_from_value(Some(" 0")));
1692    }
1693}
1694
1695#[cfg(test)]
1696mod configured_embedding_models_order_tests {
1697    use super::*;
1698
1699    /// Issue #1115: the configured engine list must preserve declaration
1700    /// order (primary first, then `additional_embedding_models` in order)
1701    /// instead of alphabetizing — any consumer that treats the list as
1702    /// ordered (e.g. recall fan-out) otherwise gets the wrong primary.
1703    #[test]
1704    fn preserves_primary_first_then_additional_in_declared_order() {
1705        let config = RuntimeConfig {
1706            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1707            additional_embedding_models: vec![
1708                EmbeddingModel::Qwen3Embedding4B,
1709                EmbeddingModel::BgeSmallEnV15,
1710            ],
1711            ..RuntimeConfig::default()
1712        };
1713
1714        assert_eq!(
1715            configured_embedding_models(&config),
1716            vec![
1717                EmbeddingModel::AllMiniLmL6V2,
1718                EmbeddingModel::Qwen3Embedding4B,
1719                EmbeddingModel::BgeSmallEnV15,
1720            ],
1721            "order must be primary-first, then additional models as declared, \
1722             not alphabetized"
1723        );
1724    }
1725
1726    /// A model repeated in both `embedding_model` and `additional_embedding_models`
1727    /// must be deduped to a single entry, keeping its first (primary) position.
1728    #[test]
1729    fn dedupes_model_shared_between_primary_and_additional() {
1730        let config = RuntimeConfig {
1731            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
1732            additional_embedding_models: vec![
1733                EmbeddingModel::AllMiniLmL6V2,
1734                EmbeddingModel::BgeSmallEnV15,
1735            ],
1736            ..RuntimeConfig::default()
1737        };
1738
1739        assert_eq!(
1740            configured_embedding_models(&config),
1741            vec![EmbeddingModel::AllMiniLmL6V2, EmbeddingModel::BgeSmallEnV15],
1742            "the shared model must appear once, in its primary position"
1743        );
1744    }
1745}
1746
1747/// Policy from the 2026-10-20 00:00Z through 2026-10-27 04:40Z event window:
1748/// completed warm spans peaked at one with no observed overlap. Configured
1749/// knowledge warm was unobserved. This is a conservative policy, not capacity.
1750pub(crate) const DEFAULT_WARM_CONCURRENCY: usize = 1;
1751
1752/// Maintenance policy uses the same 2026-10-20 00:00Z through 2026-10-27 04:40Z
1753/// observation: warm peak one, no overlaps, configured knowledge warm absent.
1754/// Checkpoint work has warm attribution; other WAL/Vamana work was uninstrumented.
1755pub(crate) const DEFAULT_MAINTENANCE_CONCURRENCY: usize = 1;