1use std::collections::HashMap;
4use std::collections::HashSet;
5use std::env;
6use std::sync::OnceLock;
7
8use super::weights::{AgentWeights, default_missing_weight};
9use crate::config;
10use crate::cooldown;
11use crate::engine;
12use crate::engine::router::selection;
13use crate::engine::runner::agents::opencode;
14use serde::{Deserialize, Serialize};
15
16const COMPLEXITY_TIERS: [&str; 3] = ["simple", "medium", "complex"];
18
19pub fn min_healthy_agents_threshold() -> usize {
22 config::get("dispatch.min_healthy_agents")
23 .ok()
24 .and_then(|v| v.parse().ok())
25 .unwrap_or(2)
26}
27
28pub fn sequential_dispatch_delay_ms() -> u64 {
30 config::get("dispatch.sequential_delay_ms")
31 .ok()
32 .and_then(|v| v.parse().ok())
33 .unwrap_or(1000)
34}
35
36pub fn health_check_window_hours() -> u32 {
41 config::get("dispatch.health_check_window_hours")
42 .ok()
43 .and_then(|v| v.parse().ok())
44 .unwrap_or(cooldown::DEFAULT_HEALTH_CHECK_WINDOW_HOURS)
45}
46
47pub fn degraded_rate_limit_threshold() -> i64 {
61 config::get("dispatch.degraded_rate_limit_threshold")
62 .ok()
63 .and_then(|v| v.parse().ok())
64 .unwrap_or(cooldown::DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD)
65}
66
67pub fn retry_base_delay_ms() -> u64 {
69 config::get("dispatch.retry_base_delay_ms")
70 .ok()
71 .and_then(|v| v.parse().ok())
72 .unwrap_or(10_000)
73}
74
75pub fn retry_max_delay_ms() -> u64 {
77 config::get("dispatch.retry_max_delay_ms")
78 .ok()
79 .and_then(|v| v.parse().ok())
80 .unwrap_or(120_000)
81}
82
83pub const MAX_ROUTER_TIMEOUT_SECS: u64 = 45;
88
89pub const SKIP_LIMITED_THRESHOLD: f64 = 0.3;
92
93pub fn max_tasks_per_routing_tick() -> usize {
100 config::get("router.max_tasks_per_tick")
101 .ok()
102 .and_then(|v| v.parse().ok())
103 .unwrap_or(1)
104}
105
106pub const DEFAULT_AGENTS: &[&str] = &[
113 "claude", "codex", "opencode", "kimi", "minimax", "glm", "grok",
114];
115
116#[derive(Debug, Clone)]
118pub struct RouterConfig {
119 pub mode: String,
126 pub profiles: HashMap<String, NamedProfile>,
128 pub profiles_error: Option<String>,
129 pub router_agent: String,
131 pub router_model: String,
133 pub timeout_seconds: u64,
135 pub fallback_executor: String,
137 pub agents: Vec<String>,
139 pub max_route_attempts: u32,
141 pub allowed_tools: Vec<String>,
143 pub model_map: HashMap<String, HashMap<String, Vec<String>>>,
147 pub weighted_round_robin: bool,
150 pub pool: Vec<String>,
154 pub fallback: String,
157 pub self_routing_penalty: f64,
165 pub weights: HashMap<String, f64>,
183 pub agent_backoff_bases: HashMap<String, i64>,
190 pub max_tasks_per_tick: usize,
197 pub ollama_url: String,
199 pub ollama_model: String,
201 pub ollama_timeout_seconds: u64,
203}
204
205pub fn parse_pool_entry(entry: &str) -> (String, String) {
212 if let Some(colon_pos) = entry.find(':') {
213 let agent = entry[..colon_pos].to_string();
214 let model = entry[colon_pos + 1..].to_string();
215 let model = RouterConfig::normalize_model_identifier(&model);
217 (agent, model)
218 } else {
219 (entry.to_string(), String::new())
220 }
221}
222
223impl Default for RouterConfig {
224 fn default() -> Self {
225 Self {
226 mode: "round_robin".to_string(),
227 profiles: HashMap::new(),
228 profiles_error: None,
229 router_agent: "claude".to_string(),
230 router_model: String::new(),
232 timeout_seconds: 45,
233 fallback_executor: "codex".to_string(),
234 agents: DEFAULT_AGENTS.iter().map(ToString::to_string).collect(),
235 max_route_attempts: 3,
236 pool: vec![],
237 fallback: String::new(),
238 self_routing_penalty: 1.0,
239 weights: HashMap::new(),
240 allowed_tools: vec![
241 "yq".to_string(),
242 "jq".to_string(),
243 "bash".to_string(),
244 "just".to_string(),
245 "git".to_string(),
246 "rg".to_string(),
247 "sed".to_string(),
248 "awk".to_string(),
249 "python3".to_string(),
250 "node".to_string(),
251 "npm".to_string(),
252 "bun".to_string(),
253 ],
254 model_map: HashMap::new(),
258 weighted_round_robin: false,
259 agent_backoff_bases: HashMap::new(),
260 max_tasks_per_tick: 1,
261 ollama_url: "http://localhost:11434".to_string(),
262 ollama_model: "qwen2.5-coder:3b-instruct".to_string(),
263 ollama_timeout_seconds: 30,
264 }
265 }
266}
267
268impl RouterConfig {
269 pub fn has_agents(&self) -> bool {
270 !self.agents.is_empty()
271 }
272
273 pub fn has_agent(&self, agent: &str) -> bool {
274 self.agents.iter().any(|a| a == agent)
275 }
276
277 pub fn has_weights(&self) -> bool {
278 !self.weights.is_empty()
279 }
280
281 pub fn falls_back_to_round_robin(&self) -> bool {
283 self.fallback_executor == "round_robin"
284 }
285
286 pub fn executor_for(&self, agent: String) -> String {
288 if self.has_agent(&agent) {
289 agent
290 } else if self.fallback_executor.is_empty() {
291 self.agents.first().cloned().unwrap_or_default()
292 } else {
293 self.fallback_executor.clone()
294 }
295 }
296
297 pub fn profile(&self, name: &str) -> anyhow::Result<&NamedProfile> {
299 let selection = self
300 .profiles
301 .get(name)
302 .ok_or_else(|| anyhow::anyhow!("unknown routing profile: {name}"))?;
303 selection
304 .validate(&self.agents)
305 .map_err(|err| anyhow::anyhow!("routing profile {name}: {err}"))?;
306 Ok(selection)
307 }
308
309 pub fn agent_weights(&self, available: &[String]) -> AgentWeights {
311 let mut weights = AgentWeights {
312 base_weights: self.weights.clone(),
313 ..Default::default()
314 };
315 weights.ensure_agents_with_weights(available, &self.weights);
316 if self.has_weights() {
317 tracing::info!(weights = ?self.weights, "configured agent routing weights");
318 }
319 weights
320 }
321
322 pub fn prompt_agents(&self, agents: Option<&[String]>) -> (String, String) {
324 let agents = agents.unwrap_or(&self.agents);
325 let weights = if self.weights.is_empty() {
326 "No weights configured — distribute evenly.".to_string()
327 } else {
328 agents
329 .iter()
330 .map(|a| {
331 let w = self
332 .weights
333 .get(a)
334 .copied()
335 .unwrap_or_else(|| default_missing_weight(&self.weights));
336 format!("{a}: {w}")
337 })
338 .collect::<Vec<_>>()
339 .join(", ")
340 };
341 (agents.join(", "), weights)
342 }
343
344 pub fn from_config() -> Self {
346 let mut config = Self::default();
347
348 if let Ok(mode) = config::get("router.mode")
350 && (mode == "round_robin" || mode == "llm" || mode == "local" || mode == "profile")
351 {
352 config.mode = mode;
353 }
354
355 if let Ok(raw) = config::get("profiles") {
356 match serde_norway::from_str(&raw) {
357 Ok(profiles) => config.profiles = profiles,
358 Err(err) => config.profiles_error = Some(err.to_string()),
359 }
360 }
361
362 if let Ok(agent) = config::get("router.agent")
363 && !agent.is_empty()
364 {
365 config.router_agent = agent;
366 }
367
368 if let Ok(model) = config::get("router.model")
369 && !model.is_empty()
370 {
371 config.router_model = RouterConfig::normalize_model_identifier(&model);
372 }
373
374 if let Ok(timeout) = config::get("router.timeout_seconds")
375 && let Ok(secs) = timeout.parse::<u64>()
376 {
377 let clamped = secs.min(MAX_ROUTER_TIMEOUT_SECS);
378 if clamped != secs {
379 static TIMEOUT_CLAMP_WARNED: OnceLock<()> = OnceLock::new();
380 TIMEOUT_CLAMP_WARNED.get_or_init(|| {
381 tracing::warn!(
382 configured_secs = secs,
383 applied_secs = clamped,
384 max_secs = MAX_ROUTER_TIMEOUT_SECS,
385 "router.timeout_seconds is too high; clamping to keep routing responsive"
386 );
387 });
388 }
389 config.timeout_seconds = clamped;
390 }
391
392 if let Ok(fallback) = config::get("router.fallback_executor")
393 && !fallback.is_empty()
394 {
395 config.fallback_executor = fallback;
396 }
397
398 config.agents = engine::configured_agents();
400
401 let exclude_agents = env::var("ORCH_EXCLUDE_AGENTS")
407 .map(|v| {
408 v.split(',')
409 .map(|s| s.trim().to_string())
410 .filter(|s| !s.is_empty())
411 .collect::<Vec<_>>()
412 })
413 .unwrap_or_default();
414 if !exclude_agents.is_empty() {
415 let original_len = config.agents.len();
416 config.agents.retain(|a| !exclude_agents.contains(a));
417 let removed_count = original_len - config.agents.len();
418 if removed_count > 0 {
419 tracing::warn!(
420 "ORCH_EXCLUDE_AGENTS={}: temporarily removing {} agent(s) from router",
421 exclude_agents.join(","),
422 removed_count
423 );
424 }
425 }
426
427 if let Ok(max_attempts) = config::get("router.max_route_attempts")
428 && let Ok(n) = max_attempts.parse::<u32>()
429 {
430 config.max_route_attempts = n;
431 }
432
433 if let Ok(tools_str) = config::get("router.allowed_tools")
435 && !tools_str.is_empty()
436 && tools_str != "[]"
437 {
438 if let Ok(tools_arr) = serde_json::from_str::<Vec<String>>(&tools_str) {
440 config.allowed_tools = tools_arr;
441 } else {
442 config.allowed_tools = tools_str
444 .split(',')
445 .map(|s| s.trim().to_string())
446 .filter(|s| !s.is_empty())
447 .collect();
448 }
449 }
450
451 if let Ok(val) = config::get("router.weighted_round_robin") {
453 config.weighted_round_robin = val == "true" || val == "1";
454 }
455
456 if let Ok(val) = config::get("router.self_routing_penalty")
458 && let Ok(penalty) = val.parse::<f64>()
459 {
460 config.self_routing_penalty = penalty.clamp(0.0, 1.0);
461 }
462
463 for agent in &config.agents {
465 let key = format!("router.weights.{agent}");
466 if let Ok(val) = config::get(&key)
467 && let Ok(w) = val.parse::<f64>()
468 {
469 config.weights.insert(agent.clone(), w.max(0.0));
470 }
471 }
472
473 for agent in &config.agents {
475 let key = format!("router.backoff_base.{agent}");
476 if let Ok(val) = config::get(&key)
477 && let Ok(secs) = val.parse::<i64>()
478 {
479 config.agent_backoff_bases.insert(agent.clone(), secs);
480 }
481 }
482
483 if let Ok(val) = config::get("router.max_tasks_per_tick")
485 && let Ok(n) = val.parse::<usize>()
486 && n > 0
487 {
488 config.max_tasks_per_tick = n;
489 }
490
491 match config::get_list("router.pool") {
495 Ok(pool_list) if !pool_list.is_empty() => {
496 config.pool = pool_list;
497 }
498 _ => {
499 if let Ok(pool_raw) = config::get("router.pool") {
501 let parsed = pool_raw
502 .split(',')
503 .map(|s| s.trim().to_string())
504 .filter(|s| !s.is_empty())
505 .collect::<Vec<_>>();
506 if !parsed.is_empty() {
507 config.pool = parsed;
508 }
509 }
510 }
511 }
512
513 if let Ok(fallback) = config::get("router.fallback")
515 && !fallback.is_empty()
516 {
517 config.fallback = fallback;
518 }
519
520 let known_agents = engine::configured_agents();
526 let known_complexities = ["simple", "medium", "complex", "review"];
527 for agent in &known_agents {
528 let key = format!("models.{agent}");
529 if let Some(models) = Self::read_model_pool_from_config(&key) {
530 for complexity in known_complexities {
531 config
532 .model_map
533 .entry(complexity.to_string())
534 .or_default()
535 .insert(agent.clone(), models.clone());
536 }
537 }
538 }
539
540 for complexity in known_complexities {
545 for agent in &known_agents {
546 let key = format!("model_map.{complexity}.{agent}");
547 if let Some(models) = Self::read_model_pool_from_config(&key) {
548 config
549 .model_map
550 .entry(complexity.to_string())
551 .or_default()
552 .insert(agent.clone(), models);
553 }
554 }
555 }
556
557 let discovered_opencode = if config.uses_opencode() {
565 opencode::discover_opencode_models()
566 } else {
567 Vec::new()
568 };
569 if !discovered_opencode.is_empty() {
570 let discovered: HashSet<String> = discovered_opencode.into_iter().collect();
571 for complexity in known_complexities {
572 if let Some(agent_models) = config.model_map.get(complexity)
573 && let Some(models) = agent_models.get("opencode")
574 {
575 for model in models {
576 if model != "opencode:free" && !discovered.contains(model) {
577 tracing::warn!(
578 complexity,
579 model,
580 "opencode model from config not present in provider model list; pruning from dispatch pool"
581 );
582 }
583 }
584 }
585 }
586 let pruned =
587 Self::prune_unavailable_opencode_models(&mut config.model_map, &discovered);
588 if pruned > 0 {
589 tracing::info!(
590 pruned_count = pruned,
591 "model_pruned_unavailable: removed opencode models absent from provider catalog"
592 );
593 }
594 }
595
596 if let Ok(url) = config::get("router.ollama_url")
598 && !url.is_empty()
599 {
600 config.ollama_url = url;
601 }
602 if let Ok(model) = config::get("router.ollama_model")
603 && !model.is_empty()
604 {
605 config.ollama_model = model;
606 }
607 if let Ok(timeout) = config::get("router.ollama_timeout_seconds")
608 && let Ok(secs) = timeout.parse::<u64>()
609 && secs > 0
610 {
611 config.ollama_timeout_seconds = secs;
612 }
613
614 config
615 }
616
617 pub fn effective_pool(&self) -> Vec<String> {
619 if self.pool.is_empty() {
620 vec![format!("{}:{}", self.router_agent, self.router_model)]
621 } else {
622 self.pool.clone()
623 }
624 }
625
626 pub fn effective_fallback(&self) -> String {
628 if self.fallback.is_empty() {
629 format!("{}:{}", self.router_agent, self.router_model)
630 } else {
631 self.fallback.clone()
632 }
633 }
634
635 fn is_valid_model_identifier(model: &str) -> bool {
638 if model.is_empty() {
639 return false;
640 }
641 if model.ends_with('/') {
643 return false;
644 }
645 if model.chars().any(char::is_whitespace) {
647 return false;
648 }
649 if let Some(slash_pos) = model.find('/') {
651 let before = &model[..slash_pos];
652 let after = &model[slash_pos + 1..];
653 if before.is_empty() || after.is_empty() {
654 return false;
655 }
656 }
657 true
658 }
659
660 pub fn normalize_model_identifier(model: &str) -> String {
664 model.trim_end_matches('/').to_string()
665 }
666
667 pub fn configured_models(agent: &str) -> Vec<String> {
669 Self::read_model_pool_from_config(&format!("models.{agent}")).unwrap_or_default()
670 }
671
672 fn read_model_pool_from_config(key: &str) -> Option<Vec<String>> {
673 match config::get_list(key) {
674 Ok(list) => {
675 if !list.is_empty() {
676 return Some(
677 list.iter()
678 .map(|m| RouterConfig::normalize_model_identifier(m))
679 .collect(),
680 );
681 }
682 }
683 _ => {
684 if let Ok(val) = config::get(key)
685 && !val.is_empty()
686 {
687 return Some(vec![RouterConfig::normalize_model_identifier(&val)]);
688 }
689 }
690 }
691
692 None
693 }
694
695 fn expanded_model_pool(&self, agent: &str, complexity: &str) -> Option<Vec<String>> {
696 let pool = self.model_map.get(complexity)?.get(agent)?;
697 if pool.is_empty() {
698 return Some(Vec::new());
699 }
700
701 let mut expanded_pool = Vec::new();
702 let mut has_free = false;
703
704 for model in pool {
705 let normalized = Self::normalize_model_identifier(model);
707 if normalized == "opencode:free" {
708 has_free = true;
709 } else if Self::is_valid_model_identifier(&normalized) {
710 expanded_pool.push(normalized);
711 } else {
712 tracing::debug!(agent, model, "skipping invalid model identifier in config");
713 }
714 }
715
716 if has_free {
717 expanded_pool.extend(opencode::discover_free_opencode_models());
718 }
719
720 expanded_pool.retain(|m| Self::is_valid_model_identifier(m));
722
723 if agent == "opencode" {
726 let discovered = opencode::discover_opencode_models();
727 if !discovered.is_empty() {
728 let discovered_set: HashSet<String> = discovered.into_iter().collect();
729 expanded_pool.retain(|m| discovered_set.contains(m));
730 }
731 }
732
733 Some(expanded_pool)
734 }
735
736 pub(crate) fn model_pool_for_complexity(
737 &self,
738 agent: &str,
739 complexity: &str,
740 ) -> Option<Vec<String>> {
741 self.expanded_model_pool(agent, complexity)
742 }
743
744 pub fn has_available_model_for_complexity(&self, agent: &str, complexity: &str) -> bool {
745 match self.expanded_model_pool(agent, complexity) {
746 None => false,
747 Some(pool) => pool
748 .iter()
749 .any(|model| !cooldown::is_model_in_cooldown(agent, model)),
750 }
751 }
752
753 pub fn has_available_model_in_any_tier(&self, agent: &str, complexity: &str) -> bool {
756 Self::tier_search_order(complexity)
757 .into_iter()
758 .any(|tier| self.has_available_model_for_complexity(agent, tier))
759 }
760
761 pub fn model_for_complexity(
769 &self,
770 agent: &str,
771 complexity: &str,
772 task_id: &str,
773 ) -> Option<String> {
774 let expanded_pool = self.expanded_model_pool(agent, complexity)?;
775 if expanded_pool.is_empty() {
776 return None;
777 }
778 let start = selection::simple_hash_index_for(expanded_pool.len(), task_id);
780 for i in 0..expanded_pool.len() {
782 let model = &expanded_pool[(start + i) % expanded_pool.len()];
783 if !Self::is_valid_model_identifier(model) {
785 tracing::debug!(
786 agent,
787 model,
788 "invalid model identifier slipped through validation"
789 );
790 continue;
791 }
792 if !cooldown::is_model_in_cooldown(agent, model) {
793 return Some(Self::normalize_model_identifier(model));
795 }
796 }
797 None
799 }
800
801 fn tier_search_order(complexity: &str) -> Vec<&str> {
804 let Some(idx) = COMPLEXITY_TIERS.iter().position(|t| *t == complexity) else {
805 return vec![complexity];
806 };
807 let mut order = vec![COMPLEXITY_TIERS[idx]];
808 order.extend(&COMPLEXITY_TIERS[idx + 1..]);
809 order.extend(COMPLEXITY_TIERS[..idx].iter().rev());
810 order
811 }
812
813 pub fn model_for_complexity_or_adjacent(
816 &self,
817 agent: &str,
818 complexity: &str,
819 task_id: &str,
820 ) -> Option<(String, String)> {
821 Self::tier_search_order(complexity)
822 .into_iter()
823 .find_map(|tier| {
824 self.model_for_complexity(agent, tier, task_id)
825 .map(|model| (model, tier.to_string()))
826 })
827 }
828
829 pub fn tier_of_model(&self, agent: &str, model: &str, complexity: &str) -> String {
832 Self::tier_search_order(complexity)
833 .into_iter()
834 .find(|tier| {
835 self.expanded_model_pool(agent, tier)
836 .is_some_and(|pool| pool.iter().any(|m| m == model))
837 })
838 .unwrap_or(complexity)
839 .to_string()
840 }
841
842 pub(crate) fn uses_opencode(&self) -> bool {
846 fn names_opencode(entry: &str) -> bool {
847 entry == "opencode" || entry.starts_with("opencode:")
848 }
849
850 if self
851 .model_map
852 .values()
853 .any(|by_agent| by_agent.contains_key("opencode"))
854 {
855 return true;
856 }
857
858 self.effective_pool().iter().any(|e| names_opencode(e))
859 || names_opencode(&self.effective_fallback())
860 }
861
862 fn prune_unavailable_opencode_models(
868 model_map: &mut HashMap<String, HashMap<String, Vec<String>>>,
869 discovered: &HashSet<String>,
870 ) -> usize {
871 let mut pruned = 0;
872 for agent_models in model_map.values_mut() {
873 if let Some(models) = agent_models.get_mut("opencode") {
874 let before = models.len();
875 models.retain(|m| m == "opencode:free" || discovered.contains(m));
876 pruned += before - models.len();
877 }
878 }
879 pruned
880 }
881}
882
883#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
885#[serde(deny_unknown_fields)]
886pub struct NamedProfile {
887 pub agent: String,
888 pub model: String,
889 #[serde(default, skip_serializing_if = "Option::is_none")]
890 pub effort: Option<String>,
891}
892
893impl NamedProfile {
894 pub fn validate(&self, agents: &[String]) -> anyhow::Result<()> {
895 anyhow::ensure!(
896 agents.contains(&self.agent),
897 "profile agent is not configured"
898 );
899 anyhow::ensure!(
900 !self.model.trim().is_empty(),
901 "profile model must not be empty"
902 );
903 if let Some(effort) = &self.effort {
904 anyhow::ensure!(
905 !effort.trim().is_empty(),
906 "profile effort must not be empty"
907 );
908 anyhow::ensure!(
909 matches!(self.agent.as_str(), "claude" | "codex" | "opencode"),
910 "profile effort is unsupported for this agent"
911 );
912 }
913 Ok(())
914 }
915
916 pub fn matches_route(&self, agent: &str, model: Option<&str>) -> bool {
919 self.agent == agent && model == Some(self.model.as_str())
920 }
921}
922
923#[cfg(test)]
924mod tests {
925 use super::{MAX_ROUTER_TIMEOUT_SECS, RouterConfig};
926 use crate::cooldown;
927 use serial_test::serial;
928 use std::collections::HashMap;
929 use std::collections::HashSet;
930 use std::env;
931 use std::fs;
932 use std::path::Path;
933 use std::path::PathBuf;
934 use std::sync::{Mutex, OnceLock};
935
936 struct CurrentDirGuard {
937 original: PathBuf,
938 }
939
940 impl CurrentDirGuard {
941 fn set(path: &Path) -> Self {
942 let original = env::current_dir().unwrap();
943 env::set_current_dir(path).unwrap();
944 Self { original }
945 }
946 }
947
948 impl Drop for CurrentDirGuard {
949 fn drop(&mut self) {
950 env::set_current_dir(&self.original).unwrap();
951 }
952 }
953
954 fn cwd_mutex() -> &'static Mutex<()> {
955 static CWD_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
956 CWD_MUTEX.get_or_init(|| Mutex::new(()))
957 }
958
959 #[serial(cooldown_state)]
960 #[tokio::test]
961 async fn model_for_complexity_returns_none_when_all_models_cooled() {
962 cooldown::reset_global_state().await;
963 let mut config = RouterConfig::default();
964 config
966 .model_map
967 .entry("complex".to_string())
968 .or_default()
969 .insert(
970 "testagent_allcooled".to_string(),
971 vec![
972 "cooldown-model-a".to_string(),
973 "cooldown-model-b".to_string(),
974 ],
975 );
976
977 cooldown::record_model_failure("testagent_allcooled", "cooldown-model-a").await;
979 cooldown::record_model_failure("testagent_allcooled", "cooldown-model-b").await;
980
981 let result = config.model_for_complexity("testagent_allcooled", "complex", "task-0");
982 assert!(
983 result.is_none(),
984 "should return None when all models in pool are in cooldown, got {result:?}"
985 );
986 }
987
988 fn tiered_config(agent: &str, tiers: &[(&str, &str)]) -> RouterConfig {
989 let mut config = RouterConfig::default();
990 config.model_map.clear();
991 for (tier, model) in tiers {
992 config
993 .model_map
994 .entry((*tier).to_string())
995 .or_default()
996 .insert(agent.to_string(), vec![(*model).to_string()]);
997 }
998 config
999 }
1000
1001 #[serial(cooldown_state)]
1002 #[tokio::test]
1003 async fn adjacent_tier_prefers_higher_over_lower() {
1004 cooldown::reset_global_state().await;
1005 let agent = "tieragent_higher";
1006 let config = tiered_config(
1007 agent,
1008 &[("simple", "t-s"), ("medium", "t-m"), ("complex", "t-c")],
1009 );
1010 cooldown::record_model_failure(agent, "t-m").await;
1011
1012 let got = config.model_for_complexity_or_adjacent(agent, "medium", "t");
1013 assert_eq!(got, Some(("t-c".to_string(), "complex".to_string())));
1014 assert_eq!(config.tier_of_model(agent, "t-c", "medium"), "complex");
1015 }
1016
1017 #[serial(cooldown_state)]
1018 #[tokio::test]
1019 async fn simple_task_tries_medium_then_complex_before_lower() {
1020 cooldown::reset_global_state().await;
1021 let agent = "tieragent_simple";
1022 let config = tiered_config(
1023 agent,
1024 &[("simple", "u-s"), ("medium", "u-m"), ("complex", "u-c")],
1025 );
1026 cooldown::record_model_failure(agent, "u-s").await;
1027 cooldown::record_model_failure(agent, "u-m").await;
1028
1029 let got = config.model_for_complexity_or_adjacent(agent, "simple", "t");
1030 assert_eq!(got, Some(("u-c".to_string(), "complex".to_string())));
1031 }
1032
1033 #[serial(cooldown_state)]
1034 #[tokio::test]
1035 async fn adjacent_tier_falls_back_to_lower_when_higher_tiers_are_unavailable() {
1036 cooldown::reset_global_state().await;
1037 let agent = "tieragent_lower";
1038 let config = tiered_config(agent, &[("simple", "v-s"), ("medium", "v-m")]);
1039 cooldown::record_model_failure(agent, "v-m").await;
1040
1041 let got = config.model_for_complexity_or_adjacent(agent, "complex", "t");
1042 assert_eq!(got, Some(("v-s".to_string(), "simple".to_string())));
1043 }
1044
1045 #[serial(cooldown_state)]
1046 #[tokio::test]
1047 async fn adjacent_tier_returns_none_when_every_tier_is_cooled() {
1048 cooldown::reset_global_state().await;
1049 let agent = "tieragent_allcooled";
1050 let config = tiered_config(
1051 agent,
1052 &[("simple", "w-s"), ("medium", "w-m"), ("complex", "w-c")],
1053 );
1054 for m in ["w-s", "w-m", "w-c"] {
1055 cooldown::record_model_failure(agent, m).await;
1056 }
1057
1058 assert_eq!(
1059 config.model_for_complexity_or_adjacent(agent, "medium", "t"),
1060 None
1061 );
1062 }
1063
1064 #[serial(cooldown_state)]
1065 #[tokio::test]
1066 async fn model_for_complexity_returns_none_when_single_model_cooled() {
1067 cooldown::reset_global_state().await;
1068 let mut config = RouterConfig::default();
1069 config
1070 .model_map
1071 .entry("complex".to_string())
1072 .or_default()
1073 .insert(
1074 "testagent_singlecooled".to_string(),
1075 vec!["single-cooled-model".to_string()],
1076 );
1077
1078 cooldown::record_model_failure("testagent_singlecooled", "single-cooled-model").await;
1079
1080 let result = config.model_for_complexity("testagent_singlecooled", "complex", "task-0");
1081 assert!(
1082 result.is_none(),
1083 "should return None when the only model in pool is in cooldown, got {result:?}"
1084 );
1085 }
1086
1087 #[serial(cooldown_state)]
1088 #[test]
1089 fn model_for_complexity_returns_model_when_not_cooled() {
1090 let mut config = RouterConfig::default();
1091 config
1092 .model_map
1093 .entry("complex".to_string())
1094 .or_default()
1095 .insert(
1096 "testagent_notcooled".to_string(),
1097 vec!["healthy-model".to_string()],
1098 );
1099
1100 let result = config.model_for_complexity("testagent_notcooled", "complex", "task-0");
1102 assert_eq!(
1103 result.as_deref(),
1104 Some("healthy-model"),
1105 "should return the model when it is not in cooldown"
1106 );
1107 }
1108
1109 #[serial(cooldown_state)]
1110 #[test]
1111 fn has_available_model_returns_false_when_no_pool_configured() {
1112 let mut config = RouterConfig::default();
1113 config
1115 .model_map
1116 .entry("simple".to_string())
1117 .or_default()
1118 .insert("olm".to_string(), vec!["qwen3.5".to_string()]);
1119 config
1120 .model_map
1121 .entry("medium".to_string())
1122 .or_default()
1123 .insert("olm".to_string(), vec!["gemma4".to_string()]);
1124 assert!(
1128 config.has_available_model_for_complexity("olm", "simple"),
1129 "should return true when model pool exists and is configured"
1130 );
1131 assert!(
1132 config.has_available_model_for_complexity("olm", "medium"),
1133 "should return true when model pool exists and is configured"
1134 );
1135 assert!(
1136 !config.has_available_model_for_complexity("olm", "complex"),
1137 "should return false when no model pool is configured for agent+complexity"
1138 );
1139 assert!(
1140 !config.has_available_model_for_complexity("olm", "review"),
1141 "should return false when no model pool is configured for agent+complexity"
1142 );
1143 }
1144
1145 #[serial(cooldown_state)]
1146 #[test]
1147 fn default_self_routing_penalty_is_one() {
1148 let config = RouterConfig::default();
1149 assert!(
1150 (config.self_routing_penalty - 1.0).abs() < f64::EPSILON,
1151 "default penalty must be 1.0 (no penalty = full self-routing allowed)"
1152 );
1153 }
1154
1155 #[serial(cooldown_state)]
1156 #[test]
1157 fn from_config_reads_self_routing_penalty() {
1158 let _lock = cwd_mutex().lock().unwrap();
1159 let dir = tempfile::tempdir().unwrap();
1160 fs::write(
1161 dir.path().join(".orch.yml"),
1162 "router:\n self_routing_penalty: 0.5\n",
1163 )
1164 .unwrap();
1165 let _guard = CurrentDirGuard::set(dir.path());
1166
1167 let config = RouterConfig::from_config();
1168 assert!((config.self_routing_penalty - 0.5).abs() < f64::EPSILON);
1169 }
1170
1171 #[serial(cooldown_state)]
1172 #[test]
1173 fn default_config_model_map_is_empty() {
1174 let config = RouterConfig::default();
1178 assert!(
1179 config.model_map.is_empty(),
1180 "Default RouterConfig must have no hardcoded models; got {:?}",
1181 config.model_map
1182 );
1183 }
1184
1185 #[serial(cooldown_state)]
1186 #[test]
1187 fn from_config_reads_router_pool_yaml_array() {
1188 let _lock = cwd_mutex().lock().unwrap();
1189 let dir = tempfile::tempdir().unwrap();
1190 fs::write(
1191 dir.path().join(".orch.yml"),
1192 "router:\n pool:\n - opencode:free\n - opencode:github-copilot/gpt-5-mini\n - kimi:k2p5\n - claude:haiku\n",
1193 )
1194 .unwrap();
1195 let _guard = CurrentDirGuard::set(dir.path());
1196
1197 let config = RouterConfig::from_config();
1198
1199 assert_eq!(
1200 config.pool,
1201 vec![
1202 "opencode:free",
1203 "opencode:github-copilot/gpt-5-mini",
1204 "kimi:k2p5",
1205 "claude:haiku",
1206 ]
1207 );
1208 }
1209
1210 #[serial(cooldown_state)]
1211 #[test]
1212 fn from_config_clamps_router_timeout_to_max() {
1213 let _lock = cwd_mutex().lock().unwrap();
1214 let dir = tempfile::tempdir().unwrap();
1215 fs::write(
1216 dir.path().join(".orch.yml"),
1217 "router:\n timeout_seconds: 90\n",
1218 )
1219 .unwrap();
1220 let _guard = CurrentDirGuard::set(dir.path());
1221
1222 let config = RouterConfig::from_config();
1223 assert_eq!(config.timeout_seconds, MAX_ROUTER_TIMEOUT_SECS);
1224 }
1225
1226 #[serial(cooldown_state)]
1227 #[test]
1228 fn normalize_model_identifier_strips_trailing_slash() {
1229 assert_eq!(
1231 RouterConfig::normalize_model_identifier("opus/"),
1232 "opus",
1233 "trailing slash should be stripped from model identifier"
1234 );
1235 assert_eq!(
1236 RouterConfig::normalize_model_identifier("sonnet/"),
1237 "sonnet",
1238 "trailing slash should be stripped from model identifier"
1239 );
1240 assert_eq!(
1241 RouterConfig::normalize_model_identifier("github-copilot/gpt-5-mini/"),
1242 "github-copilot/gpt-5-mini",
1243 "trailing slash should be stripped from model identifier with internal slash"
1244 );
1245 assert_eq!(
1247 RouterConfig::normalize_model_identifier("opus//"),
1248 "opus",
1249 "multiple trailing slashes should be stripped"
1250 );
1251 assert_eq!(
1253 RouterConfig::normalize_model_identifier("opus"),
1254 "opus",
1255 "model without trailing slash should remain unchanged"
1256 );
1257 }
1258
1259 #[serial(cooldown_state)]
1260 #[test]
1261 fn is_valid_model_identifier_rejects_trailing_slash() {
1262 assert!(
1264 !RouterConfig::is_valid_model_identifier("opus/"),
1265 "model with trailing slash should be invalid"
1266 );
1267 assert!(
1268 RouterConfig::is_valid_model_identifier("opus"),
1269 "model without trailing slash should be valid"
1270 );
1271 assert!(
1272 RouterConfig::is_valid_model_identifier("github-copilot/gpt-5-mini"),
1273 "model with internal slash should be valid"
1274 );
1275 assert!(
1276 !RouterConfig::is_valid_model_identifier("github-copilot/"),
1277 "model ending with slash after prefix should be invalid"
1278 );
1279 }
1280
1281 #[serial(cooldown_state)]
1282 #[test]
1283 fn from_config_loads_model_map_for_custom_agents() {
1284 let _lock = cwd_mutex().lock().unwrap();
1285 let dir = tempfile::tempdir().unwrap();
1286 fs::write(
1288 dir.path().join(".orch.yml"),
1289 r"
1290agents:
1291 - claude
1292 - olm
1293model_map:
1294 simple:
1295 claude: haiku
1296 olm: qwen3.5
1297 medium:
1298 claude: sonnet
1299 olm: gemma4
1300 complex:
1301 claude: opus
1302 olm: gemma4
1303",
1304 )
1305 .unwrap();
1306 let _guard = CurrentDirGuard::set(dir.path());
1307
1308 let config = RouterConfig::from_config();
1309
1310 assert_eq!(
1312 config.model_for_complexity("olm", "simple", "test-task"),
1313 Some("qwen3.5".to_string()),
1314 "custom agent olm should have simple model from config"
1315 );
1316 assert_eq!(
1317 config.model_for_complexity("olm", "medium", "test-task"),
1318 Some("gemma4".to_string()),
1319 "custom agent olm should have medium model from config"
1320 );
1321 assert_eq!(
1323 config.model_for_complexity("claude", "simple", "test-task"),
1324 Some("haiku".to_string()),
1325 );
1326 }
1327
1328 #[serial(cooldown_state)]
1329 #[test]
1330 fn from_config_loads_models_shorthand_for_all_complexities() {
1331 let _lock = cwd_mutex().lock().unwrap();
1332 let dir = tempfile::tempdir().unwrap();
1333 fs::write(
1334 dir.path().join(".orch.yml"),
1335 r"
1336agents:
1337 - shorthand
1338models:
1339 shorthand:
1340 - gpt-5.2
1341 - gpt-5.5
1342",
1343 )
1344 .unwrap();
1345 let _guard = CurrentDirGuard::set(dir.path());
1346
1347 let config = RouterConfig::from_config();
1348
1349 for complexity in ["simple", "medium", "complex", "review"] {
1350 assert_eq!(
1351 config.model_map[complexity]["shorthand"],
1352 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()],
1353 "models.shorthand should populate {complexity}"
1354 );
1355 }
1356 }
1357
1358 #[serial(cooldown_state)]
1359 #[test]
1360 fn from_config_loads_single_model_shorthand_for_all_complexities() {
1361 let _lock = cwd_mutex().lock().unwrap();
1362 let dir = tempfile::tempdir().unwrap();
1363 fs::write(
1364 dir.path().join(".orch.yml"),
1365 r"
1366agents:
1367 - shorthand
1368models:
1369 shorthand: gpt-5.2
1370",
1371 )
1372 .unwrap();
1373 let _guard = CurrentDirGuard::set(dir.path());
1374
1375 let config = RouterConfig::from_config();
1376
1377 for complexity in ["simple", "medium", "complex", "review"] {
1378 assert_eq!(
1379 config.model_map[complexity]["shorthand"],
1380 vec!["gpt-5.2".to_string()],
1381 "models.shorthand should populate {complexity}"
1382 );
1383 }
1384 }
1385
1386 #[serial(cooldown_state)]
1387 #[test]
1388 fn from_config_model_map_overrides_models_shorthand_per_tier() {
1389 let _lock = cwd_mutex().lock().unwrap();
1390 let dir = tempfile::tempdir().unwrap();
1391 fs::write(
1392 dir.path().join(".orch.yml"),
1393 r"
1394agents:
1395 - shorthand
1396models:
1397 shorthand:
1398 - gpt-5.2
1399 - gpt-5.5
1400model_map:
1401 review:
1402 shorthand: gpt-5.6-review
1403",
1404 )
1405 .unwrap();
1406 let _guard = CurrentDirGuard::set(dir.path());
1407
1408 let config = RouterConfig::from_config();
1409
1410 assert_eq!(
1411 config.model_map["simple"]["shorthand"],
1412 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1413 );
1414 assert_eq!(
1415 config.model_map["medium"]["shorthand"],
1416 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1417 );
1418 assert_eq!(
1419 config.model_map["complex"]["shorthand"],
1420 vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1421 );
1422 assert_eq!(
1423 config.model_map["review"]["shorthand"],
1424 vec!["gpt-5.6-review".to_string()]
1425 );
1426 }
1427
1428 #[serial(cooldown_state)]
1429 #[test]
1430 fn model_for_complexity_normalizes_trailing_slash_from_pool() {
1431 let mut config = RouterConfig::default();
1434 config
1435 .model_map
1436 .entry("complex".to_string())
1437 .or_default()
1438 .insert(
1439 "testagent_trailing".to_string(),
1440 vec![
1441 "opus/".to_string(),
1442 "sonnet//".to_string(),
1443 "github-copilot/gpt-5-mini/".to_string(),
1444 ],
1445 );
1446
1447 let result = config.model_for_complexity("testagent_trailing", "complex", "task-0");
1449 assert!(
1450 result.is_some(),
1451 "should return a model from pool with trailing slashes normalized, got None"
1452 );
1453 let model = result.unwrap();
1454 assert!(
1456 model == "opus" || model == "sonnet" || model == "github-copilot/gpt-5-mini",
1457 "returned model should be normalized (no trailing slash), got: {model}"
1458 );
1459 assert!(
1461 !model.ends_with('/'),
1462 "returned model should not have trailing slash, got: {model}"
1463 );
1464 }
1465
1466 #[serial(cooldown_state)]
1469 #[test]
1470 fn prune_unavailable_opencode_models_removes_missing_models() {
1471 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1472 model_map.entry("complex".to_string()).or_default().insert(
1473 "opencode".to_string(),
1474 vec![
1475 "available-model".to_string(),
1476 "unavailable-model".to_string(),
1477 "opencode:free".to_string(), ],
1479 );
1480
1481 let mut discovered = HashSet::new();
1482 discovered.insert("available-model".to_string());
1483 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1486
1487 assert_eq!(pruned, 1, "should prune exactly the one unavailable model");
1488
1489 let remaining = model_map["complex"]["opencode"].as_slice();
1490 assert!(
1491 remaining.contains(&"available-model".to_string()),
1492 "available model should remain"
1493 );
1494 assert!(
1495 remaining.contains(&"opencode:free".to_string()),
1496 "opencode:free sentinel should never be pruned"
1497 );
1498 assert!(
1499 !remaining.contains(&"unavailable-model".to_string()),
1500 "unavailable model should be removed"
1501 );
1502 }
1503
1504 #[serial(cooldown_state)]
1505 #[test]
1506 fn prune_unavailable_opencode_models_noop_when_all_available() {
1507 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1508 model_map.entry("simple".to_string()).or_default().insert(
1509 "opencode".to_string(),
1510 vec!["model-a".to_string(), "model-b".to_string()],
1511 );
1512
1513 let discovered: HashSet<String> = ["model-a", "model-b"]
1514 .iter()
1515 .map(ToString::to_string)
1516 .collect();
1517
1518 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1519
1520 assert_eq!(pruned, 0, "nothing to prune when all models are available");
1521 assert_eq!(
1522 model_map["simple"]["opencode"].len(),
1523 2,
1524 "both models should remain"
1525 );
1526 }
1527
1528 #[serial(cooldown_state)]
1529 #[test]
1530 fn prune_unavailable_opencode_models_preserves_non_opencode_agents() {
1531 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1532 model_map
1533 .entry("complex".to_string())
1534 .or_default()
1535 .insert("claude".to_string(), vec!["some-model".to_string()]);
1536
1537 let discovered: HashSet<String> = HashSet::new();
1539
1540 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1541
1542 assert_eq!(pruned, 0, "non-opencode agents must not be touched");
1543 assert_eq!(
1544 model_map["complex"]["claude"].len(),
1545 1,
1546 "claude model should be unchanged"
1547 );
1548 }
1549
1550 #[test]
1551 fn default_config_does_not_use_opencode() {
1552 assert!(!RouterConfig::default().uses_opencode());
1553 }
1554
1555 #[test]
1556 fn uses_opencode_when_a_model_map_tier_lists_it() {
1557 let mut config = RouterConfig::default();
1558 config
1559 .model_map
1560 .entry("simple".to_string())
1561 .or_default()
1562 .insert("opencode".to_string(), vec!["some-model".to_string()]);
1563 assert!(config.uses_opencode());
1564 }
1565
1566 #[test]
1567 fn uses_opencode_follows_the_effective_pool_and_fallback() {
1568 let config = RouterConfig {
1569 pool: vec!["opencode:free".to_string()],
1570 ..RouterConfig::default()
1571 };
1572 assert!(config.uses_opencode());
1573
1574 let config = RouterConfig {
1575 pool: vec!["claude:haiku".to_string()],
1576 ..RouterConfig::default()
1577 };
1578 assert!(!config.uses_opencode());
1579
1580 let config = RouterConfig {
1582 pool: vec![],
1583 router_agent: "opencode".to_string(),
1584 router_model: "free".to_string(),
1585 ..RouterConfig::default()
1586 };
1587 assert!(config.uses_opencode());
1588
1589 let config = RouterConfig {
1590 pool: vec!["claude:haiku".to_string()],
1591 fallback: "opencode:some/model".to_string(),
1592 ..RouterConfig::default()
1593 };
1594 assert!(config.uses_opencode());
1595 }
1596
1597 #[serial(cooldown_state)]
1598 #[test]
1599 fn prune_unavailable_opencode_models_covers_all_complexity_tiers() {
1600 let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1601 for tier in ["simple", "medium", "complex", "review"] {
1602 model_map
1603 .entry(tier.to_string())
1604 .or_default()
1605 .insert("opencode".to_string(), vec!["gone-model".to_string()]);
1606 }
1607
1608 let discovered: HashSet<String> = HashSet::new();
1610
1611 let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1612
1613 assert_eq!(pruned, 4, "should prune one entry per complexity tier");
1614 for tier in ["simple", "medium", "complex", "review"] {
1615 assert!(
1616 model_map[tier]["opencode"].is_empty(),
1617 "all entries for {tier} should be removed"
1618 );
1619 }
1620 }
1621}