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