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