Skip to main content

zeph_config/
loader.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::path::Path;
5
6use crate::error::ConfigError;
7use crate::root::Config;
8
9impl Config {
10    /// Load configuration from a TOML file with env var overrides.
11    ///
12    /// Falls back to sensible defaults when the file does not exist.
13    ///
14    /// # Errors
15    ///
16    /// Returns an error if the file exists but cannot be read or parsed.
17    pub fn load(path: &Path) -> Result<Self, ConfigError> {
18        let mut config = if path.exists() {
19            let content = std::fs::read_to_string(path)?;
20            toml::from_str::<Self>(&content)?
21        } else {
22            Self::default()
23        };
24
25        config.apply_env_overrides();
26        config.normalize_legacy_runtime_defaults();
27        Ok(config)
28    }
29
30    /// Serialize the default configuration to a TOML string.
31    ///
32    /// Produces a pretty-printed TOML representation of [`Config::default()`].
33    /// Useful for bootstrapping a new config file or documenting available options.
34    ///
35    /// The `secrets` field is always excluded from the output because it is
36    /// populated at runtime only and must never be written to disk.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if serialization fails (unlikely — the default value is
41    /// always structurally valid).
42    ///
43    /// # Examples
44    ///
45    /// ```no_run
46    /// use zeph_config::Config;
47    ///
48    /// let toml = Config::dump_defaults().expect("serialization failed");
49    /// assert!(toml.contains("[agent]"));
50    /// assert!(toml.contains("[memory]"));
51    /// ```
52    pub fn dump_defaults() -> Result<String, crate::error::ConfigError> {
53        let defaults = Self::default();
54        toml::to_string_pretty(&defaults).map_err(|e| {
55            crate::error::ConfigError::Validation(format!("failed to serialize defaults: {e}"))
56        })
57    }
58
59    /// Validate configuration values are within sane bounds.
60    ///
61    /// # Errors
62    ///
63    /// Returns an error if any value is out of range.
64    pub fn validate(&self) -> Result<(), ConfigError> {
65        self.validate_scalar_bounds()?;
66        self.validate_memory_compression()?;
67        self.validate_memory_probe_and_graph()?;
68        self.validate_mcp_servers()?;
69        self.experiments
70            .validate()
71            .map_err(ConfigError::Validation)?;
72        if self.orchestration.plan_cache.enabled {
73            self.orchestration
74                .plan_cache
75                .validate()
76                .map_err(ConfigError::Validation)?;
77        }
78        self.validate_orchestration()?;
79        self.validate_focus_and_sidequest()?;
80        self.validate_llm_and_skills()?;
81        self.validate_provider_names()?;
82        self.validate_mcp_misc()?;
83        Ok(())
84    }
85
86    /// Validate scalar bounds for memory, agent, a2a, and gateway fields.
87    fn validate_scalar_bounds(&self) -> Result<(), ConfigError> {
88        if self.memory.history_limit > 10_000 {
89            return Err(ConfigError::Validation(format!(
90                "history_limit must be <= 10000, got {}",
91                self.memory.history_limit
92            )));
93        }
94        if self.memory.context_budget_tokens > 1_000_000 {
95            return Err(ConfigError::Validation(format!(
96                "context_budget_tokens must be <= 1000000, got {}",
97                self.memory.context_budget_tokens
98            )));
99        }
100        if self.agent.max_tool_iterations > 100 {
101            return Err(ConfigError::Validation(format!(
102                "max_tool_iterations must be <= 100, got {}",
103                self.agent.max_tool_iterations
104            )));
105        }
106        if self.a2a.rate_limit == 0 {
107            return Err(ConfigError::Validation("a2a.rate_limit must be > 0".into()));
108        }
109        if self.gateway.rate_limit == 0 {
110            return Err(ConfigError::Validation(
111                "gateway.rate_limit must be > 0".into(),
112            ));
113        }
114        if self.gateway.max_body_size > 10_485_760 {
115            return Err(ConfigError::Validation(format!(
116                "gateway.max_body_size must be <= 10485760 (10 MiB), got {}",
117                self.gateway.max_body_size
118            )));
119        }
120        if self.memory.token_safety_margin <= 0.0 {
121            return Err(ConfigError::Validation(format!(
122                "token_safety_margin must be > 0.0, got {}",
123                self.memory.token_safety_margin
124            )));
125        }
126        if self.memory.tool_call_cutoff == 0 {
127            return Err(ConfigError::Validation(
128                "tool_call_cutoff must be >= 1".into(),
129            ));
130        }
131        Ok(())
132    }
133
134    /// Validate memory compression strategy bounds and compaction thresholds.
135    fn validate_memory_compression(&self) -> Result<(), ConfigError> {
136        if let crate::memory::CompressionStrategy::Proactive {
137            threshold_tokens,
138            max_summary_tokens,
139        } = &self.memory.compression.strategy
140        {
141            if *threshold_tokens < 1_000 {
142                return Err(ConfigError::Validation(format!(
143                    "compression.threshold_tokens must be >= 1000, got {threshold_tokens}"
144                )));
145            }
146            if *max_summary_tokens < 128 {
147                return Err(ConfigError::Validation(format!(
148                    "compression.max_summary_tokens must be >= 128, got {max_summary_tokens}"
149                )));
150            }
151        }
152        if !self.memory.soft_compaction_threshold.is_finite()
153            || self.memory.soft_compaction_threshold <= 0.0
154            || self.memory.soft_compaction_threshold >= 1.0
155        {
156            return Err(ConfigError::Validation(format!(
157                "soft_compaction_threshold must be in (0.0, 1.0) exclusive, got {}",
158                self.memory.soft_compaction_threshold
159            )));
160        }
161        if !self.memory.hard_compaction_threshold.is_finite()
162            || self.memory.hard_compaction_threshold <= 0.0
163            || self.memory.hard_compaction_threshold >= 1.0
164        {
165            return Err(ConfigError::Validation(format!(
166                "hard_compaction_threshold must be in (0.0, 1.0) exclusive, got {}",
167                self.memory.hard_compaction_threshold
168            )));
169        }
170        if self.memory.soft_compaction_threshold >= self.memory.hard_compaction_threshold {
171            return Err(ConfigError::Validation(format!(
172                "soft_compaction_threshold ({}) must be less than hard_compaction_threshold ({})",
173                self.memory.soft_compaction_threshold, self.memory.hard_compaction_threshold,
174            )));
175        }
176        Ok(())
177    }
178
179    /// Validate memory probe thresholds and graph temporal decay rate.
180    fn validate_memory_probe_and_graph(&self) -> Result<(), ConfigError> {
181        if self.memory.graph.temporal_decay_rate < 0.0
182            || self.memory.graph.temporal_decay_rate > 10.0
183        {
184            return Err(ConfigError::Validation(format!(
185                "memory.graph.temporal_decay_rate must be in [0.0, 10.0], got {}",
186                self.memory.graph.temporal_decay_rate
187            )));
188        }
189        if self.memory.compression.probe.enabled {
190            let probe = &self.memory.compression.probe;
191            if !probe.threshold.is_finite() || probe.threshold <= 0.0 || probe.threshold > 1.0 {
192                return Err(ConfigError::Validation(format!(
193                    "memory.compression.probe.threshold must be in (0.0, 1.0], got {}",
194                    probe.threshold
195                )));
196            }
197            if !probe.hard_fail_threshold.is_finite()
198                || probe.hard_fail_threshold < 0.0
199                || probe.hard_fail_threshold >= 1.0
200            {
201                return Err(ConfigError::Validation(format!(
202                    "memory.compression.probe.hard_fail_threshold must be in [0.0, 1.0), got {}",
203                    probe.hard_fail_threshold
204                )));
205            }
206            if probe.hard_fail_threshold >= probe.threshold {
207                return Err(ConfigError::Validation(format!(
208                    "memory.compression.probe.hard_fail_threshold ({}) must be less than \
209                     memory.compression.probe.threshold ({})",
210                    probe.hard_fail_threshold, probe.threshold
211                )));
212            }
213            if probe.max_questions < 1 {
214                return Err(ConfigError::Validation(
215                    "memory.compression.probe.max_questions must be >= 1".into(),
216                ));
217            }
218            if probe.timeout_secs < 1 {
219                return Err(ConfigError::Validation(
220                    "memory.compression.probe.timeout_secs must be >= 1".into(),
221                ));
222            }
223        }
224        Ok(())
225    }
226
227    /// Validate MCP server entries for header/oauth exclusivity and vault key uniqueness.
228    fn validate_mcp_servers(&self) -> Result<(), ConfigError> {
229        use std::collections::HashSet;
230        let mut seen_oauth_vault_keys: HashSet<String> = HashSet::new();
231        for s in &self.mcp.servers {
232            // headers and oauth are mutually exclusive
233            if !s.headers.is_empty() && s.oauth.as_ref().is_some_and(|o| o.enabled) {
234                return Err(ConfigError::Validation(format!(
235                    "MCP server '{}': cannot use both 'headers' and 'oauth' simultaneously",
236                    s.id
237                )));
238            }
239            // vault key collision detection
240            if s.oauth.as_ref().is_some_and(|o| o.enabled) {
241                let key = format!("ZEPH_MCP_OAUTH_{}", s.id.to_uppercase().replace('-', "_"));
242                if !seen_oauth_vault_keys.insert(key.clone()) {
243                    return Err(ConfigError::Validation(format!(
244                        "MCP server '{}' has vault key collision ('{key}'): another server \
245                         with the same normalized ID already uses this key",
246                        s.id
247                    )));
248                }
249            }
250        }
251        Ok(())
252    }
253
254    /// Validate orchestration thresholds and cascade settings.
255    fn validate_orchestration(&self) -> Result<(), ConfigError> {
256        let ct = self.orchestration.completeness_threshold;
257        if !ct.is_finite() || !(0.0..=1.0).contains(&ct) {
258            return Err(ConfigError::Validation(format!(
259                "orchestration.completeness_threshold must be in [0.0, 1.0], got {ct}"
260            )));
261        }
262        // Cascade chain threshold must not be 1 — that would abort on every single failure.
263        if self.orchestration.cascade_chain_threshold == 1 {
264            return Err(ConfigError::Validation(
265                "orchestration.cascade_chain_threshold=1 aborts on every failure; \
266                 use 0 to disable linear-chain cascade abort instead"
267                    .into(),
268            ));
269        }
270        let cfrat = self.orchestration.cascade_failure_rate_abort_threshold;
271        if !cfrat.is_finite() || !(0.0..=1.0).contains(&cfrat) {
272            return Err(ConfigError::Validation(format!(
273                "orchestration.cascade_failure_rate_abort_threshold must be in [0.0, 1.0], got {cfrat}"
274            )));
275        }
276        if self.orchestration.lineage_ttl_secs == 0 {
277            return Err(ConfigError::Validation(
278                "orchestration.lineage_ttl_secs must be > 0; \
279                 set cascade_chain_threshold=0 to disable lineage tracking instead"
280                    .into(),
281            ));
282        }
283        Ok(())
284    }
285
286    /// Validate focus and sidequest interval and ratio constraints.
287    fn validate_focus_and_sidequest(&self) -> Result<(), ConfigError> {
288        if self.agent.focus.compression_interval == 0 {
289            return Err(ConfigError::Validation(
290                "agent.focus.compression_interval must be >= 1".into(),
291            ));
292        }
293        if self.agent.focus.min_messages_per_focus == 0 {
294            return Err(ConfigError::Validation(
295                "agent.focus.min_messages_per_focus must be >= 1".into(),
296            ));
297        }
298        if self.agent.focus.auto_consolidate_min_window == 0 {
299            return Err(ConfigError::Validation(
300                "agent.focus.auto_consolidate_min_window must be >= 1 \
301                 (set focus.enabled = false to disable auto-consolidation)"
302                    .into(),
303            ));
304        }
305        if self.memory.sidequest.interval_turns == 0 {
306            return Err(ConfigError::Validation(
307                "memory.sidequest.interval_turns must be >= 1".into(),
308            ));
309        }
310        if !self.memory.sidequest.max_eviction_ratio.is_finite()
311            || self.memory.sidequest.max_eviction_ratio <= 0.0
312            || self.memory.sidequest.max_eviction_ratio > 1.0
313        {
314            return Err(ConfigError::Validation(format!(
315                "memory.sidequest.max_eviction_ratio must be in (0.0, 1.0], got {}",
316                self.memory.sidequest.max_eviction_ratio
317            )));
318        }
319        Ok(())
320    }
321
322    /// Validate LLM semantic cache threshold and skill evaluation weight sum.
323    fn validate_llm_and_skills(&self) -> Result<(), ConfigError> {
324        let sct = self.llm.semantic_cache_threshold;
325        if !(sct.is_finite() && (0.0..=1.0).contains(&sct)) {
326            return Err(ConfigError::Validation(format!(
327                "llm.semantic_cache_threshold must be in [0.0, 1.0], got {sct} \
328                 (override via ZEPH_LLM_SEMANTIC_CACHE_THRESHOLD env var)"
329            )));
330        }
331        // Skill evaluation weight-sum validation (#3319).
332        if self.skills.evaluation.enabled {
333            let weight_sum = self.skills.evaluation.weight_correctness
334                + self.skills.evaluation.weight_reusability
335                + self.skills.evaluation.weight_specificity;
336            if (weight_sum - 1.0_f32).abs() > 1e-3 {
337                return Err(ConfigError::Validation(format!(
338                    "skills.evaluation weights must sum to 1.0 (got {weight_sum:.4})"
339                )));
340            }
341        }
342        Ok(())
343    }
344
345    /// Validate miscellaneous MCP output schema hint size.
346    fn validate_mcp_misc(&self) -> Result<(), ConfigError> {
347        if self.mcp.output_schema_hint_bytes < 64 {
348            return Err(ConfigError::Validation(format!(
349                "mcp.output_schema_hint_bytes must be >= 64, got {}; \
350                 use forward_output_schema = false to disable forwarding",
351                self.mcp.output_schema_hint_bytes
352            )));
353        }
354        Ok(())
355    }
356
357    fn validate_provider_names(&self) -> Result<(), ConfigError> {
358        let known = self.known_provider_names();
359        self.validate_named_provider_refs(&known)?;
360        self.validate_optional_provider_refs(&known)?;
361        Ok(())
362    }
363
364    /// Build the set of declared provider names from all `[[llm.providers]]` entries.
365    fn known_provider_names(&self) -> std::collections::HashSet<String> {
366        self.llm
367            .providers
368            .iter()
369            .map(super::providers::ProviderEntry::effective_name)
370            .collect()
371    }
372
373    /// Validate every required `*_provider` field references a declared provider.
374    ///
375    /// The field table lists all 19 subsystem provider references. Each non-empty value must
376    /// match a name in `known`.
377    fn validate_named_provider_refs(
378        &self,
379        known: &std::collections::HashSet<String>,
380    ) -> Result<(), ConfigError> {
381        let fields: &[(&str, &crate::providers::ProviderName)] = &[
382            (
383                "memory.tiers.scene_provider",
384                &self.memory.tiers.scene_provider,
385            ),
386            (
387                "memory.compression.compress_provider",
388                &self.memory.compression.compress_provider,
389            ),
390            (
391                "memory.consolidation.consolidation_provider",
392                &self.memory.consolidation.consolidation_provider,
393            ),
394            (
395                "memory.admission.admission_provider",
396                &self.memory.admission.admission_provider,
397            ),
398            (
399                "memory.admission.goal_utility_provider",
400                &self.memory.admission.goal_utility_provider,
401            ),
402            (
403                "memory.store_routing.routing_classifier_provider",
404                &self.memory.store_routing.routing_classifier_provider,
405            ),
406            (
407                "skills.learning.feedback_provider",
408                &self.skills.learning.feedback_provider,
409            ),
410            (
411                "skills.learning.arise_trace_provider",
412                &self.skills.learning.arise_trace_provider,
413            ),
414            (
415                "skills.learning.stem_provider",
416                &self.skills.learning.stem_provider,
417            ),
418            (
419                "skills.learning.erl_extract_provider",
420                &self.skills.learning.erl_extract_provider,
421            ),
422            (
423                "mcp.pruning.pruning_provider",
424                &self.mcp.pruning.pruning_provider,
425            ),
426            (
427                "mcp.tool_discovery.embedding_provider",
428                &self.mcp.tool_discovery.embedding_provider,
429            ),
430            (
431                "security.response_verification.verifier_provider",
432                &self.security.response_verification.verifier_provider,
433            ),
434            (
435                "orchestration.planner_provider",
436                &self.orchestration.planner_provider,
437            ),
438            (
439                "orchestration.verify_provider",
440                &self.orchestration.verify_provider,
441            ),
442            (
443                "orchestration.tool_provider",
444                &self.orchestration.tool_provider,
445            ),
446            (
447                "skills.evaluation.provider",
448                &self.skills.evaluation.provider,
449            ),
450            (
451                "skills.proactive_exploration.provider",
452                &self.skills.proactive_exploration.provider,
453            ),
454            (
455                "memory.compression_spectrum.promotion_provider",
456                &self.memory.compression_spectrum.promotion_provider,
457            ),
458        ];
459
460        for (field, name) in fields {
461            if !name.is_empty() && !known.contains(name.as_str()) {
462                return Err(ConfigError::Validation(format!(
463                    "{field} = {:?} does not match any [[llm.providers]] entry",
464                    name.as_str()
465                )));
466            }
467        }
468        Ok(())
469    }
470
471    /// Validate optional provider references in complexity routing and router bandit config.
472    fn validate_optional_provider_refs(
473        &self,
474        known: &std::collections::HashSet<String>,
475    ) -> Result<(), ConfigError> {
476        if let Some(triage) = self
477            .llm
478            .complexity_routing
479            .as_ref()
480            .and_then(|cr| cr.triage_provider.as_ref())
481            .filter(|t| !t.is_empty() && !known.contains(t.as_str()))
482        {
483            return Err(ConfigError::Validation(format!(
484                "llm.complexity_routing.triage_provider = {:?} does not match any \
485                 [[llm.providers]] entry",
486                triage.as_str()
487            )));
488        }
489
490        if let Some(embed) = self
491            .llm
492            .router
493            .as_ref()
494            .and_then(|r| r.bandit.as_ref())
495            .map(|b| &b.embedding_provider)
496            .filter(|p| !p.is_empty() && !known.contains(p.as_str()))
497        {
498            return Err(ConfigError::Validation(format!(
499                "llm.router.bandit.embedding_provider = {:?} does not match any \
500                 [[llm.providers]] entry",
501                embed.as_str()
502            )));
503        }
504
505        Ok(())
506    }
507
508    fn normalize_legacy_runtime_defaults(&mut self) {
509        use crate::defaults::{
510            default_debug_dir, default_log_file_path, default_skills_dir, default_sqlite_path,
511            is_legacy_default_debug_dir, is_legacy_default_log_file, is_legacy_default_skills_path,
512            is_legacy_default_sqlite_path,
513        };
514
515        if is_legacy_default_sqlite_path(&self.memory.sqlite_path) {
516            self.memory.sqlite_path = default_sqlite_path();
517        }
518
519        for skill_path in &mut self.skills.paths {
520            if is_legacy_default_skills_path(skill_path) {
521                *skill_path = default_skills_dir();
522            }
523        }
524
525        if is_legacy_default_debug_dir(&self.debug.output_dir) {
526            self.debug.output_dir = default_debug_dir();
527        }
528
529        if is_legacy_default_log_file(&self.logging.file) {
530            self.logging.file = default_log_file_path();
531        }
532    }
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538
539    fn config_with_sct(threshold: f32) -> Config {
540        let mut cfg = Config::default();
541        cfg.llm.semantic_cache_threshold = threshold;
542        cfg
543    }
544
545    #[test]
546    fn semantic_cache_threshold_valid_zero() {
547        assert!(config_with_sct(0.0).validate().is_ok());
548    }
549
550    #[test]
551    fn semantic_cache_threshold_valid_mid() {
552        assert!(config_with_sct(0.5).validate().is_ok());
553    }
554
555    #[test]
556    fn semantic_cache_threshold_valid_one() {
557        assert!(config_with_sct(1.0).validate().is_ok());
558    }
559
560    #[test]
561    fn semantic_cache_threshold_invalid_negative() {
562        let err = config_with_sct(-0.1).validate().unwrap_err();
563        assert!(
564            err.to_string().contains("semantic_cache_threshold"),
565            "unexpected error: {err}"
566        );
567    }
568
569    #[test]
570    fn semantic_cache_threshold_invalid_above_one() {
571        let err = config_with_sct(1.1).validate().unwrap_err();
572        assert!(
573            err.to_string().contains("semantic_cache_threshold"),
574            "unexpected error: {err}"
575        );
576    }
577
578    #[test]
579    fn semantic_cache_threshold_invalid_nan() {
580        let err = config_with_sct(f32::NAN).validate().unwrap_err();
581        assert!(
582            err.to_string().contains("semantic_cache_threshold"),
583            "unexpected error: {err}"
584        );
585    }
586
587    #[test]
588    fn semantic_cache_threshold_invalid_infinity() {
589        let err = config_with_sct(f32::INFINITY).validate().unwrap_err();
590        assert!(
591            err.to_string().contains("semantic_cache_threshold"),
592            "unexpected error: {err}"
593        );
594    }
595
596    #[test]
597    fn semantic_cache_threshold_invalid_neg_infinity() {
598        let err = config_with_sct(f32::NEG_INFINITY).validate().unwrap_err();
599        assert!(
600            err.to_string().contains("semantic_cache_threshold"),
601            "unexpected error: {err}"
602        );
603    }
604
605    fn probe_config(enabled: bool, threshold: f32, hard_fail_threshold: f32) -> Config {
606        let mut cfg = Config::default();
607        cfg.memory.compression.probe.enabled = enabled;
608        cfg.memory.compression.probe.threshold = threshold;
609        cfg.memory.compression.probe.hard_fail_threshold = hard_fail_threshold;
610        cfg
611    }
612
613    #[test]
614    fn probe_disabled_skips_validation() {
615        // Invalid thresholds when probe is disabled must not cause errors.
616        let cfg = probe_config(false, 0.0, 1.0);
617        assert!(cfg.validate().is_ok());
618    }
619
620    #[test]
621    fn probe_valid_thresholds() {
622        let cfg = probe_config(true, 0.6, 0.35);
623        assert!(cfg.validate().is_ok());
624    }
625
626    #[test]
627    fn probe_threshold_zero_invalid() {
628        let err = probe_config(true, 0.0, 0.0).validate().unwrap_err();
629        assert!(
630            err.to_string().contains("probe.threshold"),
631            "unexpected error: {err}"
632        );
633    }
634
635    #[test]
636    fn probe_hard_fail_threshold_above_one_invalid() {
637        let err = probe_config(true, 0.6, 1.0).validate().unwrap_err();
638        assert!(
639            err.to_string().contains("probe.hard_fail_threshold"),
640            "unexpected error: {err}"
641        );
642    }
643
644    #[test]
645    fn probe_hard_fail_gte_threshold_invalid() {
646        let err = probe_config(true, 0.3, 0.9).validate().unwrap_err();
647        assert!(
648            err.to_string().contains("probe.hard_fail_threshold"),
649            "unexpected error: {err}"
650        );
651    }
652
653    fn config_with_completeness_threshold(ct: f32) -> Config {
654        let mut cfg = Config::default();
655        cfg.orchestration.completeness_threshold = ct;
656        cfg
657    }
658
659    #[test]
660    fn completeness_threshold_valid_zero() {
661        assert!(config_with_completeness_threshold(0.0).validate().is_ok());
662    }
663
664    #[test]
665    fn completeness_threshold_valid_default() {
666        assert!(config_with_completeness_threshold(0.7).validate().is_ok());
667    }
668
669    #[test]
670    fn completeness_threshold_valid_one() {
671        assert!(config_with_completeness_threshold(1.0).validate().is_ok());
672    }
673
674    #[test]
675    fn completeness_threshold_invalid_negative() {
676        let err = config_with_completeness_threshold(-0.1)
677            .validate()
678            .unwrap_err();
679        assert!(
680            err.to_string().contains("completeness_threshold"),
681            "unexpected error: {err}"
682        );
683    }
684
685    #[test]
686    fn completeness_threshold_invalid_above_one() {
687        let err = config_with_completeness_threshold(1.1)
688            .validate()
689            .unwrap_err();
690        assert!(
691            err.to_string().contains("completeness_threshold"),
692            "unexpected error: {err}"
693        );
694    }
695
696    #[test]
697    fn completeness_threshold_invalid_nan() {
698        let err = config_with_completeness_threshold(f32::NAN)
699            .validate()
700            .unwrap_err();
701        assert!(
702            err.to_string().contains("completeness_threshold"),
703            "unexpected error: {err}"
704        );
705    }
706
707    #[test]
708    fn completeness_threshold_invalid_infinity() {
709        let err = config_with_completeness_threshold(f32::INFINITY)
710            .validate()
711            .unwrap_err();
712        assert!(
713            err.to_string().contains("completeness_threshold"),
714            "unexpected error: {err}"
715        );
716    }
717
718    fn config_with_provider(name: &str) -> Config {
719        let mut cfg = Config::default();
720        cfg.llm.providers.push(crate::providers::ProviderEntry {
721            provider_type: crate::providers::ProviderKind::Ollama,
722            name: Some(name.into()),
723            ..Default::default()
724        });
725        cfg
726    }
727
728    #[test]
729    fn validate_provider_names_all_empty_ok() {
730        let cfg = Config::default();
731        assert!(cfg.validate_provider_names().is_ok());
732    }
733
734    #[test]
735    fn validate_provider_names_matching_provider_ok() {
736        let mut cfg = config_with_provider("fast");
737        cfg.memory.admission.admission_provider = crate::providers::ProviderName::new("fast");
738        assert!(cfg.validate_provider_names().is_ok());
739    }
740
741    #[test]
742    fn validate_provider_names_unknown_provider_err() {
743        let mut cfg = config_with_provider("fast");
744        cfg.memory.admission.admission_provider =
745            crate::providers::ProviderName::new("nonexistent");
746        let err = cfg.validate_provider_names().unwrap_err();
747        let msg = err.to_string();
748        assert!(
749            msg.contains("admission_provider") && msg.contains("nonexistent"),
750            "unexpected error: {msg}"
751        );
752    }
753
754    #[test]
755    fn validate_provider_names_triage_provider_none_ok() {
756        let mut cfg = config_with_provider("fast");
757        cfg.llm.complexity_routing = Some(crate::providers::ComplexityRoutingConfig {
758            triage_provider: None,
759            ..Default::default()
760        });
761        assert!(cfg.validate_provider_names().is_ok());
762    }
763
764    #[test]
765    fn validate_provider_names_triage_provider_matching_ok() {
766        let mut cfg = config_with_provider("fast");
767        cfg.llm.complexity_routing = Some(crate::providers::ComplexityRoutingConfig {
768            triage_provider: Some(crate::providers::ProviderName::new("fast")),
769            ..Default::default()
770        });
771        assert!(cfg.validate_provider_names().is_ok());
772    }
773
774    #[test]
775    fn validate_provider_names_triage_provider_unknown_err() {
776        let mut cfg = config_with_provider("fast");
777        cfg.llm.complexity_routing = Some(crate::providers::ComplexityRoutingConfig {
778            triage_provider: Some(crate::providers::ProviderName::new("ghost")),
779            ..Default::default()
780        });
781        let err = cfg.validate_provider_names().unwrap_err();
782        let msg = err.to_string();
783        assert!(
784            msg.contains("triage_provider") && msg.contains("ghost"),
785            "unexpected error: {msg}"
786        );
787    }
788
789    // Regression test for issue #2599: TOML float values must deserialise without error
790    // across all config sections that contain f32/f64 fields.
791    #[test]
792    fn toml_float_fields_deserialise_correctly() {
793        let toml = r"
794[llm.router.reputation]
795enabled = true
796decay_factor = 0.95
797weight = 0.3
798
799[llm.router.bandit]
800enabled = false
801cost_weight = 0.3
802alpha = 1.0
803decay_factor = 0.99
804
805[skills]
806disambiguation_threshold = 0.25
807cosine_weight = 0.7
808";
809        // Wrap in a full Config to exercise the nested paths.
810        let wrapped = format!(
811            "{}\n{}",
812            toml,
813            r"[memory.semantic]
814mmr_lambda = 0.7
815"
816        );
817        // We only need the sub-structs to round-trip; build minimal wrappers.
818        let router: crate::providers::RouterConfig = toml::from_str(
819            r"[reputation]
820enabled = true
821decay_factor = 0.95
822weight = 0.3
823",
824        )
825        .expect("RouterConfig with float fields must deserialise");
826        assert!((router.reputation.unwrap().decay_factor - 0.95).abs() < f64::EPSILON);
827
828        let bandit: crate::providers::BanditConfig =
829            toml::from_str("cost_weight = 0.3\nalpha = 1.0\n")
830                .expect("BanditConfig with float fields must deserialise");
831        assert!((bandit.cost_weight - 0.3_f32).abs() < f32::EPSILON);
832
833        let semantic: crate::memory::SemanticConfig = toml::from_str("mmr_lambda = 0.7\n")
834            .expect("SemanticConfig with float fields must deserialise");
835        assert!((semantic.mmr_lambda - 0.7_f32).abs() < f32::EPSILON);
836
837        let skills: crate::features::SkillsConfig =
838            toml::from_str("disambiguation_threshold = 0.25\n")
839                .expect("SkillsConfig with float fields must deserialise");
840        assert!((skills.disambiguation_threshold - 0.25_f32).abs() < f32::EPSILON);
841
842        let _ = wrapped; // silence unused-variable lint
843    }
844
845    #[test]
846    fn focus_auto_consolidate_min_window_zero_rejected() {
847        let mut cfg = Config::default();
848        cfg.agent.focus.auto_consolidate_min_window = 0;
849        let err = cfg.validate().unwrap_err().to_string();
850        assert!(
851            err.contains("auto_consolidate_min_window"),
852            "expected auto_consolidate_min_window in error, got: {err}"
853        );
854    }
855
856    #[test]
857    fn focus_auto_consolidate_min_window_one_accepted() {
858        let mut cfg = Config::default();
859        cfg.agent.focus.auto_consolidate_min_window = 1;
860        assert!(cfg.validate().is_ok());
861    }
862}