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