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