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