Skip to main content

khive_runtime/
engine_config.rs

1//! TOML-based embedding engine configuration for khive.
2//!
3//! Loads `.khive/config.toml` (or `--config` / `KHIVE_CONFIG`) and exposes an
4//! `[[engines]]` array for arbitrary-N embedding engine registration. Falls back
5//! to `KHIVE_EMBEDDING_MODEL` env vars when no config file is present.
6
7use std::path::{Path, PathBuf};
8
9use khive_types::namespace::Namespace;
10use serde::Deserialize;
11use thiserror::Error;
12
13use crate::presentation::OutputFormat;
14
15// ---- Error type ----
16
17/// Errors produced while loading or validating a `KhiveConfig`.
18#[derive(Debug, Error)]
19pub enum ConfigError {
20    #[error("config file I/O: {0}")]
21    Io(#[from] std::io::Error),
22
23    #[error("config TOML parse error in {path}: {source}")]
24    Parse {
25        path: PathBuf,
26        #[source]
27        source: toml::de::Error,
28    },
29
30    #[error("exactly one engine must be marked `default = true`; found {found}")]
31    DefaultCount { found: usize },
32
33    #[error("duplicate engine name: {name:?}")]
34    DuplicateName { name: String },
35
36    #[error(
37        "engine {name:?}: model {model:?} is not a recognized lattice_embed::EmbeddingModel name"
38    )]
39    UnknownModel { name: String, model: String },
40
41    #[error("engine {name:?}: fusion_weight must be > 0, got {value}")]
42    InvalidFusionWeight { name: String, value: f64 },
43
44    #[error("actor.id {id:?} is not a valid namespace: {reason}")]
45    InvalidActorId { id: String, reason: String },
46
47    #[error("duplicate backend name: {name:?}")]
48    DuplicateBackendName { name: String },
49
50    #[error(
51        "[packs.{pack}].backend = {backend:?} references an unknown backend; \
52         defined backends: {defined}"
53    )]
54    UnknownPackBackend {
55        pack: String,
56        backend: String,
57        defined: String,
58    },
59
60    #[error(
61        "[[backends]] entry {name:?}: field `{field}` is not yet supported; \
62         remove it from the config or wait for a future release that implements it"
63    )]
64    UnsupportedBackendField { name: String, field: &'static str },
65
66    #[error(
67        "top-level `db = {value:?}` is not a supported config-file key; \
68         use `--db` / `KHIVE_DB` to select a single-file database, or \
69         `[[backends]].path` to declare storage backend topology"
70    )]
71    UnsupportedTopLevelDb { value: String },
72
73    #[error("[[git_write.allowed]] entry {repo:?}: {reason}")]
74    InvalidGitWriteEntry { repo: String, reason: String },
75
76    #[error(
77        "[runtime] blob_hydration_bytes must be between {min} and {max} bytes inclusive; got {value}"
78    )]
79    InvalidBlobHydrationBytes { value: u64, min: u64, max: u64 },
80
81    #[error("the explicitly selected config file does not exist: {path}")]
82    ExplicitConfigMissing { path: PathBuf },
83
84    #[error(
85        "[gate] configuration is not supported by this build; refusing to start because the requested caller-enrollment policy would not be enforced"
86    )]
87    UnsupportedGateSection,
88
89    #[error(
90        "[display] timezone {timezone:?} is not a recognized IANA zone name (e.g. \"America/New_York\", \"UTC\")"
91    )]
92    InvalidDisplayTimezone { timezone: String },
93
94    /// Loader-context wrapper attaching the config file the error came from.
95    ///
96    /// Added as a wrapping variant, rather than reshaping the existing
97    /// variants, so every existing constructor, field access, and the
98    /// `From<std::io::Error>` conversion survive unchanged. The enum is not
99    /// `#[non_exhaustive]`, so an exhaustive `match` on `ConfigError` must
100    /// still add an arm for this variant — either matching `InFile` and
101    /// recursing into `source`, or a wildcard. `Parse` already carries its
102    /// path and is never wrapped.
103    #[error("{source} (config file: {})", path.display())]
104    InFile {
105        path: PathBuf,
106        #[source]
107        source: Box<ConfigError>,
108    },
109}
110
111impl ConfigError {
112    /// Attach the loading config file's path unless the error already names
113    /// one (`Parse`, `ExplicitConfigMissing`) or is already wrapped.
114    fn in_file(self, path: &Path) -> Self {
115        match self {
116            already @ (ConfigError::Parse { .. }
117            | ConfigError::ExplicitConfigMissing { .. }
118            | ConfigError::InFile { .. }) => already,
119            other => ConfigError::InFile {
120                path: path.to_path_buf(),
121                source: Box::new(other),
122            },
123        }
124    }
125}
126
127// ---- Config structs ----
128
129/// Configuration for a single embedding engine.
130#[derive(Debug, Clone, Deserialize)]
131pub struct EngineConfig {
132    /// Logical name used to reference this engine in logs and fusion.
133    pub name: String,
134
135    /// Lattice-embed model name (e.g. `"all-minilm-l6-v2"`).
136    ///
137    /// Must be parseable via `lattice_embed::EmbeddingModel::from_str` (or a
138    /// recognised short alias handled by `parse_embedding_model_alias`).
139    pub model: String,
140
141    /// When `true`, this engine's model becomes the primary (`RuntimeConfig::embedding_model`).
142    /// Exactly one engine in the list must set this. If absent, defaults to `false`.
143    #[serde(default)]
144    pub default: bool,
145
146    /// RRF fusion weight for weighted multi-engine fusion.
147    ///
148    /// Only meaningful when multiple engines are loaded. Must be `> 0` when
149    /// present. `None` means the engine participates in fusion with equal weight
150    /// to other engines that also lack a `fusion_weight`.
151    ///
152    /// For RRF: `fusion_weight` provides per-engine relative importance during
153    /// weighted RRF; it does NOT apply to rank-based unweighted RRF (the weights
154    /// are injected into `FusionStrategy::Weighted` only).
155    pub fusion_weight: Option<f64>,
156
157    /// Expected output dimensionality (optional sanity check).
158    ///
159    /// Not used at runtime — dimensions are authoritative from
160    /// `EmbeddingModel::dimensions()`. Present so operators can document the
161    /// expected shape alongside the model name.
162    pub dims: Option<u32>,
163}
164
165/// Actor configuration — the default namespace / identity for this khive instance.
166///
167/// Corresponds to the `[actor]` TOML section. `id` is used as the
168/// `default_namespace` for gate/attribution policy input. OSS dispatch pins
169/// writes to the shared `local` namespace regardless of this value (ADR-007
170/// Rev 4 Rule 0); cloud deployments derive the namespace from an authenticated
171/// `NamespaceToken` instead.
172///
173/// ```toml
174/// [actor]
175/// id = "lambda:leo"                          # attribution identity (required)
176/// display_name = "example actor"   # human label (optional)
177/// visible_namespaces = ["lambda:khive", "local"]  # widens default read scope (ADR-007 Rev 4 Rule 3b)
178/// ```
179///
180/// `visible_namespaces` is consumed by OSS dispatch to widen the DEFAULT
181/// multi-record read scope to `['local'] ∪ visible_namespaces` (ADR-007 Rev 4
182/// Rule 3b). Writes remain pinned to `'local'`. An explicit `namespace=` request
183/// param is a precise single-namespace escape and is not widened. A cloud gate
184/// may also consult this list as policy input at its own layer.
185#[derive(Debug, Clone, Deserialize, Default)]
186pub struct ActorConfig {
187    /// Namespace identifier used as the default actor for all operations.
188    ///
189    /// Must be a valid `Namespace` string (e.g. `"local"`, `"lambda:khive"`).
190    /// Defaults to `"local"` when absent — backward-compatible with pre-actor
191    /// deployments.
192    #[serde(default)]
193    pub id: Option<String>,
194
195    /// Optional human-readable label for this actor. Not used by the runtime;
196    /// surfaced in introspection and log output only.
197    #[serde(default)]
198    pub display_name: Option<String>,
199
200    /// Additional namespaces that widen the DEFAULT multi-record read scope
201    /// to `['local'] ∪ visible_namespaces` (ADR-007 Rev 4 Rule 3b). Each string
202    /// must be a valid `Namespace`. Writes remain pinned to `'local'`. An
203    /// explicit `namespace=` request param is a precise escape and is not widened
204    /// by this list. A cloud gate may also consult it as policy input.
205    #[serde(default)]
206    pub visible_namespaces: Option<Vec<String>>,
207
208    /// Namespaces this actor's comm.send/reply may deliver messages INTO
209    /// (outbound, sender-side). Empty by default — cross-namespace delivery
210    /// denied unless explicitly declared. The comm handler uses an ordinary
211    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
212    /// the token itself is NOT type-enforced write-only. The recipient-side
213    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
214    /// a future cloud-path authorization ADR (not yet written).
215    ///
216    /// Each entry must be a valid `Namespace` string; validated at
217    /// config-load time. An empty list preserves the prior deny-all behavior
218    /// for any actor that does not add this field.
219    #[serde(default)]
220    pub allowed_outbound_namespaces: Vec<String>,
221}
222
223// ---- Per-pack backend config (ADR-028) ----
224
225/// Storage backend kind.
226#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
227#[serde(rename_all = "lowercase")]
228pub enum BackendKind {
229    /// SQLite file-backed database (default).
230    #[default]
231    Sqlite,
232    /// In-memory database — for testing only; state is lost on restart.
233    Memory,
234}
235
236/// Configuration for a named storage backend.
237///
238/// Corresponds to a `[[backends]]` entry in `khive.toml`.
239/// When no `[[backends]]` section is present, a single implicit `main` backend
240/// is synthesised from the existing `--db` / `KHIVE_DB` / default-path resolution.
241/// All packs fall back to `main` when their name is absent from `[packs]`.
242///
243/// ```toml
244/// [[backends]]
245/// name = "knowledge"
246/// kind = "sqlite"
247/// path = "~/.khive/knowledge.db"
248/// cache_mb = 128
249/// journal_mode = "wal"
250/// read_only = false
251/// ```
252#[derive(Debug, Clone, Deserialize)]
253pub struct BackendConfig {
254    /// Unique backend name. Referenced by `[packs.<name>].backend`.
255    pub name: String,
256    /// Storage backend kind. Defaults to `sqlite`.
257    #[serde(default)]
258    pub kind: BackendKind,
259    /// Filesystem path for `sqlite` kind. Tilde is expanded to `$HOME`.
260    /// `None` for `memory` kind (path is ignored when present).
261    pub path: Option<std::path::PathBuf>,
262    /// SQLite page-cache size in MiB.
263    pub cache_mb: Option<u32>,
264    /// SQLite journal mode (e.g. `"wal"`).
265    pub journal_mode: Option<String>,
266    /// Open the backend read-only. Defaults to `false`.
267    #[serde(default)]
268    pub read_only: bool,
269}
270
271/// Per-pack backend assignment.
272///
273/// Corresponds to a `[packs.<pack-name>]` entry in `khive.toml`.
274/// Packs whose name is absent from `[packs]` fall back to the `main` backend.
275///
276/// ```toml
277/// [packs.knowledge]
278/// backend = "knowledge"
279/// ```
280#[derive(Debug, Clone, Deserialize)]
281pub struct PackConfig {
282    /// Backend name this pack is assigned to. Must match a `[[backends]].name`.
283    pub backend: String,
284}
285
286// ---- Blob store config (ADR-111 Amendment 2) ----
287
288/// `[storage.blob]` section: a closed `backend = "fs" | "s3"` selector.
289///
290/// Internally tagged on `backend` with `deny_unknown_fields`: an unknown
291/// top-level key, a field that belongs to the other backend variant (e.g.
292/// `bucket` under `backend = "fs"`), or an S3 credential field (never
293/// accepted in TOML -- ADR-111 Amendment 2 reads credentials from the
294/// process environment only) are all rejected at config-load time by the
295/// same mechanism, since each variant only declares its own fields.
296///
297/// ```toml
298/// [storage.blob]
299/// backend = "fs"
300/// root = "/var/lib/khive/blobs"
301/// floor_bytes = 100000000000
302/// ```
303///
304/// ```toml
305/// [storage.blob]
306/// backend = "s3"
307/// bucket = "khive-blobs"
308/// region = "us-east-1"
309/// endpoint = "https://objects.example.invalid"
310/// prefix = "blobs"
311/// ```
312#[derive(Debug, Clone, Deserialize)]
313#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
314pub enum BlobConfig {
315    /// Filesystem-backed blob storage (`FsBlobStore`). Root resolution is
316    /// unchanged from khive#292: `KHIVE_BLOB_ROOT` env var, then this
317    /// `root`, then `<db_dir>/blobs`.
318    Fs {
319        #[serde(default)]
320        root: Option<String>,
321        #[serde(default)]
322        floor_bytes: Option<u64>,
323    },
324    /// S3-compatible blob storage (`S3BlobStore`). `KHIVE_BLOB_ROOT` has no
325    /// effect for this backend. Credentials always come from
326    /// `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`/`AWS_SESSION_TOKEN` in the
327    /// process environment, never from this section.
328    S3 {
329        bucket: String,
330        region: String,
331        #[serde(default)]
332        endpoint: Option<String>,
333        #[serde(default)]
334        prefix: Option<String>,
335        #[serde(default)]
336        allow_http: Option<bool>,
337    },
338}
339
340/// `[storage]` section in `khive.toml`. Holds storage-layer config not
341/// already covered by `[[backends]]` (ADR-028).
342#[derive(Debug, Clone, Deserialize, Default)]
343pub struct StorageSectionConfig {
344    /// Blob store backend selector (ADR-111 Amendment 2). Absent means
345    /// `FsBlobStore` at the existing root-resolution precedence, unchanged
346    /// from khive#292 -- existing configurations keep behaving exactly as
347    /// they did before this section existed.
348    #[serde(default)]
349    pub blob: Option<BlobConfig>,
350}
351
352// ---- git-write policy (ADR-108 Amendment) ----
353
354/// One `[[git_write.allowed]]` entry: a repo this operator has declared
355/// trusted for khive-mediated git writes, plus the branches on it a write
356/// verb (`git.commit`/`git.branch`/`git.push`) may target.
357///
358/// ```toml
359/// [[git_write.allowed]]
360/// repo = "/abs/path/repo"
361/// branches = ["feat/*", "fix/*"]
362/// ```
363#[derive(Debug, Clone, Deserialize)]
364pub struct GitWriteEntryConfig {
365    /// Absolute local path to the allowlisted repository.
366    pub repo: String,
367    /// Non-empty list of exact branch names or single-`*`-wildcard globs
368    /// this repo entry permits writes against.
369    pub branches: Vec<String>,
370}
371
372/// `[git_write]` section — the closed repo/branch allowlist consulted by
373/// `khive-pack-git`'s write verbs at the handler level (ADR-108 Amendment),
374/// independent of Gate policy. Absent or empty `allowed` is the fail-closed
375/// default: the write verbs report themselves unavailable rather than
376/// defaulting open.
377///
378/// ```toml
379/// [[git_write.allowed]]
380/// repo = "/abs/path/repo"
381/// branches = ["feat/*", "fix/*"]
382/// ```
383#[derive(Debug, Clone, Deserialize, Default)]
384pub struct GitWriteSectionConfig {
385    #[serde(default)]
386    pub allowed: Vec<GitWriteEntryConfig>,
387}
388
389/// Top-level khive configuration loaded from `khive.toml` or `config.toml`.
390///
391/// Sections consumed today:
392/// - `[[engines]]`: embedding engine declarations
393/// - `[actor]`: default namespace / identity (OSS actor model)
394/// - `[runtime]`: runtime knobs (pack selection, brain profile, output format)
395/// - `[[backends]]`: storage backend declarations (ADR-028)
396/// - `[packs.<name>]`: per-pack backend assignments (ADR-028)
397/// - `[display]`: rendering timezone (ADR-169)
398///
399/// Unknown keys are silently ignored by serde for forward compatibility. The
400/// security-sensitive `[gate]` exception is detected by [`KhiveConfig::load`]
401/// before deserialization so a request for caller enrollment can never be
402/// mistaken for active enforcement.
403#[derive(Debug, Clone, Deserialize, Default)]
404pub struct KhiveConfig {
405    /// Typed only so a top-level `db` key can be rejected loudly by
406    /// [`KhiveConfig::validate`] instead of being silently ignored as an
407    /// unknown key. Not a supported config-file storage selector: single-file
408    /// database selection is `--db`/`KHIVE_DB`, and storage topology is
409    /// `[[backends]].path`.
410    #[serde(default)]
411    pub db: Option<String>,
412
413    /// Embedding engine declarations.
414    #[serde(default)]
415    pub engines: Vec<EngineConfig>,
416
417    /// Default actor identity for this khive instance.
418    ///
419    /// When present, `actor.id` feeds configuration identity and gate/attribution
420    /// policy input.  A non-`'local'` `actor.id` is folded into the default READ
421    /// visible-set at config load (ADR-007 Rev 4 Rule 3b) — it widens what default
422    /// multi-record reads return, but never routes writes or sets `default_namespace`.
423    /// Cloud model derives actor identity from an authenticated token.
424    #[serde(default)]
425    pub actor: ActorConfig,
426
427    /// Runtime knobs: namespace overrides, brain profile, etc.
428    #[serde(default)]
429    pub runtime: RuntimeSectionConfig,
430
431    /// Named storage backends (ADR-028).
432    ///
433    /// When absent or empty, a single implicit `main` backend is used and all
434    /// packs share it — identical to pre-ADR-028 behavior.
435    #[serde(default)]
436    pub backends: Vec<BackendConfig>,
437
438    /// Per-pack backend assignments (ADR-028).
439    ///
440    /// Maps pack name to backend name. Packs absent from this map fall back to
441    /// the `main` backend. Validated at load time: every referenced backend name
442    /// must appear in `backends`.
443    #[serde(default)]
444    pub packs: std::collections::HashMap<String, PackConfig>,
445
446    /// Git-write policy allowlist (ADR-108 Amendment). Absent or empty
447    /// `allowed` fails closed — `khive-pack-git`'s write verbs are
448    /// unavailable until this section is populated.
449    #[serde(default)]
450    pub git_write: GitWriteSectionConfig,
451
452    /// Storage-layer config not covered by `[[backends]]` (ADR-111
453    /// Amendment 2: `[storage.blob]`'s `fs`/`s3` selector).
454    #[serde(default)]
455    pub storage: StorageSectionConfig,
456
457    /// Rendering timezone configuration (ADR-169). Absent `timezone` resolves
458    /// to the host's local zone at [`RuntimeConfig`](crate::RuntimeConfig)
459    /// construction time.
460    #[serde(default)]
461    pub display: DisplaySectionConfig,
462}
463
464/// `[runtime]` section in `khive.toml`.
465///
466/// Carries runtime knobs resolved during process construction. Most mirror a
467/// CLI flag / environment tier; field documentation calls out exceptions.
468/// All fields are optional and preserve their already-resolved base value when
469/// absent.
470#[derive(Debug, Clone, Deserialize, Default)]
471pub struct RuntimeSectionConfig {
472    /// Packs to load when neither `--pack` nor `KHIVE_PACKS` selects them.
473    /// An absent or empty list preserves the built-in production default.
474    #[serde(default)]
475    pub packs: Option<Vec<String>>,
476
477    /// Brain profile ID to use for `memory.feedback` / `knowledge.feedback`
478    /// and recall-time score boosting (ADR-035 §Brain profile configuration).
479    ///
480    /// Mirrors `--brain-profile` / `KHIVE_BRAIN_PROFILE`. When absent, the
481    /// namespace-bound profile (via `brain.resolve`) is tried, then the
482    /// global tuning prior is used as the final fallback.
483    #[serde(default)]
484    pub brain_profile: Option<String>,
485
486    /// Default output serialization format (ADR-078).
487    ///
488    /// Mirrors `--output-format` / `KHIVE_OUTPUT_FORMAT`. Precedence (highest to lowest):
489    /// per-request `format` field → `KHIVE_OUTPUT_FORMAT` → this field → builtin `json`.
490    ///
491    /// Accepted values: `"json"` (default), `"auto"`, `"table"`.
492    #[serde(default)]
493    pub default_output_format: Option<OutputFormat>,
494
495    /// Aggregate process-local admission budget for digest-verified blob
496    /// hydration (ADR-160 D3), in raw bytes.
497    ///
498    /// This knob has no environment-variable counterpart. When absent, the
499    /// resolved runtime keeps its built-in 256 MiB default (or a value supplied
500    /// directly through `RuntimeConfig`).
501    #[serde(default)]
502    pub blob_hydration_bytes: Option<u64>,
503}
504
505/// `[display]` section in `khive.toml` — the timezone khive anchors date-only
506/// input to (ADR-169 Implementation step 1).
507///
508/// ```toml
509/// [display]
510/// timezone = "America/New_York"
511/// ```
512#[derive(Debug, Clone, Deserialize, Default)]
513pub struct DisplaySectionConfig {
514    /// IANA zone name (e.g. `"America/New_York"`, `"Asia/Tokyo"`, `"UTC"`).
515    /// Validated at load time against `chrono_tz::Tz`'s zone table — an
516    /// unrecognized name is a startup error, not a silent fallback. Absent →
517    /// the host's local zone, resolved once via `iana-time-zone` and falling
518    /// back to UTC when the host zone cannot be determined.
519    #[serde(default)]
520    pub timezone: Option<String>,
521}
522
523impl KhiveConfig {
524    /// Load and validate a `KhiveConfig` from an explicit path.
525    ///
526    /// Search order:
527    /// 1. `path` argument (explicit override — e.g. from `--config` / `KHIVE_CONFIG`)
528    /// 2. `./.khive/config.toml` (project-local config, relative to the MCP server cwd)
529    ///
530    /// The project-local default collocates config with the `khive-test.db` that already
531    /// lives under `.khive/` in each project directory. `~/.khive/config.toml` is searched
532    /// by [`KhiveConfig::load_with_home_fallback`] when the project-local file is absent.
533    ///
534    /// If the resolved file does **not exist**, returns `Ok(None)`.
535    /// A missing config is not an error — callers fall back to the env-var path.
536    ///
537    /// If the file exists but cannot be parsed, returns a `ConfigError`.
538    /// After parsing, `validate()` runs and any logical errors are returned.
539    pub fn load(path: Option<&Path>) -> Result<Option<Self>, ConfigError> {
540        let resolved = match path {
541            Some(p) => p.to_path_buf(),
542            None => PathBuf::from(".khive/config.toml"),
543        };
544
545        if !resolved.exists() {
546            return Ok(None);
547        }
548
549        // Diagnostics name the canonical path so an error is actionable from
550        // any cwd; resolution keeps using `resolved` as given.
551        let diagnostic_path = std::fs::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
552        let raw = std::fs::read_to_string(&resolved)
553            .map_err(|source| ConfigError::from(source).in_file(&diagnostic_path))?;
554        let parsed: toml::Value = toml::from_str(&raw).map_err(|source| ConfigError::Parse {
555            path: diagnostic_path.clone(),
556            source,
557        })?;
558        if parsed
559            .as_table()
560            .is_some_and(|table| table.contains_key("gate"))
561        {
562            return Err(ConfigError::UnsupportedGateSection.in_file(&diagnostic_path));
563        }
564        let cfg: KhiveConfig = parsed.try_into().map_err(|source| ConfigError::Parse {
565            path: diagnostic_path.clone(),
566            source,
567        })?;
568        cfg.validate()
569            .map_err(|error| error.in_file(&diagnostic_path))?;
570        Ok(Some(cfg))
571    }
572
573    /// Load config with the full resolution order:
574    ///
575    /// 1. Explicit `path` (from `--config` / `KHIVE_CONFIG`)
576    /// 2. `./khive.toml` (project-local, project root)
577    /// 3. `<db-dir>/config.toml` (project-local, anchored to the resolved database's
578    ///    own directory — see `project_config_anchor_dir`)
579    /// 4. `~/.khive/config.toml` (user-global)
580    ///
581    /// Returns the first file found, or `Ok(None)` when none exist.
582    /// Parse errors are propagated immediately — a malformed config is always
583    /// an error regardless of which tier it came from.
584    ///
585    /// The explicit tier (1) is stricter than the discovery tiers: a `path`
586    /// that names a file which does not exist returns
587    /// [`ConfigError::ExplicitConfigMissing`] instead of falling through to
588    /// tiers 2-4 — an operator-selected config that is missing is the same
589    /// class of mistake as one that is malformed, and silently discovering a
590    /// different file would boot against a config the operator did not select
591    /// (ADR-035).
592    ///
593    /// `db_path` should be the same database path the caller is about to open
594    /// (or has already resolved). Passing it makes tier 3 resolve identically
595    /// for any two processes that target the same database, regardless of
596    /// their process working directory — this is what lets a thin client and
597    /// a warm daemon serving the same database agree on one config file. Pass
598    /// `None` when no database path is known yet; tier 3 then falls back to
599    /// the process cwd, matching the pre-existing behavior.
600    pub fn load_with_home_fallback(
601        path: Option<&Path>,
602        db_path: Option<&Path>,
603    ) -> Result<Option<Self>, ConfigError> {
604        Ok(Self::load_with_home_fallback_and_source(path, db_path)?.map(|(config, _)| config))
605    }
606
607    /// Load config with the full resolution order and retain the exact file
608    /// that supplied it.
609    ///
610    /// This is the diagnostic-preserving form of
611    /// [`KhiveConfig::load_with_home_fallback`]. Runtime callers that need to
612    /// tell an operator which selected file must be edited should use this
613    /// method instead of reconstructing the discovery order independently.
614    pub fn load_with_home_fallback_and_source(
615        path: Option<&Path>,
616        db_path: Option<&Path>,
617    ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
618        // Tier 1: explicit path (highest priority). An explicit selection
619        // naming a MISSING file fails loud here — once, at the loader, for
620        // every entry point — instead of silently falling through to the
621        // discovery tiers: a mistyped path would otherwise boot against a
622        // config the operator did not select (ADR-035: an entry point must
623        // not document an explicit tier while silently falling back to
624        // discovery). Tiers 2-4 keep their tolerant contract.
625        if let Some(p) = path {
626            if !p.exists() {
627                return Err(ConfigError::ExplicitConfigMissing {
628                    path: p.to_path_buf(),
629                });
630            }
631            return Ok(Self::load(Some(p))?.map(|config| (config, Self::diagnostic_config_path(p))));
632        }
633
634        // Tiers 2-4: search project root, db-anchored hidden dir, user-global.
635        let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
636        let home_root = std::env::var_os("HOME").map(PathBuf::from);
637        Self::load_with_roots_and_source(&project_root, home_root.as_deref(), db_path)
638    }
639
640    /// Testable inner search: tiers 2-4, given explicit roots instead of
641    /// reading `cwd` and `HOME` from process state.
642    ///
643    /// - Tier 2: `<project_root>/khive.toml` (still cwd-anchored — unchanged)
644    /// - Tier 3: `<db_dir>/config.toml`, anchored to `db_path` rather than
645    ///   `project_root` (see `project_config_anchor_dir`); falls back to
646    ///   `<project_root>/.khive/config.toml` when `db_path` is `None`
647    /// - Tier 4: `<home_root>/.khive/config.toml` (skipped when `None`)
648    #[cfg(test)]
649    pub(crate) fn load_with_roots(
650        project_root: &Path,
651        home_root: Option<&Path>,
652        db_path: Option<&Path>,
653    ) -> Result<Option<Self>, ConfigError> {
654        Ok(
655            Self::load_with_roots_and_source(project_root, home_root, db_path)?
656                .map(|(config, _)| config),
657        )
658    }
659
660    fn load_with_roots_and_source(
661        project_root: &Path,
662        home_root: Option<&Path>,
663        db_path: Option<&Path>,
664    ) -> Result<Option<(Self, PathBuf)>, ConfigError> {
665        // Tier 2: project root khive.toml.
666        let tier2 = project_root.join("khive.toml");
667        if tier2.exists() {
668            return Ok(Self::load(Some(&tier2))?
669                .map(|config| (config, Self::diagnostic_config_path(&tier2))));
670        }
671
672        // Tier 3: project-local hidden dir, anchored to the resolved database's
673        // own directory instead of the process cwd.
674        let tier3 = Self::project_config_anchor_dir(db_path, project_root).join("config.toml");
675        if tier3.exists() {
676            return Ok(Self::load(Some(&tier3))?
677                .map(|config| (config, Self::diagnostic_config_path(&tier3))));
678        }
679
680        // Tier 4: user-global ~/.khive/config.toml.
681        if let Some(home) = home_root {
682            let tier4 = home.join(".khive/config.toml");
683            if tier4.exists() {
684                return Ok(Self::load(Some(&tier4))?
685                    .map(|config| (config, Self::diagnostic_config_path(&tier4))));
686            }
687        }
688
689        Ok(None)
690    }
691
692    fn diagnostic_config_path(path: &Path) -> PathBuf {
693        std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
694    }
695
696    /// Resolve the directory searched for the tier-3 project-local config file.
697    ///
698    /// Anchored to the directory containing the resolved database file, not the
699    /// process cwd: two processes at different working directories that open the
700    /// same database agree on this directory, which is what keeps their
701    /// `config_id` fingerprints in sync (a client and a warm daemon serving the
702    /// same database must resolve identical config so the daemon accepts the
703    /// client's forwarded requests instead of rejecting them on a config
704    /// mismatch).
705    ///
706    /// `db_path` is canonicalized first so symlinks/relative components collapse
707    /// to the same absolute directory regardless of caller cwd. The database file
708    /// may not exist yet (first run before anything has been written) — in that
709    /// case canonicalization fails and the path is absolutized against
710    /// `project_root` instead (or used as-is if already absolute); this must
711    /// never panic, it is the expected cold-start case.
712    ///
713    /// If `db_dir` (the resolved database's parent directory) is itself named
714    /// `.khive`, the config lives directly inside it (`<db_dir>/config.toml`) —
715    /// this is the common case where the database is `<root>/.khive/khive.db`.
716    /// Otherwise the config lives in a `.khive` subdirectory of `db_dir`.
717    ///
718    /// `db_path == None` (e.g. an in-memory database, or no database path known
719    /// yet) falls back to `<project_root>/.khive`, preserving the pre-existing
720    /// cwd-anchored behavior for callers with no database to anchor on.
721    fn project_config_anchor_dir(db_path: Option<&Path>, project_root: &Path) -> PathBuf {
722        let Some(db_path) = db_path else {
723            return project_root.join(".khive");
724        };
725
726        let absolute = std::fs::canonicalize(db_path).unwrap_or_else(|_| {
727            if db_path.is_absolute() {
728                db_path.to_path_buf()
729            } else {
730                project_root.join(db_path)
731            }
732        });
733
734        let db_dir = absolute.parent().map(Path::to_path_buf).unwrap_or(absolute);
735
736        if db_dir.file_name().is_some_and(|name| name == ".khive") {
737            db_dir
738        } else {
739            db_dir.join(".khive")
740        }
741    }
742
743    /// Validate the parsed config for logical consistency.
744    ///
745    /// Checks:
746    /// - Exactly one engine has `default = true` (when the list is non-empty).
747    /// - Engine names are unique.
748    /// - `fusion_weight`, when present, is `> 0`.
749    ///
750    /// Model name validity is checked lazily at runtime (the config loader does
751    /// not import `lattice_embed` directly to keep the dep surface minimal).
752    pub fn validate(&self) -> Result<(), ConfigError> {
753        // Reject a top-level `db` key loudly instead of letting serde's
754        // forward-compatible unknown-key tolerance silently swallow it: a
755        // config author expecting `db=` to select the database would
756        // otherwise get silent divergence from `--db`/`KHIVE_DB`.
757        if let Some(value) = self.db.as_deref() {
758            if !value.is_empty() {
759                return Err(ConfigError::UnsupportedTopLevelDb {
760                    value: value.to_string(),
761                });
762            }
763        }
764
765        if let Some(value) = self.runtime.blob_hydration_bytes {
766            let min = khive_storage::MAX_BLOB_WHOLE_BYTES;
767            let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
768            if value < min || value > max {
769                return Err(ConfigError::InvalidBlobHydrationBytes { value, min, max });
770            }
771        }
772
773        // Validate actor.id when present — an invalid namespace is a startup error,
774        // not a silent fallback.
775        if let Some(id) = self.actor.id.as_deref() {
776            if id.is_empty() {
777                return Err(ConfigError::InvalidActorId {
778                    id: id.to_string(),
779                    reason: "actor.id must not be empty; remove the key or provide a value"
780                        .to_string(),
781                });
782            }
783            Namespace::parse(id).map_err(|e| ConfigError::InvalidActorId {
784                id: id.to_string(),
785                reason: e.to_string(),
786            })?;
787        }
788
789        if let Some(ref vis) = self.actor.visible_namespaces {
790            for ns_str in vis {
791                if ns_str.is_empty() {
792                    return Err(ConfigError::InvalidActorId {
793                        id: ns_str.clone(),
794                        reason: "visible_namespaces entries must not be empty".to_string(),
795                    });
796                }
797                Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
798                    id: ns_str.clone(),
799                    reason: format!("invalid visible namespace: {e}"),
800                })?;
801            }
802        }
803
804        // Validate actor.allowed_outbound_namespaces (fail-closed at startup on malformed entry).
805        for ns_str in &self.actor.allowed_outbound_namespaces {
806            if ns_str.is_empty() {
807                return Err(ConfigError::InvalidActorId {
808                    id: ns_str.clone(),
809                    reason: "allowed_outbound_namespaces entries must not be empty".to_string(),
810                });
811            }
812            Namespace::parse(ns_str).map_err(|e| ConfigError::InvalidActorId {
813                id: ns_str.clone(),
814                reason: format!("invalid allowed_outbound_namespaces entry: {e}"),
815            })?;
816        }
817
818        // Backend names must be unique.
819        if !self.backends.is_empty() {
820            let mut seen_backends = std::collections::HashSet::new();
821            for backend in &self.backends {
822                if !seen_backends.insert(backend.name.clone()) {
823                    return Err(ConfigError::DuplicateBackendName {
824                        name: backend.name.clone(),
825                    });
826                }
827
828                // Reject fields that are parsed but not yet implemented: silently
829                // accepting them would let misconfiguration slip past startup.
830                if backend.cache_mb.is_some() {
831                    return Err(ConfigError::UnsupportedBackendField {
832                        name: backend.name.clone(),
833                        field: "cache_mb",
834                    });
835                }
836                if backend.journal_mode.is_some() {
837                    return Err(ConfigError::UnsupportedBackendField {
838                        name: backend.name.clone(),
839                        field: "journal_mode",
840                    });
841                }
842            }
843
844            // Every pack-referenced backend name must be declared in `backends`.
845            let defined: Vec<&str> = self.backends.iter().map(|b| b.name.as_str()).collect();
846            for (pack_name, pack_cfg) in &self.packs {
847                if !defined.contains(&pack_cfg.backend.as_str()) {
848                    return Err(ConfigError::UnknownPackBackend {
849                        pack: pack_name.clone(),
850                        backend: pack_cfg.backend.clone(),
851                        defined: defined.join(", "),
852                    });
853                }
854            }
855        }
856
857        // Validate [display] timezone (ADR-169): an unrecognized IANA zone
858        // name is a startup error, not a silent fallback to the host zone.
859        if let Some(tz) = self.display.timezone.as_deref() {
860            if tz.trim().is_empty() || tz.parse::<chrono_tz::Tz>().is_err() {
861                return Err(ConfigError::InvalidDisplayTimezone {
862                    timezone: tz.to_string(),
863                });
864            }
865        }
866
867        // Validate [[git_write.allowed]] entries (ADR-108 Amendment): each
868        // repo must be a non-empty absolute path, and each entry must carry
869        // at least one branch pattern — an entry with an empty `branches`
870        // list would silently allowlist a repo for no branch at all, which
871        // reads as "configured" while behaving identically to "not
872        // allowlisted"; reject it loudly instead of leaving that trap.
873        for entry in &self.git_write.allowed {
874            if entry.repo.trim().is_empty() {
875                return Err(ConfigError::InvalidGitWriteEntry {
876                    repo: entry.repo.clone(),
877                    reason: "repo must not be empty".to_string(),
878                });
879            }
880            if !Path::new(&entry.repo).is_absolute() {
881                return Err(ConfigError::InvalidGitWriteEntry {
882                    repo: entry.repo.clone(),
883                    reason: "repo must be an absolute path".to_string(),
884                });
885            }
886            if entry.branches.is_empty() {
887                return Err(ConfigError::InvalidGitWriteEntry {
888                    repo: entry.repo.clone(),
889                    reason: "branches must not be empty".to_string(),
890                });
891            }
892            if entry.branches.iter().any(|b| b.trim().is_empty()) {
893                return Err(ConfigError::InvalidGitWriteEntry {
894                    repo: entry.repo.clone(),
895                    reason: "branches entries must not be empty".to_string(),
896                });
897            }
898            // ADR-108 specifies exact name or a SINGLE-star wildcard per
899            // branch pattern -- a pattern with two or more `*` (e.g. `**`,
900            // `rel-*-*-final`) is a wider grammar than the ADR authorizes
901            // and must be rejected at config load, not silently accepted.
902            if let Some(bad) = entry.branches.iter().find(|b| b.matches('*').count() > 1) {
903                return Err(ConfigError::InvalidGitWriteEntry {
904                    repo: entry.repo.clone(),
905                    reason: format!(
906                        "branch pattern {bad:?} must contain at most one '*' wildcard (ADR-108)"
907                    ),
908                });
909            }
910        }
911
912        if self.engines.is_empty() {
913            return Ok(());
914        }
915
916        let mut seen_names = std::collections::HashSet::new();
917        for engine in &self.engines {
918            if !seen_names.insert(engine.name.clone()) {
919                return Err(ConfigError::DuplicateName {
920                    name: engine.name.clone(),
921                });
922            }
923        }
924
925        let default_count = self.engines.iter().filter(|e| e.default).count();
926        if default_count != 1 {
927            return Err(ConfigError::DefaultCount {
928                found: default_count,
929            });
930        }
931
932        // Reject non-finite fusion_weight explicitly: NaN doesn't satisfy `w <= 0.0`
933        // and +inf is unbounded, so neither is caught by the range check alone.
934        for engine in &self.engines {
935            if let Some(w) = engine.fusion_weight {
936                if !w.is_finite() || w <= 0.0 {
937                    return Err(ConfigError::InvalidFusionWeight {
938                        name: engine.name.clone(),
939                        value: w,
940                    });
941                }
942            }
943        }
944
945        Ok(())
946    }
947
948    /// Return the engine flagged `default = true`, or `None` if the list is empty.
949    pub fn default_engine(&self) -> Option<&EngineConfig> {
950        self.engines.iter().find(|e| e.default)
951    }
952}
953
954// ---- Env-var fallback ----
955
956/// Build an in-memory `KhiveConfig` from the legacy env-var path.
957///
958/// Used when no config file is present. Emits `tracing::info!` directing
959/// operators to migrate to `~/.khive/config.toml`.
960///
961/// The primary model (`KHIVE_EMBEDDING_MODEL`) becomes the `default = true`
962/// engine; additional models become non-default secondary engines. When only
963/// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` is set, the built-in default model is
964/// synthesized as the primary — the additional list is additive, never a
965/// replacement for the primary (khive#1221; matches `RuntimeConfig::default()`,
966/// which resolves an unset `KHIVE_EMBEDDING_MODEL` to the built-in default).
967pub fn config_from_env() -> KhiveConfig {
968    let primary_model = std::env::var("KHIVE_EMBEDDING_MODEL")
969        .ok()
970        .filter(|s| !s.trim().is_empty());
971    let additional_raw = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
972        .ok()
973        .unwrap_or_default();
974    let additional: Vec<String> = crate::runtime::parse_pack_list(&additional_raw)
975        .into_iter()
976        .filter(|s| !s.is_empty())
977        .collect();
978
979    if primary_model.is_none() && additional.is_empty() {
980        return KhiveConfig::default();
981    }
982
983    tracing::info!(
984        "using env-var embedding config; consider migrating to .khive/config.toml in your project root"
985    );
986
987    config_from_env_parts(primary_model, additional)
988}
989
990/// Pure core of [`config_from_env`], separated so the engine-list derivation
991/// is testable without mutating process-global environment variables.
992fn config_from_env_parts(primary_model: Option<String>, additional: Vec<String>) -> KhiveConfig {
993    let mut engines = Vec::new();
994
995    let primary =
996        primary_model.unwrap_or_else(|| lattice_embed::EmbeddingModel::AllMiniLmL6V2.to_string());
997    engines.push(EngineConfig {
998        name: "default".to_string(),
999        model: primary.clone(),
1000        default: true,
1001        fusion_weight: None,
1002        dims: None,
1003    });
1004
1005    for (i, model) in additional.into_iter().enumerate() {
1006        // The additional list restating the primary is a no-op, not a second engine.
1007        if model.eq_ignore_ascii_case(&primary) {
1008            continue;
1009        }
1010        engines.push(EngineConfig {
1011            name: format!("engine-{}", i + 1),
1012            model,
1013            default: false,
1014            fusion_weight: None,
1015            dims: None,
1016        });
1017    }
1018
1019    KhiveConfig {
1020        engines,
1021        ..KhiveConfig::default()
1022    }
1023}
1024
1025// ---- Tests ----
1026
1027// Kept inline (not tests/): exercises private ConfigError variants not part
1028// of the public API.
1029#[cfg(test)]
1030mod tests {
1031    use super::*;
1032
1033    fn write_toml(dir: &tempfile::TempDir, content: &str) -> PathBuf {
1034        let path = dir.path().join("config.toml");
1035        std::fs::write(&path, content).unwrap();
1036        path
1037    }
1038
1039    /// Load errors must name the config file they came from (#1892): the
1040    /// gate refusal, validation errors, and I/O errors gain the loader's
1041    /// `InFile` context, while `Parse` keeps carrying its own path. The
1042    /// message suffix is the user-facing contract.
1043    #[test]
1044    fn load_errors_name_the_config_file() {
1045        let dir = tempfile::tempdir().unwrap();
1046
1047        let gate = write_toml(&dir, "[gate]\nmode = \"x\"\n");
1048        let err = KhiveConfig::load(Some(&gate)).expect_err("gate section must fail");
1049        assert!(
1050            err.to_string().contains("(config file: ") && err.to_string().contains("config.toml"),
1051            "gate error must name the file, got: {err}"
1052        );
1053
1054        let invalid = write_toml(
1055            &dir,
1056            "[[engines]]\nname = \"a\"\nmodel = \"all-minilm-l6-v2\"\n",
1057        );
1058        let err = KhiveConfig::load(Some(&invalid)).expect_err("validation must fail");
1059        assert!(
1060            err.to_string().contains("(config file: "),
1061            "validation error must name the file, got: {err}"
1062        );
1063
1064        let parse = write_toml(&dir, "not = = toml");
1065        let err = KhiveConfig::load(Some(&parse)).expect_err("parse must fail");
1066        assert!(
1067            err.to_string().contains("config.toml"),
1068            "parse error must name the file, got: {err}"
1069        );
1070        assert!(
1071            matches!(err, ConfigError::Parse { .. }),
1072            "parse errors keep their own variant unwrapped, got: {err:?}"
1073        );
1074    }
1075
1076    /// Unwrap the loader's `InFile` context (asserting it names a real path)
1077    /// so variant-shape assertions test the underlying error.
1078    fn config_error_root(err: &ConfigError) -> &ConfigError {
1079        match err {
1080            ConfigError::InFile { path, source } => {
1081                assert!(
1082                    !path.as_os_str().is_empty(),
1083                    "InFile must carry the config path"
1084                );
1085                source
1086            }
1087            other => other,
1088        }
1089    }
1090
1091    // khive#1221: with no primary set, the additional list must ADD to the
1092    // built-in default primary, never replace it.
1093    #[test]
1094    fn env_additional_only_keeps_builtin_primary() {
1095        let cfg = super::config_from_env_parts(
1096            None,
1097            vec!["paraphrase-multilingual-minilm-l12-v2".to_string()],
1098        );
1099        assert_eq!(cfg.engines.len(), 2);
1100        let default_engine = cfg.default_engine().expect("a default engine");
1101        assert_eq!(default_engine.model, "all-minilm-l6-v2");
1102        assert!(
1103            cfg.engines
1104                .iter()
1105                .any(|e| !e.default && e.model == "paraphrase-multilingual-minilm-l12-v2"),
1106            "additional model must be a non-default secondary engine"
1107        );
1108    }
1109
1110    #[test]
1111    fn env_explicit_primary_stays_primary() {
1112        let cfg = super::config_from_env_parts(
1113            Some("paraphrase-multilingual-minilm-l12-v2".to_string()),
1114            vec![],
1115        );
1116        assert_eq!(cfg.engines.len(), 1);
1117        assert_eq!(
1118            cfg.default_engine().expect("default").model,
1119            "paraphrase-multilingual-minilm-l12-v2"
1120        );
1121    }
1122
1123    #[test]
1124    fn env_additional_restating_primary_is_deduped() {
1125        let cfg = super::config_from_env_parts(None, vec!["all-minilm-l6-v2".to_string()]);
1126        assert_eq!(cfg.engines.len(), 1);
1127        assert!(cfg.engines[0].default);
1128    }
1129
1130    #[test]
1131    fn test_load_minimal_config() {
1132        let dir = tempfile::tempdir().unwrap();
1133        let path = write_toml(
1134            &dir,
1135            r#"
1136[[engines]]
1137name = "x"
1138model = "all-minilm-l6-v2"
1139default = true
1140"#,
1141        );
1142        let cfg = KhiveConfig::load(Some(&path))
1143            .expect("load should succeed")
1144            .expect("file should be found");
1145        assert_eq!(cfg.engines.len(), 1);
1146        assert_eq!(cfg.engines[0].name, "x");
1147        assert_eq!(cfg.engines[0].model, "all-minilm-l6-v2");
1148        assert!(cfg.engines[0].default);
1149    }
1150
1151    #[test]
1152    fn test_default_engine_required_when_engines_present() {
1153        let dir = tempfile::tempdir().unwrap();
1154        let path = write_toml(
1155            &dir,
1156            r#"
1157[[engines]]
1158name = "a"
1159model = "all-minilm-l6-v2"
1160"#,
1161        );
1162        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with no default flagged");
1163        assert!(
1164            matches!(
1165                config_error_root(&err),
1166                ConfigError::DefaultCount { found: 0 }
1167            ),
1168            "expected DefaultCount {{ found: 0 }}, got {err:?}"
1169        );
1170    }
1171
1172    #[test]
1173    fn test_multiple_default_rejected() {
1174        let dir = tempfile::tempdir().unwrap();
1175        let path = write_toml(
1176            &dir,
1177            r#"
1178[[engines]]
1179name = "a"
1180model = "all-minilm-l6-v2"
1181default = true
1182
1183[[engines]]
1184name = "b"
1185model = "paraphrase-multilingual-minilm-l12-v2"
1186default = true
1187"#,
1188        );
1189        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with two defaults");
1190        assert!(
1191            matches!(
1192                config_error_root(&err),
1193                ConfigError::DefaultCount { found: 2 }
1194            ),
1195            "expected DefaultCount {{ found: 2 }}, got {err:?}"
1196        );
1197    }
1198
1199    #[test]
1200    fn test_fusion_weight_validation() {
1201        let dir = tempfile::tempdir().unwrap();
1202        let path = write_toml(
1203            &dir,
1204            r#"
1205[[engines]]
1206name = "a"
1207model = "all-minilm-l6-v2"
1208default = true
1209fusion_weight = -0.5
1210"#,
1211        );
1212        let err =
1213            KhiveConfig::load(Some(&path)).expect_err("should fail with negative fusion_weight");
1214        assert!(
1215            matches!(
1216                config_error_root(&err),
1217                ConfigError::InvalidFusionWeight { .. }
1218            ),
1219            "expected InvalidFusionWeight, got {err:?}"
1220        );
1221
1222        let path2 = write_toml(
1223            &dir,
1224            r#"
1225[[engines]]
1226name = "a"
1227model = "all-minilm-l6-v2"
1228default = true
1229fusion_weight = 0.0
1230"#,
1231        );
1232        let err2 =
1233            KhiveConfig::load(Some(&path2)).expect_err("should fail with zero fusion_weight");
1234        assert!(
1235            matches!(
1236                config_error_root(&err2),
1237                ConfigError::InvalidFusionWeight { .. }
1238            ),
1239            "expected InvalidFusionWeight, got {err2:?}"
1240        );
1241    }
1242
1243    #[test]
1244    fn test_env_var_fallback() {
1245        let dir = tempfile::tempdir().unwrap();
1246        let absent = dir.path().join("missing.toml");
1247
1248        let loaded = KhiveConfig::load(Some(&absent)).unwrap();
1249        assert!(loaded.is_none());
1250
1251        // Can't safely set env vars in a parallel test suite, so exercise the
1252        // direct construction path instead.
1253        let primary = "all-minilm-l6-v2".to_string();
1254        let additional = vec!["paraphrase-multilingual-minilm-l12-v2".to_string()];
1255
1256        let mut engines = vec![EngineConfig {
1257            name: "default".to_string(),
1258            model: primary,
1259            default: true,
1260            fusion_weight: None,
1261            dims: None,
1262        }];
1263        for (i, model) in additional.into_iter().enumerate() {
1264            engines.push(EngineConfig {
1265                name: format!("engine-{}", i + 1),
1266                model,
1267                default: false,
1268                fusion_weight: None,
1269                dims: None,
1270            });
1271        }
1272        let cfg = KhiveConfig {
1273            engines,
1274            ..KhiveConfig::default()
1275        };
1276        cfg.validate().expect("env-derived config should be valid");
1277        assert_eq!(cfg.engines.len(), 2);
1278        assert!(cfg.default_engine().is_some());
1279        assert_eq!(cfg.default_engine().unwrap().name, "default");
1280    }
1281
1282    #[test]
1283    fn test_file_overrides_env() {
1284        let dir = tempfile::tempdir().unwrap();
1285        let path = write_toml(
1286            &dir,
1287            r#"
1288[[engines]]
1289name = "file-engine"
1290model = "all-minilm-l6-v2"
1291default = true
1292"#,
1293        );
1294
1295        // KhiveConfig::load returns the file config regardless of env vars;
1296        // warning-on-conflict is the caller's responsibility.
1297        let cfg = KhiveConfig::load(Some(&path))
1298            .expect("load should succeed")
1299            .expect("file should be present");
1300        assert_eq!(cfg.engines[0].name, "file-engine");
1301    }
1302
1303    #[test]
1304    fn test_duplicate_engine_names_rejected() {
1305        let dir = tempfile::tempdir().unwrap();
1306        let path = write_toml(
1307            &dir,
1308            r#"
1309[[engines]]
1310name = "shared"
1311model = "all-minilm-l6-v2"
1312default = true
1313
1314[[engines]]
1315name = "shared"
1316model = "paraphrase-multilingual-minilm-l12-v2"
1317"#,
1318        );
1319        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
1320        assert!(
1321            matches!(config_error_root(&err), ConfigError::DuplicateName { .. }),
1322            "expected DuplicateName, got {err:?}"
1323        );
1324    }
1325
1326    #[test]
1327    fn test_empty_config_is_valid() {
1328        let dir = tempfile::tempdir().unwrap();
1329        let path = write_toml(&dir, "# no engines\n");
1330        let cfg = KhiveConfig::load(Some(&path))
1331            .expect("load should succeed")
1332            .expect("file should be found");
1333        assert!(cfg.engines.is_empty());
1334        cfg.validate().expect("empty config should be valid");
1335    }
1336
1337    #[test]
1338    fn runtime_blob_hydration_budget_parses_and_resolves_before_engine_early_return() {
1339        use crate::runtime::runtime_config_from_khive_config;
1340        use crate::RuntimeConfig;
1341
1342        let dir = tempfile::tempdir().unwrap();
1343        let path = write_toml(
1344            &dir,
1345            r#"
1346[runtime]
1347blob_hydration_bytes = 134217728
1348"#,
1349        );
1350        let cfg = KhiveConfig::load(Some(&path))
1351            .expect("load should succeed")
1352            .expect("file should be found");
1353
1354        assert_eq!(cfg.runtime.blob_hydration_bytes, Some(134_217_728));
1355        let resolved = runtime_config_from_khive_config(&cfg, RuntimeConfig::default());
1356        assert_eq!(resolved.blob_hydration_bytes, 134_217_728);
1357    }
1358
1359    #[test]
1360    fn runtime_blob_hydration_budget_below_one_whole_blob_is_rejected() {
1361        let dir = tempfile::tempdir().unwrap();
1362        let value = khive_storage::MAX_BLOB_WHOLE_BYTES - 1;
1363        let path = write_toml(
1364            &dir,
1365            &format!("[runtime]\nblob_hydration_bytes = {value}\n"),
1366        );
1367
1368        let err = KhiveConfig::load(Some(&path)).expect_err("undersized budget must fail closed");
1369        assert!(
1370            matches!(
1371                config_error_root(&err),
1372                ConfigError::InvalidBlobHydrationBytes {
1373                    value: actual,
1374                    min,
1375                    ..
1376                } if *actual == value && *min == khive_storage::MAX_BLOB_WHOLE_BYTES
1377            ),
1378            "got {err:?}"
1379        );
1380    }
1381
1382    #[test]
1383    fn runtime_blob_hydration_budget_accepts_the_inclusive_portable_minimum() {
1384        let dir = tempfile::tempdir().unwrap();
1385        let value = khive_storage::MAX_BLOB_WHOLE_BYTES;
1386        let path = write_toml(
1387            &dir,
1388            &format!("[runtime]\nblob_hydration_bytes = {value}\n"),
1389        );
1390
1391        let cfg = KhiveConfig::load(Some(&path))
1392            .expect("the inclusive minimum must be valid")
1393            .expect("config should exist");
1394        assert_eq!(cfg.runtime.blob_hydration_bytes, Some(value));
1395    }
1396
1397    #[test]
1398    fn runtime_blob_hydration_budget_above_semaphore_capacity_is_rejected() {
1399        let dir = tempfile::tempdir().unwrap();
1400        let max = tokio::sync::Semaphore::MAX_PERMITS as u64;
1401        let value = max
1402            .checked_add(1)
1403            .expect("tokio maximum fits below u64::MAX");
1404        let path = write_toml(
1405            &dir,
1406            &format!("[runtime]\nblob_hydration_bytes = {value}\n"),
1407        );
1408
1409        let err = KhiveConfig::load(Some(&path)).expect_err("oversized budget must fail closed");
1410        assert!(
1411            matches!(
1412                config_error_root(&err),
1413                ConfigError::InvalidBlobHydrationBytes {
1414                    value: actual,
1415                    max: actual_max,
1416                    ..
1417                } if *actual == value && *actual_max == max
1418            ),
1419            "got {err:?}"
1420        );
1421    }
1422
1423    #[test]
1424    fn test_multi_engine_positive_fusion_weight() {
1425        let dir = tempfile::tempdir().unwrap();
1426        let path = write_toml(
1427            &dir,
1428            r#"
1429[[engines]]
1430name = "primary"
1431model = "all-minilm-l6-v2"
1432default = true
1433fusion_weight = 0.7
1434
1435[[engines]]
1436name = "secondary"
1437model = "paraphrase-multilingual-minilm-l12-v2"
1438fusion_weight = 0.3
1439"#,
1440        );
1441        let cfg = KhiveConfig::load(Some(&path))
1442            .expect("load should succeed")
1443            .expect("file should be found");
1444        assert_eq!(cfg.engines.len(), 2);
1445        assert_eq!(cfg.engines[0].fusion_weight, Some(0.7));
1446        assert_eq!(cfg.engines[1].fusion_weight, Some(0.3));
1447    }
1448
1449    #[test]
1450    fn test_actor_id_parsed() {
1451        let dir = tempfile::tempdir().unwrap();
1452        let path = write_toml(
1453            &dir,
1454            r#"
1455[actor]
1456id = "lambda:khive"
1457display_name = "example actor"
1458"#,
1459        );
1460        let cfg = KhiveConfig::load(Some(&path))
1461            .expect("load should succeed")
1462            .expect("file should be found");
1463        assert_eq!(cfg.actor.id.as_deref(), Some("lambda:khive"));
1464        assert_eq!(cfg.actor.display_name.as_deref(), Some("example actor"));
1465        assert!(cfg.engines.is_empty());
1466    }
1467
1468    #[test]
1469    fn test_actor_and_engines_together() {
1470        let dir = tempfile::tempdir().unwrap();
1471        let path = write_toml(
1472            &dir,
1473            r#"
1474[actor]
1475id = "lambda:test"
1476
1477[[engines]]
1478name = "default"
1479model = "all-minilm-l6-v2"
1480default = true
1481"#,
1482        );
1483        let cfg = KhiveConfig::load(Some(&path))
1484            .expect("load should succeed")
1485            .expect("file should be found");
1486        assert_eq!(cfg.actor.id.as_deref(), Some("lambda:test"));
1487        assert_eq!(cfg.engines.len(), 1);
1488    }
1489
1490    #[test]
1491    fn test_actor_absent_defaults_to_none() {
1492        let dir = tempfile::tempdir().unwrap();
1493        let path = write_toml(
1494            &dir,
1495            r#"
1496[[engines]]
1497name = "x"
1498model = "all-minilm-l6-v2"
1499default = true
1500"#,
1501        );
1502        let cfg = KhiveConfig::load(Some(&path))
1503            .expect("load should succeed")
1504            .expect("file should be found");
1505        assert!(
1506            cfg.actor.id.is_none(),
1507            "actor.id must be None when [actor] section is absent"
1508        );
1509    }
1510
1511    #[test]
1512    fn test_load_with_home_fallback_no_files() {
1513        let project_dir = tempfile::tempdir().unwrap();
1514        let home_dir = tempfile::tempdir().unwrap();
1515        let result = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None);
1516        assert!(
1517            result.expect("no error expected").is_none(),
1518            "should return None when no config files exist in the given roots"
1519        );
1520    }
1521
1522    #[test]
1523    fn home_gate_config_is_rejected_while_explicit_empty_config_is_hermetic() {
1524        let project_dir = tempfile::tempdir().unwrap();
1525        let home_dir = tempfile::tempdir().unwrap();
1526        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1527        std::fs::write(
1528            home_dir.path().join(".khive/config.toml"),
1529            "[gate]\ngranted_actors = [\"lambda:enrolled\"]\n",
1530        )
1531        .unwrap();
1532
1533        let err = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1534            .expect_err("an unsupported home gate policy must still fail loud");
1535        assert!(matches!(
1536            config_error_root(&err),
1537            ConfigError::UnsupportedGateSection
1538        ));
1539
1540        let empty = project_dir.path().join("empty-khive-config.toml");
1541        std::fs::write(&empty, "").unwrap();
1542        let isolated = KhiveConfig::load_with_home_fallback(Some(&empty), None)
1543            .expect("an explicit empty fixture must isolate config discovery")
1544            .expect("the explicit config exists");
1545        assert!(isolated.engines.is_empty());
1546        assert!(isolated.actor.id.is_none());
1547    }
1548
1549    #[test]
1550    fn test_load_with_home_fallback_explicit_path() {
1551        let dir = tempfile::tempdir().unwrap();
1552        let path = write_toml(
1553            &dir,
1554            r#"
1555[actor]
1556id = "lambda:explicit"
1557"#,
1558        );
1559        let cfg = KhiveConfig::load_with_home_fallback(Some(&path), None)
1560            .expect("no error expected")
1561            .expect("file found");
1562        assert_eq!(cfg.actor.id.as_deref(), Some("lambda:explicit"));
1563    }
1564
1565    #[test]
1566    fn load_with_home_fallback_and_source_names_selected_file() {
1567        let project_dir = tempfile::tempdir().unwrap();
1568        let home_dir = tempfile::tempdir().unwrap();
1569        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1570        let selected = home_dir.path().join(".khive/config.toml");
1571        std::fs::write(&selected, "[actor]\nid = \"lambda:home\"\n").unwrap();
1572
1573        let (config, source) = KhiveConfig::load_with_roots_and_source(
1574            project_dir.path(),
1575            Some(home_dir.path()),
1576            None,
1577        )
1578        .expect("load should succeed")
1579        .expect("home fallback should be selected");
1580
1581        assert_eq!(config.actor.id.as_deref(), Some("lambda:home"));
1582        assert_eq!(
1583            source,
1584            std::fs::canonicalize(selected).expect("canonical selected config path")
1585        );
1586    }
1587
1588    #[test]
1589    fn test_invalid_actor_id_rejected_at_load() {
1590        let dir = tempfile::tempdir().unwrap();
1591        let path = write_toml(
1592            &dir,
1593            r#"
1594[actor]
1595id = "bad namespace"
1596"#,
1597        );
1598        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with invalid actor.id");
1599        assert!(
1600            matches!(config_error_root(&err), ConfigError::InvalidActorId { .. }),
1601            "expected InvalidActorId, got {err:?}"
1602        );
1603    }
1604
1605    #[test]
1606    fn test_empty_actor_id_rejected() {
1607        let dir = tempfile::tempdir().unwrap();
1608        let path = write_toml(
1609            &dir,
1610            r#"
1611[actor]
1612id = ""
1613"#,
1614        );
1615        let err = KhiveConfig::load(Some(&path)).expect_err("empty actor.id should be rejected");
1616        assert!(
1617            matches!(config_error_root(&err), ConfigError::InvalidActorId { .. }),
1618            "expected InvalidActorId for empty string, got {err:?}"
1619        );
1620    }
1621
1622    #[test]
1623    fn test_malformed_actor_id_lambda_colon_only() {
1624        let dir = tempfile::tempdir().unwrap();
1625        let path = write_toml(
1626            &dir,
1627            r#"
1628[actor]
1629id = "lambda:"
1630"#,
1631        );
1632        let err =
1633            KhiveConfig::load(Some(&path)).expect_err("lambda: with no slug should be rejected");
1634        assert!(
1635            matches!(config_error_root(&err), ConfigError::InvalidActorId { .. }),
1636            "expected InvalidActorId for 'lambda:', got {err:?}"
1637        );
1638    }
1639
1640    // actor.id must not become default_namespace: writes stay pinned to `local`
1641    // even though a non-local actor.id widens the default read visible-set.
1642    #[test]
1643    fn test_runtime_config_actor_id_does_not_override_namespace() {
1644        use crate::runtime::runtime_config_from_khive_config;
1645        use crate::RuntimeConfig;
1646        use khive_types::namespace::Namespace;
1647
1648        let cfg = KhiveConfig {
1649            engines: vec![],
1650            actor: ActorConfig {
1651                id: Some("lambda:test-actor".to_string()),
1652                display_name: None,
1653                ..Default::default()
1654            },
1655            ..KhiveConfig::default()
1656        };
1657        cfg.validate().expect("valid config");
1658
1659        let base = RuntimeConfig::default();
1660        let result = runtime_config_from_khive_config(&cfg, base);
1661        assert_eq!(
1662            result.default_namespace,
1663            Namespace::local(),
1664            "actor.id must NOT become default_namespace (ADR-007 Rev 4 Rule 0); \
1665             writes stay pinned to local"
1666        );
1667        // actor.id must also appear in visible_namespaces: the load-bearing
1668        // side effect that widens default reads to {local} ∪ {actor namespace}.
1669        assert!(
1670            result
1671                .visible_namespaces
1672                .contains(&Namespace::parse("lambda:test-actor").unwrap()),
1673            "actor.id must be folded into visible_namespaces (ADR-007 Rev 4 Rule 3b fold-in); \
1674             got: {:?}",
1675            result.visible_namespaces
1676        );
1677    }
1678
1679    #[test]
1680    fn test_runtime_config_no_actor_preserves_base() {
1681        use crate::runtime::runtime_config_from_khive_config;
1682        use crate::RuntimeConfig;
1683        use khive_types::namespace::Namespace;
1684
1685        let cfg = KhiveConfig {
1686            engines: vec![],
1687            actor: ActorConfig {
1688                id: None,
1689                display_name: None,
1690                ..Default::default()
1691            },
1692            ..KhiveConfig::default()
1693        };
1694        cfg.validate().expect("valid config");
1695
1696        let base_ns = Namespace::parse("lambda:base").unwrap();
1697        let base = RuntimeConfig {
1698            default_namespace: base_ns.clone(),
1699            ..RuntimeConfig::default()
1700        };
1701        let result = runtime_config_from_khive_config(&cfg, base);
1702        assert_eq!(
1703            result.default_namespace, base_ns,
1704            "no actor.id must leave base namespace unchanged"
1705        );
1706    }
1707
1708    #[test]
1709    fn test_load_with_home_fallback_project_root_over_hidden() {
1710        let dir = tempfile::tempdir().unwrap();
1711
1712        // Write .khive/config.toml (tier 3).
1713        std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
1714        std::fs::write(
1715            dir.path().join(".khive/config.toml"),
1716            "[actor]\nid = \"lambda:hidden\"\n",
1717        )
1718        .unwrap();
1719
1720        // Write khive.toml (tier 2) — should win.
1721        std::fs::write(
1722            dir.path().join("khive.toml"),
1723            "[actor]\nid = \"lambda:project-root\"\n",
1724        )
1725        .unwrap();
1726
1727        let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
1728            .expect("no error expected")
1729            .expect("file should be found");
1730        assert_eq!(
1731            cfg.actor.id.as_deref(),
1732            Some("lambda:project-root"),
1733            "khive.toml (tier 2) must win over .khive/config.toml (tier 3)"
1734        );
1735    }
1736
1737    #[test]
1738    fn test_load_with_home_fallback_hidden_over_absent_root() {
1739        let dir = tempfile::tempdir().unwrap();
1740
1741        std::fs::create_dir_all(dir.path().join(".khive")).unwrap();
1742        std::fs::write(
1743            dir.path().join(".khive/config.toml"),
1744            "[actor]\nid = \"lambda:hidden-config\"\n",
1745        )
1746        .unwrap();
1747        // No khive.toml.
1748
1749        let cfg = KhiveConfig::load_with_roots(dir.path(), None, None)
1750            .expect("no error expected")
1751            .expect("file should be found");
1752        assert_eq!(
1753            cfg.actor.id.as_deref(),
1754            Some("lambda:hidden-config"),
1755            ".khive/config.toml (tier 3) must be found when khive.toml is absent"
1756        );
1757    }
1758
1759    #[test]
1760    fn test_load_with_roots_home_tier_found() {
1761        let project_dir = tempfile::tempdir().unwrap();
1762        let home_dir = tempfile::tempdir().unwrap();
1763
1764        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1765        std::fs::write(
1766            home_dir.path().join(".khive/config.toml"),
1767            "[actor]\nid = \"lambda:user-global\"\n",
1768        )
1769        .unwrap();
1770        // No project-level files.
1771
1772        let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1773            .expect("no error expected")
1774            .expect("file should be found");
1775        assert_eq!(
1776            cfg.actor.id.as_deref(),
1777            Some("lambda:user-global"),
1778            "~/.khive/config.toml (tier 4) must be found when project files absent"
1779        );
1780    }
1781
1782    #[test]
1783    fn test_load_with_roots_project_wins_over_home() {
1784        let project_dir = tempfile::tempdir().unwrap();
1785        let home_dir = tempfile::tempdir().unwrap();
1786
1787        // Home has a config.
1788        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1789        std::fs::write(
1790            home_dir.path().join(".khive/config.toml"),
1791            "[actor]\nid = \"lambda:user-global\"\n",
1792        )
1793        .unwrap();
1794
1795        // Project also has a config — should win.
1796        std::fs::create_dir_all(project_dir.path().join(".khive")).unwrap();
1797        std::fs::write(
1798            project_dir.path().join(".khive/config.toml"),
1799            "[actor]\nid = \"lambda:project-wins\"\n",
1800        )
1801        .unwrap();
1802
1803        let cfg = KhiveConfig::load_with_roots(project_dir.path(), Some(home_dir.path()), None)
1804            .expect("no error expected")
1805            .expect("file should be found");
1806        assert_eq!(
1807            cfg.actor.id.as_deref(),
1808            Some("lambda:project-wins"),
1809            "project .khive/config.toml (tier 3) must win over ~/.khive/config.toml (tier 4)"
1810        );
1811    }
1812
1813    // ── tier-3 db-dir anchor tests (config discovery canonicalization) ─────
1814
1815    // Two different process working directories, targeting the same database,
1816    // must resolve the identical tier-3 config file. Each cwd also carries its
1817    // own decoy `.khive/config.toml` so the test fails loudly (mismatched
1818    // actor ids) if the resolver ever falls back to the old cwd anchor instead
1819    // of the db-dir anchor.
1820    #[test]
1821    fn test_load_with_roots_same_db_different_cwd_resolves_identical_config() {
1822        let cwd_a = tempfile::tempdir().unwrap();
1823        let cwd_b = tempfile::tempdir().unwrap();
1824
1825        // Decoy cwd-anchored configs — must NOT be picked up once anchoring
1826        // moves to the db directory.
1827        std::fs::create_dir_all(cwd_a.path().join(".khive")).unwrap();
1828        std::fs::write(
1829            cwd_a.path().join(".khive/config.toml"),
1830            "[actor]\nid = \"lambda:wrong-cwd-a\"\n",
1831        )
1832        .unwrap();
1833        std::fs::create_dir_all(cwd_b.path().join(".khive")).unwrap();
1834        std::fs::write(
1835            cwd_b.path().join(".khive/config.toml"),
1836            "[actor]\nid = \"lambda:wrong-cwd-b\"\n",
1837        )
1838        .unwrap();
1839
1840        // The database and its co-located config live under a THIRD root,
1841        // distinct from either simulated cwd.
1842        let db_root = tempfile::tempdir().unwrap();
1843        let khive_dir = db_root.path().join(".khive");
1844        std::fs::create_dir_all(&khive_dir).unwrap();
1845        let db_path = khive_dir.join("khive.db");
1846        std::fs::write(&db_path, b"").unwrap(); // must exist for canonicalize to succeed
1847        std::fs::write(
1848            khive_dir.join("config.toml"),
1849            "[actor]\nid = \"lambda:db-anchored\"\n",
1850        )
1851        .unwrap();
1852
1853        let cfg_a = KhiveConfig::load_with_roots(cwd_a.path(), None, Some(&db_path))
1854            .expect("no error expected")
1855            .expect("db-anchored config must be found from cwd A");
1856        let cfg_b = KhiveConfig::load_with_roots(cwd_b.path(), None, Some(&db_path))
1857            .expect("no error expected")
1858            .expect("db-anchored config must be found from cwd B");
1859
1860        assert_eq!(
1861            cfg_a.actor.id.as_deref(),
1862            Some("lambda:db-anchored"),
1863            "cwd A must resolve the db-anchored config, not its own decoy"
1864        );
1865        assert_eq!(
1866            cfg_b.actor.id.as_deref(),
1867            Some("lambda:db-anchored"),
1868            "cwd B must resolve the db-anchored config, not its own decoy"
1869        );
1870        assert_eq!(
1871            cfg_a.actor.id, cfg_b.actor.id,
1872            "two processes at different cwds targeting the same db must resolve \
1873             identical config, killing config_id drift between client and daemon"
1874        );
1875    }
1876
1877    // Explicit `--config`/`KHIVE_CONFIG` (tier 1) must still win over the new
1878    // db-dir anchor (tier 3) — precedence is preserved, only the tier-3 anchor
1879    // moved.
1880    #[test]
1881    fn test_load_with_home_fallback_explicit_config_wins_over_db_anchor() {
1882        let explicit_dir = tempfile::tempdir().unwrap();
1883        let explicit_path = write_toml(&explicit_dir, "[actor]\nid = \"lambda:explicit-wins\"\n");
1884
1885        let db_root = tempfile::tempdir().unwrap();
1886        let khive_dir = db_root.path().join(".khive");
1887        std::fs::create_dir_all(&khive_dir).unwrap();
1888        let db_path = khive_dir.join("khive.db");
1889        std::fs::write(&db_path, b"").unwrap();
1890        std::fs::write(
1891            khive_dir.join("config.toml"),
1892            "[actor]\nid = \"lambda:db-anchor-loses\"\n",
1893        )
1894        .unwrap();
1895
1896        let cfg = KhiveConfig::load_with_home_fallback(Some(&explicit_path), Some(&db_path))
1897            .expect("no error expected")
1898            .expect("explicit path must be found");
1899        assert_eq!(
1900            cfg.actor.id.as_deref(),
1901            Some("lambda:explicit-wins"),
1902            "explicit --config/KHIVE_CONFIG must win over the db-dir anchor"
1903        );
1904    }
1905
1906    // Tier 4 (`~/.khive/config.toml`) must still be reached when the db-anchored
1907    // tier-3 directory has no `config.toml` alongside it.
1908    #[test]
1909    fn test_load_with_roots_home_fallback_reached_when_db_anchor_has_no_config() {
1910        let cwd = tempfile::tempdir().unwrap();
1911        let home_dir = tempfile::tempdir().unwrap();
1912        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1913        std::fs::write(
1914            home_dir.path().join(".khive/config.toml"),
1915            "[actor]\nid = \"lambda:home-fallback\"\n",
1916        )
1917        .unwrap();
1918
1919        // A real db directory that exists but has no co-located config.toml.
1920        let db_root = tempfile::tempdir().unwrap();
1921        let khive_dir = db_root.path().join(".khive");
1922        std::fs::create_dir_all(&khive_dir).unwrap();
1923        let db_path = khive_dir.join("khive.db");
1924        std::fs::write(&db_path, b"").unwrap();
1925
1926        let cfg = KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&db_path))
1927            .expect("no error expected")
1928            .expect("home-tier config must be found");
1929        assert_eq!(
1930            cfg.actor.id.as_deref(),
1931            Some("lambda:home-fallback"),
1932            "tier 4 (~/.khive/config.toml) must still be reached when the db-anchored \
1933             tier-3 directory has no config.toml"
1934        );
1935    }
1936
1937    // Cold start: the database file does not exist yet (first run). Anchor
1938    // resolution must not panic and must fall through the remaining tiers.
1939    #[test]
1940    fn test_load_with_roots_nonexistent_db_path_does_not_panic_and_falls_through() {
1941        let cwd = tempfile::tempdir().unwrap();
1942        let home_dir = tempfile::tempdir().unwrap();
1943        std::fs::create_dir_all(home_dir.path().join(".khive")).unwrap();
1944        std::fs::write(
1945            home_dir.path().join(".khive/config.toml"),
1946            "[actor]\nid = \"lambda:home-cold-start\"\n",
1947        )
1948        .unwrap();
1949
1950        // Absolute path under a directory tree that was never created.
1951        let nonexistent_db = cwd.path().join("never-created/.khive/khive.db");
1952
1953        let cfg =
1954            KhiveConfig::load_with_roots(cwd.path(), Some(home_dir.path()), Some(&nonexistent_db))
1955                .expect("cold-start db path must not error or panic")
1956                .expect("home-tier config must still be found");
1957        assert_eq!(
1958            cfg.actor.id.as_deref(),
1959            Some("lambda:home-cold-start"),
1960            "a nonexistent db path (cold start) must fall through to tier 4, not panic"
1961        );
1962    }
1963
1964    // Cold start with a *relative* nonexistent db path exercises the
1965    // cwd-join fallback branch specifically (as opposed to the
1966    // already-absolute fallback branch above). Must not panic; no config
1967    // exists anywhere so the result is `Ok(None)`.
1968    #[test]
1969    fn test_load_with_roots_relative_nonexistent_db_path_does_not_panic() {
1970        let cwd = tempfile::tempdir().unwrap();
1971        let relative_db = PathBuf::from("never-created/.khive/khive.db");
1972
1973        let result = KhiveConfig::load_with_roots(cwd.path(), None, Some(&relative_db));
1974        assert!(
1975            result.is_ok(),
1976            "relative cold-start db path must not error or panic: {result:?}"
1977        );
1978        assert!(
1979            result.unwrap().is_none(),
1980            "no config exists anywhere in this test; result must be None"
1981        );
1982    }
1983
1984    // ── ADR-028 backend / pack config tests ─────────────────────────────────
1985
1986    #[test]
1987    fn test_no_backends_section_is_valid() {
1988        let dir = tempfile::tempdir().unwrap();
1989        let path = write_toml(
1990            &dir,
1991            r#"
1992[[engines]]
1993name = "default"
1994model = "all-minilm-l6-v2"
1995default = true
1996"#,
1997        );
1998        let cfg = KhiveConfig::load(Some(&path))
1999            .expect("no error")
2000            .expect("file found");
2001        assert!(cfg.backends.is_empty());
2002        assert!(cfg.packs.is_empty());
2003    }
2004
2005    #[test]
2006    fn test_single_sqlite_backend_parses() {
2007        let dir = tempfile::tempdir().unwrap();
2008        let path = write_toml(
2009            &dir,
2010            r#"
2011[[backends]]
2012name = "knowledge"
2013kind = "sqlite"
2014path = "/tmp/knowledge.db"
2015"#,
2016        );
2017        let cfg = KhiveConfig::load(Some(&path))
2018            .expect("no error")
2019            .expect("file found");
2020        assert_eq!(cfg.backends.len(), 1);
2021        let b = &cfg.backends[0];
2022        assert_eq!(b.name, "knowledge");
2023        assert!(matches!(b.kind, BackendKind::Sqlite));
2024        assert_eq!(
2025            b.path.as_ref().and_then(|p| p.to_str()),
2026            Some("/tmp/knowledge.db")
2027        );
2028    }
2029
2030    #[test]
2031    fn test_memory_backend_parses() {
2032        let dir = tempfile::tempdir().unwrap();
2033        let path = write_toml(
2034            &dir,
2035            r#"
2036[[backends]]
2037name = "ephemeral"
2038kind = "memory"
2039"#,
2040        );
2041        let cfg = KhiveConfig::load(Some(&path))
2042            .expect("no error")
2043            .expect("file found");
2044        assert_eq!(cfg.backends.len(), 1);
2045        assert!(matches!(cfg.backends[0].kind, BackendKind::Memory));
2046    }
2047
2048    #[test]
2049    fn test_pack_backend_assignment_parses() {
2050        let dir = tempfile::tempdir().unwrap();
2051        let path = write_toml(
2052            &dir,
2053            r#"
2054[[backends]]
2055name = "knowledge"
2056kind = "memory"
2057
2058[packs.knowledge]
2059backend = "knowledge"
2060"#,
2061        );
2062        let cfg = KhiveConfig::load(Some(&path))
2063            .expect("no error")
2064            .expect("file found");
2065        assert_eq!(cfg.packs.len(), 1);
2066        let pc = cfg.packs.get("knowledge").expect("knowledge pack present");
2067        assert_eq!(pc.backend, "knowledge");
2068    }
2069
2070    #[test]
2071    fn test_duplicate_backend_name_rejected() {
2072        let dir = tempfile::tempdir().unwrap();
2073        let path = write_toml(
2074            &dir,
2075            r#"
2076[[backends]]
2077name = "dup"
2078kind = "memory"
2079
2080[[backends]]
2081name = "dup"
2082kind = "memory"
2083"#,
2084        );
2085        let err = KhiveConfig::load(Some(&path)).expect_err("should fail with duplicate name");
2086        assert!(
2087            matches!(config_error_root(&err), ConfigError::DuplicateBackendName { ref name } if name == "dup"),
2088            "expected DuplicateBackendName {{ name: \"dup\" }}, got {err:?}"
2089        );
2090    }
2091
2092    #[test]
2093    fn test_pack_referencing_undefined_backend_rejected() {
2094        let dir = tempfile::tempdir().unwrap();
2095        let path = write_toml(
2096            &dir,
2097            r#"
2098[[backends]]
2099name = "knowledge"
2100kind = "memory"
2101
2102[packs.kg]
2103backend = "nonexistent"
2104"#,
2105        );
2106        let err =
2107            KhiveConfig::load(Some(&path)).expect_err("should fail with unknown backend reference");
2108        assert!(
2109            matches!(config_error_root(&err), ConfigError::UnknownPackBackend { ref pack, ref backend, .. }
2110                if pack == "kg" && backend == "nonexistent"),
2111            "expected UnknownPackBackend for kg→nonexistent, got {err:?}"
2112        );
2113    }
2114
2115    #[test]
2116    fn test_pack_config_without_backends_section_is_allowed() {
2117        let dir = tempfile::tempdir().unwrap();
2118        // When [[backends]] is absent/empty, packs are not validated: all
2119        // packs fall through to the implicit main backend.
2120        let path = write_toml(
2121            &dir,
2122            r#"
2123[packs.kg]
2124backend = "main"
2125"#,
2126        );
2127        let cfg = KhiveConfig::load(Some(&path))
2128            .expect("no error expected")
2129            .expect("file found");
2130        assert_eq!(cfg.backends.len(), 0);
2131        assert_eq!(cfg.packs.len(), 1);
2132    }
2133
2134    #[test]
2135    fn test_backend_cache_mb_rejected_at_validate() {
2136        let dir = tempfile::tempdir().unwrap();
2137        let path = write_toml(
2138            &dir,
2139            r#"
2140[[backends]]
2141name = "main"
2142kind = "memory"
2143cache_mb = 128
2144"#,
2145        );
2146        let err = KhiveConfig::load(Some(&path)).expect_err("cache_mb must be rejected");
2147        assert!(
2148            matches!(config_error_root(&err), ConfigError::UnsupportedBackendField { ref name, field: "cache_mb" } if name == "main"),
2149            "expected UnsupportedBackendField {{ name: \"main\", field: \"cache_mb\" }}, got {err:?}"
2150        );
2151    }
2152
2153    #[test]
2154    fn test_backend_journal_mode_rejected_at_validate() {
2155        let dir = tempfile::tempdir().unwrap();
2156        let path = write_toml(
2157            &dir,
2158            r#"
2159[[backends]]
2160name = "main"
2161kind = "memory"
2162journal_mode = "wal"
2163"#,
2164        );
2165        let err = KhiveConfig::load(Some(&path)).expect_err("journal_mode must be rejected");
2166        assert!(
2167            matches!(config_error_root(&err), ConfigError::UnsupportedBackendField { ref name, field: "journal_mode" } if name == "main"),
2168            "expected UnsupportedBackendField {{ name: \"main\", field: \"journal_mode\" }}, got {err:?}"
2169        );
2170    }
2171
2172    // A top-level `db` key must be rejected loudly instead of silently
2173    // ignored as an unknown key by serde's forward-compatible default.
2174    #[test]
2175    fn test_top_level_db_rejected_at_validate() {
2176        let dir = tempfile::tempdir().unwrap();
2177        let path = write_toml(
2178            &dir,
2179            r#"
2180db = "/tmp/scratch/demo.db"
2181"#,
2182        );
2183        let err = KhiveConfig::load(Some(&path)).expect_err("top-level db must be rejected");
2184        assert!(
2185            matches!(config_error_root(&err), ConfigError::UnsupportedTopLevelDb { ref value } if value == "/tmp/scratch/demo.db"),
2186            "expected UnsupportedTopLevelDb {{ value: \"/tmp/scratch/demo.db\" }}, got {err:?}"
2187        );
2188    }
2189
2190    #[test]
2191    fn gate_caller_enrollment_is_rejected_instead_of_ignored() {
2192        let dir = tempfile::tempdir().unwrap();
2193        let path = write_toml(
2194            &dir,
2195            r#"
2196[gate]
2197granted_actors = ["lambda:enrolled"]
2198grant_unattributed = false
2199"#,
2200        );
2201
2202        let err = KhiveConfig::load(Some(&path))
2203            .expect_err("an unenforced caller-enrollment policy must abort startup");
2204        assert!(
2205            matches!(config_error_root(&err), ConfigError::UnsupportedGateSection),
2206            "expected UnsupportedGateSection, got {err:?}"
2207        );
2208        assert!(
2209            err.to_string().contains("would not be enforced"),
2210            "operator-facing error must explain the fail-loud reason: {err}"
2211        );
2212    }
2213
2214    #[test]
2215    fn empty_gate_table_is_still_rejected() {
2216        let dir = tempfile::tempdir().unwrap();
2217        let path = write_toml(&dir, "[gate]\n");
2218        let err = KhiveConfig::load(Some(&path))
2219            .expect_err("a present gate table must never disappear through serde defaults");
2220        assert!(matches!(
2221            config_error_root(&err),
2222            ConfigError::UnsupportedGateSection
2223        ));
2224    }
2225
2226    #[test]
2227    fn unrelated_unknown_top_level_sections_remain_forward_compatible() {
2228        let dir = tempfile::tempdir().unwrap();
2229        let path = write_toml(&dir, "[future_feature]\nenabled = true\n");
2230        KhiveConfig::load(Some(&path))
2231            .expect("unrelated future config stays forward compatible")
2232            .expect("config exists");
2233    }
2234
2235    // ── [git_write] section (ADR-108 Amendment) ─────────────────────────────
2236
2237    // No [git_write] section at all -> empty allowlist, valid config.
2238    #[test]
2239    fn test_no_git_write_section_is_valid_and_empty() {
2240        let dir = tempfile::tempdir().unwrap();
2241        let path = write_toml(&dir, "# no git_write section\n");
2242        let cfg = KhiveConfig::load(Some(&path))
2243            .expect("no error")
2244            .expect("file found");
2245        assert!(cfg.git_write.allowed.is_empty());
2246    }
2247
2248    // A well-formed [[git_write.allowed]] entry parses correctly.
2249    #[test]
2250    fn test_git_write_entry_parses() {
2251        let dir = tempfile::tempdir().unwrap();
2252        let path = write_toml(
2253            &dir,
2254            r#"
2255[[git_write.allowed]]
2256repo = "/abs/path/repo"
2257branches = ["feat/*", "fix/*"]
2258"#,
2259        );
2260        let cfg = KhiveConfig::load(Some(&path))
2261            .expect("no error")
2262            .expect("file found");
2263        assert_eq!(cfg.git_write.allowed.len(), 1);
2264        assert_eq!(cfg.git_write.allowed[0].repo, "/abs/path/repo");
2265        assert_eq!(
2266            cfg.git_write.allowed[0].branches,
2267            vec!["feat/*".to_string(), "fix/*".to_string()]
2268        );
2269    }
2270
2271    // A relative repo path is rejected at validate() time.
2272    #[test]
2273    fn test_git_write_relative_repo_rejected() {
2274        let dir = tempfile::tempdir().unwrap();
2275        let path = write_toml(
2276            &dir,
2277            r#"
2278[[git_write.allowed]]
2279repo = "relative/path"
2280branches = ["main"]
2281"#,
2282        );
2283        let err = KhiveConfig::load(Some(&path)).expect_err("relative repo must be rejected");
2284        assert!(
2285            matches!(config_error_root(&err), ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "relative/path"),
2286            "expected InvalidGitWriteEntry, got {err:?}"
2287        );
2288    }
2289
2290    // ADR-108: a branch pattern with more than one `*` is rejected at
2291    // validate() time -- the ADR authorizes exact-name or single-wildcard
2292    // patterns only.
2293    #[test]
2294    fn test_git_write_multi_star_branch_pattern_rejected() {
2295        let dir = tempfile::tempdir().unwrap();
2296        let path = write_toml(
2297            &dir,
2298            r#"
2299[[git_write.allowed]]
2300repo = "/abs/path"
2301branches = ["**"]
2302"#,
2303        );
2304        let err = KhiveConfig::load(Some(&path)).expect_err("** must be rejected");
2305        assert!(
2306            matches!(config_error_root(&err), ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
2307            "expected InvalidGitWriteEntry, got {err:?}"
2308        );
2309
2310        let dir2 = tempfile::tempdir().unwrap();
2311        let path2 = write_toml(
2312            &dir2,
2313            r#"
2314[[git_write.allowed]]
2315repo = "/abs/path"
2316branches = ["rel-*-*-final"]
2317"#,
2318        );
2319        let err2 = KhiveConfig::load(Some(&path2)).expect_err("rel-*-*-final must be rejected");
2320        assert!(
2321            matches!(
2322                config_error_root(&err2),
2323                ConfigError::InvalidGitWriteEntry { .. }
2324            ),
2325            "expected InvalidGitWriteEntry, got {err2:?}"
2326        );
2327    }
2328
2329    // Single-wildcard patterns remain accepted.
2330    #[test]
2331    fn test_git_write_single_star_branch_pattern_accepted() {
2332        let dir = tempfile::tempdir().unwrap();
2333        let path = write_toml(
2334            &dir,
2335            r#"
2336[[git_write.allowed]]
2337repo = "/abs/path"
2338branches = ["a*b", "main"]
2339"#,
2340        );
2341        let cfg = KhiveConfig::load(Some(&path))
2342            .expect("no error")
2343            .expect("file found");
2344        assert_eq!(cfg.git_write.allowed[0].branches, vec!["a*b", "main"]);
2345    }
2346
2347    // An entry with an empty branches list is rejected at validate() time --
2348    // it would otherwise silently allowlist a repo for no branch at all.
2349    #[test]
2350    fn test_git_write_empty_branches_rejected() {
2351        let dir = tempfile::tempdir().unwrap();
2352        let path = write_toml(
2353            &dir,
2354            r#"
2355[[git_write.allowed]]
2356repo = "/abs/path"
2357branches = []
2358"#,
2359        );
2360        let err = KhiveConfig::load(Some(&path)).expect_err("empty branches must be rejected");
2361        assert!(
2362            matches!(config_error_root(&err), ConfigError::InvalidGitWriteEntry { ref repo, .. } if repo == "/abs/path"),
2363            "expected InvalidGitWriteEntry, got {err:?}"
2364        );
2365    }
2366
2367    // ── [storage.blob] section (ADR-111 Amendment 2) ─────────────────────────
2368
2369    // No [storage] section at all -> fs default, existing configurations
2370    // keep behaving exactly as they did before this section existed.
2371    #[test]
2372    fn test_no_storage_section_defaults_to_fs() {
2373        let dir = tempfile::tempdir().unwrap();
2374        let path = write_toml(&dir, "# no storage section\n");
2375        let cfg = KhiveConfig::load(Some(&path))
2376            .expect("no error")
2377            .expect("file found");
2378        assert!(cfg.storage.blob.is_none());
2379    }
2380
2381    #[test]
2382    fn test_storage_blob_fs_selection_parses() {
2383        let dir = tempfile::tempdir().unwrap();
2384        let path = write_toml(
2385            &dir,
2386            r#"
2387[storage.blob]
2388backend = "fs"
2389root = "/var/lib/khive/blobs"
2390floor_bytes = 100000000000
2391"#,
2392        );
2393        let cfg = KhiveConfig::load(Some(&path))
2394            .expect("no error")
2395            .expect("file found");
2396        match cfg.storage.blob {
2397            Some(BlobConfig::Fs { root, floor_bytes }) => {
2398                assert_eq!(root.as_deref(), Some("/var/lib/khive/blobs"));
2399                assert_eq!(floor_bytes, Some(100_000_000_000));
2400            }
2401            other => panic!("expected BlobConfig::Fs, got {other:?}"),
2402        }
2403    }
2404
2405    #[test]
2406    fn test_storage_blob_s3_selection_parses() {
2407        let dir = tempfile::tempdir().unwrap();
2408        let path = write_toml(
2409            &dir,
2410            r#"
2411[storage.blob]
2412backend = "s3"
2413bucket = "khive-blobs"
2414region = "us-east-1"
2415endpoint = "https://objects.example.invalid"
2416prefix = "blobs"
2417"#,
2418        );
2419        let cfg = KhiveConfig::load(Some(&path))
2420            .expect("no error")
2421            .expect("file found");
2422        match cfg.storage.blob {
2423            Some(BlobConfig::S3 {
2424                bucket,
2425                region,
2426                endpoint,
2427                prefix,
2428                allow_http,
2429            }) => {
2430                assert_eq!(bucket, "khive-blobs");
2431                assert_eq!(region, "us-east-1");
2432                assert_eq!(endpoint.as_deref(), Some("https://objects.example.invalid"));
2433                assert_eq!(prefix.as_deref(), Some("blobs"));
2434                assert_eq!(allow_http, None);
2435            }
2436            other => panic!("expected BlobConfig::S3, got {other:?}"),
2437        }
2438    }
2439
2440    // An unknown field under [storage.blob] must be a startup error, not
2441    // silently ignored -- unlike the rest of KhiveConfig, this section is
2442    // strict (deny_unknown_fields).
2443    #[test]
2444    fn test_storage_blob_unknown_field_rejected() {
2445        let dir = tempfile::tempdir().unwrap();
2446        let path = write_toml(
2447            &dir,
2448            r#"
2449[storage.blob]
2450backend = "fs"
2451made_up_field = "x"
2452"#,
2453        );
2454        let err = KhiveConfig::load(Some(&path)).expect_err("unknown field must be rejected");
2455        assert!(
2456            matches!(config_error_root(&err), ConfigError::Parse { .. }),
2457            "got {err:?}"
2458        );
2459    }
2460
2461    // An s3-only field (bucket) under backend = "fs" must be rejected: the
2462    // internally tagged enum's Fs variant doesn't declare it, so it is an
2463    // unknown field for that variant.
2464    #[test]
2465    fn test_storage_blob_other_backend_field_rejected() {
2466        let dir = tempfile::tempdir().unwrap();
2467        let path = write_toml(
2468            &dir,
2469            r#"
2470[storage.blob]
2471backend = "fs"
2472bucket = "khive-blobs"
2473"#,
2474        );
2475        let err = KhiveConfig::load(Some(&path)).expect_err("s3 field under fs must be rejected");
2476        assert!(
2477            matches!(config_error_root(&err), ConfigError::Parse { .. }),
2478            "got {err:?}"
2479        );
2480    }
2481
2482    // Credentials are never accepted in TOML (ADR-111 Amendment 2): an
2483    // access-key field under backend = "s3" is unknown to that variant and
2484    // must be rejected, the same way an other-backend field is.
2485    #[test]
2486    fn test_storage_blob_credential_field_rejected() {
2487        let dir = tempfile::tempdir().unwrap();
2488        let path = write_toml(
2489            &dir,
2490            r#"
2491[storage.blob]
2492backend = "s3"
2493bucket = "khive-blobs"
2494region = "us-east-1"
2495access_key_id = "AKIAEXAMPLE"
2496"#,
2497        );
2498        let err = KhiveConfig::load(Some(&path))
2499            .expect_err("a credential field in TOML must be rejected");
2500        assert!(
2501            matches!(config_error_root(&err), ConfigError::Parse { .. }),
2502            "got {err:?}"
2503        );
2504    }
2505
2506    // An unrecognized backend value is rejected by the internally tagged
2507    // enum's own tag matching, same mechanism as an unknown field.
2508    #[test]
2509    fn test_storage_blob_unknown_backend_value_rejected() {
2510        let dir = tempfile::tempdir().unwrap();
2511        let path = write_toml(
2512            &dir,
2513            r#"
2514[storage.blob]
2515backend = "gcs"
2516"#,
2517        );
2518        let err = KhiveConfig::load(Some(&path)).expect_err("unknown backend must be rejected");
2519        assert!(
2520            matches!(config_error_root(&err), ConfigError::Parse { .. }),
2521            "got {err:?}"
2522        );
2523    }
2524
2525    // ── [display] section (ADR-169) ──────────────────────────────────────────
2526
2527    // No [display] section at all -> None, resolved to the host zone downstream.
2528    #[test]
2529    fn test_no_display_section_defaults_to_none() {
2530        let dir = tempfile::tempdir().unwrap();
2531        let path = write_toml(&dir, "# no display section\n");
2532        let cfg = KhiveConfig::load(Some(&path))
2533            .expect("no error")
2534            .expect("file found");
2535        assert!(cfg.display.timezone.is_none());
2536    }
2537
2538    #[test]
2539    fn test_display_timezone_valid_iana_name_parses() {
2540        let dir = tempfile::tempdir().unwrap();
2541        let path = write_toml(
2542            &dir,
2543            r#"
2544[display]
2545timezone = "America/New_York"
2546"#,
2547        );
2548        let cfg = KhiveConfig::load(Some(&path))
2549            .expect("no error")
2550            .expect("file found");
2551        assert_eq!(cfg.display.timezone.as_deref(), Some("America/New_York"));
2552    }
2553
2554    #[test]
2555    fn test_display_timezone_unrecognized_name_rejected() {
2556        let dir = tempfile::tempdir().unwrap();
2557        let path = write_toml(
2558            &dir,
2559            r#"
2560[display]
2561timezone = "Mars/Olympus_Mons"
2562"#,
2563        );
2564        let err = KhiveConfig::load(Some(&path))
2565            .expect_err("an unrecognized IANA zone name must fail at load, not silently fall back");
2566        assert!(
2567            matches!(config_error_root(&err), ConfigError::InvalidDisplayTimezone { ref timezone } if timezone == "Mars/Olympus_Mons"),
2568            "expected InvalidDisplayTimezone, got {err:?}"
2569        );
2570    }
2571
2572    #[test]
2573    fn test_display_timezone_empty_string_rejected() {
2574        let dir = tempfile::tempdir().unwrap();
2575        let path = write_toml(
2576            &dir,
2577            r#"
2578[display]
2579timezone = ""
2580"#,
2581        );
2582        let err =
2583            KhiveConfig::load(Some(&path)).expect_err("an empty timezone string must be rejected");
2584        assert!(
2585            matches!(
2586                config_error_root(&err),
2587                ConfigError::InvalidDisplayTimezone { .. }
2588            ),
2589            "expected InvalidDisplayTimezone, got {err:?}"
2590        );
2591    }
2592}