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