Skip to main content

orch/engine/router/
config.rs

1//! Router configuration — loading, defaults, and model map.
2
3use std::collections::HashMap;
4use std::collections::HashSet;
5use std::env;
6use std::sync::OnceLock;
7
8use crate::config;
9use crate::engine;
10use crate::engine::cooldown;
11use crate::engine::router::selection;
12use crate::engine::runner::agents::opencode;
13
14/// Model tiers in ascending order
15const COMPLEXITY_TIERS: [&str; 3] = ["simple", "medium", "complex"];
16
17/// Minimum healthy agents threshold for graceful degradation.
18/// When healthy agents fall below this number, dispatch switches to sequential mode.
19pub fn min_healthy_agents_threshold() -> usize {
20    config::get("dispatch.min_healthy_agents")
21        .ok()
22        .and_then(|v| v.parse().ok())
23        .unwrap_or(2)
24}
25
26/// Base delay in milliseconds between dispatches in sequential (degraded) mode.
27pub fn sequential_dispatch_delay_ms() -> u64 {
28    config::get("dispatch.sequential_delay_ms")
29        .ok()
30        .and_then(|v| v.parse().ok())
31        .unwrap_or(1000)
32}
33
34/// Lookback window (in hours) for the pre-emptive agent health check.
35///
36/// The health check queries `rate_limits` for events within this window.
37/// Configurable via `dispatch.health_check_window_hours` (default: 6).
38pub fn health_check_window_hours() -> u32 {
39    config::get("dispatch.health_check_window_hours")
40        .ok()
41        .and_then(|v| v.parse().ok())
42        .unwrap_or(cooldown::DEFAULT_HEALTH_CHECK_WINDOW_HOURS)
43}
44
45/// Minimum number of rate-limit events within the health check window to
46/// consider an agent degraded.
47///
48/// A single transient 429 error shouldn't mark an agent degraded; we need
49/// a pattern of repeated failures to detect genuine degradation. This
50/// threshold is compared against the count of rate_limit events in the
51/// `rate_limits` table within the health check window.
52///
53/// IMPORTANT: An agent with `rate_limit_count == 0` is NOT degraded by this
54/// criterion — it must meet or exceed the threshold. The threshold should
55/// be set to a value >= 2 to avoid false positives when there are no events.
56///
57/// Configurable via `dispatch.degraded_rate_limit_threshold` (default: 3).
58pub fn degraded_rate_limit_threshold() -> i64 {
59    config::get("dispatch.degraded_rate_limit_threshold")
60        .ok()
61        .and_then(|v| v.parse().ok())
62        .unwrap_or(cooldown::DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD)
63}
64
65/// Base delay in milliseconds for exponential backoff between fallback retries.
66pub fn retry_base_delay_ms() -> u64 {
67    config::get("dispatch.retry_base_delay_ms")
68        .ok()
69        .and_then(|v| v.parse().ok())
70        .unwrap_or(10_000)
71}
72
73/// Maximum delay in milliseconds for exponential backoff between fallback retries.
74pub fn retry_max_delay_ms() -> u64 {
75    config::get("dispatch.retry_max_delay_ms")
76        .ok()
77        .and_then(|v| v.parse().ok())
78        .unwrap_or(120_000)
79}
80
81/// Upper bound for router LLM timeout (seconds).
82///
83/// Routing is a short classification step and should fail fast so a single
84/// slow model does not stall fallback to other healthy agents.
85pub const MAX_ROUTER_TIMEOUT_SECS: u64 = 45;
86
87/// With weighted round robin, an agent whose routing weight decays below this
88/// value is skipped during pre-emptive routability checks.
89pub const SKIP_LIMITED_THRESHOLD: f64 = 0.3;
90
91/// Return the configured base backoff (seconds) for an agent.
92///
93/// Returns the value of `router.backoff_base.{agent}` if set, otherwise
94/// the default BACKOFF_BASE_SECS (5 minutes).
95///
96/// This lets opencode and other higher-failure-rate agents use a longer
97/// initial backoff to reduce wasted retry attempts against consistently
98/// failing models.
99pub fn get_agent_backoff_base(agent: &str) -> i64 {
100    let key = format!("router.backoff_base.{agent}");
101    config::get(&key)
102        .ok()
103        .and_then(|v| v.parse().ok())
104        .unwrap_or(cooldown::BACKOFF_BASE_SECS)
105}
106
107/// Maximum number of tasks to route per tick. Prevents blocking the tick loop
108/// when multiple tasks are queued simultaneously (e.g., cron jobs). Each routing
109/// operation involves an LLM call taking 10-45 seconds, so routing N tasks
110/// sequentially would block for N×LLM-latency seconds.
111///
112/// Configurable via `router.max_tasks_per_tick` (default: 1).
113pub fn max_tasks_per_routing_tick() -> usize {
114    config::get("router.max_tasks_per_tick")
115        .ok()
116        .and_then(|v| v.parse().ok())
117        .unwrap_or(1)
118}
119
120/// Default agents to check in PATH.
121///
122/// All 7 agents are listed, but availability is checked at runtime via
123/// `which::which()`. Agents not installed (e.g. kimi, minimax, glm) are
124/// automatically skipped during routing. Users can customize this list
125/// in their `config.yml` under `agents:`.
126pub const DEFAULT_AGENTS: &[&str] = &[
127    "claude", "codex", "opencode", "kimi", "minimax", "glm", "grok",
128];
129
130/// Router configuration.
131#[derive(Debug, Clone)]
132pub struct RouterConfig {
133    /// Routing mode: "llm", "local", or "round_robin"
134    ///
135    /// - "llm": Use cloud LLMs for routing (default, supports pool-based routing)
136    /// - "local": Use local Ollama model for routing
137    /// - "round_robin": Distribute tasks evenly across available agents
138    pub mode: String,
139    /// Which agent performs routing (default: "claude")
140    pub router_agent: String,
141    /// Model for routing (default: "haiku")
142    pub router_model: String,
143    /// Timeout for routing LLM call in seconds
144    pub timeout_seconds: u64,
145    /// Fallback executor if routing fails
146    pub fallback_executor: String,
147    /// Configurable agent list (checked against PATH at runtime)
148    pub agents: Vec<String>,
149    /// Max LLM routing attempts before falling back to round-robin
150    pub max_route_attempts: u32,
151    /// Default tools allowed
152    pub allowed_tools: Vec<String>,
153    /// Model map for complexity levels.
154    /// Each entry is a pool of models; one is selected randomly (skipping cooled ones) per dispatch.
155    /// A single-model pool `vec!["model"]` behaves identically to the old string format.
156    pub model_map: HashMap<String, HashMap<String, Vec<String>>>,
157    /// Enable weighted round-robin routing based on rate limit capacity.
158    /// When true, agents that hit rate limits get fewer tasks.
159    pub weighted_round_robin: bool,
160    /// Pool of `agent:model` entries to round-robin the router LLM call.
161    /// When empty, a single-entry pool is derived from `router_agent:router_model`.
162    /// Special value `opencode:free` is expanded at startup via `opencode models`.
163    pub pool: Vec<String>,
164    /// Fallback `agent:model` when all pool entries are cooled or fail.
165    /// When empty, defaults to `router_agent:router_model`.
166    pub fallback: String,
167    /// Penalty weight applied when the LLM routes a task to itself (the routing agent).
168    ///
169    /// Range: `0.0` (always redirect away from router agent) to `1.0` (no penalty, default).
170    /// When `< 1.0` and the LLM selects its own agent, the router probabilistically
171    /// redirects to another available agent, reducing self-routing bias.
172    ///
173    /// Example: `0.5` means ~50% of self-routed tasks are redirected to another agent.
174    pub self_routing_penalty: f64,
175    /// Configurable base weights per agent.
176    ///
177    /// Higher weight = more tasks routed to this agent. Agents without an explicit
178    /// weight default to 1.0. The weighted selection normalizes these into
179    /// probabilities, so `{claude: 0.6, minimax: 0.03}` means claude gets ~95%
180    /// of tasks when both are available.
181    ///
182    /// Set in `config.yml` under `router.weights`:
183    /// ```yaml
184    /// router:
185    ///   weights:
186    ///     claude: 0.6
187    ///     codex: 0.2
188    ///     opencode: 0.15
189    ///     minimax: 0.03
190    ///     kimi: 0.02
191    /// ```
192    pub weights: HashMap<String, f64>,
193    /// Per-agent base backoff overrides (seconds). Agents not listed use the
194    /// default BACKOFF_BASE_SECS (5 minutes). Configure as `router.backoff_base.{agent}`.
195    ///
196    /// Example: set `router.backoff_base.opencode: 600` for a 10-minute base
197    /// instead of the default 5-minute base (useful for agents with higher
198    /// failure rates like opencode at 24.8%).
199    pub agent_backoff_bases: HashMap<String, i64>,
200    /// Maximum number of tasks to route per tick. Prevents blocking the tick loop
201    /// when multiple tasks are queued simultaneously (e.g., cron jobs). Each routing
202    /// operation involves an LLM call taking 10-45 seconds, so routing N tasks
203    /// sequentially would block for N×LLM-latency seconds.
204    ///
205    /// Configurable via `router.max_tasks_per_tick` (default: 1).
206    pub max_tasks_per_tick: usize,
207    /// Ollama base URL for local routing (default: "http://localhost:11434").
208    pub ollama_url: String,
209    /// Ollama model name for routing (default: "qwen2.5-coder:3b-instruct").
210    pub ollama_model: String,
211    /// Timeout for Ollama HTTP call in seconds (default: 30).
212    pub ollama_timeout_seconds: u64,
213}
214
215/// Parse an `agent:model` pool entry string, splitting on the first colon.
216///
217/// Examples:
218/// - `"claude:haiku"` → `("claude", "haiku")`
219/// - `"opencode:github-copilot/gpt-5-mini"` → `("opencode", "github-copilot/gpt-5-mini")`
220/// - `"claude"` → `("claude", "")`
221pub fn parse_pool_entry(entry: &str) -> (String, String) {
222    if let Some(colon_pos) = entry.find(':') {
223        let agent = entry[..colon_pos].to_string();
224        let model = entry[colon_pos + 1..].to_string();
225        // Normalize trailing slashes in model part (defense-in-depth for bug #1507)
226        let model = RouterConfig::normalize_model_identifier(&model);
227        (agent, model)
228    } else {
229        (entry.to_string(), String::new())
230    }
231}
232
233impl Default for RouterConfig {
234    fn default() -> Self {
235        Self {
236            mode: "round_robin".to_string(),
237            router_agent: "claude".to_string(),
238            // Empty passes no `--model`, so the router agent's CLI uses its own default
239            router_model: String::new(),
240            timeout_seconds: 45,
241            fallback_executor: "codex".to_string(),
242            agents: DEFAULT_AGENTS.iter().map(ToString::to_string).collect(),
243            max_route_attempts: 3,
244            pool: vec![],
245            fallback: String::new(),
246            self_routing_penalty: 1.0,
247            weights: HashMap::new(),
248            allowed_tools: vec![
249                "yq".to_string(),
250                "jq".to_string(),
251                "bash".to_string(),
252                "just".to_string(),
253                "git".to_string(),
254                "rg".to_string(),
255                "sed".to_string(),
256                "awk".to_string(),
257                "python3".to_string(),
258                "node".to_string(),
259                "npm".to_string(),
260                "bun".to_string(),
261            ],
262            // model_map is intentionally empty — config.yml is the sole source of truth.
263            // Hardcoded models cause "Model not found" failures when the model does not
264            // exist for a particular agent (e.g. anthropic/ prefixed models for opencode).
265            model_map: HashMap::new(),
266            weighted_round_robin: false,
267            agent_backoff_bases: HashMap::new(),
268            max_tasks_per_tick: 1,
269            ollama_url: "http://localhost:11434".to_string(),
270            ollama_model: "qwen2.5-coder:3b-instruct".to_string(),
271            ollama_timeout_seconds: 30,
272        }
273    }
274}
275
276impl RouterConfig {
277    /// Load configuration from config files.
278    pub fn from_config() -> Self {
279        let mut config = Self::default();
280
281        // Try to load from config
282        if let Ok(mode) = config::get("router.mode")
283            && (mode == "round_robin" || mode == "llm" || mode == "local")
284        {
285            config.mode = mode;
286        }
287
288        if let Ok(agent) = config::get("router.agent")
289            && !agent.is_empty()
290        {
291            config.router_agent = agent;
292        }
293
294        if let Ok(model) = config::get("router.model")
295            && !model.is_empty()
296        {
297            config.router_model = RouterConfig::normalize_model_identifier(&model);
298        }
299
300        if let Ok(timeout) = config::get("router.timeout_seconds")
301            && let Ok(secs) = timeout.parse::<u64>()
302        {
303            let clamped = secs.min(MAX_ROUTER_TIMEOUT_SECS);
304            if clamped != secs {
305                static TIMEOUT_CLAMP_WARNED: OnceLock<()> = OnceLock::new();
306                TIMEOUT_CLAMP_WARNED.get_or_init(|| {
307                    tracing::warn!(
308                        configured_secs = secs,
309                        applied_secs = clamped,
310                        max_secs = MAX_ROUTER_TIMEOUT_SECS,
311                        "router.timeout_seconds is too high; clamping to keep routing responsive"
312                    );
313                });
314            }
315            config.timeout_seconds = clamped;
316        }
317
318        if let Ok(fallback) = config::get("router.fallback_executor")
319            && !fallback.is_empty()
320        {
321            config.fallback_executor = fallback;
322        }
323
324        // Parse agents list from top-level `agents:` config key
325        config.agents = engine::configured_agents();
326
327        // Temporary operational toggle: allow disabling agents without editing
328        // config files. Controlled by ORCH_EXCLUDE_AGENTS env var (comma-separated
329        // list of agent names to exclude from routing). This keeps changes reversible
330        // (unset the env var to restore behavior) and avoids editing user config files.
331        // Example: ORCH_EXCLUDE_AGENTS=glm,some-other-agent
332        let exclude_agents = env::var("ORCH_EXCLUDE_AGENTS")
333            .map(|v| {
334                v.split(',')
335                    .map(|s| s.trim().to_string())
336                    .filter(|s| !s.is_empty())
337                    .collect::<Vec<_>>()
338            })
339            .unwrap_or_default();
340        if !exclude_agents.is_empty() {
341            let original_len = config.agents.len();
342            config.agents.retain(|a| !exclude_agents.contains(a));
343            let removed_count = original_len - config.agents.len();
344            if removed_count > 0 {
345                tracing::warn!(
346                    "ORCH_EXCLUDE_AGENTS={}: temporarily removing {} agent(s) from router",
347                    exclude_agents.join(","),
348                    removed_count
349                );
350            }
351        }
352
353        if let Ok(max_attempts) = config::get("router.max_route_attempts")
354            && let Ok(n) = max_attempts.parse::<u32>()
355        {
356            config.max_route_attempts = n;
357        }
358
359        // Parse allowed_tools as comma-separated or YAML array
360        if let Ok(tools_str) = config::get("router.allowed_tools")
361            && !tools_str.is_empty()
362            && tools_str != "[]"
363        {
364            // Try to parse as JSON/YAML array first
365            if let Ok(tools_arr) = serde_json::from_str::<Vec<String>>(&tools_str) {
366                config.allowed_tools = tools_arr;
367            } else {
368                // Fall back to comma-separated
369                config.allowed_tools = tools_str
370                    .split(',')
371                    .map(|s| s.trim().to_string())
372                    .filter(|s| !s.is_empty())
373                    .collect();
374            }
375        }
376
377        // Parse weighted_round_robin
378        if let Ok(val) = config::get("router.weighted_round_robin") {
379            config.weighted_round_robin = val == "true" || val == "1";
380        }
381
382        // Parse self_routing_penalty
383        if let Ok(val) = config::get("router.self_routing_penalty")
384            && let Ok(penalty) = val.parse::<f64>()
385        {
386            config.self_routing_penalty = penalty.clamp(0.0, 1.0);
387        }
388
389        // Parse per-agent weights from router.weights.<agent>
390        for agent in &config.agents {
391            let key = format!("router.weights.{agent}");
392            if let Ok(val) = config::get(&key)
393                && let Ok(w) = val.parse::<f64>()
394            {
395                config.weights.insert(agent.clone(), w.max(0.0));
396            }
397        }
398
399        // Parse per-agent backoff base seconds from router.backoff_base.<agent>
400        for agent in &config.agents {
401            let key = format!("router.backoff_base.{agent}");
402            if let Ok(val) = config::get(&key)
403                && let Ok(secs) = val.parse::<i64>()
404            {
405                config.agent_backoff_bases.insert(agent.clone(), secs);
406            }
407        }
408
409        // Parse max_tasks_per_tick
410        if let Ok(val) = config::get("router.max_tasks_per_tick")
411            && let Ok(n) = val.parse::<usize>()
412            && n > 0
413        {
414            config.max_tasks_per_tick = n;
415        }
416
417        // Parse pool: list of "agent:model" entries.
418        // `config::get_list()` returns Ok(vec![]) when the key is missing, so we
419        // can't rely on `is_ok()` to indicate presence.
420        match config::get_list("router.pool") {
421            Ok(pool_list) if !pool_list.is_empty() => {
422                config.pool = pool_list;
423            }
424            _ => {
425                // Accept comma-separated string lists: "a,b,c"
426                if let Ok(pool_raw) = config::get("router.pool") {
427                    let parsed = pool_raw
428                        .split(',')
429                        .map(|s| s.trim().to_string())
430                        .filter(|s| !s.is_empty())
431                        .collect::<Vec<_>>();
432                    if !parsed.is_empty() {
433                        config.pool = parsed;
434                    }
435                }
436            }
437        }
438
439        // Parse fallback: single "agent:model" entry
440        if let Ok(fallback) = config::get("router.fallback")
441            && !fallback.is_empty()
442        {
443            config.fallback = fallback;
444        }
445
446        // Load top-level model shorthand from config (models.{agent}).
447        //
448        // These candidates apply to every complexity tier by default. More
449        // specific model_map.{complexity}.{agent} entries below override the
450        // shorthand for that one tier.
451        let known_agents = engine::configured_agents();
452        let known_complexities = ["simple", "medium", "complex", "review"];
453        for agent in &known_agents {
454            let key = format!("models.{agent}");
455            if let Some(models) = Self::read_model_pool_from_config(&key) {
456                for complexity in known_complexities {
457                    config
458                        .model_map
459                        .entry(complexity.to_string())
460                        .or_default()
461                        .insert(agent.clone(), models.clone());
462                }
463            }
464        }
465
466        // Load model_map overrides from config (model_map.{complexity}.{agent})
467        // Value may be a single string ("model-name") or a JSON array (["m1","m2"]).
468        // Iterate over all known complexity tiers regardless of what is in model_map —
469        // the Default impl has no hardcoded entries, so iterating over keys() would be a no-op.
470        for complexity in known_complexities {
471            for agent in &known_agents {
472                let key = format!("model_map.{complexity}.{agent}");
473                if let Some(models) = Self::read_model_pool_from_config(&key) {
474                    config
475                        .model_map
476                        .entry(complexity.to_string())
477                        .or_default()
478                        .insert(agent.clone(), models);
479                }
480            }
481        }
482
483        // Startup config hygiene: warn about and prune opencode model_map entries that
484        // the provider catalog does not currently list.  Running this at load time avoids
485        // dispatching unavailable models during routing — the dynamic filter in
486        // `expanded_model_pool` also catches these, but fails open when discovery returns
487        // empty (e.g. during a background cache refresh), allowing stale models through.
488        // Reading the catalog costs an `opencode models` run, so only configs that can
489        // reach opencode pay for it
490        let discovered_opencode = if config.uses_opencode() {
491            opencode::discover_opencode_models()
492        } else {
493            Vec::new()
494        };
495        if !discovered_opencode.is_empty() {
496            let discovered: HashSet<String> = discovered_opencode.into_iter().collect();
497            for complexity in known_complexities {
498                if let Some(agent_models) = config.model_map.get(complexity)
499                    && let Some(models) = agent_models.get("opencode")
500                {
501                    for model in models {
502                        if model != "opencode:free" && !discovered.contains(model) {
503                            tracing::warn!(
504                                complexity,
505                                model,
506                                "opencode model from config not present in provider model list; pruning from dispatch pool"
507                            );
508                        }
509                    }
510                }
511            }
512            let pruned =
513                Self::prune_unavailable_opencode_models(&mut config.model_map, &discovered);
514            if pruned > 0 {
515                tracing::info!(
516                    pruned_count = pruned,
517                    "model_pruned_unavailable: removed opencode models absent from provider catalog"
518                );
519            }
520        }
521
522        // Parse Ollama-specific config for local routing mode
523        if let Ok(url) = config::get("router.ollama_url")
524            && !url.is_empty()
525        {
526            config.ollama_url = url;
527        }
528        if let Ok(model) = config::get("router.ollama_model")
529            && !model.is_empty()
530        {
531            config.ollama_model = model;
532        }
533        if let Ok(timeout) = config::get("router.ollama_timeout_seconds")
534            && let Ok(secs) = timeout.parse::<u64>()
535            && secs > 0
536        {
537            config.ollama_timeout_seconds = secs;
538        }
539
540        config
541    }
542
543    /// Return the effective pool — the configured pool, or a single-entry pool from `router_agent:router_model`.
544    pub fn effective_pool(&self) -> Vec<String> {
545        if self.pool.is_empty() {
546            vec![format!("{}:{}", self.router_agent, self.router_model)]
547        } else {
548            self.pool.clone()
549        }
550    }
551
552    /// Return the effective fallback entry — the configured fallback, or `router_agent:router_model`.
553    pub fn effective_fallback(&self) -> String {
554        if self.fallback.is_empty() {
555            format!("{}:{}", self.router_agent, self.router_model)
556        } else {
557            self.fallback.clone()
558        }
559    }
560
561    /// Check if a model identifier looks syntactically valid.
562    /// Rejects empty strings, strings ending with slash, and strings with whitespace.
563    fn is_valid_model_identifier(model: &str) -> bool {
564        if model.is_empty() {
565            return false;
566        }
567        // Reject trailing slash (e.g., "opus/")
568        if model.ends_with('/') {
569            return false;
570        }
571        // Reject whitespace
572        if model.chars().any(char::is_whitespace) {
573            return false;
574        }
575        // Ensure that if there is a slash, both parts are non-empty
576        if let Some(slash_pos) = model.find('/') {
577            let before = &model[..slash_pos];
578            let after = &model[slash_pos + 1..];
579            if before.is_empty() || after.is_empty() {
580                return false;
581            }
582        }
583        true
584    }
585
586    /// Normalize a model identifier by stripping trailing slashes.
587    /// This is a defense-in-depth measure to handle edge cases where
588    /// a model string might have been incorrectly formatted.
589    pub fn normalize_model_identifier(model: &str) -> String {
590        model.trim_end_matches('/').to_string()
591    }
592
593    /// The models listed for the agent under `models:` in the config, empty when it has none.
594    pub fn configured_models(agent: &str) -> Vec<String> {
595        Self::read_model_pool_from_config(&format!("models.{agent}")).unwrap_or_default()
596    }
597
598    fn read_model_pool_from_config(key: &str) -> Option<Vec<String>> {
599        match config::get_list(key) {
600            Ok(list) => {
601                if !list.is_empty() {
602                    return Some(
603                        list.iter()
604                            .map(|m| RouterConfig::normalize_model_identifier(m))
605                            .collect(),
606                    );
607                }
608            }
609            _ => {
610                if let Ok(val) = config::get(key)
611                    && !val.is_empty()
612                {
613                    return Some(vec![RouterConfig::normalize_model_identifier(&val)]);
614                }
615            }
616        }
617
618        None
619    }
620
621    fn expanded_model_pool(&self, agent: &str, complexity: &str) -> Option<Vec<String>> {
622        let pool = self.model_map.get(complexity)?.get(agent)?;
623        if pool.is_empty() {
624            return Some(Vec::new());
625        }
626
627        let mut expanded_pool = Vec::new();
628        let mut has_free = false;
629
630        for model in pool {
631            // Normalize the model identifier first to handle edge cases like trailing slashes
632            let normalized = Self::normalize_model_identifier(model);
633            if normalized == "opencode:free" {
634                has_free = true;
635            } else if Self::is_valid_model_identifier(&normalized) {
636                expanded_pool.push(normalized);
637            } else {
638                tracing::debug!(agent, model, "skipping invalid model identifier in config");
639            }
640        }
641
642        if has_free {
643            expanded_pool.extend(opencode::discover_free_opencode_models());
644        }
645
646        // Also filter out invalid discovered free models (should be valid but just in case)
647        expanded_pool.retain(|m| Self::is_valid_model_identifier(m));
648
649        // For opencode, filter configured entries against the provider model catalog
650        // when available. This proactively avoids dispatching non-existent model IDs.
651        if agent == "opencode" {
652            let discovered = opencode::discover_opencode_models();
653            if !discovered.is_empty() {
654                let discovered_set: HashSet<String> = discovered.into_iter().collect();
655                expanded_pool.retain(|m| discovered_set.contains(m));
656            }
657        }
658
659        Some(expanded_pool)
660    }
661
662    pub(crate) fn model_pool_for_complexity(
663        &self,
664        agent: &str,
665        complexity: &str,
666    ) -> Option<Vec<String>> {
667        self.expanded_model_pool(agent, complexity)
668    }
669
670    pub fn has_available_model_for_complexity(&self, agent: &str, complexity: &str) -> bool {
671        match self.expanded_model_pool(agent, complexity) {
672            None => false,
673            Some(pool) => pool
674                .iter()
675                .any(|model| !cooldown::is_model_in_cooldown(agent, model)),
676        }
677    }
678
679    /// True when `complexity` or any adjacent tier has a model out of cooldown, the same search
680    /// `model_for_complexity_or_adjacent` runs
681    pub fn has_available_model_in_any_tier(&self, agent: &str, complexity: &str) -> bool {
682        Self::tier_search_order(complexity)
683            .into_iter()
684            .any(|tier| self.has_available_model_for_complexity(agent, tier))
685    }
686
687    /// Get the model for a given agent and complexity level.
688    ///
689    /// When the complexity tier has a pool of models, selects randomly using
690    /// `task_id` as an entropy source and skips models currently in cooldown.
691    /// Falls back to `pool[0]` if all models are cooled.
692    ///
693    /// Backward-compatible: a single-model pool always returns that model.
694    pub fn model_for_complexity(
695        &self,
696        agent: &str,
697        complexity: &str,
698        task_id: &str,
699    ) -> Option<String> {
700        let expanded_pool = self.expanded_model_pool(agent, complexity)?;
701        if expanded_pool.is_empty() {
702            return None;
703        }
704        // Random starting index — varies per task_id to distribute across the pool
705        let start = selection::simple_hash_index_for(expanded_pool.len(), task_id);
706        // Walk the pool from start, skipping cooled and invalid models
707        for i in 0..expanded_pool.len() {
708            let model = &expanded_pool[(start + i) % expanded_pool.len()];
709            // Safety check: skip invalid identifiers (should already be filtered)
710            if !Self::is_valid_model_identifier(model) {
711                tracing::debug!(
712                    agent,
713                    model,
714                    "invalid model identifier slipped through validation"
715                );
716                continue;
717            }
718            if !cooldown::is_model_in_cooldown(agent, model) {
719                // Normalize the model identifier to handle edge cases like trailing slashes
720                return Some(Self::normalize_model_identifier(model));
721            }
722        }
723        // All models cooled — return None so the caller can fall back to a different agent
724        None
725    }
726
727    /// Tiers to try for `complexity`, in order: its own, the higher tiers nearest first, then the
728    /// lower tiers nearest first. A tier outside simple, medium and complex has only itself
729    fn tier_search_order(complexity: &str) -> Vec<&str> {
730        let Some(idx) = COMPLEXITY_TIERS.iter().position(|t| *t == complexity) else {
731            return vec![complexity];
732        };
733        let mut order = vec![COMPLEXITY_TIERS[idx]];
734        order.extend(&COMPLEXITY_TIERS[idx + 1..]);
735        order.extend(COMPLEXITY_TIERS[..idx].iter().rev());
736        order
737    }
738
739    /// Like `model_for_complexity`, but when the task's own tier has no available model it takes
740    /// one from the tiers above, then below. Returns the model and the tier it came from
741    pub fn model_for_complexity_or_adjacent(
742        &self,
743        agent: &str,
744        complexity: &str,
745        task_id: &str,
746    ) -> Option<(String, String)> {
747        Self::tier_search_order(complexity)
748            .into_iter()
749            .find_map(|tier| {
750                self.model_for_complexity(agent, tier, task_id)
751                    .map(|model| (model, tier.to_string()))
752            })
753    }
754
755    /// The tier `model` runs from for a task of `complexity`: the first tier in the search order
756    /// whose pool lists it, or `complexity` itself when none does
757    pub fn tier_of_model(&self, agent: &str, model: &str, complexity: &str) -> String {
758        Self::tier_search_order(complexity)
759            .into_iter()
760            .find(|tier| {
761                self.expanded_model_pool(agent, tier)
762                    .is_some_and(|pool| pool.iter().any(|m| m == model))
763            })
764            .unwrap_or(complexity)
765            .to_string()
766    }
767
768    /// True when this config can reach opencode: a `model_map` tier lists it, or the
769    /// effective router pool or fallback names it. Those are the only entries read out of
770    /// `opencode models`, so every other config can skip the call
771    pub(crate) fn uses_opencode(&self) -> bool {
772        fn names_opencode(entry: &str) -> bool {
773            entry == "opencode" || entry.starts_with("opencode:")
774        }
775
776        if self
777            .model_map
778            .values()
779            .any(|by_agent| by_agent.contains_key("opencode"))
780        {
781            return true;
782        }
783
784        self.effective_pool().iter().any(|e| names_opencode(e))
785            || names_opencode(&self.effective_fallback())
786    }
787
788    /// Remove `model_map` entries for the `opencode` agent whose identifiers do not
789    /// appear in `discovered`.  The sentinel value `"opencode:free"` is never pruned
790    /// because it is expanded at routing time and is not dispatched as a literal model ID.
791    ///
792    /// Returns the total number of model entries removed across all complexity tiers.
793    fn prune_unavailable_opencode_models(
794        model_map: &mut HashMap<String, HashMap<String, Vec<String>>>,
795        discovered: &HashSet<String>,
796    ) -> usize {
797        let mut pruned = 0;
798        for agent_models in model_map.values_mut() {
799            if let Some(models) = agent_models.get_mut("opencode") {
800                let before = models.len();
801                models.retain(|m| m == "opencode:free" || discovered.contains(m));
802                pruned += before - models.len();
803            }
804        }
805        pruned
806    }
807}
808
809#[cfg(test)]
810mod tests {
811    use super::{MAX_ROUTER_TIMEOUT_SECS, RouterConfig};
812    use crate::engine::cooldown;
813    use serial_test::serial;
814    use std::collections::HashMap;
815    use std::collections::HashSet;
816    use std::env;
817    use std::fs;
818    use std::path::Path;
819    use std::path::PathBuf;
820    use std::sync::{Mutex, OnceLock};
821
822    struct CurrentDirGuard {
823        original: PathBuf,
824    }
825
826    impl CurrentDirGuard {
827        fn set(path: &Path) -> Self {
828            let original = env::current_dir().unwrap();
829            env::set_current_dir(path).unwrap();
830            Self { original }
831        }
832    }
833
834    impl Drop for CurrentDirGuard {
835        fn drop(&mut self) {
836            env::set_current_dir(&self.original).unwrap();
837        }
838    }
839
840    fn cwd_mutex() -> &'static Mutex<()> {
841        static CWD_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
842        CWD_MUTEX.get_or_init(|| Mutex::new(()))
843    }
844
845    #[serial(cooldown_state)]
846    #[tokio::test]
847    async fn model_for_complexity_returns_none_when_all_models_cooled() {
848        cooldown::reset_global_state().await;
849        let mut config = RouterConfig::default();
850        // Inject a two-model pool for a unique agent name to avoid cross-test pollution
851        config
852            .model_map
853            .entry("complex".to_string())
854            .or_default()
855            .insert(
856                "testagent_allcooled".to_string(),
857                vec![
858                    "cooldown-model-a".to_string(),
859                    "cooldown-model-b".to_string(),
860                ],
861            );
862
863        // Put both models into cooldown
864        cooldown::record_model_failure("testagent_allcooled", "cooldown-model-a").await;
865        cooldown::record_model_failure("testagent_allcooled", "cooldown-model-b").await;
866
867        let result = config.model_for_complexity("testagent_allcooled", "complex", "task-0");
868        assert!(
869            result.is_none(),
870            "should return None when all models in pool are in cooldown, got {result:?}"
871        );
872    }
873
874    fn tiered_config(agent: &str, tiers: &[(&str, &str)]) -> RouterConfig {
875        let mut config = RouterConfig::default();
876        config.model_map.clear();
877        for (tier, model) in tiers {
878            config
879                .model_map
880                .entry((*tier).to_string())
881                .or_default()
882                .insert(agent.to_string(), vec![(*model).to_string()]);
883        }
884        config
885    }
886
887    #[serial(cooldown_state)]
888    #[tokio::test]
889    async fn adjacent_tier_prefers_higher_over_lower() {
890        cooldown::reset_global_state().await;
891        let agent = "tieragent_higher";
892        let config = tiered_config(
893            agent,
894            &[("simple", "t-s"), ("medium", "t-m"), ("complex", "t-c")],
895        );
896        cooldown::record_model_failure(agent, "t-m").await;
897
898        let got = config.model_for_complexity_or_adjacent(agent, "medium", "t");
899        assert_eq!(got, Some(("t-c".to_string(), "complex".to_string())));
900        assert_eq!(config.tier_of_model(agent, "t-c", "medium"), "complex");
901    }
902
903    #[serial(cooldown_state)]
904    #[tokio::test]
905    async fn simple_task_tries_medium_then_complex_before_lower() {
906        cooldown::reset_global_state().await;
907        let agent = "tieragent_simple";
908        let config = tiered_config(
909            agent,
910            &[("simple", "u-s"), ("medium", "u-m"), ("complex", "u-c")],
911        );
912        cooldown::record_model_failure(agent, "u-s").await;
913        cooldown::record_model_failure(agent, "u-m").await;
914
915        let got = config.model_for_complexity_or_adjacent(agent, "simple", "t");
916        assert_eq!(got, Some(("u-c".to_string(), "complex".to_string())));
917    }
918
919    #[serial(cooldown_state)]
920    #[tokio::test]
921    async fn adjacent_tier_falls_back_to_lower_when_higher_tiers_are_unavailable() {
922        cooldown::reset_global_state().await;
923        let agent = "tieragent_lower";
924        let config = tiered_config(agent, &[("simple", "v-s"), ("medium", "v-m")]);
925        cooldown::record_model_failure(agent, "v-m").await;
926
927        let got = config.model_for_complexity_or_adjacent(agent, "complex", "t");
928        assert_eq!(got, Some(("v-s".to_string(), "simple".to_string())));
929    }
930
931    #[serial(cooldown_state)]
932    #[tokio::test]
933    async fn adjacent_tier_returns_none_when_every_tier_is_cooled() {
934        cooldown::reset_global_state().await;
935        let agent = "tieragent_allcooled";
936        let config = tiered_config(
937            agent,
938            &[("simple", "w-s"), ("medium", "w-m"), ("complex", "w-c")],
939        );
940        for m in ["w-s", "w-m", "w-c"] {
941            cooldown::record_model_failure(agent, m).await;
942        }
943
944        assert_eq!(
945            config.model_for_complexity_or_adjacent(agent, "medium", "t"),
946            None
947        );
948    }
949
950    #[serial(cooldown_state)]
951    #[tokio::test]
952    async fn model_for_complexity_returns_none_when_single_model_cooled() {
953        cooldown::reset_global_state().await;
954        let mut config = RouterConfig::default();
955        config
956            .model_map
957            .entry("complex".to_string())
958            .or_default()
959            .insert(
960                "testagent_singlecooled".to_string(),
961                vec!["single-cooled-model".to_string()],
962            );
963
964        cooldown::record_model_failure("testagent_singlecooled", "single-cooled-model").await;
965
966        let result = config.model_for_complexity("testagent_singlecooled", "complex", "task-0");
967        assert!(
968            result.is_none(),
969            "should return None when the only model in pool is in cooldown, got {result:?}"
970        );
971    }
972
973    #[serial(cooldown_state)]
974    #[test]
975    fn model_for_complexity_returns_model_when_not_cooled() {
976        let mut config = RouterConfig::default();
977        config
978            .model_map
979            .entry("complex".to_string())
980            .or_default()
981            .insert(
982                "testagent_notcooled".to_string(),
983                vec!["healthy-model".to_string()],
984            );
985
986        // Ensure no cooldown is active for this specific model
987        let result = config.model_for_complexity("testagent_notcooled", "complex", "task-0");
988        assert_eq!(
989            result.as_deref(),
990            Some("healthy-model"),
991            "should return the model when it is not in cooldown"
992        );
993    }
994
995    #[serial(cooldown_state)]
996    #[test]
997    fn has_available_model_returns_false_when_no_pool_configured() {
998        let mut config = RouterConfig::default();
999        // Simulate olm agent with only simple and medium configured (missing complex and review)
1000        config
1001            .model_map
1002            .entry("simple".to_string())
1003            .or_default()
1004            .insert("olm".to_string(), vec!["qwen3.5".to_string()]);
1005        config
1006            .model_map
1007            .entry("medium".to_string())
1008            .or_default()
1009            .insert("olm".to_string(), vec!["gemma4".to_string()]);
1010        // Note: complex and review tiers are NOT configured for olm
1011
1012        // has_available_model_for_complexity should return false when no pool exists
1013        assert!(
1014            config.has_available_model_for_complexity("olm", "simple"),
1015            "should return true when model pool exists and is configured"
1016        );
1017        assert!(
1018            config.has_available_model_for_complexity("olm", "medium"),
1019            "should return true when model pool exists and is configured"
1020        );
1021        assert!(
1022            !config.has_available_model_for_complexity("olm", "complex"),
1023            "should return false when no model pool is configured for agent+complexity"
1024        );
1025        assert!(
1026            !config.has_available_model_for_complexity("olm", "review"),
1027            "should return false when no model pool is configured for agent+complexity"
1028        );
1029    }
1030
1031    #[serial(cooldown_state)]
1032    #[test]
1033    fn default_self_routing_penalty_is_one() {
1034        let config = RouterConfig::default();
1035        assert!(
1036            (config.self_routing_penalty - 1.0).abs() < f64::EPSILON,
1037            "default penalty must be 1.0 (no penalty = full self-routing allowed)"
1038        );
1039    }
1040
1041    #[serial(cooldown_state)]
1042    #[test]
1043    fn from_config_reads_self_routing_penalty() {
1044        let _lock = cwd_mutex().lock().unwrap();
1045        let dir = tempfile::tempdir().unwrap();
1046        fs::write(
1047            dir.path().join(".orch.yml"),
1048            "router:\n  self_routing_penalty: 0.5\n",
1049        )
1050        .unwrap();
1051        let _guard = CurrentDirGuard::set(dir.path());
1052
1053        let config = RouterConfig::from_config();
1054        assert!((config.self_routing_penalty - 0.5).abs() < f64::EPSILON);
1055    }
1056
1057    #[serial(cooldown_state)]
1058    #[test]
1059    fn default_config_model_map_is_empty() {
1060        // model_map must be empty — config.yml is the sole source of truth for models.
1061        // Hardcoded defaults (especially anthropic/ prefixed opencode models) cause
1062        // "Model not found" failures when the model does not exist for a given agent.
1063        let config = RouterConfig::default();
1064        assert!(
1065            config.model_map.is_empty(),
1066            "Default RouterConfig must have no hardcoded models; got {:?}",
1067            config.model_map
1068        );
1069    }
1070
1071    #[serial(cooldown_state)]
1072    #[test]
1073    fn from_config_reads_router_pool_yaml_array() {
1074        let _lock = cwd_mutex().lock().unwrap();
1075        let dir = tempfile::tempdir().unwrap();
1076        fs::write(
1077            dir.path().join(".orch.yml"),
1078            "router:\n  pool:\n    - opencode:free\n    - opencode:github-copilot/gpt-5-mini\n    - kimi:k2p5\n    - claude:haiku\n",
1079        )
1080        .unwrap();
1081        let _guard = CurrentDirGuard::set(dir.path());
1082
1083        let config = RouterConfig::from_config();
1084
1085        assert_eq!(
1086            config.pool,
1087            vec![
1088                "opencode:free",
1089                "opencode:github-copilot/gpt-5-mini",
1090                "kimi:k2p5",
1091                "claude:haiku",
1092            ]
1093        );
1094    }
1095
1096    #[serial(cooldown_state)]
1097    #[test]
1098    fn from_config_clamps_router_timeout_to_max() {
1099        let _lock = cwd_mutex().lock().unwrap();
1100        let dir = tempfile::tempdir().unwrap();
1101        fs::write(
1102            dir.path().join(".orch.yml"),
1103            "router:\n  timeout_seconds: 90\n",
1104        )
1105        .unwrap();
1106        let _guard = CurrentDirGuard::set(dir.path());
1107
1108        let config = RouterConfig::from_config();
1109        assert_eq!(config.timeout_seconds, MAX_ROUTER_TIMEOUT_SECS);
1110    }
1111
1112    #[serial(cooldown_state)]
1113    #[test]
1114    fn normalize_model_identifier_strips_trailing_slash() {
1115        // Bug #1507: model assignment was producing "opus/" instead of "opus"
1116        assert_eq!(
1117            RouterConfig::normalize_model_identifier("opus/"),
1118            "opus",
1119            "trailing slash should be stripped from model identifier"
1120        );
1121        assert_eq!(
1122            RouterConfig::normalize_model_identifier("sonnet/"),
1123            "sonnet",
1124            "trailing slash should be stripped from model identifier"
1125        );
1126        assert_eq!(
1127            RouterConfig::normalize_model_identifier("github-copilot/gpt-5-mini/"),
1128            "github-copilot/gpt-5-mini",
1129            "trailing slash should be stripped from model identifier with internal slash"
1130        );
1131        // Edge cases: multiple trailing slashes
1132        assert_eq!(
1133            RouterConfig::normalize_model_identifier("opus//"),
1134            "opus",
1135            "multiple trailing slashes should be stripped"
1136        );
1137        // Edge cases: no trailing slash
1138        assert_eq!(
1139            RouterConfig::normalize_model_identifier("opus"),
1140            "opus",
1141            "model without trailing slash should remain unchanged"
1142        );
1143    }
1144
1145    #[serial(cooldown_state)]
1146    #[test]
1147    fn is_valid_model_identifier_rejects_trailing_slash() {
1148        // Ensure validation correctly rejects models with trailing slashes
1149        assert!(
1150            !RouterConfig::is_valid_model_identifier("opus/"),
1151            "model with trailing slash should be invalid"
1152        );
1153        assert!(
1154            RouterConfig::is_valid_model_identifier("opus"),
1155            "model without trailing slash should be valid"
1156        );
1157        assert!(
1158            RouterConfig::is_valid_model_identifier("github-copilot/gpt-5-mini"),
1159            "model with internal slash should be valid"
1160        );
1161        assert!(
1162            !RouterConfig::is_valid_model_identifier("github-copilot/"),
1163            "model ending with slash after prefix should be invalid"
1164        );
1165    }
1166
1167    #[serial(cooldown_state)]
1168    #[test]
1169    fn from_config_loads_model_map_for_custom_agents() {
1170        let _lock = cwd_mutex().lock().unwrap();
1171        let dir = tempfile::tempdir().unwrap();
1172        // Simulate a config with a custom agent (olm) in both agents and model_map
1173        fs::write(
1174            dir.path().join(".orch.yml"),
1175            r"
1176agents:
1177  - claude
1178  - olm
1179model_map:
1180  simple:
1181    claude: haiku
1182    olm: qwen3.5
1183  medium:
1184    claude: sonnet
1185    olm: gemma4
1186  complex:
1187    claude: opus
1188    olm: gemma4
1189",
1190        )
1191        .unwrap();
1192        let _guard = CurrentDirGuard::set(dir.path());
1193
1194        let config = RouterConfig::from_config();
1195
1196        // olm models should be loaded from the model_map
1197        assert_eq!(
1198            config.model_for_complexity("olm", "simple", "test-task"),
1199            Some("qwen3.5".to_string()),
1200            "custom agent olm should have simple model from config"
1201        );
1202        assert_eq!(
1203            config.model_for_complexity("olm", "medium", "test-task"),
1204            Some("gemma4".to_string()),
1205            "custom agent olm should have medium model from config"
1206        );
1207        // claude should also work
1208        assert_eq!(
1209            config.model_for_complexity("claude", "simple", "test-task"),
1210            Some("haiku".to_string()),
1211        );
1212    }
1213
1214    #[serial(cooldown_state)]
1215    #[test]
1216    fn from_config_loads_models_shorthand_for_all_complexities() {
1217        let _lock = cwd_mutex().lock().unwrap();
1218        let dir = tempfile::tempdir().unwrap();
1219        fs::write(
1220            dir.path().join(".orch.yml"),
1221            r"
1222agents:
1223  - shorthand
1224models:
1225  shorthand:
1226    - gpt-5.2
1227    - gpt-5.5
1228",
1229        )
1230        .unwrap();
1231        let _guard = CurrentDirGuard::set(dir.path());
1232
1233        let config = RouterConfig::from_config();
1234
1235        for complexity in ["simple", "medium", "complex", "review"] {
1236            assert_eq!(
1237                config.model_map[complexity]["shorthand"],
1238                vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()],
1239                "models.shorthand should populate {complexity}"
1240            );
1241        }
1242    }
1243
1244    #[serial(cooldown_state)]
1245    #[test]
1246    fn from_config_loads_single_model_shorthand_for_all_complexities() {
1247        let _lock = cwd_mutex().lock().unwrap();
1248        let dir = tempfile::tempdir().unwrap();
1249        fs::write(
1250            dir.path().join(".orch.yml"),
1251            r"
1252agents:
1253  - shorthand
1254models:
1255  shorthand: gpt-5.2
1256",
1257        )
1258        .unwrap();
1259        let _guard = CurrentDirGuard::set(dir.path());
1260
1261        let config = RouterConfig::from_config();
1262
1263        for complexity in ["simple", "medium", "complex", "review"] {
1264            assert_eq!(
1265                config.model_map[complexity]["shorthand"],
1266                vec!["gpt-5.2".to_string()],
1267                "models.shorthand should populate {complexity}"
1268            );
1269        }
1270    }
1271
1272    #[serial(cooldown_state)]
1273    #[test]
1274    fn from_config_model_map_overrides_models_shorthand_per_tier() {
1275        let _lock = cwd_mutex().lock().unwrap();
1276        let dir = tempfile::tempdir().unwrap();
1277        fs::write(
1278            dir.path().join(".orch.yml"),
1279            r"
1280agents:
1281  - shorthand
1282models:
1283  shorthand:
1284    - gpt-5.2
1285    - gpt-5.5
1286model_map:
1287  review:
1288    shorthand: gpt-5.6-review
1289",
1290        )
1291        .unwrap();
1292        let _guard = CurrentDirGuard::set(dir.path());
1293
1294        let config = RouterConfig::from_config();
1295
1296        assert_eq!(
1297            config.model_map["simple"]["shorthand"],
1298            vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1299        );
1300        assert_eq!(
1301            config.model_map["medium"]["shorthand"],
1302            vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1303        );
1304        assert_eq!(
1305            config.model_map["complex"]["shorthand"],
1306            vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
1307        );
1308        assert_eq!(
1309            config.model_map["review"]["shorthand"],
1310            vec!["gpt-5.6-review".to_string()]
1311        );
1312    }
1313
1314    #[serial(cooldown_state)]
1315    #[test]
1316    fn model_for_complexity_normalizes_trailing_slash_from_pool() {
1317        // Bug #1507: full path test - model identifiers with trailing slashes
1318        // should be normalized (not dropped) when loading from model_map pool
1319        let mut config = RouterConfig::default();
1320        config
1321            .model_map
1322            .entry("complex".to_string())
1323            .or_default()
1324            .insert(
1325                "testagent_trailing".to_string(),
1326                vec![
1327                    "opus/".to_string(),
1328                    "sonnet//".to_string(),
1329                    "github-copilot/gpt-5-mini/".to_string(),
1330                ],
1331            );
1332
1333        // Should return normalized "opus" instead of dropping it as invalid
1334        let result = config.model_for_complexity("testagent_trailing", "complex", "task-0");
1335        assert!(
1336            result.is_some(),
1337            "should return a model from pool with trailing slashes normalized, got None"
1338        );
1339        let model = result.unwrap();
1340        // The model returned should be one of the normalized versions
1341        assert!(
1342            model == "opus" || model == "sonnet" || model == "github-copilot/gpt-5-mini",
1343            "returned model should be normalized (no trailing slash), got: {model}"
1344        );
1345        // Verify no trailing slashes in the returned model
1346        assert!(
1347            !model.ends_with('/'),
1348            "returned model should not have trailing slash, got: {model}"
1349        );
1350    }
1351
1352    // --- prune_unavailable_opencode_models regression tests (bug #3169) ---
1353
1354    #[serial(cooldown_state)]
1355    #[test]
1356    fn prune_unavailable_opencode_models_removes_missing_models() {
1357        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1358        model_map.entry("complex".to_string()).or_default().insert(
1359            "opencode".to_string(),
1360            vec![
1361                "available-model".to_string(),
1362                "unavailable-model".to_string(),
1363                "opencode:free".to_string(), // sentinel — must survive pruning
1364            ],
1365        );
1366
1367        let mut discovered = HashSet::new();
1368        discovered.insert("available-model".to_string());
1369        // "unavailable-model" intentionally absent
1370
1371        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1372
1373        assert_eq!(pruned, 1, "should prune exactly the one unavailable model");
1374
1375        let remaining = model_map["complex"]["opencode"].as_slice();
1376        assert!(
1377            remaining.contains(&"available-model".to_string()),
1378            "available model should remain"
1379        );
1380        assert!(
1381            remaining.contains(&"opencode:free".to_string()),
1382            "opencode:free sentinel should never be pruned"
1383        );
1384        assert!(
1385            !remaining.contains(&"unavailable-model".to_string()),
1386            "unavailable model should be removed"
1387        );
1388    }
1389
1390    #[serial(cooldown_state)]
1391    #[test]
1392    fn prune_unavailable_opencode_models_noop_when_all_available() {
1393        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1394        model_map.entry("simple".to_string()).or_default().insert(
1395            "opencode".to_string(),
1396            vec!["model-a".to_string(), "model-b".to_string()],
1397        );
1398
1399        let discovered: HashSet<String> = ["model-a", "model-b"]
1400            .iter()
1401            .map(ToString::to_string)
1402            .collect();
1403
1404        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1405
1406        assert_eq!(pruned, 0, "nothing to prune when all models are available");
1407        assert_eq!(
1408            model_map["simple"]["opencode"].len(),
1409            2,
1410            "both models should remain"
1411        );
1412    }
1413
1414    #[serial(cooldown_state)]
1415    #[test]
1416    fn prune_unavailable_opencode_models_preserves_non_opencode_agents() {
1417        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1418        model_map
1419            .entry("complex".to_string())
1420            .or_default()
1421            .insert("claude".to_string(), vec!["some-model".to_string()]);
1422
1423        // discovered is empty — irrelevant for non-opencode agents
1424        let discovered: HashSet<String> = HashSet::new();
1425
1426        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1427
1428        assert_eq!(pruned, 0, "non-opencode agents must not be touched");
1429        assert_eq!(
1430            model_map["complex"]["claude"].len(),
1431            1,
1432            "claude model should be unchanged"
1433        );
1434    }
1435
1436    #[test]
1437    fn default_config_does_not_use_opencode() {
1438        assert!(!RouterConfig::default().uses_opencode());
1439    }
1440
1441    #[test]
1442    fn uses_opencode_when_a_model_map_tier_lists_it() {
1443        let mut config = RouterConfig::default();
1444        config
1445            .model_map
1446            .entry("simple".to_string())
1447            .or_default()
1448            .insert("opencode".to_string(), vec!["some-model".to_string()]);
1449        assert!(config.uses_opencode());
1450    }
1451
1452    #[test]
1453    fn uses_opencode_follows_the_effective_pool_and_fallback() {
1454        let config = RouterConfig {
1455            pool: vec!["opencode:free".to_string()],
1456            ..RouterConfig::default()
1457        };
1458        assert!(config.uses_opencode());
1459
1460        let config = RouterConfig {
1461            pool: vec!["claude:haiku".to_string()],
1462            ..RouterConfig::default()
1463        };
1464        assert!(!config.uses_opencode());
1465
1466        // An empty pool derives its single entry from router_agent:router_model
1467        let config = RouterConfig {
1468            pool: vec![],
1469            router_agent: "opencode".to_string(),
1470            router_model: "free".to_string(),
1471            ..RouterConfig::default()
1472        };
1473        assert!(config.uses_opencode());
1474
1475        let config = RouterConfig {
1476            pool: vec!["claude:haiku".to_string()],
1477            fallback: "opencode:some/model".to_string(),
1478            ..RouterConfig::default()
1479        };
1480        assert!(config.uses_opencode());
1481    }
1482
1483    #[serial(cooldown_state)]
1484    #[test]
1485    fn prune_unavailable_opencode_models_covers_all_complexity_tiers() {
1486        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
1487        for tier in ["simple", "medium", "complex", "review"] {
1488            model_map
1489                .entry(tier.to_string())
1490                .or_default()
1491                .insert("opencode".to_string(), vec!["gone-model".to_string()]);
1492        }
1493
1494        // "gone-model" is not in discovered
1495        let discovered: HashSet<String> = HashSet::new();
1496
1497        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);
1498
1499        assert_eq!(pruned, 4, "should prune one entry per complexity tier");
1500        for tier in ["simple", "medium", "complex", "review"] {
1501            assert!(
1502                model_map[tier]["opencode"].is_empty(),
1503                "all entries for {tier} should be removed"
1504            );
1505        }
1506    }
1507}