1use std::collections::HashMap;
4use std::collections::HashSet;
5use std::env;
6use std::sync::OnceLock;
7
8use crate::config;
9use crate::engine;
10use crate::engine::cooldown;
11use crate::engine::router::selection;
12use crate::engine::runner::agents::opencode;
13
14const COMPLEXITY_TIERS: [&str; 3] = ["simple", "medium", "complex"];
16
17pub fn min_healthy_agents_threshold() -> usize {
20 config::get("dispatch.min_healthy_agents")
21 .ok()
22 .and_then(|v| v.parse().ok())
23 .unwrap_or(2)
24}
25
26pub fn sequential_dispatch_delay_ms() -> u64 {
28 config::get("dispatch.sequential_delay_ms")
29 .ok()
30 .and_then(|v| v.parse().ok())
31 .unwrap_or(1000)
32}
33
34pub fn health_check_window_hours() -> u32 {
39 config::get("dispatch.health_check_window_hours")
40 .ok()
41 .and_then(|v| v.parse().ok())
42 .unwrap_or(cooldown::DEFAULT_HEALTH_CHECK_WINDOW_HOURS)
43}
44
45pub fn degraded_rate_limit_threshold() -> i64 {
59 config::get("dispatch.degraded_rate_limit_threshold")
60 .ok()
61 .and_then(|v| v.parse().ok())
62 .unwrap_or(cooldown::DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD)
63}
64
65pub fn retry_base_delay_ms() -> u64 {
67 config::get("dispatch.retry_base_delay_ms")
68 .ok()
69 .and_then(|v| v.parse().ok())
70 .unwrap_or(10_000)
71}
72
73pub fn retry_max_delay_ms() -> u64 {
75 config::get("dispatch.retry_max_delay_ms")
76 .ok()
77 .and_then(|v| v.parse().ok())
78 .unwrap_or(120_000)
79}
80
81pub const MAX_ROUTER_TIMEOUT_SECS: u64 = 45;
86
87pub const SKIP_LIMITED_THRESHOLD: f64 = 0.3;
90
91pub fn get_agent_backoff_base(agent: &str) -> i64 {
100 let key = format!("router.backoff_base.{agent}");
101 config::get(&key)
102 .ok()
103 .and_then(|v| v.parse().ok())
104 .unwrap_or(cooldown::BACKOFF_BASE_SECS)
105}
106
107pub fn max_tasks_per_routing_tick() -> usize {
114 config::get("router.max_tasks_per_tick")
115 .ok()
116 .and_then(|v| v.parse().ok())
117 .unwrap_or(1)
118}
119
120pub const DEFAULT_AGENTS: &[&str] = &[
127 "claude", "codex", "opencode", "kimi", "minimax", "glm", "grok",
128];
129
130#[derive(Debug, Clone)]
132pub struct RouterConfig {
133 pub mode: String,
139 pub router_agent: String,
141 pub router_model: String,
143 pub timeout_seconds: u64,
145 pub fallback_executor: String,
147 pub agents: Vec<String>,
149 pub max_route_attempts: u32,
151 pub allowed_tools: Vec<String>,
153 pub model_map: HashMap<String, HashMap<String, Vec<String>>>,
157 pub weighted_round_robin: bool,
160 pub pool: Vec<String>,
164 pub fallback: String,
167 pub self_routing_penalty: f64,
175 pub weights: HashMap<String, f64>,
193 pub agent_backoff_bases: HashMap<String, i64>,
200 pub max_tasks_per_tick: usize,
207 pub ollama_url: String,
209 pub ollama_model: String,
211 pub ollama_timeout_seconds: u64,
213}
214
215pub fn parse_pool_entry(entry: &str) -> (String, String) {
222 if let Some(colon_pos) = entry.find(':') {
223 let agent = entry[..colon_pos].to_string();
224 let model = entry[colon_pos + 1..].to_string();
225 let model = RouterConfig::normalize_model_identifier(&model);
227 (agent, model)
228 } else {
229 (entry.to_string(), String::new())
230 }
231}
232
233impl Default for RouterConfig {
234 fn default() -> Self {
235 Self {
236 mode: "round_robin".to_string(),
237 router_agent: "claude".to_string(),
238 router_model: String::new(),
240 timeout_seconds: 45,
241 fallback_executor: "codex".to_string(),
242 agents: DEFAULT_AGENTS.iter().map(ToString::to_string).collect(),
243 max_route_attempts: 3,
244 pool: vec![],
245 fallback: String::new(),
246 self_routing_penalty: 1.0,
247 weights: HashMap::new(),
248 allowed_tools: vec![
249 "yq".to_string(),
250 "jq".to_string(),
251 "bash".to_string(),
252 "just".to_string(),
253 "git".to_string(),
254 "rg".to_string(),
255 "sed".to_string(),
256 "awk".to_string(),
257 "python3".to_string(),
258 "node".to_string(),
259 "npm".to_string(),
260 "bun".to_string(),
261 ],
262 model_map: HashMap::new(),
266 weighted_round_robin: false,
267 agent_backoff_bases: HashMap::new(),
268 max_tasks_per_tick: 1,
269 ollama_url: "http://localhost:11434".to_string(),
270 ollama_model: "qwen2.5-coder:3b-instruct".to_string(),
271 ollama_timeout_seconds: 30,
272 }
273 }
274}
275
276impl RouterConfig {
277 pub fn from_config() -> Self {
279 let mut config = Self::default();
280
281 if let Ok(mode) = config::get("router.mode")
283 && (mode == "round_robin" || mode == "llm" || mode == "local")
284 {
285 config.mode = mode;
286 }
287
288 if let Ok(agent) = config::get("router.agent")
289 && !agent.is_empty()
290 {
291 config.router_agent = agent;
292 }
293
294 if let Ok(model) = config::get("router.model")
295 && !model.is_empty()
296 {
297 config.router_model = RouterConfig::normalize_model_identifier(&model);
298 }
299
300 if let Ok(timeout) = config::get("router.timeout_seconds")
301 && let Ok(secs) = timeout.parse::<u64>()
302 {
303 let clamped = secs.min(MAX_ROUTER_TIMEOUT_SECS);
304 if clamped != secs {
305 static TIMEOUT_CLAMP_WARNED: OnceLock<()> = OnceLock::new();
306 TIMEOUT_CLAMP_WARNED.get_or_init(|| {
307 tracing::warn!(
308 configured_secs = secs,
309 applied_secs = clamped,
310 max_secs = MAX_ROUTER_TIMEOUT_SECS,
311 "router.timeout_seconds is too high; clamping to keep routing responsive"
312 );
313 });
314 }
315 config.timeout_seconds = clamped;
316 }
317
318 if let Ok(fallback) = config::get("router.fallback_executor")
319 && !fallback.is_empty()
320 {
321 config.fallback_executor = fallback;
322 }
323
324 config.agents = engine::configured_agents();
326
327 let exclude_agents = env::var("ORCH_EXCLUDE_AGENTS")
333 .map(|v| {
334 v.split(',')
335 .map(|s| s.trim().to_string())
336 .filter(|s| !s.is_empty())
337 .collect::<Vec<_>>()
338 })
339 .unwrap_or_default();
340 if !exclude_agents.is_empty() {
341 let original_len = config.agents.len();
342 config.agents.retain(|a| !exclude_agents.contains(a));
343 let removed_count = original_len - config.agents.len();
344 if removed_count > 0 {
345 tracing::warn!(
346 "ORCH_EXCLUDE_AGENTS={}: temporarily removing {} agent(s) from router",
347 exclude_agents.join(","),
348 removed_count
349 );
350 }
351 }
352
353 if let Ok(max_attempts) = config::get("router.max_route_attempts")
354 && let Ok(n) = max_attempts.parse::<u32>()
355 {
356 config.max_route_attempts = n;
357 }
358
359 if let Ok(tools_str) = config::get("router.allowed_tools")
361 && !tools_str.is_empty()
362 && tools_str != "[]"
363 {
364 if let Ok(tools_arr) = serde_json::from_str::<Vec<String>>(&tools_str) {
366 config.allowed_tools = tools_arr;
367 } else {
368 config.allowed_tools = tools_str
370 .split(',')
371 .map(|s| s.trim().to_string())
372 .filter(|s| !s.is_empty())
373 .collect();
374 }
375 }
376
377 if let Ok(val) = config::get("router.weighted_round_robin") {
379 config.weighted_round_robin = val == "true" || val == "1";
380 }
381
382 if let Ok(val) = config::get("router.self_routing_penalty")
384 && let Ok(penalty) = val.parse::<f64>()
385 {
386 config.self_routing_penalty = penalty.clamp(0.0, 1.0);
387 }
388
389 for agent in &config.agents {
391 let key = format!("router.weights.{agent}");
392 if let Ok(val) = config::get(&key)
393 && let Ok(w) = val.parse::<f64>()
394 {
395 config.weights.insert(agent.clone(), w.max(0.0));
396 }
397 }
398
399 for agent in &config.agents {
401 let key = format!("router.backoff_base.{agent}");
402 if let Ok(val) = config::get(&key)
403 && let Ok(secs) = val.parse::<i64>()
404 {
405 config.agent_backoff_bases.insert(agent.clone(), secs);
406 }
407 }
408
409 if let Ok(val) = config::get("router.max_tasks_per_tick")
411 && let Ok(n) = val.parse::<usize>()
412 && n > 0
413 {
414 config.max_tasks_per_tick = n;
415 }
416
417 match config::get_list("router.pool") {
421 Ok(pool_list) if !pool_list.is_empty() => {
422 config.pool = pool_list;
423 }
424 _ => {
425 if let Ok(pool_raw) = config::get("router.pool") {
427 let parsed = pool_raw
428 .split(',')
429 .map(|s| s.trim().to_string())
430 .filter(|s| !s.is_empty())
431 .collect::<Vec<_>>();
432 if !parsed.is_empty() {
433 config.pool = parsed;
434 }
435 }
436 }
437 }
438
439 if let Ok(fallback) = config::get("router.fallback")
441 && !fallback.is_empty()
442 {
443 config.fallback = fallback;
444 }
445
446 let known_agents = engine::configured_agents();
452 let known_complexities = ["simple", "medium", "complex", "review"];
453 for agent in &known_agents {
454 let key = format!("models.{agent}");
455 if let Some(models) = Self::read_model_pool_from_config(&key) {
456 for complexity in known_complexities {
457 config
458 .model_map
459 .entry(complexity.to_string())
460 .or_default()
461 .insert(agent.clone(), models.clone());
462 }
463 }
464 }
465
466 for complexity in known_complexities {
471 for agent in &known_agents {
472 let key = format!("model_map.{complexity}.{agent}");
473 if let Some(models) = Self::read_model_pool_from_config(&key) {
474 config
475 .model_map
476 .entry(complexity.to_string())
477 .or_default()
478 .insert(agent.clone(), models);
479 }
480 }
481 }
482
483 let discovered_opencode = if config.uses_opencode() {
491 opencode::discover_opencode_models()
492 } else {
493 Vec::new()
494 };
495 if !discovered_opencode.is_empty() {
496 let discovered: HashSet<String> = discovered_opencode.into_iter().collect();
497 for complexity in known_complexities {
498 if let Some(agent_models) = config.model_map.get(complexity)
499 && let Some(models) = agent_models.get("opencode")
500 {
501 for model in models {
502 if model != "opencode:free" && !discovered.contains(model) {
503 tracing::warn!(
504 complexity,
505 model,
506 "opencode model from config not present in provider model list; pruning from dispatch pool"
507 );
508 }
509 }
510 }
511 }
512 let pruned =
513 Self::prune_unavailable_opencode_models(&mut config.model_map, &discovered);
514 if pruned > 0 {
515 tracing::info!(
516 pruned_count = pruned,
517 "model_pruned_unavailable: removed opencode models absent from provider catalog"
518 );
519 }
520 }
521
522 if let Ok(url) = config::get("router.ollama_url")
524 && !url.is_empty()
525 {
526 config.ollama_url = url;
527 }
528 if let Ok(model) = config::get("router.ollama_model")
529 && !model.is_empty()
530 {
531 config.ollama_model = model;
532 }
533 if let Ok(timeout) = config::get("router.ollama_timeout_seconds")
534 && let Ok(secs) = timeout.parse::<u64>()
535 && secs > 0
536 {
537 config.ollama_timeout_seconds = secs;
538 }
539
540 config
541 }
542
543 pub fn effective_pool(&self) -> Vec<String> {
545 if self.pool.is_empty() {
546 vec![format!("{}:{}", self.router_agent, self.router_model)]
547 } else {
548 self.pool.clone()
549 }
550 }
551
552 pub fn effective_fallback(&self) -> String {
554 if self.fallback.is_empty() {
555 format!("{}:{}", self.router_agent, self.router_model)
556 } else {
557 self.fallback.clone()
558 }
559 }
560
561 fn is_valid_model_identifier(model: &str) -> bool {
564 if model.is_empty() {
565 return false;
566 }
567 if model.ends_with('/') {
569 return false;
570 }
571 if model.chars().any(char::is_whitespace) {
573 return false;
574 }
575 if let Some(slash_pos) = model.find('/') {
577 let before = &model[..slash_pos];
578 let after = &model[slash_pos + 1..];
579 if before.is_empty() || after.is_empty() {
580 return false;
581 }
582 }
583 true
584 }
585
586 pub fn normalize_model_identifier(model: &str) -> String {
590 model.trim_end_matches('/').to_string()
591 }
592
593 pub fn configured_models(agent: &str) -> Vec<String> {
595 Self::read_model_pool_from_config(&format!("models.{agent}")).unwrap_or_default()
596 }
597
598 fn read_model_pool_from_config(key: &str) -> Option<Vec<String>> {
599 match config::get_list(key) {
600 Ok(list) => {
601 if !list.is_empty() {
602 return Some(
603 list.iter()
604 .map(|m| RouterConfig::normalize_model_identifier(m))
605 .collect(),
606 );
607 }
608 }
609 _ => {
610 if let Ok(val) = config::get(key)
611 && !val.is_empty()
612 {
613 return Some(vec![RouterConfig::normalize_model_identifier(&val)]);
614 }
615 }
616 }
617
618 None
619 }
620
621 fn expanded_model_pool(&self, agent: &str, complexity: &str) -> Option<Vec<String>> {
622 let pool = self.model_map.get(complexity)?.get(agent)?;
623 if pool.is_empty() {
624 return Some(Vec::new());
625 }
626
627 let mut expanded_pool = Vec::new();
628 let mut has_free = false;
629
630 for model in pool {
631 let normalized = Self::normalize_model_identifier(model);
633 if normalized == "opencode:free" {
634 has_free = true;
635 } else if Self::is_valid_model_identifier(&normalized) {
636 expanded_pool.push(normalized);
637 } else {
638 tracing::debug!(agent, model, "skipping invalid model identifier in config");
639 }
640 }
641
642 if has_free {
643 expanded_pool.extend(opencode::discover_free_opencode_models());
644 }
645
646 expanded_pool.retain(|m| Self::is_valid_model_identifier(m));
648
649 if agent == "opencode" {
652 let discovered = opencode::discover_opencode_models();
653 if !discovered.is_empty() {
654 let discovered_set: HashSet<String> = discovered.into_iter().collect();
655 expanded_pool.retain(|m| discovered_set.contains(m));
656 }
657 }
658
659 Some(expanded_pool)
660 }
661
662 pub(crate) fn model_pool_for_complexity(
663 &self,
664 agent: &str,
665 complexity: &str,
666 ) -> Option<Vec<String>> {
667 self.expanded_model_pool(agent, complexity)
668 }
669
670 pub fn has_available_model_for_complexity(&self, agent: &str, complexity: &str) -> bool {
671 match self.expanded_model_pool(agent, complexity) {
672 None => false,
673 Some(pool) => pool
674 .iter()
675 .any(|model| !cooldown::is_model_in_cooldown(agent, model)),
676 }
677 }
678
679 pub fn has_available_model_in_any_tier(&self, agent: &str, complexity: &str) -> bool {
682 Self::tier_search_order(complexity)
683 .into_iter()
684 .any(|tier| self.has_available_model_for_complexity(agent, tier))
685 }
686
687 pub fn model_for_complexity(
695 &self,
696 agent: &str,
697 complexity: &str,
698 task_id: &str,
699 ) -> Option<String> {
700 let expanded_pool = self.expanded_model_pool(agent, complexity)?;
701 if expanded_pool.is_empty() {
702 return None;
703 }
704 let start = selection::simple_hash_index_for(expanded_pool.len(), task_id);
706 for i in 0..expanded_pool.len() {
708 let model = &expanded_pool[(start + i) % expanded_pool.len()];
709 if !Self::is_valid_model_identifier(model) {
711 tracing::debug!(
712 agent,
713 model,
714 "invalid model identifier slipped through validation"
715 );
716 continue;
717 }
718 if !cooldown::is_model_in_cooldown(agent, model) {
719 return Some(Self::normalize_model_identifier(model));
721 }
722 }
723 None
725 }
726
727 fn tier_search_order(complexity: &str) -> Vec<&str> {
730 let Some(idx) = COMPLEXITY_TIERS.iter().position(|t| *t == complexity) else {
731 return vec![complexity];
732 };
733 let mut order = vec![COMPLEXITY_TIERS[idx]];
734 order.extend(&COMPLEXITY_TIERS[idx + 1..]);
735 order.extend(COMPLEXITY_TIERS[..idx].iter().rev());
736 order
737 }
738
739 pub fn model_for_complexity_or_adjacent(
742 &self,
743 agent: &str,
744 complexity: &str,
745 task_id: &str,
746 ) -> Option<(String, String)> {
747 Self::tier_search_order(complexity)
748 .into_iter()
749 .find_map(|tier| {
750 self.model_for_complexity(agent, tier, task_id)
751 .map(|model| (model, tier.to_string()))
752 })
753 }
754
755 pub fn tier_of_model(&self, agent: &str, model: &str, complexity: &str) -> String {
758 Self::tier_search_order(complexity)
759 .into_iter()
760 .find(|tier| {
761 self.expanded_model_pool(agent, tier)
762 .is_some_and(|pool| pool.iter().any(|m| m == model))
763 })
764 .unwrap_or(complexity)
765 .to_string()
766 }
767
768 pub(crate) fn uses_opencode(&self) -> bool {
772 fn names_opencode(entry: &str) -> bool {
773 entry == "opencode" || entry.starts_with("opencode:")
774 }
775
776 if self
777 .model_map
778 .values()
779 .any(|by_agent| by_agent.contains_key("opencode"))
780 {
781 return true;
782 }
783
784 self.effective_pool().iter().any(|e| names_opencode(e))
785 || names_opencode(&self.effective_fallback())
786 }
787
788 fn prune_unavailable_opencode_models(
794 model_map: &mut HashMap<String, HashMap<String, Vec<String>>>,
795 discovered: &HashSet<String>,
796 ) -> usize {
797 let mut pruned = 0;
798 for agent_models in model_map.values_mut() {
799 if let Some(models) = agent_models.get_mut("opencode") {
800 let before = models.len();
801 models.retain(|m| m == "opencode:free" || discovered.contains(m));
802 pruned += before - models.len();
803 }
804 }
805 pruned
806 }
807}
808
809#[cfg(test)]
810mod tests {
811 use super::{MAX_ROUTER_TIMEOUT_SECS, RouterConfig};
812 use crate::engine::cooldown;
813 use serial_test::serial;
814 use std::collections::HashMap;
815 use std::collections::HashSet;
816 use std::env;
817 use std::fs;
818 use std::path::Path;
819 use std::path::PathBuf;
820 use std::sync::{Mutex, OnceLock};
821
822 struct CurrentDirGuard {
823 original: PathBuf,
824 }
825
826 impl CurrentDirGuard {
827 fn set(path: &Path) -> Self {
828 let original = env::current_dir().unwrap();
829 env::set_current_dir(path).unwrap();
830 Self { original }
831 }
832 }
833
834 impl Drop for CurrentDirGuard {
835 fn drop(&mut self) {
836 env::set_current_dir(&self.original).unwrap();
837 }
838 }
839
840 fn cwd_mutex() -> &'static Mutex<()> {
841 static CWD_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
842 CWD_MUTEX.get_or_init(|| Mutex::new(()))
843 }
844
845 #[serial(cooldown_state)]
846 #[tokio::test]
847 async fn model_for_complexity_returns_none_when_all_models_cooled() {
848 cooldown::reset_global_state().await;
849 let mut config = RouterConfig::default();
850 config
852 .model_map
853 .entry("complex".to_string())
854 .or_default()
855 .insert(
856 "testagent_allcooled".to_string(),
857 vec![
858 "cooldown-model-a".to_string(),
859 "cooldown-model-b".to_string(),
860 ],
861 );
862
863 cooldown::record_model_failure("testagent_allcooled", "cooldown-model-a").await;
865 cooldown::record_model_failure("testagent_allcooled", "cooldown-model-b").await;
866
867 let result = config.model_for_complexity("testagent_allcooled", "complex", "task-0");
868 assert!(
869 result.is_none(),
870 "should return None when all models in pool are in cooldown, got {result:?}"
871 );
872 }
873
874 fn tiered_config(agent: &str, tiers: &[(&str, &str)]) -> RouterConfig {
875 let mut config = RouterConfig::default();
876 config.model_map.clear();
877 for (tier, model) in tiers {
878 config
879 .model_map
880 .entry((*tier).to_string())
881 .or_default()
882 .insert(agent.to_string(), vec![(*model).to_string()]);
883 }
884 config
885 }
886
887 #[serial(cooldown_state)]
888 #[tokio::test]
889 async fn adjacent_tier_prefers_higher_over_lower() {
890 cooldown::reset_global_state().await;
891 let agent = "tieragent_higher";
892 let config = tiered_config(
893 agent,
894 &[("simple", "t-s"), ("medium", "t-m"), ("complex", "t-c")],
895 );
896 cooldown::record_model_failure(agent, "t-m").await;
897
898 let got = config.model_for_complexity_or_adjacent(agent, "medium", "t");
899 assert_eq!(got, Some(("t-c".to_string(), "complex".to_string())));
900 assert_eq!(config.tier_of_model(agent, "t-c", "medium"), "complex");
901 }
902
903 #[serial(cooldown_state)]
904 #[tokio::test]
905 async fn simple_task_tries_medium_then_complex_before_lower() {
906 cooldown::reset_global_state().await;
907 let agent = "tieragent_simple";
908 let config = tiered_config(
909 agent,
910 &[("simple", "u-s"), ("medium", "u-m"), ("complex", "u-c")],
911 );
912 cooldown::record_model_failure(agent, "u-s").await;
913 cooldown::record_model_failure(agent, "u-m").await;
914
915 let got = config.model_for_complexity_or_adjacent(agent, "simple", "t");
916 assert_eq!(got, Some(("u-c".to_string(), "complex".to_string())));
917 }
918
919 #[serial(cooldown_state)]
920 #[tokio::test]
921 async fn adjacent_tier_falls_back_to_lower_when_higher_tiers_are_unavailable() {
922 cooldown::reset_global_state().await;
923 let agent = "tieragent_lower";
924 let config = tiered_config(agent, &[("simple", "v-s"), ("medium", "v-m")]);
925 cooldown::record_model_failure(agent, "v-m").await;
926
927 let got = config.model_for_complexity_or_adjacent(agent, "complex", "t");
928 assert_eq!(got, Some(("v-s".to_string(), "simple".to_string())));
929 }
930
931 #[serial(cooldown_state)]
932 #[tokio::test]
933 async fn adjacent_tier_returns_none_when_every_tier_is_cooled() {
934 cooldown::reset_global_state().await;
935 let agent = "tieragent_allcooled";
936 let config = tiered_config(
937 agent,
938 &[("simple", "w-s"), ("medium", "w-m"), ("complex", "w-c")],
939 );
940 for m in ["w-s", "w-m", "w-c"] {
941 cooldown::record_model_failure(agent, m).await;
942 }
943
944 assert_eq!(
945 config.model_for_complexity_or_adjacent(agent, "medium", "t"),
946 None
947 );
948 }
949
950 #[serial(cooldown_state)]
951 #[tokio::test]
952 async fn model_for_complexity_returns_none_when_single_model_cooled() {
953 cooldown::reset_global_state().await;
954 let mut config = RouterConfig::default();
955 config
956 .model_map
957 .entry("complex".to_string())
958 .or_default()
959 .insert(
960 "testagent_singlecooled".to_string(),
961 vec!["single-cooled-model".to_string()],
962 );
963
964 cooldown::record_model_failure("testagent_singlecooled", "single-cooled-model").await;
965
966 let result = config.model_for_complexity("testagent_singlecooled", "complex", "task-0");
967 assert!(
968 result.is_none(),
969 "should return None when the only model in pool is in cooldown, got {result:?}"
970 );
971 }
972
973 #[serial(cooldown_state)]
974 #[test]
975 fn model_for_complexity_returns_model_when_not_cooled() {
976 let mut config = RouterConfig::default();
977 config
978 .model_map
979 .entry("complex".to_string())
980 .or_default()
981 .insert(
982 "testagent_notcooled".to_string(),
983 vec!["healthy-model".to_string()],
984 );
985
986 let result = config.model_for_complexity("testagent_notcooled", "complex", "task-0");
988 assert_eq!(
989 result.as_deref(),
990 Some("healthy-model"),
991 "should return the model when it is not in cooldown"
992 );
993 }
994
995 #[serial(cooldown_state)]
996 #[test]
997 fn has_available_model_returns_false_when_no_pool_configured() {
998 let mut config = RouterConfig::default();
999 config
1001 .model_map
1002 .entry("simple".to_string())
1003 .or_default()
1004 .insert("olm".to_string(), vec!["qwen3.5".to_string()]);
1005 config
1006 .model_map
1007 .entry("medium".to_string())
1008 .or_default()
1009 .insert("olm".to_string(), vec!["gemma4".to_string()]);
1010 assert!(
1014 config.has_available_model_for_complexity("olm", "simple"),
1015 "should return true when model pool exists and is configured"
1016 );
1017 assert!(
1018 config.has_available_model_for_complexity("olm", "medium"),
1019 "should return true when model pool exists and is configured"
1020 );
1021 assert!(
1022 !config.has_available_model_for_complexity("olm", "complex"),
1023 "should return false when no model pool is configured for agent+complexity"
1024 );
1025 assert!(
1026 !config.has_available_model_for_complexity("olm", "review"),
1027 "should return false when no model pool is configured for agent+complexity"
1028 );
1029 }
1030
1031 #[serial(cooldown_state)]
1032 #[test]
1033 fn default_self_routing_penalty_is_one() {
1034 let config = RouterConfig::default();
1035 assert!(
1036 (config.self_routing_penalty - 1.0).abs() < f64::EPSILON,
1037 "default penalty must be 1.0 (no penalty = full self-routing allowed)"
1038 );
1039 }
1040
1041 #[serial(cooldown_state)]
1042 #[test]
1043 fn from_config_reads_self_routing_penalty() {
1044 let _lock = cwd_mutex().lock().unwrap();
1045 let dir = tempfile::tempdir().unwrap();
1046 fs::write(
1047 dir.path().join(".orch.yml"),
1048 "router:\n self_routing_penalty: 0.5\n",
1049 )
1050 .unwrap();
1051 let _guard = CurrentDirGuard::set(dir.path());
1052
1053 let config = RouterConfig::from_config();
1054 assert!((config.self_routing_penalty - 0.5).abs() < f64::EPSILON);
1055 }
1056
1057 #[serial(cooldown_state)]
1058 #[test]
1059 fn default_config_model_map_is_empty() {
1060 let config = RouterConfig::default();
1064 assert!(
1065 config.model_map.is_empty(),
1066 "Default RouterConfig must have no hardcoded models; got {:?}",
1067 config.model_map
1068 );
1069 }
1070
1071 #[serial(cooldown_state)]
1072 #[test]
1073 fn from_config_reads_router_pool_yaml_array() {
1074 let _lock = cwd_mutex().lock().unwrap();
1075 let dir = tempfile::tempdir().unwrap();
1076 fs::write(
1077 dir.path().join(".orch.yml"),
1078 "router:\n pool:\n - opencode:free\n - opencode:github-copilot/gpt-5-mini\n - kimi:k2p5\n - claude:haiku\n",
1079 )
1080 .unwrap();
1081 let _guard = CurrentDirGuard::set(dir.path());
1082
1083 let config = RouterConfig::from_config();
1084
1085 assert_eq!(
1086 config.pool,
1087 vec![
1088 "opencode:free",
1089 "opencode:github-copilot/gpt-5-mini",
1090 "kimi:k2p5",
1091 "claude:haiku",
1092 ]
1093 );
1094 }
1095
1096 #[serial(cooldown_state)]
1097 #[test]
1098 fn from_config_clamps_router_timeout_to_max() {
1099 let _lock = cwd_mutex().lock().unwrap();
1100 let dir = tempfile::tempdir().unwrap();
1101 fs::write(
1102 dir.path().join(".orch.yml"),
1103 "router:\n timeout_seconds: 90\n",
1104 )
1105 .unwrap();
1106 let _guard = CurrentDirGuard::set(dir.path());
1107
1108 let config = RouterConfig::from_config();
1109 assert_eq!(config.timeout_seconds, MAX_ROUTER_TIMEOUT_SECS);
1110 }
1111
1112 #[serial(cooldown_state)]
1113 #[test]
1114 fn normalize_model_identifier_strips_trailing_slash() {
1115 assert_eq!(
1117 RouterConfig::normalize_model_identifier("opus/"),
1118 "opus",
1119 "trailing slash should be stripped from model identifier"
1120 );
1121 assert_eq!(
1122 RouterConfig::normalize_model_identifier("sonnet/"),
1123 "sonnet",
1124 "trailing slash should be stripped from model identifier"
1125 );
1126 assert_eq!(
1127 RouterConfig::normalize_model_identifier("github-copilot/gpt-5-mini/"),
1128 "github-copilot/gpt-5-mini",
1129 "trailing slash should be stripped from model identifier with internal slash"
1130 );
1131 assert_eq!(
1133 RouterConfig::normalize_model_identifier("opus//"),
1134 "opus",
1135 "multiple trailing slashes should be stripped"
1136 );
1137 assert_eq!(
1139 RouterConfig::normalize_model_identifier("opus"),
1140 "opus",
1141 "model without trailing slash should remain unchanged"
1142 );
1143 }
1144
1145 #[serial(cooldown_state)]
1146 #[test]
1147 fn is_valid_model_identifier_rejects_trailing_slash() {
1148 assert!(
1150 !RouterConfig::is_valid_model_identifier("opus/"),
1151 "model with trailing slash should be invalid"
1152 );
1153 assert!(
1154 RouterConfig::is_valid_model_identifier("opus"),
1155 "model without trailing slash should be valid"
1156 );
1157 assert!(
1158 RouterConfig::is_valid_model_identifier("github-copilot/gpt-5-mini"),
1159 "model with internal slash should be valid"
1160 );
1161 assert!(
1162 !RouterConfig::is_valid_model_identifier("github-copilot/"),
1163 "model ending with slash after prefix should be invalid"
1164 );
1165 }
1166
1167 #[serial(cooldown_state)]
1168 #[test]
1169 fn from_config_loads_model_map_for_custom_agents() {
1170 let _lock = cwd_mutex().lock().unwrap();
1171 let dir = tempfile::tempdir().unwrap();
1172 fs::write(
1174 dir.path().join(".orch.yml"),
1175 r"
1176agents:
1177 - claude
1178 - olm
1179model_map:
1180 simple:
1181 claude: haiku
1182 olm: qwen3.5
1183 medium:
1184 claude: sonnet
1185 olm: gemma4
1186 complex:
1187 claude: opus
1188 olm: gemma4
1189",
1190 )
1191 .unwrap();
1192 let _guard = CurrentDirGuard::set(dir.path());
1193
1194 let config = RouterConfig::from_config();
1195
1196 assert_eq!(
1198 config.model_for_complexity("olm", "simple", "test-task"),
1199 Some("qwen3.5".to_string()),
1200 "custom agent olm should have simple model from config"
1201 );
1202 assert_eq!(
1203 config.model_for_complexity("olm", "medium", "test-task"),
1204 Some("gemma4".to_string()),
1205 "custom agent olm should have medium model from config"
1206 );
1207 assert_eq!(
1209 config.model_for_complexity("claude", "simple", "test-task"),
1210 Some("haiku".to_string()),
1211 );
1212 }
1213
1214 #[serial(cooldown_state)]
1215 #[test]
1216 fn from_config_loads_models_shorthand_for_all_complexities() {
1217 let _lock = cwd_mutex().lock().unwrap();
1218 let dir = tempfile::tempdir().unwrap();
1219 fs::write(
1220 dir.path().join(".orch.yml"),
1221 r"
1222agents:
1223 - shorthand
1224models:
1225 shorthand:
1226 - gpt-5.2
1227 - gpt-5.5
1228",
1229 )
1230 .unwrap();
1231 let _guard = CurrentDirGuard::set(dir.path());
1232
1233 let config = RouterConfig::from_config();
1234
1235 for complexity in ["simple", "medium", "complex", "review"] {
1236 assert_eq!(
1237 config.model_map[complexity]["shorthand"],
1238 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()],
1239 "models.shorthand should populate {complexity}"
1240 );
1241 }
1242 }
1243
1244 #[serial(cooldown_state)]
1245 #[test]
1246 fn from_config_loads_single_model_shorthand_for_all_complexities() {
1247 let _lock = cwd_mutex().lock().unwrap();
1248 let dir = tempfile::tempdir().unwrap();
1249 fs::write(
1250 dir.path().join(".orch.yml"),
1251 r"
1252agents:
1253 - shorthand
1254models:
1255 shorthand: gpt-5.2
1256",
1257 )
1258 .unwrap();
1259 let _guard = CurrentDirGuard::set(dir.path());
1260
1261 let config = RouterConfig::from_config();
1262
1263 for complexity in ["simple", "medium", "complex", "review"] {
1264 assert_eq!(
1265 config.model_map[complexity]["shorthand"],
1266 vec!["gpt-5.2".to_string()],
1267 "models.shorthand should populate {complexity}"
1268 );
1269 }
1270 }
1271
1272 #[serial(cooldown_state)]
1273 #[test]
1274 fn from_config_model_map_overrides_models_shorthand_per_tier() {
1275 let _lock = cwd_mutex().lock().unwrap();
1276 let dir = tempfile::tempdir().unwrap();
1277 fs::write(
1278 dir.path().join(".orch.yml"),
1279 r"
1280agents:
1281 - shorthand
1282models:
1283 shorthand:
1284 - gpt-5.2
1285 - gpt-5.5
1286model_map:
1287 review:
1288 shorthand: gpt-5.6-review
1289",
1290 )
1291 .unwrap();
1292 let _guard = CurrentDirGuard::set(dir.path());
1293
1294 let config = RouterConfig::from_config();
1295
1296 assert_eq!(
1297 config.model_map["simple"]["shorthand"],
1298 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1299 );
1300 assert_eq!(
1301 config.model_map["medium"]["shorthand"],
1302 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1303 );
1304 assert_eq!(
1305 config.model_map["complex"]["shorthand"],
1306 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1307 );
1308 assert_eq!(
1309 config.model_map["review"]["shorthand"],
1310 vec!["gpt-5.6-review".to_string()]
1311 );
1312 }
1313
1314 #[serial(cooldown_state)]
1315 #[test]
1316 fn model_for_complexity_normalizes_trailing_slash_from_pool() {
1317 let mut config = RouterConfig::default();
1320 config
1321 .model_map
1322 .entry("complex".to_string())
1323 .or_default()
1324 .insert(
1325 "testagent_trailing".to_string(),
1326 vec![
1327 "opus/".to_string(),
1328 "sonnet//".to_string(),
1329 "github-copilot/gpt-5-mini/".to_string(),
1330 ],
1331 );
1332
1333 let result = config.model_for_complexity("testagent_trailing", "complex", "task-0");
1335 assert!(
1336 result.is_some(),
1337 "should return a model from pool with trailing slashes normalized, got None"
1338 );
1339 let model = result.unwrap();
1340 assert!(
1342 model == "opus" || model == "sonnet" || model == "github-copilot/gpt-5-mini",
1343 "returned model should be normalized (no trailing slash), got: {model}"
1344 );
1345 assert!(
1347 !model.ends_with('/'),
1348 "returned model should not have trailing slash, got: {model}"
1349 );
1350 }
1351
1352 #[serial(cooldown_state)]
1355 #[test]
1356 fn prune_unavailable_opencode_models_removes_missing_models() {
1357 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1358 model_map.entry("complex".to_string()).or_default().insert(
1359 "opencode".to_string(),
1360 vec![
1361 "available-model".to_string(),
1362 "unavailable-model".to_string(),
1363 "opencode:free".to_string(), ],
1365 );
1366
1367 let mut discovered = HashSet::new();
1368 discovered.insert("available-model".to_string());
1369 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1372
1373 assert_eq!(pruned, 1, "should prune exactly the one unavailable model");
1374
1375 let remaining = model_map["complex"]["opencode"].as_slice();
1376 assert!(
1377 remaining.contains(&"available-model".to_string()),
1378 "available model should remain"
1379 );
1380 assert!(
1381 remaining.contains(&"opencode:free".to_string()),
1382 "opencode:free sentinel should never be pruned"
1383 );
1384 assert!(
1385 !remaining.contains(&"unavailable-model".to_string()),
1386 "unavailable model should be removed"
1387 );
1388 }
1389
1390 #[serial(cooldown_state)]
1391 #[test]
1392 fn prune_unavailable_opencode_models_noop_when_all_available() {
1393 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1394 model_map.entry("simple".to_string()).or_default().insert(
1395 "opencode".to_string(),
1396 vec!["model-a".to_string(), "model-b".to_string()],
1397 );
1398
1399 let discovered: HashSet<String> = ["model-a", "model-b"]
1400 .iter()
1401 .map(ToString::to_string)
1402 .collect();
1403
1404 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1405
1406 assert_eq!(pruned, 0, "nothing to prune when all models are available");
1407 assert_eq!(
1408 model_map["simple"]["opencode"].len(),
1409 2,
1410 "both models should remain"
1411 );
1412 }
1413
1414 #[serial(cooldown_state)]
1415 #[test]
1416 fn prune_unavailable_opencode_models_preserves_non_opencode_agents() {
1417 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1418 model_map
1419 .entry("complex".to_string())
1420 .or_default()
1421 .insert("claude".to_string(), vec!["some-model".to_string()]);
1422
1423 let discovered: HashSet<String> = HashSet::new();
1425
1426 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1427
1428 assert_eq!(pruned, 0, "non-opencode agents must not be touched");
1429 assert_eq!(
1430 model_map["complex"]["claude"].len(),
1431 1,
1432 "claude model should be unchanged"
1433 );
1434 }
1435
1436 #[test]
1437 fn default_config_does_not_use_opencode() {
1438 assert!(!RouterConfig::default().uses_opencode());
1439 }
1440
1441 #[test]
1442 fn uses_opencode_when_a_model_map_tier_lists_it() {
1443 let mut config = RouterConfig::default();
1444 config
1445 .model_map
1446 .entry("simple".to_string())
1447 .or_default()
1448 .insert("opencode".to_string(), vec!["some-model".to_string()]);
1449 assert!(config.uses_opencode());
1450 }
1451
1452 #[test]
1453 fn uses_opencode_follows_the_effective_pool_and_fallback() {
1454 let config = RouterConfig {
1455 pool: vec!["opencode:free".to_string()],
1456 ..RouterConfig::default()
1457 };
1458 assert!(config.uses_opencode());
1459
1460 let config = RouterConfig {
1461 pool: vec!["claude:haiku".to_string()],
1462 ..RouterConfig::default()
1463 };
1464 assert!(!config.uses_opencode());
1465
1466 let config = RouterConfig {
1468 pool: vec![],
1469 router_agent: "opencode".to_string(),
1470 router_model: "free".to_string(),
1471 ..RouterConfig::default()
1472 };
1473 assert!(config.uses_opencode());
1474
1475 let config = RouterConfig {
1476 pool: vec!["claude:haiku".to_string()],
1477 fallback: "opencode:some/model".to_string(),
1478 ..RouterConfig::default()
1479 };
1480 assert!(config.uses_opencode());
1481 }
1482
1483 #[serial(cooldown_state)]
1484 #[test]
1485 fn prune_unavailable_opencode_models_covers_all_complexity_tiers() {
1486 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1487 for tier in ["simple", "medium", "complex", "review"] {
1488 model_map
1489 .entry(tier.to_string())
1490 .or_default()
1491 .insert("opencode".to_string(), vec!["gone-model".to_string()]);
1492 }
1493
1494 let discovered: HashSet<String> = HashSet::new();
1496
1497 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1498
1499 assert_eq!(pruned, 4, "should prune one entry per complexity tier");
1500 for tier in ["simple", "medium", "complex", "review"] {
1501 assert!(
1502 model_map[tier]["opencode"].is_empty(),
1503 "all entries for {tier} should be removed"
1504 );
1505 }
1506 }
1507}