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