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