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