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