1use std::path::Path;
5
6use crate::error::ConfigError;
7use crate::root::Config;
8
9impl Config {
10 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 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 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 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 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 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 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 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 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 fn validate_orchestration(&self) -> Result<(), ConfigError> {
256 if self.orchestration.max_parallel == 0 {
257 return Err(ConfigError::Validation(
258 "orchestration.max_parallel must be > 0".into(),
259 ));
260 }
261 if self.orchestration.max_tasks == 0 {
262 return Err(ConfigError::Validation(
263 "orchestration.max_tasks must be > 0".into(),
264 ));
265 }
266 let ct = self.orchestration.completeness_threshold;
267 if !ct.is_finite() || !(0.0..=1.0).contains(&ct) {
268 return Err(ConfigError::Validation(format!(
269 "orchestration.completeness_threshold must be in [0.0, 1.0], got {ct}"
270 )));
271 }
272 if self.orchestration.cascade_chain_threshold == 1 {
274 return Err(ConfigError::Validation(
275 "orchestration.cascade_chain_threshold=1 aborts on every failure; \
276 use 0 to disable linear-chain cascade abort instead"
277 .into(),
278 ));
279 }
280 let cfrat = self.orchestration.cascade_failure_rate_abort_threshold;
281 if !cfrat.is_finite() || !(0.0..=1.0).contains(&cfrat) {
282 return Err(ConfigError::Validation(format!(
283 "orchestration.cascade_failure_rate_abort_threshold must be in [0.0, 1.0], got {cfrat}"
284 )));
285 }
286 if self.orchestration.lineage_ttl_secs == 0 {
287 return Err(ConfigError::Validation(
288 "orchestration.lineage_ttl_secs must be > 0; \
289 set cascade_chain_threshold=0 to disable lineage tracking instead"
290 .into(),
291 ));
292 }
293 if self.orchestration.aggregator_timeout_secs == 0 {
294 return Err(ConfigError::Validation(
295 "orchestration.aggregator_timeout_secs must be > 0".into(),
296 ));
297 }
298 if self.orchestration.planner_timeout_secs == 0 {
299 return Err(ConfigError::Validation(
300 "orchestration.planner_timeout_secs must be > 0".into(),
301 ));
302 }
303 if self.orchestration.verifier_timeout_secs == 0 {
304 return Err(ConfigError::Validation(
305 "orchestration.verifier_timeout_secs must be > 0".into(),
306 ));
307 }
308 Ok(())
309 }
310
311 fn validate_focus_and_sidequest(&self) -> Result<(), ConfigError> {
313 if self.agent.focus.compression_interval == 0 {
314 return Err(ConfigError::Validation(
315 "agent.focus.compression_interval must be >= 1".into(),
316 ));
317 }
318 if self.agent.focus.min_messages_per_focus == 0 {
319 return Err(ConfigError::Validation(
320 "agent.focus.min_messages_per_focus must be >= 1".into(),
321 ));
322 }
323 if self.agent.focus.auto_consolidate_min_window == 0 {
324 return Err(ConfigError::Validation(
325 "agent.focus.auto_consolidate_min_window must be >= 1 \
326 (set focus.enabled = false to disable auto-consolidation)"
327 .into(),
328 ));
329 }
330 if self.memory.sidequest.interval_turns == 0 {
331 return Err(ConfigError::Validation(
332 "memory.sidequest.interval_turns must be >= 1".into(),
333 ));
334 }
335 if !self.memory.sidequest.max_eviction_ratio.is_finite()
336 || self.memory.sidequest.max_eviction_ratio <= 0.0
337 || self.memory.sidequest.max_eviction_ratio > 1.0
338 {
339 return Err(ConfigError::Validation(format!(
340 "memory.sidequest.max_eviction_ratio must be in (0.0, 1.0], got {}",
341 self.memory.sidequest.max_eviction_ratio
342 )));
343 }
344 Ok(())
345 }
346
347 fn validate_llm_and_skills(&self) -> Result<(), ConfigError> {
349 let sct = self.llm.semantic_cache_threshold;
350 if !(sct.is_finite() && (0.0..=1.0).contains(&sct)) {
351 return Err(ConfigError::Validation(format!(
352 "llm.semantic_cache_threshold must be in [0.0, 1.0], got {sct} \
353 (override via ZEPH_LLM_SEMANTIC_CACHE_THRESHOLD env var)"
354 )));
355 }
356 if self.memory.memcot.enabled && !self.memory.memcot.distill_provider.is_empty() {
358 self.llm.warn_non_fast_tier_provider(
359 &self.memory.memcot.distill_provider,
360 "memory.memcot.distill_provider",
361 &self.memory.memcot.fast_tier_models,
362 );
363 }
364 if self.skills.evaluation.enabled {
366 let weight_sum = self.skills.evaluation.weight_correctness
367 + self.skills.evaluation.weight_reusability
368 + self.skills.evaluation.weight_specificity;
369 if (weight_sum - 1.0_f32).abs() > 1e-3 {
370 return Err(ConfigError::Validation(format!(
371 "skills.evaluation weights must sum to 1.0 (got {weight_sum:.4})"
372 )));
373 }
374 }
375 Ok(())
376 }
377
378 fn validate_mcp_misc(&self) -> Result<(), ConfigError> {
380 if self.mcp.output_schema_hint_bytes < 64 {
381 return Err(ConfigError::Validation(format!(
382 "mcp.output_schema_hint_bytes must be >= 64, got {}; \
383 use forward_output_schema = false to disable forwarding",
384 self.mcp.output_schema_hint_bytes
385 )));
386 }
387 Ok(())
388 }
389
390 fn validate_provider_names(&self) -> Result<(), ConfigError> {
391 let known = self.known_provider_names();
392 self.validate_named_provider_refs(&known)?;
393 self.validate_optional_provider_refs(&known)?;
394 Ok(())
395 }
396
397 fn known_provider_names(&self) -> std::collections::HashSet<String> {
399 self.llm
400 .providers
401 .iter()
402 .map(super::providers::ProviderEntry::effective_name)
403 .collect()
404 }
405
406 fn validate_named_provider_refs(
411 &self,
412 known: &std::collections::HashSet<String>,
413 ) -> Result<(), ConfigError> {
414 self.validate_core_provider_refs(known)?;
415 self.validate_tool_and_quality_provider_refs(known)
416 }
417
418 fn validate_core_provider_refs(
419 &self,
420 known: &std::collections::HashSet<String>,
421 ) -> Result<(), ConfigError> {
422 let fields: &[(&str, &crate::providers::ProviderName)] = &[
423 (
424 "memory.tiers.scene_provider",
425 &self.memory.tiers.scene_provider,
426 ),
427 (
428 "memory.compression.compress_provider",
429 &self.memory.compression.compress_provider,
430 ),
431 (
432 "memory.consolidation.consolidation_provider",
433 &self.memory.consolidation.consolidation_provider,
434 ),
435 (
436 "memory.admission.admission_provider",
437 &self.memory.admission.admission_provider,
438 ),
439 (
440 "memory.admission.goal_utility_provider",
441 &self.memory.admission.goal_utility_provider,
442 ),
443 (
444 "memory.store_routing.routing_classifier_provider",
445 &self.memory.store_routing.routing_classifier_provider,
446 ),
447 (
448 "skills.learning.feedback_provider",
449 &self.skills.learning.feedback_provider,
450 ),
451 (
452 "skills.learning.arise_trace_provider",
453 &self.skills.learning.arise_trace_provider,
454 ),
455 (
456 "skills.learning.stem_provider",
457 &self.skills.learning.stem_provider,
458 ),
459 (
460 "skills.learning.erl_extract_provider",
461 &self.skills.learning.erl_extract_provider,
462 ),
463 (
464 "mcp.pruning.pruning_provider",
465 &self.mcp.pruning.pruning_provider,
466 ),
467 (
468 "mcp.tool_discovery.embedding_provider",
469 &self.mcp.tool_discovery.embedding_provider,
470 ),
471 (
472 "security.response_verification.verifier_provider",
473 &self.security.response_verification.verifier_provider,
474 ),
475 (
476 "orchestration.planner_provider",
477 &self.orchestration.planner_provider,
478 ),
479 (
480 "orchestration.verify_provider",
481 &self.orchestration.verify_provider,
482 ),
483 (
484 "orchestration.tool_provider",
485 &self.orchestration.tool_provider,
486 ),
487 (
488 "skills.evaluation.provider",
489 &self.skills.evaluation.provider,
490 ),
491 (
492 "skills.proactive_exploration.provider",
493 &self.skills.proactive_exploration.provider,
494 ),
495 (
496 "memory.compression_spectrum.promotion_provider",
497 &self.memory.compression_spectrum.promotion_provider,
498 ),
499 ];
500 Self::check_provider_refs(fields, known)
501 }
502
503 fn validate_tool_and_quality_provider_refs(
504 &self,
505 known: &std::collections::HashSet<String>,
506 ) -> Result<(), ConfigError> {
507 let fields: &[(&str, &crate::providers::ProviderName)] = &[
508 (
509 "security.shadow_sentinel.probe_provider",
510 &self.security.shadow_sentinel.probe_provider,
511 ),
512 (
513 "tools.retry.parameter_reformat_provider",
514 &self.tools.retry.parameter_reformat_provider,
515 ),
516 (
517 "tools.adversarial_policy.policy_provider",
518 &self.tools.adversarial_policy.policy_provider,
519 ),
520 (
521 "tools.speculative.pattern.rerank_provider",
522 &self.tools.speculative.pattern.rerank_provider,
523 ),
524 (
525 "tools.compression.evolution_provider",
526 &self.tools.compression.evolution_provider,
527 ),
528 ("quality.proposer_provider", &self.quality.proposer_provider),
529 ("quality.checker_provider", &self.quality.checker_provider),
530 ];
531 Self::check_provider_refs(fields, known)
532 }
533
534 fn check_provider_refs(
535 fields: &[(&str, &crate::providers::ProviderName)],
536 known: &std::collections::HashSet<String>,
537 ) -> Result<(), ConfigError> {
538 for (field, name) in fields {
539 if !name.is_empty() && !known.contains(name.as_str()) {
540 return Err(ConfigError::Validation(format!(
541 "{field} = {:?} does not match any [[llm.providers]] entry",
542 name.as_str()
543 )));
544 }
545 }
546 Ok(())
547 }
548
549 fn validate_optional_provider_refs(
551 &self,
552 known: &std::collections::HashSet<String>,
553 ) -> Result<(), ConfigError> {
554 if let Some(triage) = self
555 .llm
556 .complexity_routing
557 .as_ref()
558 .and_then(|cr| cr.triage_provider.as_ref())
559 .filter(|t| !t.is_empty() && !known.contains(t.as_str()))
560 {
561 return Err(ConfigError::Validation(format!(
562 "llm.complexity_routing.triage_provider = {:?} does not match any \
563 [[llm.providers]] entry",
564 triage.as_str()
565 )));
566 }
567
568 if let Some(embed) = self
569 .llm
570 .router
571 .as_ref()
572 .and_then(|r| r.bandit.as_ref())
573 .map(|b| &b.embedding_provider)
574 .filter(|p| !p.is_empty() && !known.contains(p.as_str()))
575 {
576 return Err(ConfigError::Validation(format!(
577 "llm.router.bandit.embedding_provider = {:?} does not match any \
578 [[llm.providers]] entry",
579 embed.as_str()
580 )));
581 }
582
583 Ok(())
584 }
585
586 fn normalize_legacy_runtime_defaults(&mut self) {
587 use crate::defaults::{
588 default_debug_dir, default_log_file_path, default_skills_dir, default_sqlite_path,
589 is_legacy_default_debug_dir, is_legacy_default_log_file, is_legacy_default_skills_path,
590 is_legacy_default_sqlite_path,
591 };
592
593 if is_legacy_default_sqlite_path(&self.memory.sqlite_path) {
594 self.memory.sqlite_path = default_sqlite_path();
595 }
596
597 for skill_path in &mut self.skills.paths {
598 if is_legacy_default_skills_path(skill_path) {
599 *skill_path = default_skills_dir();
600 }
601 }
602
603 if is_legacy_default_debug_dir(&self.debug.output_dir) {
604 self.debug.output_dir = default_debug_dir();
605 }
606
607 if is_legacy_default_log_file(&self.logging.file) {
608 self.logging.file = default_log_file_path();
609 }
610 }
611}
612
613#[cfg(test)]
614mod tests {
615 use super::*;
616
617 fn config_with_sct(threshold: f32) -> Config {
618 let mut cfg = Config::default();
619 cfg.llm.semantic_cache_threshold = threshold;
620 cfg
621 }
622
623 #[test]
624 fn semantic_cache_threshold_valid_zero() {
625 assert!(config_with_sct(0.0).validate().is_ok());
626 }
627
628 #[test]
629 fn semantic_cache_threshold_valid_mid() {
630 assert!(config_with_sct(0.5).validate().is_ok());
631 }
632
633 #[test]
634 fn semantic_cache_threshold_valid_one() {
635 assert!(config_with_sct(1.0).validate().is_ok());
636 }
637
638 #[test]
639 fn semantic_cache_threshold_invalid_negative() {
640 let err = config_with_sct(-0.1).validate().unwrap_err();
641 assert!(
642 err.to_string().contains("semantic_cache_threshold"),
643 "unexpected error: {err}"
644 );
645 }
646
647 #[test]
648 fn semantic_cache_threshold_invalid_above_one() {
649 let err = config_with_sct(1.1).validate().unwrap_err();
650 assert!(
651 err.to_string().contains("semantic_cache_threshold"),
652 "unexpected error: {err}"
653 );
654 }
655
656 #[test]
657 fn semantic_cache_threshold_invalid_nan() {
658 let err = config_with_sct(f32::NAN).validate().unwrap_err();
659 assert!(
660 err.to_string().contains("semantic_cache_threshold"),
661 "unexpected error: {err}"
662 );
663 }
664
665 #[test]
666 fn semantic_cache_threshold_invalid_infinity() {
667 let err = config_with_sct(f32::INFINITY).validate().unwrap_err();
668 assert!(
669 err.to_string().contains("semantic_cache_threshold"),
670 "unexpected error: {err}"
671 );
672 }
673
674 #[test]
675 fn semantic_cache_threshold_invalid_neg_infinity() {
676 let err = config_with_sct(f32::NEG_INFINITY).validate().unwrap_err();
677 assert!(
678 err.to_string().contains("semantic_cache_threshold"),
679 "unexpected error: {err}"
680 );
681 }
682
683 fn probe_config(enabled: bool, threshold: f32, hard_fail_threshold: f32) -> Config {
684 let mut cfg = Config::default();
685 cfg.memory.compression.probe.enabled = enabled;
686 cfg.memory.compression.probe.threshold = threshold;
687 cfg.memory.compression.probe.hard_fail_threshold = hard_fail_threshold;
688 cfg
689 }
690
691 #[test]
692 fn probe_disabled_skips_validation() {
693 let cfg = probe_config(false, 0.0, 1.0);
695 assert!(cfg.validate().is_ok());
696 }
697
698 #[test]
699 fn probe_valid_thresholds() {
700 let cfg = probe_config(true, 0.6, 0.35);
701 assert!(cfg.validate().is_ok());
702 }
703
704 #[test]
705 fn probe_threshold_zero_invalid() {
706 let err = probe_config(true, 0.0, 0.0).validate().unwrap_err();
707 assert!(
708 err.to_string().contains("probe.threshold"),
709 "unexpected error: {err}"
710 );
711 }
712
713 #[test]
714 fn probe_hard_fail_threshold_above_one_invalid() {
715 let err = probe_config(true, 0.6, 1.0).validate().unwrap_err();
716 assert!(
717 err.to_string().contains("probe.hard_fail_threshold"),
718 "unexpected error: {err}"
719 );
720 }
721
722 #[test]
723 fn probe_hard_fail_gte_threshold_invalid() {
724 let err = probe_config(true, 0.3, 0.9).validate().unwrap_err();
725 assert!(
726 err.to_string().contains("probe.hard_fail_threshold"),
727 "unexpected error: {err}"
728 );
729 }
730
731 fn config_with_completeness_threshold(ct: f32) -> Config {
732 let mut cfg = Config::default();
733 cfg.orchestration.completeness_threshold = ct;
734 cfg
735 }
736
737 #[test]
738 fn completeness_threshold_valid_zero() {
739 assert!(config_with_completeness_threshold(0.0).validate().is_ok());
740 }
741
742 #[test]
743 fn completeness_threshold_valid_default() {
744 assert!(config_with_completeness_threshold(0.7).validate().is_ok());
745 }
746
747 #[test]
748 fn completeness_threshold_valid_one() {
749 assert!(config_with_completeness_threshold(1.0).validate().is_ok());
750 }
751
752 #[test]
753 fn completeness_threshold_invalid_negative() {
754 let err = config_with_completeness_threshold(-0.1)
755 .validate()
756 .unwrap_err();
757 assert!(
758 err.to_string().contains("completeness_threshold"),
759 "unexpected error: {err}"
760 );
761 }
762
763 #[test]
764 fn completeness_threshold_invalid_above_one() {
765 let err = config_with_completeness_threshold(1.1)
766 .validate()
767 .unwrap_err();
768 assert!(
769 err.to_string().contains("completeness_threshold"),
770 "unexpected error: {err}"
771 );
772 }
773
774 #[test]
775 fn completeness_threshold_invalid_nan() {
776 let err = config_with_completeness_threshold(f32::NAN)
777 .validate()
778 .unwrap_err();
779 assert!(
780 err.to_string().contains("completeness_threshold"),
781 "unexpected error: {err}"
782 );
783 }
784
785 #[test]
786 fn completeness_threshold_invalid_infinity() {
787 let err = config_with_completeness_threshold(f32::INFINITY)
788 .validate()
789 .unwrap_err();
790 assert!(
791 err.to_string().contains("completeness_threshold"),
792 "unexpected error: {err}"
793 );
794 }
795
796 fn config_with_provider(name: &str) -> Config {
797 let mut cfg = Config::default();
798 cfg.llm.providers.push(crate::providers::ProviderEntry {
799 provider_type: crate::providers::ProviderKind::Ollama,
800 name: Some(name.into()),
801 ..Default::default()
802 });
803 cfg
804 }
805
806 #[test]
807 fn validate_provider_names_all_empty_ok() {
808 let cfg = Config::default();
809 assert!(cfg.validate_provider_names().is_ok());
810 }
811
812 #[test]
813 fn validate_provider_names_matching_provider_ok() {
814 let mut cfg = config_with_provider("fast");
815 cfg.memory.admission.admission_provider = crate::providers::ProviderName::new("fast");
816 assert!(cfg.validate_provider_names().is_ok());
817 }
818
819 #[test]
820 fn validate_provider_names_unknown_provider_err() {
821 let mut cfg = config_with_provider("fast");
822 cfg.memory.admission.admission_provider =
823 crate::providers::ProviderName::new("nonexistent");
824 let err = cfg.validate_provider_names().unwrap_err();
825 let msg = err.to_string();
826 assert!(
827 msg.contains("admission_provider") && msg.contains("nonexistent"),
828 "unexpected error: {msg}"
829 );
830 }
831
832 #[test]
833 fn validate_provider_names_triage_provider_none_ok() {
834 let mut cfg = config_with_provider("fast");
835 cfg.llm.complexity_routing = Some(crate::providers::ComplexityRoutingConfig {
836 triage_provider: None,
837 ..Default::default()
838 });
839 assert!(cfg.validate_provider_names().is_ok());
840 }
841
842 #[test]
843 fn validate_provider_names_triage_provider_matching_ok() {
844 let mut cfg = config_with_provider("fast");
845 cfg.llm.complexity_routing = Some(crate::providers::ComplexityRoutingConfig {
846 triage_provider: Some(crate::providers::ProviderName::new("fast")),
847 ..Default::default()
848 });
849 assert!(cfg.validate_provider_names().is_ok());
850 }
851
852 #[test]
853 fn validate_provider_names_triage_provider_unknown_err() {
854 let mut cfg = config_with_provider("fast");
855 cfg.llm.complexity_routing = Some(crate::providers::ComplexityRoutingConfig {
856 triage_provider: Some(crate::providers::ProviderName::new("ghost")),
857 ..Default::default()
858 });
859 let err = cfg.validate_provider_names().unwrap_err();
860 let msg = err.to_string();
861 assert!(
862 msg.contains("triage_provider") && msg.contains("ghost"),
863 "unexpected error: {msg}"
864 );
865 }
866
867 #[test]
870 fn toml_float_fields_deserialise_correctly() {
871 let toml = r"
872[llm.router.reputation]
873enabled = true
874decay_factor = 0.95
875weight = 0.3
876
877[llm.router.bandit]
878enabled = false
879cost_weight = 0.3
880alpha = 1.0
881decay_factor = 0.99
882
883[skills]
884disambiguation_threshold = 0.25
885cosine_weight = 0.7
886";
887 let wrapped = format!(
889 "{}\n{}",
890 toml,
891 r"[memory.semantic]
892mmr_lambda = 0.7
893"
894 );
895 let router: crate::providers::RouterConfig = toml::from_str(
897 r"[reputation]
898enabled = true
899decay_factor = 0.95
900weight = 0.3
901",
902 )
903 .expect("RouterConfig with float fields must deserialise");
904 assert!((router.reputation.unwrap().decay_factor - 0.95).abs() < f64::EPSILON);
905
906 let bandit: crate::providers::BanditConfig =
907 toml::from_str("cost_weight = 0.3\nalpha = 1.0\n")
908 .expect("BanditConfig with float fields must deserialise");
909 assert!((bandit.cost_weight - 0.3_f32).abs() < f32::EPSILON);
910
911 let semantic: crate::memory::SemanticConfig = toml::from_str("mmr_lambda = 0.7\n")
912 .expect("SemanticConfig with float fields must deserialise");
913 assert!((semantic.mmr_lambda - 0.7_f32).abs() < f32::EPSILON);
914
915 let skills: crate::features::SkillsConfig =
916 toml::from_str("disambiguation_threshold = 0.25\n")
917 .expect("SkillsConfig with float fields must deserialise");
918 assert!((skills.disambiguation_threshold - 0.25_f32).abs() < f32::EPSILON);
919
920 let _ = wrapped; }
922
923 #[test]
924 fn validate_max_parallel_zero_rejected() {
925 let mut cfg = Config::default();
926 cfg.orchestration.max_parallel = 0;
927 let err = cfg.validate().unwrap_err().to_string();
928 assert!(
929 err.contains("max_parallel"),
930 "expected max_parallel in error, got: {err}"
931 );
932 }
933
934 #[test]
935 fn validate_max_parallel_one_accepted() {
936 let mut cfg = Config::default();
937 cfg.orchestration.max_parallel = 1;
938 assert!(cfg.validate().is_ok());
939 }
940
941 #[test]
942 fn validate_max_tasks_zero_rejected() {
943 let mut cfg = Config::default();
944 cfg.orchestration.max_tasks = 0;
945 let err = cfg.validate().unwrap_err().to_string();
946 assert!(
947 err.contains("max_tasks"),
948 "expected max_tasks in error, got: {err}"
949 );
950 }
951
952 #[test]
953 fn validate_max_tasks_one_accepted() {
954 let mut cfg = Config::default();
955 cfg.orchestration.max_tasks = 1;
956 assert!(cfg.validate().is_ok());
957 }
958
959 #[test]
960 fn validate_aggregator_timeout_zero_rejected() {
961 let mut cfg = Config::default();
962 cfg.orchestration.aggregator_timeout_secs = 0;
963 let err = cfg.validate().unwrap_err().to_string();
964 assert!(
965 err.contains("aggregator_timeout_secs"),
966 "expected aggregator_timeout_secs in error, got: {err}"
967 );
968 }
969
970 #[test]
971 fn validate_planner_timeout_zero_rejected() {
972 let mut cfg = Config::default();
973 cfg.orchestration.planner_timeout_secs = 0;
974 let err = cfg.validate().unwrap_err().to_string();
975 assert!(
976 err.contains("planner_timeout_secs"),
977 "expected planner_timeout_secs in error, got: {err}"
978 );
979 }
980
981 #[test]
982 fn validate_verifier_timeout_zero_rejected() {
983 let mut cfg = Config::default();
984 cfg.orchestration.verifier_timeout_secs = 0;
985 let err = cfg.validate().unwrap_err().to_string();
986 assert!(
987 err.contains("verifier_timeout_secs"),
988 "expected verifier_timeout_secs in error, got: {err}"
989 );
990 }
991
992 #[test]
993 fn focus_auto_consolidate_min_window_zero_rejected() {
994 let mut cfg = Config::default();
995 cfg.agent.focus.auto_consolidate_min_window = 0;
996 let err = cfg.validate().unwrap_err().to_string();
997 assert!(
998 err.contains("auto_consolidate_min_window"),
999 "expected auto_consolidate_min_window in error, got: {err}"
1000 );
1001 }
1002
1003 #[test]
1004 fn focus_auto_consolidate_min_window_one_accepted() {
1005 let mut cfg = Config::default();
1006 cfg.agent.focus.auto_consolidate_min_window = 1;
1007 assert!(cfg.validate().is_ok());
1008 }
1009}