Skip to main content

orch/engine/router/
mod.rs

1//! Agent router — selects the best agent and model for each task.
2//!
3//! The router uses LLM-based classification to route tasks to the best agent
4//! (claude, codex, opencode, kimi, or minimax) based on task content, labels,
5//! and configured routing rules. It also generates a specialized agent profile.
6//!
7//! Routing logic (in priority order):
8//! 1. Check for `agent:*` label on task — use that agent directly
9//! 2. If weighted_round_robin enabled, select by capacity-weighted probability
10//! 3. If round_robin mode, cycle through agents (stateful, skips last-used)
11//! 4. Call LLM classifier for intelligent routing
12//! 5. After N LLM failures, fall back to round-robin
13//! 6. Track last routed agent to distribute load across agents
14
15pub mod config;
16mod llm;
17mod ollama;
18pub mod profiles;
19mod selection;
20mod strategies;
21pub mod weights;
22
23use crate::backends::ExternalTask;
24use crate::cmd_cache;
25use crate::engine::cooldown;
26use crate::engine::cooldown::{
27    cooldown_until, is_agent_degraded, is_agent_in_cooldown, is_model_in_cooldown,
28    list_degraded_agents, record_agent_success, refresh_degraded_agents, sync_from_kv,
29};
30use crate::engine::runner::agents::opencode;
31use crate::engine::runner::response;
32use crate::store::WaitingOnDependency;
33use crate::store::{TaskStore, get_task_field_direct, store_log_activity};
34pub use config::{RouterConfig, parse_pool_entry};
35use llm::{LlmRouter, TIMEOUT_PREFIX};
36use serde::{Deserialize, Serialize};
37use std::fmt;
38use std::fmt::Debug;
39use std::fmt::Formatter;
40use std::sync::Arc;
41use tokio::task;
42pub use weights::AgentWeights;
43
44fn fmt_degraded(degraded: &[String]) -> String {
45    if degraded.is_empty() {
46        String::new()
47    } else {
48        format!(" (degraded: {})", degraded.join(", "))
49    }
50}
51
52/// A turn-cap error comes from the router command line (`--max-turns 1`)
53fn is_max_turns_error(err_msg: &str) -> bool {
54    let lower = err_msg.to_ascii_lowercase();
55    lower.contains("max turns reached") || lower.contains("reached the maximum number of turns")
56}
57
58/// Error returned when all agents/models are in cooldown and routing is temporarily unavailable.
59///
60/// This is a transient error that should not count against `max_route_attempts` since
61/// no agent was actually invoked. The caller should back off and retry later.
62#[derive(Debug, thiserror::Error)]
63pub enum AllAgentsCooledError {
64    #[error("all agents/models in cooldown for {scope}{}", fmt_degraded(.degraded))]
65    AllCooled {
66        scope: String,
67        remaining_secs: Option<u64>,
68        degraded: Vec<String>,
69    },
70}
71
72impl AllAgentsCooledError {
73    /// Create a new error for the given scope, naming currently degraded agents
74    pub fn new(scope: String, remaining_secs: Option<u64>) -> Self {
75        Self::AllCooled {
76            scope,
77            remaining_secs,
78            degraded: list_degraded_agents()
79                .into_iter()
80                .map(|(agent, _reason)| agent)
81                .collect(),
82        }
83    }
84
85    // LLM bypass helpers moved to `impl Router` so they can access Router fields.
86
87    /// Get the scope of the cooldown (e.g., "medium", "all agents", "router pool").
88    pub fn scope(&self) -> &str {
89        match self {
90            Self::AllCooled { scope, .. } => scope,
91        }
92    }
93
94    /// Remaining cooldown duration in seconds when available.
95    pub fn remaining_secs(&self) -> Option<u64> {
96        match self {
97            Self::AllCooled { remaining_secs, .. } => *remaining_secs,
98        }
99    }
100
101    /// Agents currently marked degraded, shown by `orch cooldown list`
102    pub fn degraded(&self) -> &[String] {
103        match self {
104            Self::AllCooled { degraded, .. } => degraded,
105        }
106    }
107}
108
109/// Typed error returned by [`get_route_result`].
110#[derive(Debug, thiserror::Error)]
111pub enum RouteResultError {
112    /// The task has no agent field — it needs to be re-routed.
113    #[error("no agent configured for task {task_id}")]
114    NoAgent { task_id: String },
115    /// Any other failure (store lookup, SQL, etc.).
116    #[error(transparent)]
117    Other(#[from] anyhow::Error),
118}
119
120/// Result of routing a task to an agent.
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
122pub struct RouteResult {
123    /// The selected agent: "claude", "codex", or "opencode"
124    pub agent: String,
125    /// Optional model suggestion, e.g., "claude-sonnet-4-6", "claude-opus-4-6", "o3"
126    pub model: Option<String>,
127    /// Complexity level: "simple", "medium", or "complex"
128    pub complexity: String,
129    /// Fibonacci effort estimate (1, 2, 3, 5, 8, 13, or 21). 0 means not provided.
130    pub estimate: u8,
131    /// Why this agent was selected
132    pub reason: String,
133    /// Specialized agent profile (role, tools, constraints)
134    pub profile: AgentProfile,
135    /// Optional warning about routing decision
136    pub warning: Option<String>,
137}
138
139/// Specialized agent profile for a task.
140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
141pub struct AgentProfile {
142    /// Role name, e.g., "backend specialist"
143    pub role: String,
144    /// Tools allowed for this task
145    pub tools: Vec<String>,
146    /// Constraints for this task
147    pub constraints: Vec<String>,
148    /// The model/effort choice associated with this route, cleared on failover.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub execution: Option<profiles::NamedProfile>,
151}
152
153impl AgentProfile {
154    /// Build the default "general" profile from router config.
155    pub fn default_from_config(config: &RouterConfig) -> Self {
156        Self {
157            role: "general".to_string(),
158            tools: config.allowed_tools.clone(),
159            constraints: vec![],
160            execution: None,
161        }
162    }
163}
164
165impl RouteResult {
166    /// The model for the task's tier, or one from the nearest tier with a free model. The warning
167    /// names the tier used when it differs, so the switch shows in the route activity
168    pub(crate) fn resolve_model(
169        config: &RouterConfig,
170        agent: &str,
171        complexity: &str,
172        task_id: &str,
173    ) -> (Option<String>, Option<String>) {
174        match config.model_for_complexity_or_adjacent(agent, complexity, task_id) {
175            Some((model, tier)) if tier != complexity => {
176                let warning =
177                    format!("no available {complexity} model for {agent}; using {tier} tier");
178                (Some(model), Some(warning))
179            }
180            Some((model, _)) => (Some(model), None),
181            None => (None, None),
182        }
183    }
184
185    /// Build a standard route result from the three task-specific values.
186    ///
187    /// Fills `profile` and `warning` with router-config defaults so call sites
188    /// only need to supply what varies per task.
189    pub fn from_config(
190        agent: String,
191        complexity: String,
192        reason: String,
193        config: &RouterConfig,
194        task_id: &str,
195    ) -> Self {
196        let (model, warning) = Self::resolve_model(config, &agent, &complexity, task_id);
197        Self {
198            agent,
199            model,
200            complexity,
201            estimate: 0,
202            reason,
203            profile: AgentProfile::default_from_config(config),
204            warning,
205        }
206    }
207}
208
209/// The agent router.
210#[expect(
211    clippy::struct_field_names,
212    reason = "the router holds sub-routers whose names say which backend they use"
213)]
214pub struct Router {
215    /// Router configuration
216    pub config: RouterConfig,
217    /// Available agents discovered at runtime
218    pub available_agents: Vec<String>,
219    /// Per-agent rate limit weights (used when weighted_round_robin is enabled)
220    pub weights: AgentWeights,
221    /// LLM routing subsystem (wrapped in Arc so callers can clone a handle
222    /// without holding the router RwLock across async operations)
223    llm_router: Arc<LlmRouter>,
224    /// Ollama router for local routing (contains reusable reqwest::Client)
225    ollama_router: Option<ollama::OllamaRouter>,
226    /// Round-robin index for task routing
227    pub(crate) rr_index: usize,
228    /// Last agent routed to (for distribution tracking)
229    pub(crate) last_agent: Option<String>,
230    /// Round-robin index for review agent selection
231    pub(crate) review_rr_index: usize,
232    /// Expanded pool of (agent, model) pairs for router LLM round-robin.
233    /// `opencode:free` entries are expanded at construction time.
234    pub(crate) router_pool: Vec<(String, String)>,
235    /// Current round-robin index into router_pool
236    pub(crate) pool_index: usize,
237}
238
239impl Debug for Router {
240    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
241        f.debug_struct("Router")
242            .field("config", &self.config)
243            .field("available_agents", &self.available_agents)
244            .field("weights", &self.weights)
245            .field("ollama_router", &self.ollama_router)
246            .field("rr_index", &self.rr_index)
247            .field("last_agent", &self.last_agent)
248            .field("review_rr_index", &self.review_rr_index)
249            .field("router_pool", &self.router_pool)
250            .field("pool_index", &self.pool_index)
251            .finish_non_exhaustive()
252    }
253}
254
255impl Router {
256    /// Create a new router with the given configuration.
257    pub fn new(config: RouterConfig) -> Self {
258        let available_agents = Self::discover_agents(&config.agents);
259        let mut weights = AgentWeights {
260            base_weights: config.weights.clone(),
261            ..Default::default()
262        };
263        weights.ensure_agents_with_weights(&available_agents, &config.weights);
264        if !config.weights.is_empty() {
265            tracing::info!(
266                weights = ?config.weights,
267                "configured agent routing weights"
268            );
269        }
270        let router_pool = Self::expand_pool(&config);
271        tracing::info!(
272            pool = ?router_pool,
273            fallback = %config.effective_fallback(),
274            "router LLM pool initialized"
275        );
276        // Prime only when this config names opencode, so a default or claude-only
277        // router never runs `opencode models`
278        if config.uses_opencode() {
279            opencode::prime_free_model_cache();
280        }
281        let ollama_router = if config.mode == "local" {
282            Some(ollama::OllamaRouter::new(&config))
283        } else {
284            None
285        };
286        Self {
287            config,
288            available_agents,
289            weights,
290            llm_router: Arc::new(LlmRouter::new()),
291            ollama_router,
292            rr_index: 0,
293            last_agent: None,
294            review_rr_index: 0,
295            router_pool,
296            pool_index: 0,
297        }
298    }
299
300    /// Create a router with default configuration loaded from files.
301    pub fn from_config() -> Self {
302        Self::new(RouterConfig::from_config())
303    }
304
305    /// Create a router with a forced agent list, bypassing CLI discovery.
306    /// Only for use in unit tests.
307    #[cfg(test)]
308    pub(crate) fn new_for_test(config: RouterConfig, available_agents: Vec<String>) -> Self {
309        let mut weights = AgentWeights {
310            base_weights: config.weights.clone(),
311            ..Default::default()
312        };
313        weights.ensure_agents(&available_agents);
314        let router_pool = Self::expand_pool(&config);
315        Self {
316            config,
317            available_agents,
318            weights,
319            llm_router: Arc::new(LlmRouter::new()),
320            ollama_router: None,
321            rr_index: 0,
322            last_agent: None,
323            review_rr_index: 0,
324            router_pool,
325            pool_index: 0,
326        }
327    }
328
329    fn advance_pool_index_after_attempt(&mut self, idx: usize, pool_len: usize) {
330        debug_assert!(pool_len > 0, "router pool must not be empty");
331        self.pool_index = (idx + 1) % pool_len;
332    }
333
334    /// Discover available agent CLIs in PATH.
335    /// Checks all agents from the configured list.
336    fn discover_agents(configured_agents: &[String]) -> Vec<String> {
337        let mut agents = Vec::new();
338        for agent in configured_agents {
339            if cmd_cache::command_exists(agent) {
340                agents.push(agent.clone());
341            }
342        }
343        agents
344    }
345
346    /// Expand the router LLM pool, resolving `opencode:free` to discovered free models.
347    ///
348    /// - Entries other than `opencode:free` are parsed as `agent:model` and added as-is.
349    /// - `opencode:free` is expanded by running `opencode models | grep free` at startup.
350    /// - If `opencode` is not installed or the command fails, the entry is skipped.
351    /// - If the expanded pool is empty, falls back to a single entry from `effective_fallback()`.
352    fn expand_pool(config: &RouterConfig) -> Vec<(String, String)> {
353        let raw_pool = config.effective_pool();
354        let mut expanded: Vec<(String, String)> = Vec::new();
355
356        for entry in &raw_pool {
357            if entry == "opencode:free" {
358                let free_models = Self::discover_free_opencode_models();
359                if free_models.is_empty() {
360                    tracing::debug!("opencode:free expanded to nothing — skipping");
361                } else {
362                    tracing::debug!(models = ?free_models, "opencode:free expanded");
363                    for model in free_models {
364                        expanded.push(("opencode".to_string(), model));
365                    }
366                }
367            } else {
368                let (agent, model) = parse_pool_entry(entry);
369                expanded.push((agent, model));
370            }
371        }
372
373        if expanded.is_empty() {
374            // All entries were opencode:free and opencode isn't installed — use fallback
375            let (agent, model) = parse_pool_entry(&config.effective_fallback());
376            tracing::debug!(
377                agent = %agent, model = %model,
378                "pool empty after expansion, using fallback as sole pool entry"
379            );
380            expanded.push((agent, model));
381        }
382
383        expanded
384    }
385
386    /// Async version of expand_pool which may query the opencode CLI without
387    /// blocking the Tokio runtime.
388    async fn expand_pool_async(config: &RouterConfig) -> Vec<(String, String)> {
389        let raw_pool = config.effective_pool();
390        let mut expanded: Vec<(String, String)> = Vec::new();
391
392        for entry in &raw_pool {
393            if entry == "opencode:free" {
394                let free_models = Self::discover_free_opencode_models_async().await;
395                if free_models.is_empty() {
396                    tracing::debug!("opencode:free expanded to nothing — skipping (async)");
397                } else {
398                    tracing::debug!(models = ?free_models, "opencode:free expanded (async)");
399                    for model in free_models {
400                        expanded.push(("opencode".to_string(), model));
401                    }
402                }
403            } else {
404                let (agent, model) = parse_pool_entry(entry);
405                expanded.push((agent, model));
406            }
407        }
408
409        if expanded.is_empty() {
410            // All entries were opencode:free and opencode isn't installed — use fallback
411            let (agent, model) = parse_pool_entry(&config.effective_fallback());
412            tracing::debug!(
413                agent = %agent, model = %model,
414                "pool empty after async expansion, using fallback as sole pool entry"
415            );
416            expanded.push((agent, model));
417        }
418
419        expanded
420    }
421
422    /// Async reload that uses async pool expansion to avoid blocking the runtime
423    /// when discovering opencode free models.
424    pub async fn reload_async(&mut self) {
425        let new_config = RouterConfig::from_config();
426        let new_agents = Self::discover_agents(&new_config.agents);
427        let new_pool = Self::expand_pool_async(&new_config).await;
428        tracing::info!(
429            mode = %new_config.mode,
430            agents = ?new_agents,
431            fallback = %new_config.fallback_executor,
432            weighted_rr = new_config.weighted_round_robin,
433            pool = ?new_pool,
434            "router reloaded (async)"
435        );
436        self.config = new_config;
437        self.available_agents.clone_from(&new_agents);
438        // Ensure new agents have weight entries (preserves existing weights)
439        self.weights.ensure_agents(&new_agents);
440        self.router_pool = new_pool;
441        self.pool_index = 0;
442        // Reinitialize Ollama router if mode changed to local
443        self.ollama_router = if self.config.mode == "local" {
444            Some(ollama::OllamaRouter::new(&self.config))
445        } else {
446            None
447        };
448    }
449
450    fn discover_free_opencode_models() -> Vec<String> {
451        opencode::discover_free_opencode_models()
452    }
453
454    async fn discover_free_opencode_models_async() -> Vec<String> {
455        task::spawn_blocking(Self::discover_free_opencode_models)
456            .await
457            .unwrap_or_default()
458    }
459
460    /// Run the pre-emptive health check, refreshing the degraded-agent set.
461    ///
462    /// Queries the `rate_limits` table for recent events and combines with
463    /// cooldown state to mark agents as degraded before routing attempts them.
464    pub async fn refresh_health(&self, store: &Arc<TaskStore>) {
465        // KV is the source of truth for cooldowns. Reconcile the in-memory map
466        // from KV every tick so external mutations (e.g. `orch cooldown clear`
467        // from a separate CLI process) actually take effect on the running
468        // service. Without this, the engine keeps stale entries until they
469        // expire on their own, producing the "all agents cooled" log with
470        // `orch cooldown list` simultaneously reporting "No active cooldowns".
471        sync_from_kv(store).await;
472
473        let agents = self.available_agents.clone();
474        let model_checker = |agent: &str| -> bool { self.agent_has_any_available_model(agent) };
475        refresh_degraded_agents(
476            store,
477            &agents,
478            &model_checker,
479            config::health_check_window_hours(),
480            config::degraded_rate_limit_threshold(),
481        )
482        .await;
483    }
484
485    /// Check if an agent is available.
486    pub fn is_agent_available(&self, agent: &str) -> bool {
487        self.available_agents.contains(&agent.to_string())
488    }
489
490    /// True if the agent has at least one uncooled model across any complexity
491    /// tier. Used where the eventual complexity isn't known yet (e.g. before
492    /// LLM classification), so we can't check a single tier.
493    fn agent_has_any_available_model(&self, agent: &str) -> bool {
494        ["simple", "medium", "complex", "review"]
495            .iter()
496            .any(|comp| self.config.has_available_model_for_complexity(agent, comp))
497    }
498
499    /// True if the agent has an available (uncooled) model for the `medium`
500    /// and `complex` tiers — the tiers real coding tasks are classified into
501    /// by the LLM classifier. Used to pre-filter the candidate list handed to
502    /// that classifier so an agent whose healthy tiers are only `simple` isn't
503    /// offered: the classifier can't be constrained to `simple`, so offering
504    /// such an agent produces a near-certain wasted classification call whenever
505    /// it picks `medium`/`complex` (issue #3521). `review` is not a candidate
506    /// outcome of initial classification and is deliberately excluded.
507    fn agent_has_available_model_for_coding_tiers(&self, agent: &str) -> bool {
508        ["medium", "complex"]
509            .iter()
510            .all(|comp| self.config.has_available_model_for_complexity(agent, comp))
511    }
512
513    fn agent_is_routable(&self, agent: &str, complexity: &str) -> bool {
514        if !self.is_agent_available(agent) {
515            return false;
516        }
517        if is_agent_in_cooldown(agent) {
518            tracing::debug!(agent, "agent skipped: in cooldown");
519            return false;
520        }
521        if is_agent_degraded(agent) {
522            tracing::debug!(agent, "agent skipped: degraded (pre-emptive health check)");
523            return false;
524        }
525        // If weighted routing is used, consider the agent degraded when its
526        // weight has decayed below the threshold. This avoids
527        // proactively routing to agents that recently hit many rate limits.
528        if self.config.weighted_round_robin {
529            let weight = self.weights.get_weight(agent);
530            if weight < config::SKIP_LIMITED_THRESHOLD {
531                tracing::debug!(
532                    agent,
533                    weight,
534                    "agent considered degraded by weight threshold, skipping"
535                );
536                return false;
537            }
538        }
539        if !self
540            .config
541            .has_available_model_in_any_tier(agent, complexity)
542        {
543            tracing::debug!(agent, complexity, "agent skipped: no available model");
544            return false;
545        }
546        true
547    }
548
549    fn available_agents_for_complexity(&self, complexity: &str) -> Vec<String> {
550        self.available_agents
551            .iter()
552            .filter(|agent| self.agent_is_routable(agent, complexity))
553            .cloned()
554            .collect()
555    }
556
557    /// Count of healthy (routable) agents for a given complexity.
558    /// Returns the number of agents that are available, not in cooldown, and have an available model.
559    pub fn healthy_agent_count(&self, complexity: &str) -> usize {
560        self.available_agents_for_complexity(complexity).len()
561    }
562
563    /// Check if the system is in degraded mode (fewer than threshold healthy agents).
564    /// Uses "simple" complexity as the baseline since it has the widest model support.
565    pub fn is_degraded(&self, threshold: usize) -> bool {
566        self.healthy_agent_count("simple") < threshold
567    }
568
569    pub fn earliest_cooldown_until(&self, complexity: Option<&str>) -> Option<i64> {
570        let mut earliest: Option<i64> = None;
571
572        for agent in &self.available_agents {
573            if let Some(until) = cooldown_until(agent) {
574                earliest = Some(earliest.map_or(until, |current| current.min(until)));
575            }
576
577            if let Some(comp) = complexity
578                && let Some(pool) = self.config.model_pool_for_complexity(agent, comp)
579            {
580                for model in pool {
581                    let key = format!("{agent}:{model}");
582                    if let Some(until) = cooldown_until(&key) {
583                        earliest = Some(earliest.map_or(until, |current| current.min(until)));
584                    }
585                }
586            }
587        }
588
589        earliest
590    }
591
592    /// Find the earliest cooldown expiration among the router LLM pool entries.
593    ///
594    /// Returns `Some(earliest_ts)` if at least one pool model is on cooldown,
595    /// or `None` if no pool model has a cooldown.
596    fn earliest_pool_cooldown(&self) -> Option<i64> {
597        let mut earliest: Option<i64> = None;
598        for (agent, model) in &self.router_pool {
599            let key = format!("{agent}:{model}");
600            if let Some(until) = cooldown_until(&key) {
601                earliest = Some(earliest.map_or(until, |current| current.min(until)));
602            }
603        }
604        earliest
605    }
606
607    fn wait_for_cooldown(&self, complexity: Option<&str>) -> anyhow::Result<()> {
608        // If any cooldowns are present, return an error immediately so the
609        // caller (the tick loop) can skip this task and retry on the next tick.
610        // Sleeping inside the router blocks the entire tick loop for the
611        // cooldown duration which starves other tasks. The engine tick already
612        // retries every `tick_interval` (default 10s), so allow the tick loop
613        // to drive retries instead of sleeping here.
614        let now = chrono::Utc::now().timestamp();
615        let Some(earliest) = self.earliest_cooldown_until(complexity) else {
616            // All agents are degraded but none have a timed cooldown entry
617            // (e.g. over-threshold rate limiting without explicit cooldown duration).
618            // Log at warn and return an error so the tick skips this task and retries after backoff.
619            tracing::warn!(
620                scope = complexity.unwrap_or("all agents"),
621                "all agents degraded (no cooldown timestamp available) — skipping task, will retry after backoff"
622            );
623            // Return an error similar to the cooldown case to trigger backoff in the tick loop
624            return Err(AllAgentsCooledError::new(
625                complexity.unwrap_or("all agents").to_string(),
626                None,
627            )
628            .into());
629        };
630
631        let remaining = earliest.saturating_sub(now);
632        if remaining > 0 {
633            let scope_str = complexity.unwrap_or("all agents").to_string();
634            tracing::warn!(
635                remaining_secs = remaining,
636                scope = %scope_str,
637                "all agents/models cooled — routing is unavailable until cooldown expires; failing fast to let tick retry"
638            );
639            // Return a domain error indicating all candidates are cooled so the
640            // caller can handle it (tick will skip this task and retry later).
641            return Err(AllAgentsCooledError::new(scope_str, u64::try_from(remaining).ok()).into());
642        }
643
644        Ok(())
645    }
646
647    /// Get the first available agent.
648    /// Pick next agent via round-robin (for review or other non-task routing).
649    /// Pick the next review agent, optionally excluding one (e.g. the task's original agent).
650    /// Falls back to the first candidate whenever every candidate is excluded (#3645).
651    pub fn next_round_robin_agent(&mut self, exclude: &[&str], complexity: &str) -> Option<String> {
652        // Use available_agents_for_complexity which already filters using agent_is_routable,
653        // eliminating duplicate cooldown/degraded/model checks.
654        let candidates = self.available_agents_for_complexity(complexity);
655        if candidates.is_empty() {
656            return None;
657        }
658        let idx = self.review_rr_index;
659        let n = candidates.len();
660
661        // Try to find an agent that isn't excluded
662        let agent = (0..n)
663            .map(|offset| &candidates[(idx + offset) % n])
664            .find(|a| !exclude.contains(&a.as_str()))
665            .cloned()
666            // Fallback: use the first available candidate (even if excluded)
667            .or_else(|| candidates.first().cloned())?;
668
669        self.review_rr_index = (idx + 1) % candidates.len().max(1);
670        Some(agent)
671    }
672
673    /// If the selected agent matches `no_code_last_agent` for this task, filter it
674    /// out of the candidates and return the filtered list. Used to prevent the
675    /// same agent from being selected twice in a row after a no-code failure (#2410).
676    async fn skip_no_code_agent(
677        &self,
678        store: &Arc<TaskStore>,
679        repo: &str,
680        task_id: &str,
681        candidates: &[String],
682    ) -> Option<Vec<String>> {
683        let no_code_agent = get_task_field_direct(store, repo, task_id, "no_code_last_agent")
684            .await
685            .unwrap_or_else(|| {
686                tracing::warn!(
687                    task_id,
688                    "no_code_last_agent DB read returned None — loop detection may be impaired"
689                );
690                String::new()
691            });
692        if no_code_agent.is_empty() || !candidates.iter().any(|a| a == &no_code_agent) {
693            return None;
694        }
695        let filtered: Vec<String> = candidates
696            .iter()
697            .filter(|a| a.as_str() != no_code_agent)
698            .cloned()
699            .collect();
700        if filtered.is_empty() {
701            tracing::warn!(
702                task_id,
703                no_code_agent = %no_code_agent,
704                "all available agents are the no-code agent — cannot skip"
705            );
706            return None;
707        }
708        tracing::info!(
709            task_id,
710            skipped = %no_code_agent,
711            remaining = ?filtered,
712            "skipping no-code agent, routing to alternative"
713        );
714        Some(filtered)
715    }
716
717    /// Route a task to the best agent.
718    ///
719    /// Routing logic (in priority order):
720    /// 1. Check for `agent:*` label — use that agent directly
721    /// 2. If weighted_round_robin enabled, select by capacity-weighted probability
722    /// 3. If round_robin mode, cycle through agents (stateful)
723    /// 4. Call LLM classifier for intelligent routing
724    /// 5. After max_route_attempts LLM failures, fall back to round-robin
725    pub async fn route(
726        &mut self,
727        task: &ExternalTask,
728        store: &Arc<TaskStore>,
729        repo: &str,
730    ) -> anyhow::Result<RouteResult> {
731        // NOTE: refresh_health() is called once per tick in tick_route_tasks()
732        // before the routing loop, not per-task. Do not re-add it here.
733
734        // Hold the task before any classification, label override, or fallback.
735        // A waiting task must not increment route_attempts.
736        match store.resolve_id_by_external(repo, &task.id.0).await {
737            Ok(Some(id)) => match store.block_claim_if_waiting(id).await {
738                Ok(Some(blockers)) => {
739                    return Err(WaitingOnDependency { blockers }.into());
740                }
741                Ok(None) => {}
742                Err(err) => return Err(err),
743            },
744            Ok(None) => {}
745            Err(err) => return Err(err),
746        }
747
748        loop {
749            // 1. Check store agent field first (set by failover, authoritative over labels)
750            // Use a lightweight lookup to avoid deserializing the full Task row when
751            // only the `agent` column is needed. This avoids two full-row loads
752            // per routing pass (resolve_task_id + get) and significantly reduces
753            // CPU work on busy instances.
754            let store_agent = match store.get_agent_by_external_id(repo, &task.id.0).await {
755                Ok(Some(agent)) => {
756                    // Router enforces that the agent string matches a configured agent
757                    if !agent.is_empty() && self.config.agents.iter().any(|cfg| cfg == &agent) {
758                        Some(agent)
759                    } else {
760                        None
761                    }
762                }
763                Ok(None) => None,
764                Err(e) => {
765                    tracing::warn!(
766                        repo,
767                        task_id = %task.id.0,
768                        err = %e,
769                        "failed to fetch stored agent, falling back to label/LLM routing"
770                    );
771                    None
772                }
773            };
774
775            // Named profiles select a route after dependencies and stored recovery.
776            if store_agent.is_none()
777                && let Some(result) = self.route_profile(task)?
778            {
779                self.log_route_activity(store, repo, &task.id.0, &result, None)
780                    .await;
781                return Ok(result);
782            }
783
784            // 2. Fall back to explicit agent label
785            let resolved_agent = store_agent.or_else(|| {
786                strategies::extract_agent_from_labels(&self.config.agents, &task.labels)
787            });
788
789            if let Some(agent) = resolved_agent {
790                let complexity = strategies::extract_complexity_from_labels(&task.labels);
791                // If agent appears routable (not in agent-wide cooldown and has
792                // available models or no model_map configured), check whether
793                // we actually have a concrete model to dispatch. If the
794                // resolved label maps to no model (None), we fall through to
795                // the standard routing logic so the router LLM can pick a
796                // proper agent/model, instead of dispatching with an empty
797                // model which causes some agents (e.g. opencode) to exit
798                // silently.
799                if self.agent_is_routable(&agent, &complexity) {
800                    let (model, tier_warning) =
801                        RouteResult::resolve_model(&self.config, &agent, &complexity, &task.id.0);
802
803                    // Only dispatch label overrides when we have a concrete
804                    // model to send to the executor. Dispatching with an
805                    // empty model led to silent exits for some agents
806                    // (notably opencode). If no concrete model is available
807                    // for the labeled agent, fall through to the standard
808                    // routing logic so the LLM or round-robin can pick an
809                    // appropriate agent/model.
810                    if model.is_some() {
811                        tracing::debug!(
812                            task_id = %task.id.0,
813                            agent = %agent,
814                            complexity = %complexity,
815                            "routed via label"
816                        );
817                        let mut result = RouteResult::from_config(
818                            agent.clone(),
819                            complexity.clone(),
820                            format!("label agent:{agent}"),
821                            &self.config,
822                            &task.id.0,
823                        );
824                        // Label routing uses agent-specific role and the
825                        // resolved model (may differ from from_config's default).
826                        result.profile.role = format!("{agent} specialist");
827                        result.model = model.clone();
828                        result.warning = tier_warning;
829                        self.log_route_activity(store, repo, &task.id.0, &result, None)
830                            .await;
831                        return Ok(result);
832                    }
833                    // No concrete model found for the labeled agent — do
834                    // not honor the label override. Fall through to the
835                    // standard routing logic so another agent or the LLM
836                    // can be chosen with a valid model.
837                    tracing::warn!(task_id = %task.id.0, agent = %agent, "label agent has no available model — falling through to LLM routing");
838                }
839
840                let candidates = self.available_agents_for_complexity(&complexity);
841                if candidates.is_empty() {
842                    self.wait_for_cooldown(Some(&complexity))?;
843                    continue;
844                }
845                // Label target is cooled or lacked model; fall through to standard routing.
846            }
847
848            let complexity = strategies::extract_complexity_from_labels(&task.labels);
849
850            // Check if any agents have available models for this complexity
851            let mut candidates = self.available_agents_for_complexity(&complexity);
852            if candidates.is_empty() {
853                self.wait_for_cooldown(Some(&complexity))?;
854                continue;
855            }
856
857            // Skip the no-code agent if one is recorded for this task (#2410).
858            // If all available agents are filtered out, we fall through to
859            // LLM routing with no constraints (LLM will pick the same agent but
860            // the response_handler will block it immediately via same-agent check).
861            if let Some(filtered) = self
862                .skip_no_code_agent(store, repo, &task.id.0, &candidates)
863                .await
864            {
865                candidates = filtered;
866            }
867
868            // 2. Weighted round-robin — capacity-based selection
869            if self.config.weighted_round_robin {
870                let result = strategies::route_via_weighted_round_robin(
871                    &candidates,
872                    &self.weights,
873                    &self.config,
874                    task,
875                    &mut self.last_agent,
876                )?;
877                self.log_route_activity(store, repo, &task.id.0, &result, None)
878                    .await;
879                return Ok(result);
880            }
881
882            // 3. Round-robin mode — use stateful round-robin
883            if self.config.mode == "round_robin" || self.config.mode == "profile" {
884                tracing::debug!(task_id = %task.id.0, "routing via round-robin mode");
885                let result = strategies::route_via_round_robin_stateful(
886                    &candidates,
887                    &self.config,
888                    task,
889                    &mut self.rr_index,
890                    &mut self.last_agent,
891                )?;
892                self.log_route_activity(store, repo, &task.id.0, &result, None)
893                    .await;
894                return Ok(result);
895            }
896
897            // 4. Local Ollama routing
898            if self.config.mode == "local" {
899                tracing::debug!(task_id = %task.id.0, ollama_url = %self.config.ollama_url, "routing via local Ollama");
900                let ollama_router = self
901                    .ollama_router
902                    .as_ref()
903                    .expect("ollama_router must be initialized in Router::new when mode=local");
904                match ollama_router.route(task, &self.config).await {
905                    Ok(result) => {
906                        self.log_route_activity(store, repo, &task.id.0, &result, None)
907                            .await;
908                        return Ok(result);
909                    }
910                    Err(e) => {
911                        tracing::warn!(
912                            task_id = %task.id.0,
913                            error = %e,
914                            "Ollama routing failed, falling back to round-robin"
915                        );
916                        let result = strategies::route_via_round_robin_stateful(
917                            &candidates,
918                            &self.config,
919                            task,
920                            &mut self.rr_index,
921                            &mut self.last_agent,
922                        )?;
923                        self.log_route_activity(store, repo, &task.id.0, &result, None)
924                            .await;
925                        return Ok(result);
926                    }
927                }
928            }
929
930            // 5. LLM-based routing with retry tracking
931            let route_attempts = self.get_route_attempts(&task.id.0, store, repo).await;
932
933            if route_attempts >= self.config.max_route_attempts {
934                tracing::warn!(
935                    task_id = %task.id.0,
936                    attempts = route_attempts,
937                    max = self.config.max_route_attempts,
938                    "max LLM route attempts reached, falling back to round-robin"
939                );
940                let candidates = self.available_agents_for_complexity(&complexity);
941                if candidates.is_empty() {
942                    self.wait_for_cooldown(Some(&complexity))?;
943                    continue;
944                }
945                let result = strategies::route_via_round_robin_stateful(
946                    &candidates,
947                    &self.config,
948                    task,
949                    &mut self.rr_index,
950                    &mut self.last_agent,
951                )?;
952                self.log_route_activity(store, repo, &task.id.0, &result, None)
953                    .await;
954                return Ok(result);
955            }
956
957            // Log routing start (before await)
958            tracing::debug!(task_id = %task.id.0, "starting LLM routing");
959
960            match self.route_with_llm(task, repo).await {
961                Ok(result) => {
962                    let candidates = self.available_agents_for_complexity(&result.complexity);
963                    if candidates.is_empty() {
964                        self.wait_for_cooldown(Some(&result.complexity))?;
965                        continue;
966                    }
967
968                    // If the LLM selected the no-code agent, filter it out and
969                    // pick an alternative (#2410). Re-use the existing fallback logic.
970                    let no_code_agent =
971                         get_task_field_direct(store, repo, &task.id.0, "no_code_last_agent")
972                             .await
973                             .unwrap_or_else(|| {
974                                 tracing::warn!(task_id = %task.id.0, "no_code_last_agent DB read returned None — loop detection may be impaired");
975                                 String::new()
976                             });
977                    if result.agent == no_code_agent {
978                        // Pick the first agent that isn't the no-code agent.
979                        let fallback_agent = candidates
980                            .iter()
981                            .find(|a| a.as_str() != no_code_agent)
982                            .cloned()
983                            .unwrap_or_else(|| candidates[0].clone());
984                        if fallback_agent.as_str() == no_code_agent {
985                            tracing::warn!(
986                                task_id = %task.id.0,
987                                no_code_agent = %no_code_agent,
988                                complexity = %result.complexity,
989                                "all available agents are the no-code agent — waiting for another agent"
990                            );
991                            self.wait_for_cooldown(Some(&result.complexity))?;
992                            continue;
993                        }
994                        tracing::info!(
995                            task_id = %task.id.0,
996                            llm_selected = %result.agent,
997                            skipped = %no_code_agent,
998                            fallback = %fallback_agent,
999                            "LLM selected the no-code agent — routing to alternative"
1000                        );
1001                        let (fallback_model, _) = RouteResult::resolve_model(
1002                            &self.config,
1003                            &fallback_agent,
1004                            &result.complexity,
1005                            &task.id.0,
1006                        );
1007
1008                        self.set_route_attempts(&task.id.0, 0, store, repo).await;
1009                        let result = RouteResult {
1010                            agent: fallback_agent.clone(),
1011                            model: fallback_model,
1012                            complexity: result.complexity.clone(),
1013                            estimate: result.estimate,
1014                            reason: format!(
1015                                "LLM selected no-code agent {}; routed to {}",
1016                                result.agent, fallback_agent
1017                            ),
1018                            profile: result.profile.clone(),
1019                            warning: Some(format!(
1020                                "LLM selected no-code agent {}; used fallback {}",
1021                                result.agent, fallback_agent
1022                            )),
1023                        };
1024                        self.log_route_activity(store, repo, &task.id.0, &result, None)
1025                            .await;
1026                        return Ok(result);
1027                    }
1028
1029                    let model_cooled = result
1030                        .model
1031                        .as_deref()
1032                        .is_some_and(|model| is_model_in_cooldown(&result.agent, model));
1033                    if !candidates.contains(&result.agent) || model_cooled {
1034                        let fallback_agent = candidates
1035                            .iter()
1036                            .find(|agent| *agent != &result.agent)
1037                            .cloned()
1038                            .unwrap_or_else(|| candidates[0].clone());
1039                        let (fallback_model, _) = RouteResult::resolve_model(
1040                            &self.config,
1041                            &fallback_agent,
1042                            &result.complexity,
1043                            &task.id.0,
1044                        );
1045
1046                        // If the fallback model is None and the fallback agent is the
1047                        // same as the LLM-selected agent, it means all models for the
1048                        // only available agent are cooled. In that case, wait for
1049                        // cooldowns instead of returning a RouteResult with
1050                        // model: None which would be dispatched incorrectly.
1051                        if fallback_model.is_none() && fallback_agent == result.agent {
1052                            tracing::warn!(
1053                                task_id = %task.id.0,
1054                                agent = %result.agent,
1055                                complexity = %result.complexity,
1056                                "LLM-selected model(s) are cooled for the only available agent; waiting for cooldown"
1057                            );
1058                            self.wait_for_cooldown(Some(&result.complexity))?;
1059                            continue;
1060                        }
1061
1062                        // Distinguish logging and reasons when we actually switch
1063                        // agents vs when we keep the same agent but pick a
1064                        // different (non-cooled) model.
1065                        if fallback_agent == result.agent {
1066                            tracing::warn!(
1067                                task_id = %task.id.0,
1068                                agent = %result.agent,
1069                                complexity = %result.complexity,
1070                                "LLM-selected model was cooled; selecting an alternative model for the same agent"
1071                            );
1072                        } else {
1073                            tracing::warn!(
1074                                task_id = %task.id.0,
1075                                agent = %result.agent,
1076                                fallback = %fallback_agent,
1077                                complexity = %result.complexity,
1078                                "LLM selected cooled agent/model; rerouting to available agent"
1079                            );
1080                        }
1081
1082                        // Reset attempts on success
1083                        self.set_route_attempts(&task.id.0, 0, store, repo).await;
1084
1085                        let reason = if fallback_agent == result.agent {
1086                            format!(
1087                                "LLM selected cooled model; using same agent {fallback_agent} with different model"
1088                            )
1089                        } else {
1090                            format!("LLM selected cooled agent/model; rerouted to {fallback_agent}")
1091                        };
1092
1093                        let result = RouteResult {
1094                            agent: fallback_agent.clone(),
1095                            model: fallback_model,
1096                            complexity: result.complexity.clone(),
1097                            estimate: result.estimate,
1098                            reason: reason.clone(),
1099                            profile: result.profile.clone(),
1100                            warning: Some(if fallback_agent == result.agent {
1101                                "LLM-selected model was cooled; selected alternative model for same agent"
1102                                    .to_string()
1103                            } else {
1104                                "LLM-selected agent/model was cooled; rerouted to available agent"
1105                                    .to_string()
1106                            }),
1107                        };
1108                        self.log_route_activity(store, repo, &task.id.0, &result, None)
1109                            .await;
1110                        return Ok(result);
1111                    }
1112
1113                    // Reset attempts on success
1114                    self.set_route_attempts(&task.id.0, 0, store, repo).await;
1115                    tracing::info!(
1116                        task_id = %task.id.0,
1117                        agent = %result.agent,
1118                        complexity = %result.complexity,
1119                        "routed via LLM"
1120                    );
1121                    self.log_route_activity(store, repo, &task.id.0, &result, None)
1122                        .await;
1123                    return Ok(result);
1124                }
1125                Err(e) => {
1126                    if let Some(err) = e.downcast_ref::<AllAgentsCooledError>() {
1127                        let scope = err.scope();
1128                        tracing::warn!(scope = %scope, "router cooldown gate tripped");
1129                        // "router pool" scope means all router LLM pool entries were pre-cooled.
1130                        // Pass None so wait_for_cooldown queries all agent+model cooldowns generically
1131                        // (no complexity-specific pool lookup, which would fail for "router pool").
1132                        let scope_opt = match scope {
1133                            "all agents" | "router pool" => None,
1134                            _ => Some(scope),
1135                        };
1136                        self.wait_for_cooldown(scope_opt)?;
1137                        continue;
1138                    }
1139
1140                    let new_attempts = route_attempts + 1;
1141                    self.set_route_attempts(&task.id.0, new_attempts, store, repo)
1142                        .await;
1143                    tracing::warn!(
1144                        task_id = %task.id.0,
1145                        error = %e,
1146                        error_chain = ?e,
1147                        attempt = new_attempts,
1148                        max = self.config.max_route_attempts,
1149                        "LLM routing failed"
1150                    );
1151
1152                    if new_attempts >= self.config.max_route_attempts {
1153                        tracing::info!(
1154                            task_id = %task.id.0,
1155                            "falling back to round-robin after {} failed attempts",
1156                            new_attempts
1157                        );
1158                        let candidates = self.available_agents_for_complexity(&complexity);
1159                        if candidates.is_empty() {
1160                            self.wait_for_cooldown(Some(&complexity))?;
1161                            continue;
1162                        }
1163                        let result = strategies::route_via_round_robin_stateful(
1164                            &candidates,
1165                            &self.config,
1166                            task,
1167                            &mut self.rr_index,
1168                            &mut self.last_agent,
1169                        )?;
1170                        self.log_route_activity(store, repo, &task.id.0, &result, None)
1171                            .await;
1172                        return Ok(result);
1173                    }
1174
1175                    let candidates = self.available_agents_for_complexity(&complexity);
1176                    if candidates.is_empty() {
1177                        self.wait_for_cooldown(Some(&complexity))?;
1178                        continue;
1179                    }
1180                    let result = strategies::route_via_fallback(
1181                        &candidates,
1182                        &self.config,
1183                        task,
1184                        Some(&self.weights),
1185                    )?;
1186                    self.log_route_activity(store, repo, &task.id.0, &result, None)
1187                        .await;
1188                    return Ok(result);
1189                }
1190            }
1191        }
1192    }
1193
1194    /// Get the number of LLM routing attempts for a task from the store.
1195    async fn get_route_attempts(&self, task_id: &str, store: &Arc<TaskStore>, repo: &str) -> u32 {
1196        match store.resolve_task_id(repo, task_id).await {
1197            Ok(Some(store_id)) => store
1198                .get(store_id)
1199                .await
1200                .map_or(0, |t| u32::try_from(t.route_attempts).unwrap_or(0)),
1201            _ => 0,
1202        }
1203    }
1204
1205    /// Set the number of LLM routing attempts for a task in the store.
1206    async fn set_route_attempts(
1207        &self,
1208        task_id: &str,
1209        attempts: u32,
1210        store: &Arc<TaskStore>,
1211        repo: &str,
1212    ) {
1213        if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
1214            && let Err(e) = store
1215                .set_fields(store_id, &[("route_attempts", serde_json::json!(attempts))])
1216                .await
1217        {
1218            tracing::warn!(task_id, error = %e, "failed to store route_attempts");
1219        }
1220    }
1221
1222    /// Log a route event to task activity timeline.
1223    async fn log_route_activity(
1224        &self,
1225        store: &Arc<TaskStore>,
1226        repo: &str,
1227        task_id: &str,
1228        result: &RouteResult,
1229        from_agent: Option<&str>,
1230    ) {
1231        let details = serde_json::json!({
1232            "reason": result.reason,
1233            "complexity": result.complexity,
1234            "role": result.profile.role,
1235            "warning": result.warning,
1236        });
1237        let event_type = if from_agent.is_some() {
1238            "rerouted"
1239        } else {
1240            "routed"
1241        };
1242        store_log_activity(
1243            &Some(Arc::clone(store)),
1244            repo,
1245            task_id,
1246            event_type,
1247            None,
1248            Some("routed"),
1249            Some(&result.agent),
1250            result.model.as_deref(),
1251            Some(&details),
1252        )
1253        .await;
1254    }
1255
1256    /// Route using LLM classification with pool round-robin.
1257    ///
1258    /// Iterates through `router_pool` (skipping cooled entries) until one succeeds.
1259    /// On full exhaustion, tries the configured fallback. If the fallback also fails,
1260    /// returns the last error (the caller falls back to round-robin agent selection).
1261    async fn route_with_llm(
1262        &mut self,
1263        task: &ExternalTask,
1264        repo: &str,
1265    ) -> anyhow::Result<RouteResult> {
1266        // Filter out cooled and degraded agents, and agents without an available
1267        // model for the coding tiers (`medium`/`complex`) that real tasks are
1268        // classified into, so the LLM only sees candidates that could actually
1269        // be dispatched for whatever complexity it picks. An agent whose only
1270        // healthy tier is `simple` is excluded too: the classifier can't be
1271        // constrained to `simple`, so leaving such an agent in would waste the
1272        // call whenever it picks `medium`/`complex` (issue #3521).
1273        // Fall back to the full list if all agents are cooled/degraded.
1274        // Cloned to avoid borrow conflict with &mut self in the loop.
1275        let uncooled_agents: Vec<String> = self
1276            .available_agents
1277            .iter()
1278            .filter(|a| {
1279                !is_agent_in_cooldown(a)
1280                    && !is_agent_degraded(a)
1281                    && self.agent_has_available_model_for_coding_tiers(a)
1282            })
1283            .cloned()
1284            .collect();
1285        if uncooled_agents.is_empty() {
1286            return Err(AllAgentsCooledError::new("all agents".to_string(), None).into());
1287        }
1288        let llm_agents = uncooled_agents;
1289
1290        let pool = self.router_pool.clone();
1291        let n = pool.len();
1292        let start = self.pool_index;
1293        let mut last_err: Option<anyhow::Error> = None;
1294        let mut attempted_any = false;
1295
1296        // Try pool entries in round-robin order, skipping cooled ones
1297        for i in 0..n {
1298            let idx = (start + i) % n;
1299            let (agent, model) = &pool[idx];
1300            let model_str = model.as_str();
1301
1302            if response::is_model_in_cooldown(agent, model_str) {
1303                tracing::debug!(agent, model = model_str, "pool entry on cooldown, skipping");
1304                continue;
1305            }
1306
1307            // At least one pool entry was available to attempt
1308            attempted_any = true;
1309
1310            let model_opt = if model_str.is_empty() {
1311                None
1312            } else {
1313                Some(model_str)
1314            };
1315
1316            match self
1317                .llm_router
1318                .route_with_llm_using(
1319                    task,
1320                    &llm_agents,
1321                    &self.config,
1322                    &mut self.last_agent,
1323                    repo,
1324                    agent,
1325                    model_opt,
1326                )
1327                .await
1328            {
1329                Ok(result) => {
1330                    // Advance index so the next call starts at the next pool entry
1331                    self.advance_pool_index_after_attempt(idx, n);
1332                    tracing::debug!(
1333                        agent,
1334                        model = model_str,
1335                        pool_idx = idx,
1336                        "router LLM pool entry succeeded"
1337                    );
1338                    record_agent_success(agent, model_str).await;
1339                    return Ok(result);
1340                }
1341                Err(e) => {
1342                    let err_msg = e.to_string();
1343                    let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1344                    if is_timeout {
1345                        // Advance pool index so the next tick starts at the next entry,
1346                        // then return immediately. Continuing to try further pool entries
1347                        // in the same tick would accumulate multiple timeout windows and
1348                        // stall the tick loop for minutes (issue #3187).
1349                        //
1350                        // Also record a standard cooldown, same as the non-timeout branch,
1351                        // so a chronically-timing-out entry is skipped by is_model_in_cooldown
1352                        // on future ticks instead of burning the full timeout window again
1353                        // every time round-robin reaches it (issue #3422).
1354                        self.advance_pool_index_after_attempt(idx, n);
1355                        tracing::warn!(
1356                            agent,
1357                            model = model_str,
1358                            next_pool_idx = self.pool_index,
1359                            "router LLM pool entry timed out — recording cooldown, will retry next tick"
1360                        );
1361                        response::record_model_failure(agent, model_str).await;
1362                        return Err(e);
1363                    }
1364                    if is_max_turns_error(&err_msg) {
1365                        tracing::warn!(
1366                            agent,
1367                            model = model_str,
1368                            error = %e,
1369                            "pool entry hit max turns — trying next without cooldown"
1370                        );
1371                    } else {
1372                        tracing::warn!(
1373                            agent,
1374                            model = model_str,
1375                            error = %e,
1376                            "pool entry failed, recording cooldown and trying next"
1377                        );
1378                        if !cooldown::record_credit_exhaustion_from_message(
1379                            agent,
1380                            Some(model_str),
1381                            &err_msg,
1382                        )
1383                        .await
1384                        {
1385                            response::record_model_failure(agent, model_str).await;
1386                        }
1387                    }
1388                    last_err = Some(e);
1389                    self.advance_pool_index_after_attempt(idx, n);
1390                }
1391            }
1392        }
1393
1394        // If every pool entry was pre-cooled (nothing was attempted), do not
1395        // immediately exhaust the pool again — fail fast and let the tick loop
1396        // retry on the next cycle instead of cascading failures.
1397        // However, we should still try the fallback if configured.
1398        if !attempted_any {
1399            let now = chrono::Utc::now().timestamp();
1400            let earliest = self.earliest_pool_cooldown();
1401            if let Some(until) = earliest {
1402                // Pool entries exist but are all cooled - we'll try fallback below
1403                let remaining = until.saturating_sub(now);
1404                tracing::warn!(
1405                    remaining_secs = remaining,
1406                    pool = ?pool,
1407                    "all router LLM pool entries on cooldown — will try fallback"
1408                );
1409                // Continue to fallback logic instead of returning early
1410            } else {
1411                // No pool cooldowns found either — this means the pool was empty
1412                // or every entry was filtered out for some other reason.
1413                return Err(last_err
1414                    .unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")));
1415            }
1416        }
1417
1418        // All pool entries failed or were cooled — try the configured fallback
1419        let fallback = self.config.effective_fallback();
1420        let (fb_agent, fb_model) = parse_pool_entry(&fallback);
1421        let fb_model_str = fb_model.as_str();
1422
1423        // Only try fallback if it wasn't already in the pool (avoid double-try)
1424        let fallback_already_tried = pool.iter().any(|(a, m)| a == &fb_agent && m == &fb_model);
1425
1426        if !fallback_already_tried && !response::is_model_in_cooldown(&fb_agent, fb_model_str) {
1427            tracing::info!(
1428                agent = %fb_agent,
1429                model = %fb_model_str,
1430                "all pool entries exhausted — trying fallback router LLM"
1431            );
1432            let fb_model_opt = if fb_model_str.is_empty() {
1433                None
1434            } else {
1435                Some(fb_model_str)
1436            };
1437            match self
1438                .llm_router
1439                .route_with_llm_using(
1440                    task,
1441                    &llm_agents,
1442                    &self.config,
1443                    &mut self.last_agent,
1444                    repo,
1445                    &fb_agent,
1446                    fb_model_opt,
1447                )
1448                .await
1449            {
1450                Ok(result) => {
1451                    record_agent_success(&fb_agent, fb_model_str).await;
1452                    return Ok(result);
1453                }
1454                Err(e) => {
1455                    let err_msg = e.to_string();
1456                    let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1457                    if is_timeout {
1458                        // Cool down on timeout like pool entries (#3422), else a
1459                        // chronically-timing-out fallback burns the full timeout window every tick (#3616)
1460                        response::record_model_failure(&fb_agent, fb_model_str).await;
1461                        tracing::warn!(
1462                            agent = %fb_agent,
1463                            model = %fb_model_str,
1464                            "fallback router LLM timed out — returning immediately to unblock tick loop"
1465                        );
1466                        return Err(e);
1467                    }
1468                    tracing::warn!(
1469                        agent = %fb_agent,
1470                        model = %fb_model_str,
1471                        error = %e,
1472                        "fallback router LLM also failed"
1473                    );
1474                    if !is_max_turns_error(&err_msg) {
1475                        response::record_model_failure(&fb_agent, fb_model_str).await;
1476                    }
1477                    last_err = Some(e);
1478                }
1479            }
1480        }
1481
1482        Err(last_err.unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")))
1483    }
1484
1485    /// Record a rate limit event for an agent, reducing its routing weight.
1486    ///
1487    /// Called by the engine when an agent returns a 429/rate limit error.
1488    pub fn record_rate_limit(&mut self, agent: &str) {
1489        self.weights.record_rate_limit(agent);
1490    }
1491
1492    /// Record a successful task completion, restoring agent weight.
1493    pub fn record_success(&mut self, agent: &str) {
1494        self.weights.record_success(agent);
1495    }
1496
1497    /// Tick weight recovery for all agents.
1498    ///
1499    /// Called periodically by the engine to gradually restore weights
1500    /// as rate limit windows expire.
1501    pub fn tick_weight_recovery(&mut self) {
1502        self.weights.tick_recovery();
1503    }
1504
1505    /// Store routing result in the task store.
1506    pub async fn store_route_result(
1507        &self,
1508        task_id: &str,
1509        result: &RouteResult,
1510        store: &Arc<TaskStore>,
1511        repo: &str,
1512    ) -> anyhow::Result<()> {
1513        if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await {
1514            store
1515                .set_fields(
1516                    store_id,
1517                    &[
1518                        ("agent", serde_json::json!(result.agent)),
1519                        ("complexity", serde_json::json!(result.complexity)),
1520                        ("route_reason", serde_json::json!(result.reason)),
1521                        (
1522                            "agent_profile",
1523                            serde_json::json!(serde_json::to_string(&result.profile)?),
1524                        ),
1525                        (
1526                            "model",
1527                            serde_json::json!(result.model.as_deref().unwrap_or("")),
1528                        ),
1529                    ],
1530                )
1531                .await?;
1532        }
1533        Ok(())
1534    }
1535}
1536
1537/// Retrieve routing result from the task store.
1538pub async fn get_route_result(
1539    store: &Arc<TaskStore>,
1540    repo: &str,
1541    task_id: &str,
1542) -> Result<RouteResult, RouteResultError> {
1543    let store_id = store
1544        .resolve_task_id(repo, task_id)
1545        .await
1546        .map_err(RouteResultError::Other)?
1547        .ok_or_else(|| {
1548            RouteResultError::Other(anyhow::anyhow!("task {task_id} not found in store"))
1549        })?;
1550    let task = store.get(store_id).await.map_err(RouteResultError::Other)?;
1551
1552    let agent = task
1553        .agent
1554        .clone()
1555        .filter(|a| !a.is_empty())
1556        .ok_or_else(|| RouteResultError::NoAgent {
1557            task_id: task_id.to_string(),
1558        })?;
1559
1560    let complexity = if task.complexity.is_empty() {
1561        "medium".to_string()
1562    } else {
1563        task.complexity.clone()
1564    };
1565
1566    let reason = task.route_reason.clone();
1567    let model = task.model.clone().filter(|m| !m.is_empty());
1568    // Only a profile route's model/effort choice is restored; every other route
1569    // keeps the default profile, as before. Recovery that changed the agent or
1570    // model invalidates the stored choice.
1571    let profile = AgentProfile {
1572        execution: serde_json::from_str::<AgentProfile>(&task.agent_profile)
1573            .ok()
1574            .and_then(|stored| stored.execution)
1575            .filter(|p| p.matches_route(&agent, model.as_deref())),
1576        ..AgentProfile::default()
1577    };
1578
1579    // Validate that the stored model is valid for the resolved agent.
1580    // Agent-specific aliases (e.g. "opus") can leak across agents during
1581    // failover, so we verify against the router's model pools (#1604).
1582    let config = RouterConfig::from_config();
1583    let model = model.filter(|m| {
1584        let complexities = ["simple", "medium", "complex", "review"];
1585        // Collect all model pools configured for this agent across complexity tiers.
1586        let all_pools: Vec<Vec<String>> = complexities
1587            .iter()
1588            .filter_map(|comp| config.model_pool_for_complexity(&agent, comp))
1589            .collect();
1590        // If the agent has no model pools configured, we can't validate — pass through.
1591        if all_pools.is_empty() {
1592            return true;
1593        }
1594        let valid = all_pools.iter().any(|pool| pool.contains(m))
1595            || profile
1596                .execution
1597                .as_ref()
1598                .is_some_and(|p| p.matches_route(&agent, Some(m)));
1599        if !valid {
1600            tracing::warn!(
1601                task_id,
1602                agent,
1603                model = %m,
1604                "discarding stale model: not in agent's model pools"
1605            );
1606        }
1607        valid
1608    });
1609
1610    // A stale model is replaced by the agent's model for the task's complexity, an empty
1611    // model would reach the agent as `--model ""`. last_error keeps the reason (#2527)
1612    let original_model = task.model.clone().filter(|m| !m.is_empty());
1613    let mut model = model;
1614    if original_model.is_some() && model.is_none() {
1615        model = config.model_for_complexity(&agent, &complexity, task_id);
1616        let stale_model = original_model.as_deref().unwrap_or("unknown");
1617        let stale_err = format!(
1618            "stale model discarded: {stale_model} not in {agent} model pools, using {}",
1619            model.as_deref().unwrap_or("the agent default")
1620        );
1621        if let Err(e) = store
1622            .set_fields(
1623                store_id,
1624                &[
1625                    (
1626                        "model",
1627                        serde_json::json!(model.clone().unwrap_or_default()),
1628                    ),
1629                    ("last_error", serde_json::json!(stale_err)),
1630                ],
1631            )
1632            .await
1633        {
1634            // Log the error so transient DB failures are visible and diagnosable.
1635            tracing::warn!(task_id = %task_id, error = %e, "failed to clear stale model from store — will retry on next dispatch");
1636        }
1637    }
1638
1639    Ok(RouteResult {
1640        agent,
1641        model,
1642        complexity,
1643        estimate: 0,
1644        reason,
1645        profile,
1646        warning: None,
1647    })
1648}
1649
1650#[cfg(test)]
1651#[expect(
1652    clippy::float_cmp,
1653    reason = "the weights are stored constants, so they compare exactly"
1654)]
1655mod tests {
1656    use super::config::DEFAULT_AGENTS;
1657    use super::llm::LlmRouteResponse;
1658    use super::strategies;
1659    use super::weights::default_missing_weight;
1660    use super::weights::{
1661        AgentWeights, DEFAULT_WEIGHT, MIN_WEIGHT, RATE_LIMIT_DECAY, RECOVERY_DELAY, RateLimitState,
1662    };
1663    use super::*;
1664    use crate::backends::{ExternalId, ExternalTask};
1665    use crate::engine::cooldown::{
1666        clear_agent_degraded, is_agent_degraded, is_model_in_cooldown, mark_agent_degraded,
1667        record_model_failure, set_model_cooldown,
1668    };
1669    use crate::store::NewTask;
1670    use crate::store::TaskStore;
1671    use serial_test::serial;
1672    use std::collections::HashMap;
1673    use std::env;
1674    #[cfg(unix)]
1675    use std::ffi::OsString;
1676    use std::fs;
1677    #[cfg(unix)]
1678    use std::fs::Permissions;
1679    #[cfg(unix)]
1680    use std::os::unix::fs::PermissionsExt;
1681    #[cfg(unix)]
1682    use std::process;
1683    #[cfg(unix)]
1684    use std::process::Command;
1685    #[cfg(unix)]
1686    use std::thread;
1687    use std::time::{Duration, Instant};
1688
1689    #[test]
1690    fn max_turns_error_matches_grok_phrases() {
1691        assert!(is_max_turns_error(
1692            "router LLM returned error: Reached the maximum number of turns"
1693        ));
1694        assert!(is_max_turns_error("Error: max turns reached"));
1695        assert!(is_max_turns_error(
1696            "router LLM failed: router LLM returned error: Reached the maximum number of turns"
1697        ));
1698        assert!(!is_max_turns_error("router LLM timed out after 30s"));
1699        assert!(!is_max_turns_error("rate limited"));
1700    }
1701
1702    #[tokio::test]
1703    #[serial_test::serial(orch_home)]
1704    async fn get_route_result_replaces_a_stale_model_with_the_complexity_model() {
1705        let home = tempfile::tempdir().unwrap();
1706        fs::write(
1707            home.path().join("config.yml"),
1708            "model_map:\n  medium:\n    claude: sonnet\n",
1709        )
1710        .unwrap();
1711        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1712        unsafe { env::set_var("ORCH_HOME", home.path()) };
1713
1714        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1715        let store_id = store
1716            .create(&NewTask {
1717                external_id: Some("7".to_string()),
1718                repo: "owner/repo".to_string(),
1719                origin: "github".to_string(),
1720                title: "stale model".to_string(),
1721                ..Default::default()
1722            })
1723            .await
1724            .unwrap();
1725        store
1726            .set_fields(
1727                store_id,
1728                &[
1729                    ("agent", serde_json::json!("claude")),
1730                    ("model", serde_json::json!("claude-removed-model")),
1731                    ("complexity", serde_json::json!("medium")),
1732                ],
1733            )
1734            .await
1735            .unwrap();
1736
1737        let route = get_route_result(&store, "owner/repo", "7").await;
1738        let stored = store.get(store_id).await.unwrap().model;
1739        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1740        unsafe { env::remove_var("ORCH_HOME") };
1741
1742        assert_eq!(route.unwrap().model.as_deref(), Some("sonnet"));
1743        assert_eq!(stored.as_deref(), Some("sonnet"));
1744    }
1745
1746    // Test-only delegate so tests can call router.parse_llm_response() directly
1747    // without referencing llm_router.
1748    impl Router {
1749        #[expect(
1750            clippy::unused_self,
1751            reason = "the test helper keeps the router method syntax"
1752        )]
1753        fn parse_llm_response(&self, response: &str) -> anyhow::Result<LlmRouteResponse> {
1754            LlmRouter::parse_llm_response("claude", response)
1755        }
1756    }
1757
1758    async fn test_store() -> Arc<TaskStore> {
1759        Arc::new(TaskStore::open_memory().await.unwrap())
1760    }
1761
1762    fn create_test_task(id: &str, title: &str, labels: Vec<String>) -> ExternalTask {
1763        ExternalTask {
1764            id: ExternalId(id.to_string()),
1765            title: title.to_string(),
1766            body: "Test body".to_string(),
1767            state: "open".to_string(),
1768            labels,
1769            author: "test".to_string(),
1770            created_at: "2026-01-01T00:00:00Z".to_string(),
1771            updated_at: "2026-01-01T00:00:00Z".to_string(),
1772            url: format!("https://github.com/test/test/issues/{id}"),
1773        }
1774    }
1775
1776    #[serial(cooldown_state)]
1777    #[test]
1778    fn extract_agent_from_labels() {
1779        let mut config = RouterConfig::default();
1780        // Ensure a concrete model exists for the labeled agent so the label
1781        // override is honored by the router (routing requires a model).
1782        config
1783            .model_map
1784            .entry("medium".to_string())
1785            .or_default()
1786            .insert("claude".to_string(), vec!["haiku".to_string()]);
1787
1788        assert_eq!(
1789            strategies::extract_agent_from_labels(&config.agents, &["agent:claude".to_string()]),
1790            Some("claude".to_string())
1791        );
1792        assert_eq!(
1793            strategies::extract_agent_from_labels(&config.agents, &["agent:codex".to_string()]),
1794            Some("codex".to_string())
1795        );
1796        assert_eq!(
1797            strategies::extract_agent_from_labels(&config.agents, &["agent:opencode".to_string()]),
1798            Some("opencode".to_string())
1799        );
1800        assert_eq!(
1801            strategies::extract_agent_from_labels(&config.agents, &["status:new".to_string()]),
1802            None
1803        );
1804        // Verify kimi and minimax are recognized from labels
1805        assert_eq!(
1806            strategies::extract_agent_from_labels(&config.agents, &["agent:kimi".to_string()]),
1807            Some("kimi".to_string())
1808        );
1809        assert_eq!(
1810            strategies::extract_agent_from_labels(&config.agents, &["agent:minimax".to_string()]),
1811            Some("minimax".to_string())
1812        );
1813    }
1814
1815    #[serial(cooldown_state)]
1816    #[tokio::test]
1817    async fn all_agents_cooled_error_names_degraded_agents() {
1818        cooldown::reset_global_state().await;
1819        mark_agent_degraded("claude");
1820        mark_agent_degraded("grok");
1821        let err = AllAgentsCooledError::new("all agents".to_string(), None);
1822        let msg = err.to_string();
1823        assert!(
1824            msg.contains("degraded: claude, grok"),
1825            "ALL AGENTS COOLED must name degraded agents, got {msg}"
1826        );
1827        assert_eq!(err.degraded(), &["claude".to_string(), "grok".to_string()]);
1828        clear_agent_degraded("claude");
1829        clear_agent_degraded("grok");
1830    }
1831
1832    #[serial(cooldown_state)]
1833    #[test]
1834    fn default_agents_constant() {
1835        assert_eq!(DEFAULT_AGENTS.len(), 7);
1836        assert!(DEFAULT_AGENTS.contains(&"claude"));
1837        assert!(DEFAULT_AGENTS.contains(&"kimi"));
1838        assert!(DEFAULT_AGENTS.contains(&"minimax"));
1839        assert!(DEFAULT_AGENTS.contains(&"glm"));
1840        assert!(DEFAULT_AGENTS.contains(&"grok"));
1841    }
1842
1843    #[serial(cooldown_state)]
1844    #[test]
1845    fn extract_complexity_from_labels() {
1846        assert_eq!(
1847            strategies::extract_complexity_from_labels(&["complexity:simple".to_string()]),
1848            "simple"
1849        );
1850        assert_eq!(
1851            strategies::extract_complexity_from_labels(&["complexity:medium".to_string()]),
1852            "medium"
1853        );
1854        assert_eq!(
1855            strategies::extract_complexity_from_labels(&["complexity:complex".to_string()]),
1856            "complex"
1857        );
1858        assert_eq!(
1859            strategies::extract_complexity_from_labels(&["status:new".to_string()]),
1860            "medium"
1861        );
1862    }
1863
1864    #[serial(cooldown_state)]
1865    #[test]
1866    fn route_result_serialization() {
1867        let result = RouteResult {
1868            agent: "claude".to_string(),
1869            model: Some("sonnet".to_string()),
1870            complexity: "medium".to_string(),
1871            estimate: 5,
1872            reason: "test".to_string(),
1873            profile: AgentProfile {
1874                role: "backend".to_string(),
1875                tools: vec!["git".to_string()],
1876                constraints: vec![],
1877                execution: None,
1878            },
1879            warning: None,
1880        };
1881
1882        let json = serde_json::to_string(&result).unwrap();
1883        assert!(json.contains("claude"));
1884        assert!(json.contains("sonnet"));
1885
1886        let deserialized: RouteResult = serde_json::from_str(&json).unwrap();
1887        assert_eq!(deserialized.agent, "claude");
1888        assert_eq!(deserialized.model, Some("sonnet".to_string()));
1889    }
1890
1891    #[serial(cooldown_state)]
1892    #[test]
1893    fn router_config_default() {
1894        let mut config = RouterConfig::default();
1895        // Ensure a concrete model exists for the labeled agent so the label
1896        // override is honored by the router (routing requires a model).
1897        config
1898            .model_map
1899            .entry("medium".to_string())
1900            .or_default()
1901            .insert("claude".to_string(), vec!["haiku".to_string()]);
1902
1903        assert_eq!(config.mode, "round_robin");
1904        assert_eq!(config.router_agent, "claude");
1905        assert_eq!(
1906            config.router_model, "",
1907            "no router.model means the router agent's CLI default"
1908        );
1909        assert_eq!(config.fallback_executor, "codex");
1910        assert_eq!(config.max_route_attempts, 3);
1911        assert_ne!(config.allowed_tools, [] as [String; 0]);
1912
1913        // Verify configurable agents list includes all 7 agents
1914        assert_eq!(config.agents.len(), 7);
1915        assert!(config.agents.contains(&"claude".to_string()));
1916        assert!(config.agents.contains(&"codex".to_string()));
1917        assert!(config.agents.contains(&"opencode".to_string()));
1918        assert!(config.agents.contains(&"kimi".to_string()));
1919        assert!(config.agents.contains(&"minimax".to_string()));
1920        assert!(config.agents.contains(&"glm".to_string()));
1921        assert!(config.agents.contains(&"grok".to_string()));
1922    }
1923
1924    #[serial(cooldown_state)]
1925    #[test]
1926    fn model_map_lookup_returns_none_without_config() {
1927        // Default config has no hardcoded models — config.yml is the source of truth.
1928        let config = RouterConfig::default();
1929        assert!(
1930            config
1931                .model_for_complexity("claude", "simple", "")
1932                .is_none()
1933        );
1934        assert!(
1935            config
1936                .model_for_complexity("claude", "medium", "")
1937                .is_none()
1938        );
1939        assert!(
1940            config
1941                .model_for_complexity("claude", "complex", "")
1942                .is_none()
1943        );
1944        assert!(
1945            config
1946                .model_for_complexity("opencode", "review", "")
1947                .is_none()
1948        );
1949    }
1950
1951    #[serial(cooldown_state)]
1952    #[test]
1953    fn model_map_lookup_returns_configured_value() {
1954        // When model_map is populated (from config), it is returned correctly.
1955        let mut config = RouterConfig::default();
1956        config
1957            .model_map
1958            .entry("simple".to_string())
1959            .or_default()
1960            .insert("claude".to_string(), vec!["haiku".to_string()]);
1961        assert_eq!(
1962            config.model_for_complexity("claude", "simple", ""),
1963            Some("haiku".to_string())
1964        );
1965    }
1966
1967    #[serial(cooldown_state)]
1968    #[tokio::test]
1969    async fn model_pool_selection_skips_cooled() {
1970        cooldown::reset_global_state().await;
1971
1972        let mut config = RouterConfig::default();
1973        // Set up a two-model pool for opencode/simple
1974        config
1975            .model_map
1976            .entry("simple".to_string())
1977            .or_default()
1978            .insert(
1979                "opencode".to_string(),
1980                vec!["model-a".to_string(), "model-b".to_string()],
1981            );
1982
1983        // Before any cooldown, both models are candidates
1984        let m = config.model_for_complexity("opencode", "simple", "task-1");
1985        assert!(m == Some("model-a".to_string()) || m == Some("model-b".to_string()));
1986
1987        // Cool model-a
1988        record_model_failure("opencode", "model-a").await;
1989        assert!(is_model_in_cooldown("opencode", "model-a"));
1990
1991        // Now only model-b should be returned
1992        // (try many task_ids to rule out hash coincidence)
1993        for i in 0..20 {
1994            let result = config.model_for_complexity("opencode", "simple", &i.to_string());
1995            assert_eq!(
1996                result,
1997                Some("model-b".to_string()),
1998                "expected model-b when model-a is cooled, got {result:?} for task_id={i}"
1999            );
2000        }
2001
2002        // Cool model-b too — now all models are cooled
2003        record_model_failure("opencode", "model-b").await;
2004        // All cooled → return None so the caller can fall back to a different agent
2005        let fallback = config.model_for_complexity("opencode", "simple", "task-fallback");
2006        assert_eq!(fallback, None);
2007    }
2008
2009    #[serial(cooldown_state)]
2010    #[test]
2011    fn model_pool_single_string_backward_compat() {
2012        // Single-item pools behave identically to the old string format.
2013        // Manually insert a single-item pool and verify it is returned correctly.
2014        let mut config = RouterConfig::default();
2015        config
2016            .model_map
2017            .entry("simple".to_string())
2018            .or_default()
2019            .insert("claude".to_string(), vec!["haiku".to_string()]);
2020        let m = config.model_for_complexity("claude", "simple", "any-task");
2021        assert_eq!(m, Some("haiku".to_string()));
2022    }
2023
2024    #[serial(cooldown_state)]
2025    #[test]
2026    fn parse_llm_response_direct_json() {
2027        let config = RouterConfig::default();
2028        let router = Router::new(config);
2029
2030        let response = r#"{
2031            "executor": "claude",
2032            "complexity": "complex",
2033            "reason": "requires architecture analysis",
2034            "profile": {
2035                "role": "architect",
2036                "skills": ["rust", "design"],
2037                "tools": ["git", "rg"],
2038                "constraints": []
2039            },
2040            "selected_skills": ["gh"]
2041        }"#;
2042
2043        let parsed = router.parse_llm_response(response).unwrap();
2044        assert_eq!(parsed.executor, "claude");
2045        assert_eq!(parsed.complexity, "complex");
2046        assert_eq!(parsed.reason, "requires architecture analysis");
2047        assert_eq!(parsed.profile.role, "architect");
2048    }
2049
2050    #[serial(cooldown_state)]
2051    #[test]
2052    fn parse_llm_response_markdown_fenced() {
2053        let config = RouterConfig::default();
2054        let router = Router::new(config);
2055
2056        let response = r#"Here's my analysis:
2057
2058```json
2059{
2060    "executor": "codex",
2061    "complexity": "medium",
2062    "reason": "coding task",
2063    "profile": {
2064        "role": "developer",
2065        "skills": ["coding"],
2066        "tools": [],
2067        "constraints": []
2068    },
2069    "selected_skills": []
2070}
2071```
2072
2073Hope that helps!"#;
2074
2075        let parsed = router.parse_llm_response(response).unwrap();
2076        assert_eq!(parsed.executor, "codex");
2077        assert_eq!(parsed.complexity, "medium");
2078    }
2079
2080    #[serial(cooldown_state)]
2081    #[test]
2082    fn parse_llm_response_claude_envelope() {
2083        let config = RouterConfig::default();
2084        let router = Router::new(config);
2085
2086        // Claude --output-format json wraps the response in an envelope
2087        let response = r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":1500,"result":"{\"executor\":\"claude\",\"complexity\":\"complex\",\"reason\":\"requires deep analysis\",\"profile\":{\"role\":\"architect\",\"skills\":[],\"tools\":[],\"constraints\":[]},\"selected_skills\":[]}","usage":{"input_tokens":100,"output_tokens":50}}"#;
2088
2089        let parsed = router.parse_llm_response(response).unwrap();
2090        assert_eq!(parsed.executor, "claude");
2091        assert_eq!(parsed.complexity, "complex");
2092        assert_eq!(parsed.reason, "requires deep analysis");
2093    }
2094
2095    #[serial(cooldown_state)]
2096    #[test]
2097    fn parse_llm_response_claude_envelope_with_code_block() {
2098        let config = RouterConfig::default();
2099        let router = Router::new(config);
2100
2101        // Claude may return the JSON inside a code block within the envelope
2102        let inner = "```json\n{\"executor\":\"codex\",\"complexity\":\"simple\",\"reason\":\"simple fix\",\"profile\":{\"role\":\"developer\",\"skills\":[],\"tools\":[],\"constraints\":[]},\"selected_skills\":[]}\n```";
2103        let envelope = serde_json::json!({
2104            "type": "result",
2105            "subtype": "success",
2106            "is_error": false,
2107            "result": inner,
2108            "usage": {"input_tokens": 50, "output_tokens": 30}
2109        });
2110
2111        let parsed = router.parse_llm_response(&envelope.to_string()).unwrap();
2112        assert_eq!(parsed.executor, "codex");
2113        assert_eq!(parsed.complexity, "simple");
2114    }
2115
2116    #[serial(cooldown_state)]
2117    #[test]
2118    fn parse_llm_response_claude_envelope_error() {
2119        let config = RouterConfig::default();
2120        let router = Router::new(config);
2121
2122        let response = r#"{"type":"result","subtype":"error","is_error":true,"result":"rate limit exceeded","usage":{}}"#;
2123
2124        let err = router.parse_llm_response(response).unwrap_err();
2125        assert!(err.to_string().contains("error"), "got: {err}");
2126    }
2127
2128    #[serial(cooldown_state)]
2129    #[test]
2130    fn parse_llm_response_empty() {
2131        let config = RouterConfig::default();
2132        let router = Router::new(config);
2133
2134        let err = router.parse_llm_response("").unwrap_err();
2135        assert!(err.to_string().contains("empty"), "got: {err}");
2136    }
2137
2138    /// Claude envelope where result is a JSON object, not a string.
2139    /// Some Claude versions may return the result as a nested object.
2140    #[serial(cooldown_state)]
2141    #[test]
2142    fn parse_llm_response_claude_envelope_result_as_object() {
2143        let config = RouterConfig::default();
2144        let router = Router::new(config);
2145
2146        let response = r#"{"type":"result","subtype":"success","is_error":false,"result":{"executor":"claude","complexity":"medium","reason":"multi-file feature","profile":{"role":"developer","skills":[],"tools":[],"constraints":[]},"selected_skills":[]},"usage":{"input_tokens":100,"output_tokens":50}}"#;
2147
2148        let parsed = router.parse_llm_response(response);
2149        assert!(
2150            parsed.is_ok(),
2151            "should handle result-as-object: {}",
2152            parsed.unwrap_err()
2153        );
2154        assert_eq!(parsed.unwrap().executor, "claude");
2155    }
2156
2157    /// LLM returns "agent" instead of "executor" — common hallucination.
2158    #[serial(cooldown_state)]
2159    #[test]
2160    fn parse_llm_response_agent_instead_of_executor() {
2161        let config = RouterConfig::default();
2162        let router = Router::new(config);
2163
2164        let response = r#"{"agent":"claude","complexity":"medium","reason":"multi-file feature","profile":{"role":"developer","skills":[],"tools":[],"constraints":[]},"selected_skills":[]}"#;
2165
2166        let parsed = router.parse_llm_response(response);
2167        assert!(
2168            parsed.is_ok(),
2169            "should accept 'agent' alias: {}",
2170            parsed.unwrap_err()
2171        );
2172        assert_eq!(parsed.unwrap().executor, "claude");
2173    }
2174
2175    /// LLM returns minimal JSON without profile or reason.
2176    #[serial(cooldown_state)]
2177    #[test]
2178    fn parse_llm_response_minimal_json() {
2179        let config = RouterConfig::default();
2180        let router = Router::new(config);
2181
2182        let response = r#"{"executor":"codex","complexity":"simple"}"#;
2183
2184        let parsed = router.parse_llm_response(response);
2185        assert!(
2186            parsed.is_ok(),
2187            "should accept minimal JSON: {}",
2188            parsed.unwrap_err()
2189        );
2190        assert_eq!(parsed.unwrap().executor, "codex");
2191    }
2192
2193    // ── Real fixture tests: route prompt → response → parsed result ──
2194
2195    /// Real Claude envelope with result as escaped JSON string.
2196    #[serial(cooldown_state)]
2197    #[test]
2198    fn fixture_route_response_string() {
2199        let config = RouterConfig::default();
2200        let router = Router::new(config);
2201
2202        let response = include_str!("../../../tests/fixtures/route-response-string.json");
2203        let parsed = router.parse_llm_response(response).unwrap();
2204        assert_eq!(parsed.executor, "codex");
2205        assert_eq!(parsed.complexity, "medium");
2206        assert_ne!(parsed.reason, "");
2207        assert_ne!(parsed.profile.role, "");
2208    }
2209
2210    /// Real Claude envelope with result as JSON object (not string).
2211    /// This was the root cause of all router failures on 2026-02-27.
2212    #[serial(cooldown_state)]
2213    #[test]
2214    fn fixture_route_response_object() {
2215        let config = RouterConfig::default();
2216        let router = Router::new(config);
2217
2218        let response = include_str!("../../../tests/fixtures/route-response-object.json");
2219        let parsed = router.parse_llm_response(response).unwrap();
2220        assert_eq!(parsed.executor, "claude");
2221        assert_eq!(parsed.complexity, "complex");
2222    }
2223
2224    /// Real Claude envelope with result as string containing markdown + JSON.
2225    #[serial(cooldown_state)]
2226    #[test]
2227    fn fixture_route_response_markdown() {
2228        let config = RouterConfig::default();
2229        let router = Router::new(config);
2230
2231        let response = include_str!("../../../tests/fixtures/route-response-markdown.json");
2232        let parsed = router.parse_llm_response(response).unwrap();
2233        assert_eq!(parsed.executor, "codex");
2234        assert_eq!(parsed.complexity, "medium");
2235    }
2236
2237    /// Claude envelope with escaped JSON string containing newlines and markdown.
2238    #[serial(cooldown_state)]
2239    #[test]
2240    fn parse_llm_response_claude_envelope_with_prose() {
2241        let config = RouterConfig::default();
2242        let router = Router::new(config);
2243
2244        let inner = "Based on the task description, here's my routing decision:\n\n```json\n{\"executor\":\"codex\",\"complexity\":\"medium\",\"reason\":\"standard feature work\",\"profile\":{\"role\":\"developer\",\"skills\":[\"rust\"],\"tools\":[\"git\",\"cargo\"],\"constraints\":[]},\"selected_skills\":[]}\n```\n\nThis task involves adding slash commands which is standard development work.";
2245        let envelope = serde_json::json!({
2246            "type": "result",
2247            "subtype": "success",
2248            "is_error": false,
2249            "result": inner,
2250            "usage": {"input_tokens": 100, "output_tokens": 80}
2251        });
2252
2253        let parsed = router.parse_llm_response(&envelope.to_string());
2254        assert!(
2255            parsed.is_ok(),
2256            "should handle prose + code block in envelope: {}",
2257            parsed.unwrap_err()
2258        );
2259        assert_eq!(parsed.unwrap().executor, "codex");
2260    }
2261
2262    #[serial(cooldown_state)]
2263    #[tokio::test]
2264    async fn route_round_robin_basic() {
2265        cooldown::reset_global_state().await;
2266        // Force at least one agent to be available for testing
2267        // In real usage, discover_agents finds installed CLIs
2268        let config = RouterConfig {
2269            mode: "round_robin".to_string(),
2270            ..Default::default()
2271        };
2272
2273        // Create router with mock available agents
2274        let agents = vec!["claude".to_string(), "codex".to_string()];
2275        let mut weights = AgentWeights::default();
2276        weights.ensure_agents(&agents);
2277        let router = Router {
2278            config,
2279            available_agents: agents,
2280            weights,
2281            llm_router: Arc::new(LlmRouter::new()),
2282            ollama_router: None,
2283            rr_index: 0,
2284            last_agent: None,
2285            review_rr_index: 0,
2286            router_pool: vec![],
2287            pool_index: 0,
2288        };
2289
2290        let task = create_test_task("1", "Test task", vec![]);
2291        let result =
2292            strategies::route_via_round_robin(&router.available_agents, &router.config, &task)
2293                .unwrap();
2294
2295        // Task 1 % 2 agents = agent at index 1 = codex
2296        assert_eq!(result.agent, "codex");
2297        assert_eq!(result.reason, "round_robin (task 1 % 2 agents)");
2298    }
2299
2300    #[serial(cooldown_state)]
2301    #[tokio::test]
2302    async fn route_uses_label_override() {
2303        cooldown::reset_global_state().await;
2304        let mut config = RouterConfig::default();
2305        // Ensure a concrete model exists so the label override can be honored
2306        // in the test environment where no external config.yml is present.
2307        config
2308            .model_map
2309            .entry("medium".to_string())
2310            .or_default()
2311            .insert("claude".to_string(), vec!["haiku".to_string()]);
2312        let agents = vec!["claude".to_string(), "codex".to_string()];
2313        let mut weights = AgentWeights::default();
2314        weights.ensure_agents(&agents);
2315        let mut router = Router {
2316            config,
2317            available_agents: agents,
2318            weights,
2319            llm_router: Arc::new(LlmRouter::new()),
2320            ollama_router: None,
2321            rr_index: 0,
2322            last_agent: None,
2323            review_rr_index: 0,
2324            router_pool: vec![],
2325            pool_index: 0,
2326        };
2327
2328        let task = create_test_task("1", "Test", vec!["agent:claude".to_string()]);
2329        let store = test_store().await;
2330
2331        // Should use label override, not LLM
2332        let result = router.route(&task, &store, "test/repo").await.unwrap();
2333        assert_eq!(result.agent, "claude");
2334        assert!(result.reason.contains("label"));
2335    }
2336
2337    #[serial(cooldown_state)]
2338    #[tokio::test]
2339    async fn route_uses_stored_agent_over_label() {
2340        cooldown::reset_global_state().await;
2341        let mut config = RouterConfig::default();
2342        let medium = config.model_map.entry("medium".to_string()).or_default();
2343        medium.insert("claude".to_string(), vec!["haiku".to_string()]);
2344        medium.insert("codex".to_string(), vec!["gpt-test".to_string()]);
2345        let agents = vec!["claude".to_string(), "codex".to_string()];
2346        let mut router = Router::new_for_test(config, agents);
2347
2348        let store = test_store().await;
2349        let store_id = store
2350            .create(&NewTask {
2351                external_id: Some("1".to_string()),
2352                repo: "test/repo".to_string(),
2353                origin: "github".to_string(),
2354                title: "Test".to_string(),
2355                ..Default::default()
2356            })
2357            .await
2358            .unwrap();
2359        store
2360            .set_fields(store_id, &[("agent", serde_json::json!("codex"))])
2361            .await
2362            .unwrap();
2363
2364        let task = create_test_task("1", "Test", vec!["agent:claude".to_string()]);
2365        let result = router.route(&task, &store, "test/repo").await.unwrap();
2366        assert_eq!(result.agent, "codex");
2367    }
2368
2369    #[serial(cooldown_state)]
2370    #[test]
2371    fn check_routing_sanity_warnings() {
2372        // Backend task routed to claude should warn
2373        let task = create_test_task("1", "Fix API", vec!["backend".to_string()]);
2374        let profile = AgentProfile {
2375            role: "general".to_string(),
2376            tools: vec![],
2377            constraints: vec![],
2378            execution: None,
2379        };
2380        let warning = LlmRouter::check_routing_sanity(&task, "claude", &profile);
2381        assert!(warning.is_some());
2382        assert!(warning.unwrap().contains("backend"));
2383
2384        // Docs task routed to codex should warn
2385        let task = create_test_task("1", "Update README", vec!["docs".to_string()]);
2386        let warning = LlmRouter::check_routing_sanity(&task, "codex", &profile);
2387        assert!(warning.is_some());
2388        assert!(warning.unwrap().contains("docs"));
2389
2390        // Normal routing should not warn
2391        let task = create_test_task("1", "Fix bug", vec!["bug".to_string()]);
2392        let warning = LlmRouter::check_routing_sanity(&task, "codex", &profile);
2393        assert!(warning.is_none());
2394    }
2395
2396    #[serial(cooldown_state)]
2397    #[tokio::test]
2398    async fn router_reload_preserves_structure() {
2399        cooldown::reset_global_state().await;
2400        let config = RouterConfig::default();
2401        let agents = vec!["claude".to_string()];
2402        let mut weights = AgentWeights::default();
2403        weights.ensure_agents(&agents);
2404        let mut router = Router {
2405            config,
2406            available_agents: agents,
2407            weights,
2408            llm_router: Arc::new(LlmRouter::new()),
2409            ollama_router: None,
2410            rr_index: 0,
2411            last_agent: None,
2412            review_rr_index: 0,
2413            router_pool: vec![],
2414            pool_index: 0,
2415        };
2416
2417        // Reload — should re-read config and remain valid
2418        router.reload_async().await;
2419
2420        // After reload, mode should be a valid value (llm, local, or round_robin)
2421        assert!(
2422            router.config.mode == "llm"
2423                || router.config.mode == "round_robin"
2424                || router.config.mode == "local",
2425            "mode should be 'llm', 'local', or 'round_robin', got '{}'",
2426            router.config.mode
2427        );
2428        // Fallback executor should always be set
2429        assert_ne!(router.config.fallback_executor, "");
2430        // Tools should always be populated
2431        assert_ne!(router.config.allowed_tools, [] as [String; 0]);
2432    }
2433
2434    // --- Weighted round-robin tests ---
2435
2436    #[serial(cooldown_state)]
2437    #[test]
2438    fn rate_limit_state_defaults_to_full_weight() {
2439        let state = RateLimitState::default();
2440        assert_eq!(state.weight, DEFAULT_WEIGHT);
2441        assert_eq!(state.consecutive_hits, 0);
2442        assert!(state.last_limited_at.is_none());
2443        assert!(!state.is_limited());
2444    }
2445
2446    #[serial(cooldown_state)]
2447    #[test]
2448    fn rate_limit_state_decays_on_hit() {
2449        let mut state = RateLimitState::default();
2450        state.record_rate_limit();
2451
2452        assert!(state.weight < DEFAULT_WEIGHT);
2453        assert_eq!(state.consecutive_hits, 1);
2454        assert!(state.last_limited_at.is_some());
2455        assert!(state.is_limited());
2456
2457        // Weight should be DEFAULT_WEIGHT * RATE_LIMIT_DECAY
2458        let expected = DEFAULT_WEIGHT * RATE_LIMIT_DECAY;
2459        assert!((state.weight - expected).abs() < 1e-10);
2460    }
2461
2462    #[serial(cooldown_state)]
2463    #[test]
2464    fn rate_limit_state_never_drops_below_min() {
2465        let mut state = RateLimitState::default();
2466
2467        // Hit many times
2468        for _ in 0..100 {
2469            state.record_rate_limit();
2470        }
2471
2472        assert!(state.weight >= MIN_WEIGHT);
2473        assert_eq!(state.consecutive_hits, 100);
2474    }
2475
2476    #[serial(cooldown_state)]
2477    #[test]
2478    fn rate_limit_state_recovers_on_success() {
2479        let mut state = RateLimitState::default();
2480
2481        // Decay first
2482        state.record_rate_limit();
2483        state.record_rate_limit();
2484        let after_decay = state.weight;
2485
2486        // Record success
2487        state.record_success();
2488        assert!(state.weight > after_decay);
2489        assert_eq!(state.consecutive_hits, 0);
2490    }
2491
2492    #[serial(cooldown_state)]
2493    #[test]
2494    fn rate_limit_state_success_caps_at_default() {
2495        let mut state = RateLimitState::default();
2496
2497        // Already at full weight, success shouldn't exceed it
2498        state.record_success();
2499        assert_eq!(state.weight, DEFAULT_WEIGHT);
2500    }
2501
2502    #[serial(cooldown_state)]
2503    #[test]
2504    fn agent_weights_ensure_agents() {
2505        let mut weights = AgentWeights::default();
2506        let agents = vec!["claude".to_string(), "codex".to_string()];
2507        weights.ensure_agents(&agents);
2508
2509        assert_eq!(weights.states.len(), 2);
2510        assert_eq!(weights.get_weight("claude"), DEFAULT_WEIGHT);
2511        assert_eq!(weights.get_weight("codex"), DEFAULT_WEIGHT);
2512    }
2513
2514    #[serial(cooldown_state)]
2515    #[test]
2516    fn agent_weights_ensure_agents_preserves_existing() {
2517        let mut weights = AgentWeights::default();
2518        let agents = vec!["claude".to_string(), "codex".to_string()];
2519        weights.ensure_agents(&agents);
2520
2521        // Reduce claude's weight
2522        weights.record_rate_limit("claude");
2523        let claude_weight = weights.get_weight("claude");
2524        assert!(claude_weight < DEFAULT_WEIGHT);
2525
2526        // Ensure agents again — claude's weight should be preserved
2527        let agents2 = vec![
2528            "claude".to_string(),
2529            "codex".to_string(),
2530            "opencode".to_string(),
2531        ];
2532        weights.ensure_agents(&agents2);
2533
2534        assert_eq!(weights.get_weight("claude"), claude_weight);
2535        assert_eq!(weights.get_weight("opencode"), DEFAULT_WEIGHT);
2536    }
2537
2538    #[test]
2539    fn default_missing_weight_uses_minimum_of_configured() {
2540        let mut configured = HashMap::new();
2541        configured.insert("claude".to_string(), 0.2);
2542        configured.insert("codex".to_string(), 0.2);
2543        configured.insert("opencode".to_string(), 0.2);
2544        configured.insert("kimi".to_string(), 0.2);
2545
2546        // minimax omitted from router.weights — must not silently outrank
2547        // every explicitly configured agent (issue #3596).
2548        assert_eq!(default_missing_weight(&configured), 0.2);
2549    }
2550
2551    #[test]
2552    fn default_missing_weight_falls_back_when_none_configured() {
2553        let configured = HashMap::new();
2554        assert_eq!(default_missing_weight(&configured), DEFAULT_WEIGHT);
2555    }
2556
2557    #[serial(cooldown_state)]
2558    #[test]
2559    fn ensure_agents_with_weights_missing_agent_does_not_outrank_configured() {
2560        let mut weights = AgentWeights::default();
2561        let mut configured = HashMap::new();
2562        configured.insert("claude".to_string(), 0.2);
2563        configured.insert("codex".to_string(), 0.2);
2564        configured.insert("opencode".to_string(), 0.2);
2565        configured.insert("kimi".to_string(), 0.2);
2566
2567        let agents = vec![
2568            "claude".to_string(),
2569            "codex".to_string(),
2570            "opencode".to_string(),
2571            "kimi".to_string(),
2572            "minimax".to_string(),
2573        ];
2574        weights.ensure_agents_with_weights(&agents, &configured);
2575
2576        // minimax was omitted from router.weights but must not get the old
2577        // DEFAULT_WEIGHT of 1.0, which would outrank every configured agent.
2578        assert_eq!(weights.get_weight("minimax"), 0.2);
2579        assert_eq!(weights.get_weight("claude"), 0.2);
2580    }
2581
2582    #[serial(cooldown_state)]
2583    #[test]
2584    fn agent_weights_record_rate_limit() {
2585        let mut weights = AgentWeights::default();
2586        weights.ensure_agents(&["claude".to_string(), "codex".to_string()]);
2587
2588        weights.record_rate_limit("claude");
2589
2590        assert!(weights.get_weight("claude") < DEFAULT_WEIGHT);
2591        assert_eq!(weights.get_weight("codex"), DEFAULT_WEIGHT);
2592    }
2593
2594    #[serial(cooldown_state)]
2595    #[test]
2596    fn agent_weights_record_success() {
2597        let mut weights = AgentWeights::default();
2598        weights.ensure_agents(&["claude".to_string()]);
2599
2600        weights.record_rate_limit("claude");
2601        let after_limit = weights.get_weight("claude");
2602
2603        weights.record_success("claude");
2604        assert!(weights.get_weight("claude") > after_limit);
2605    }
2606
2607    #[serial(cooldown_state)]
2608    #[test]
2609    fn agent_weights_snapshot() {
2610        let mut weights = AgentWeights::default();
2611        weights.ensure_agents(&["claude".to_string(), "codex".to_string()]);
2612        weights.record_rate_limit("claude");
2613
2614        let snap = weights.snapshot();
2615        assert_eq!(snap.len(), 2);
2616
2617        // Snapshot is sorted alphabetically
2618        assert_eq!(snap[0].0, "claude");
2619        assert!(snap[0].1 < DEFAULT_WEIGHT);
2620        assert_eq!(snap[0].2, 1); // 1 hit
2621
2622        assert_eq!(snap[1].0, "codex");
2623        assert_eq!(snap[1].1, DEFAULT_WEIGHT);
2624        assert_eq!(snap[1].2, 0); // 0 hits
2625    }
2626
2627    #[serial(cooldown_state)]
2628    #[test]
2629    fn agent_weights_weighted_select_favors_higher_weight() {
2630        let mut weights = AgentWeights::default();
2631        let agents = vec!["claude".to_string(), "codex".to_string()];
2632        weights.ensure_agents(&agents);
2633
2634        // Heavily penalize claude
2635        for _ in 0..10 {
2636            weights.record_rate_limit("claude");
2637        }
2638
2639        // Run many selections and count
2640        let mut claude_count = 0;
2641        let mut codex_count = 0;
2642        for _ in 0..100 {
2643            match weights.weighted_select(&agents, "task-1") {
2644                Some(ref a) if a == "claude" => claude_count += 1,
2645                Some(ref a) if a == "codex" => codex_count += 1,
2646                _ => {}
2647            }
2648        }
2649
2650        // Codex should get significantly more selections
2651        // (claude weight is near MIN_WEIGHT, codex is at 1.0)
2652        assert!(
2653            codex_count > claude_count,
2654            "codex ({codex_count}) should get more selections than claude ({claude_count})"
2655        );
2656    }
2657
2658    #[serial(cooldown_state)]
2659    #[test]
2660    fn agent_weights_weighted_select_empty_returns_none() {
2661        let weights = AgentWeights::default();
2662        assert!(weights.weighted_select(&[], "task-1").is_none());
2663    }
2664
2665    #[serial(cooldown_state)]
2666    #[test]
2667    fn agent_weights_batch_routing_produces_varied_selections() {
2668        // Regression test: when routing a batch of tasks in the same tick,
2669        // different task IDs should not all select the same agent.
2670        let mut weights = AgentWeights::default();
2671        let agents = vec!["claude".to_string(), "codex".to_string()];
2672        weights.ensure_agents(&agents);
2673
2674        // Simulate batch routing: 20 different task IDs called in rapid succession
2675        let task_ids: Vec<String> = (1..=20).map(|i| format!("task-{i}")).collect();
2676        let selections: Vec<String> = task_ids
2677            .iter()
2678            .filter_map(|id| weights.weighted_select(&agents, id))
2679            .collect();
2680
2681        // With 20 tasks and 2 agents of equal weight, we should see both agents selected.
2682        // The probability of all 20 selecting the same agent by chance is (0.5)^19 < 1e-6.
2683        let claude_count = selections.iter().filter(|a| a.as_str() == "claude").count();
2684        let codex_count = selections.iter().filter(|a| a.as_str() == "codex").count();
2685        assert!(
2686            claude_count > 0 && codex_count > 0,
2687            "batch routing should distribute across agents; got claude={claude_count} codex={codex_count}"
2688        );
2689    }
2690
2691    #[serial(cooldown_state)]
2692    #[test]
2693    fn agent_weights_weighted_select_single_agent() {
2694        let mut weights = AgentWeights::default();
2695        let agents = vec!["claude".to_string()];
2696        weights.ensure_agents(&agents);
2697
2698        let selected = weights.weighted_select(&agents, "task-1");
2699        assert_eq!(selected, Some("claude".to_string()));
2700    }
2701
2702    #[serial(cooldown_state)]
2703    #[test]
2704    fn agent_weights_tick_recovery_restores_weight() {
2705        let mut weights = AgentWeights::default();
2706        weights.ensure_agents(&["claude".to_string()]);
2707
2708        // Set up a rate limit that looks like it happened long ago
2709        let state = weights.states.get_mut("claude").unwrap();
2710        state.weight = 0.5;
2711        state.last_limited_at = Some(
2712            Instant::now()
2713                .checked_sub(RECOVERY_DELAY + Duration::from_secs(1))
2714                .expect("the clock is past the recovery delay"),
2715        );
2716        state.consecutive_hits = 2;
2717
2718        let before = weights.get_weight("claude");
2719        weights.tick_recovery();
2720        let after = weights.get_weight("claude");
2721
2722        assert!(after > before, "weight should increase after recovery tick");
2723    }
2724
2725    #[serial(cooldown_state)]
2726    #[test]
2727    fn agent_weights_tick_recovery_clears_on_full_restore() {
2728        let mut weights = AgentWeights::default();
2729        weights.ensure_agents(&["claude".to_string()]);
2730
2731        // Set weight just below full with an old limit
2732        let state = weights.states.get_mut("claude").unwrap();
2733        state.weight = DEFAULT_WEIGHT - 0.01;
2734        state.last_limited_at = Some(
2735            Instant::now()
2736                .checked_sub(RECOVERY_DELAY + Duration::from_secs(1))
2737                .expect("the clock is past the recovery delay"),
2738        );
2739        state.consecutive_hits = 1;
2740
2741        weights.tick_recovery();
2742
2743        let state = weights.states.get("claude").unwrap();
2744        assert_eq!(state.weight, DEFAULT_WEIGHT);
2745        assert!(state.last_limited_at.is_none());
2746        assert_eq!(state.consecutive_hits, 0);
2747    }
2748
2749    #[serial(cooldown_state)]
2750    #[tokio::test]
2751    async fn route_weighted_round_robin_basic() {
2752        cooldown::reset_global_state().await;
2753        let mut config = RouterConfig {
2754            weighted_round_robin: true,
2755            ..Default::default()
2756        };
2757        // Provide a concrete model for codex so label override can be used.
2758        config
2759            .model_map
2760            .entry("medium".to_string())
2761            .or_default()
2762            .insert("codex".to_string(), vec!["gpt-5.2".to_string()]);
2763
2764        let agents = vec!["claude".to_string(), "codex".to_string()];
2765        let mut weights = AgentWeights::default();
2766        weights.ensure_agents(&agents);
2767        let mut router = Router {
2768            config,
2769            available_agents: agents,
2770            weights,
2771            llm_router: Arc::new(LlmRouter::new()),
2772            ollama_router: None,
2773            rr_index: 0,
2774            last_agent: None,
2775            review_rr_index: 0,
2776            router_pool: vec![],
2777            pool_index: 0,
2778        };
2779
2780        let task = create_test_task("1", "Test task", vec![]);
2781        let store = test_store().await;
2782        let result = router.route(&task, &store, "test/repo").await.unwrap();
2783
2784        // Should use weighted_round_robin
2785        assert!(result.reason.contains("weighted_round_robin"));
2786        assert!(
2787            result.agent == "claude" || result.agent == "codex",
2788            "agent should be claude or codex, got '{}'",
2789            result.agent
2790        );
2791    }
2792
2793    #[serial(cooldown_state)]
2794    #[tokio::test]
2795    async fn route_weighted_round_robin_respects_label_override() {
2796        cooldown::reset_global_state().await;
2797        let mut config = RouterConfig {
2798            weighted_round_robin: true,
2799            ..Default::default()
2800        };
2801        // Provide a concrete model for codex so label override can be used.
2802        config
2803            .model_map
2804            .entry("medium".to_string())
2805            .or_default()
2806            .insert("codex".to_string(), vec!["gpt-5.2".to_string()]);
2807
2808        let agents = vec!["claude".to_string(), "codex".to_string()];
2809        let mut weights = AgentWeights::default();
2810        weights.ensure_agents(&agents);
2811        let mut router = Router {
2812            config,
2813            available_agents: agents,
2814            weights,
2815            llm_router: Arc::new(LlmRouter::new()),
2816            ollama_router: None,
2817            rr_index: 0,
2818            last_agent: None,
2819            review_rr_index: 0,
2820            router_pool: vec![],
2821            pool_index: 0,
2822        };
2823
2824        // Label override should take precedence over weighted routing
2825        let task = create_test_task("1", "Test task", vec!["agent:codex".to_string()]);
2826        let store = test_store().await;
2827        let result = router.route(&task, &store, "test/repo").await.unwrap();
2828        assert_eq!(result.agent, "codex");
2829        assert!(result.reason.contains("label"));
2830    }
2831
2832    #[serial(cooldown_state)]
2833    #[tokio::test]
2834    async fn route_takes_the_adjacent_tier_model_when_the_own_tier_is_cooled() {
2835        cooldown::reset_global_state().await;
2836        let agent = "tierroute_agent";
2837        let mut config = RouterConfig {
2838            agents: vec![agent.to_string()],
2839            ..Default::default()
2840        };
2841        config.model_map.clear();
2842        for (tier, model) in [("medium", "tr-m"), ("complex", "tr-c")] {
2843            config
2844                .model_map
2845                .entry(tier.to_string())
2846                .or_default()
2847                .insert(agent.to_string(), vec![model.to_string()]);
2848        }
2849        cooldown::record_model_failure(agent, "tr-m").await;
2850        let mut router = Router::new_for_test(config, vec![agent.to_string()]);
2851
2852        let task = create_test_task(
2853            "1",
2854            "Test task",
2855            vec![format!("agent:{agent}"), "complexity:medium".to_string()],
2856        );
2857        let store = test_store().await;
2858        let result = router.route(&task, &store, "test/repo").await.unwrap();
2859        assert_eq!(result.agent, agent);
2860        assert_eq!(result.model.as_deref(), Some("tr-c"));
2861        assert_eq!(result.complexity, "medium");
2862        assert!(result.warning.unwrap().contains("complex tier"));
2863    }
2864
2865    #[serial(cooldown_state)]
2866    #[test]
2867    fn router_config_weighted_round_robin_default_false() {
2868        let config = RouterConfig::default();
2869        assert!(!config.weighted_round_robin);
2870    }
2871
2872    #[serial(cooldown_state)]
2873    #[test]
2874    fn router_record_and_recover_weights() {
2875        let config = RouterConfig {
2876            weighted_round_robin: true,
2877            ..Default::default()
2878        };
2879        let mut router = Router::new(config);
2880        // Override discovered agents for test
2881        router.available_agents = vec!["claude".to_string(), "codex".to_string()];
2882        router.weights.ensure_agents(&router.available_agents);
2883
2884        // Record rate limit
2885        router.record_rate_limit("claude");
2886        assert!(router.weights.get_weight("claude") < DEFAULT_WEIGHT);
2887        assert_eq!(router.weights.get_weight("codex"), DEFAULT_WEIGHT);
2888
2889        // Record success for claude
2890        router.record_success("claude");
2891        let after_success = router.weights.get_weight("claude");
2892        assert!(after_success > MIN_WEIGHT);
2893    }
2894
2895    #[serial(cooldown_state)]
2896    #[test]
2897    fn review_rr_index_advances() {
2898        let mut config = RouterConfig::default();
2899        // Set up model_map so has_available_model_for_complexity returns true for test agents
2900        for agent in &["test_a", "test_b", "test_c"] {
2901            config
2902                .model_map
2903                .entry("medium".to_string())
2904                .or_default()
2905                .insert((*agent).to_string(), vec!["test-model".to_string()]);
2906        }
2907        let agents = vec![
2908            "test_a".to_string(),
2909            "test_b".to_string(),
2910            "test_c".to_string(),
2911        ];
2912        let mut weights = AgentWeights::default();
2913        weights.ensure_agents(&agents);
2914        let mut router = Router {
2915            config,
2916            available_agents: agents,
2917            weights,
2918            llm_router: Arc::new(LlmRouter::new()),
2919            ollama_router: None,
2920            rr_index: 0,
2921            last_agent: None,
2922            review_rr_index: 0,
2923            router_pool: vec![],
2924            pool_index: 0,
2925        };
2926
2927        let a1 = router.next_round_robin_agent(&[], "medium").unwrap();
2928        let a2 = router.next_round_robin_agent(&[], "medium").unwrap();
2929        let a3 = router.next_round_robin_agent(&[], "medium").unwrap();
2930
2931        // All three agents should appear (order depends on start index)
2932        let mut seen = vec![a1, a2, a3];
2933        seen.sort();
2934        assert_eq!(seen, vec!["test_a", "test_b", "test_c"]);
2935    }
2936
2937    #[serial(cooldown_state)]
2938    #[test]
2939    fn review_rr_fallback_with_cooled_agent() {
2940        // Regression test for #2428: when one agent is in cooldown (candidates.len() <
2941        // available_agents.len()), review_rr_index can exceed candidates.len()-1 causing
2942        // candidates.get(idx) to return None even though candidates is non-empty.
2943        let mut config = RouterConfig::default();
2944        // Register 3 agents in model_map but only 2 will be "available" (simulate cooldown)
2945        for agent in &["test_a", "test_b", "test_c"] {
2946            config
2947                .model_map
2948                .entry("medium".to_string())
2949                .or_default()
2950                .insert((*agent).to_string(), vec!["test-model".to_string()]);
2951        }
2952        // Only 2 candidates available (test_c is in cooldown / not in available_agents)
2953        let agents = vec!["test_a".to_string(), "test_b".to_string()];
2954        let mut weights = AgentWeights::default();
2955        weights.ensure_agents(&agents);
2956        let mut router = Router {
2957            config,
2958            available_agents: agents,
2959            weights,
2960            llm_router: Arc::new(LlmRouter::new()),
2961            ollama_router: None,
2962            rr_index: 0,
2963            last_agent: None,
2964            // Start index at 2, which is >= candidates.len() (2), triggering the bug
2965            review_rr_index: 2,
2966            router_pool: vec![],
2967            pool_index: 0,
2968        };
2969
2970        // All candidates excluded — should fall back to first candidate, not None
2971        let result = router.next_round_robin_agent(&["test_a", "test_b"], "medium");
2972        assert!(
2973            result.is_some(),
2974            "next_round_robin_agent must not return None when candidates is non-empty"
2975        );
2976    }
2977
2978    #[serial(cooldown_state)]
2979    #[test]
2980    fn review_rr_index_uses_candidates_len_not_available_len() {
2981        // Regression test for #2449: review_rr_index must advance modulo candidates.len(),
2982        // not available_agents.len(). When an agent has no model for the complexity,
2983        // candidates.len() < available_agents.len() and the old code produced a drifting
2984        // index that caused non-uniform distribution.
2985        let mut config = RouterConfig::default();
2986        // Only register models for test_a and test_b — test_c has no model, so it is
2987        // filtered out by has_available_model_for_complexity → candidates.len() == 2.
2988        for agent in &["test_a", "test_b"] {
2989            config
2990                .model_map
2991                .entry("medium".to_string())
2992                .or_default()
2993                .insert((*agent).to_string(), vec!["test-model".to_string()]);
2994        }
2995        let agents = vec![
2996            "test_a".to_string(),
2997            "test_b".to_string(),
2998            "test_c".to_string(), // available but no model → filtered out of candidates
2999        ];
3000        let mut weights = AgentWeights::default();
3001        weights.ensure_agents(&agents);
3002        let mut router = Router {
3003            config,
3004            available_agents: agents,
3005            weights,
3006            llm_router: Arc::new(LlmRouter::new()),
3007            ollama_router: None,
3008            rr_index: 0,
3009            last_agent: None,
3010            review_rr_index: 0,
3011            router_pool: vec![],
3012            pool_index: 0,
3013        };
3014
3015        // With the bug: index advances modulo 3 (available_agents.len()), so the
3016        // sequence would be idx=0→1, idx=1→2, idx=2→0, meaning selection is
3017        // candidates[0%2]=test_a, candidates[1%2]=test_b, candidates[2%2]=test_a —
3018        // looks uniform by accident, but adding a 4th available agent breaks it.
3019        //
3020        // The fix: index advances modulo 2 (candidates.len()), giving a clean 0→1→0→1
3021        // cycle. Verify this by checking review_rr_index after each call.
3022
3023        let r1 = router.next_round_robin_agent(&[], "medium").unwrap();
3024        assert_eq!(
3025            router.review_rr_index, 1,
3026            "index should be 1 after first call"
3027        );
3028
3029        let r2 = router.next_round_robin_agent(&[], "medium").unwrap();
3030        assert_eq!(
3031            router.review_rr_index, 0,
3032            "index should wrap to 0 after second call"
3033        );
3034
3035        let r3 = router.next_round_robin_agent(&[], "medium").unwrap();
3036        assert_eq!(
3037            router.review_rr_index, 1,
3038            "index should be 1 after third call"
3039        );
3040
3041        // Agents must alternate uniformly
3042        assert_ne!(r1, r2, "consecutive calls should select different agents");
3043        assert_eq!(r1, r3, "third call should match first (clean cycle)");
3044    }
3045
3046    #[serial(cooldown_state)]
3047    #[tokio::test]
3048    async fn last_agent_tracks_routing() {
3049        cooldown::reset_global_state().await;
3050        let mut config = RouterConfig {
3051            mode: "round_robin".to_string(),
3052            ..Default::default()
3053        };
3054        config
3055            .model_map
3056            .entry("medium".to_string())
3057            .or_default()
3058            .insert("test_x".to_string(), vec!["test-model-x".to_string()]);
3059        config
3060            .model_map
3061            .entry("medium".to_string())
3062            .or_default()
3063            .insert("test_y".to_string(), vec!["test-model-y".to_string()]);
3064        let agents = vec!["test_x".to_string(), "test_y".to_string()];
3065        let mut weights = AgentWeights::default();
3066        weights.ensure_agents(&agents);
3067        let mut router = Router {
3068            config,
3069            available_agents: agents,
3070            weights,
3071            llm_router: Arc::new(LlmRouter::new()),
3072            ollama_router: None,
3073            rr_index: 0,
3074            last_agent: None,
3075            review_rr_index: 0,
3076            router_pool: vec![],
3077            pool_index: 0,
3078        };
3079
3080        assert!(router.last_agent.is_none());
3081
3082        let task = create_test_task("1", "Test routing", vec![]);
3083        let store = test_store().await;
3084        let result = router.route(&task, &store, "test/repo").await.unwrap();
3085
3086        assert!(router.last_agent.is_some());
3087        assert_eq!(router.last_agent.as_deref(), Some(result.agent.as_str()));
3088    }
3089
3090    // ── pool config ───────────────────────────────────────────────────────────
3091
3092    #[serial(cooldown_state)]
3093    #[test]
3094    fn parse_pool_entry_splits_on_first_colon() {
3095        let (agent, model) = super::parse_pool_entry("claude:haiku");
3096        assert_eq!(agent, "claude");
3097        assert_eq!(model, "haiku");
3098    }
3099
3100    #[serial(cooldown_state)]
3101    #[test]
3102    fn parse_pool_entry_model_with_slash() {
3103        // Models like "github-copilot/gpt-5-mini" must not be split on the slash
3104        let (agent, model) = super::parse_pool_entry("opencode:github-copilot/gpt-5-mini");
3105        assert_eq!(agent, "opencode");
3106        assert_eq!(model, "github-copilot/gpt-5-mini");
3107    }
3108
3109    #[serial(cooldown_state)]
3110    #[test]
3111    fn parse_pool_entry_no_colon() {
3112        let (agent, model) = super::parse_pool_entry("claude");
3113        assert_eq!(agent, "claude");
3114        assert_eq!(model, "");
3115    }
3116
3117    #[serial(cooldown_state)]
3118    #[test]
3119    fn effective_pool_uses_configured_pool() {
3120        let config = RouterConfig {
3121            pool: vec!["kimi:k2p5".to_string(), "claude:haiku".to_string()],
3122            ..RouterConfig::default()
3123        };
3124        let pool = config.effective_pool();
3125        assert_eq!(pool, vec!["kimi:k2p5", "claude:haiku"]);
3126    }
3127
3128    #[serial(cooldown_state)]
3129    #[test]
3130    fn effective_pool_falls_back_to_router_agent_model() {
3131        let config = RouterConfig::default();
3132        // Default has no pool → derives from router_agent:router_model
3133        let pool = config.effective_pool();
3134        assert_eq!(pool.len(), 1);
3135        assert!(pool[0].starts_with(&config.router_agent));
3136        assert!(pool[0].contains(&config.router_model));
3137    }
3138
3139    #[serial(cooldown_state)]
3140    #[test]
3141    fn effective_fallback_uses_configured_fallback() {
3142        let config = RouterConfig {
3143            fallback: "claude:haiku".to_string(),
3144            ..RouterConfig::default()
3145        };
3146        assert_eq!(config.effective_fallback(), "claude:haiku");
3147    }
3148
3149    #[serial(cooldown_state)]
3150    #[test]
3151    fn effective_fallback_derives_from_router_agent_model() {
3152        let config = RouterConfig::default();
3153        let fallback = config.effective_fallback();
3154        assert!(fallback.starts_with(&config.router_agent));
3155        assert!(fallback.contains(&config.router_model));
3156    }
3157
3158    // ── pool expansion ────────────────────────────────────────────────────────
3159
3160    #[serial(cooldown_state)]
3161    #[test]
3162    fn expand_pool_basic_entries() {
3163        let config = RouterConfig {
3164            pool: vec!["claude:haiku".to_string(), "kimi:k2p5".to_string()],
3165            ..RouterConfig::default()
3166        };
3167        let expanded = Router::expand_pool(&config);
3168        assert_eq!(expanded.len(), 2);
3169        assert_eq!(expanded[0], ("claude".to_string(), "haiku".to_string()));
3170        assert_eq!(expanded[1], ("kimi".to_string(), "k2p5".to_string()));
3171    }
3172
3173    #[serial(cooldown_state)]
3174    #[test]
3175    fn expand_pool_uses_effective_pool_when_pool_is_empty() {
3176        let config = RouterConfig {
3177            pool: vec![],
3178            router_agent: "claude".to_string(),
3179            router_model: "haiku".to_string(),
3180            ..RouterConfig::default()
3181        };
3182        let expanded = Router::expand_pool(&config);
3183        assert_eq!(expanded.len(), 1);
3184        assert_eq!(expanded[0], ("claude".to_string(), "haiku".to_string()));
3185    }
3186
3187    #[serial(cooldown_state)]
3188    #[test]
3189    fn expand_pool_opencode_free_skipped_when_not_installed() {
3190        // Test/debug builds skip live `opencode models`, so `opencode:free` expands
3191        // to nothing and the pool falls back to effective_fallback
3192        let config = RouterConfig {
3193            pool: vec!["opencode:free".to_string()],
3194            fallback: "claude:haiku".to_string(),
3195            ..RouterConfig::default()
3196        };
3197        let expanded = Router::expand_pool(&config);
3198        assert_eq!(expanded.len(), 1);
3199        assert_eq!(expanded[0].0, "claude");
3200        assert_eq!(expanded[0].1, "haiku");
3201    }
3202
3203    #[serial(cooldown_state)]
3204    #[test]
3205    fn expand_pool_single_entry_from_default() {
3206        let config = RouterConfig::default();
3207        let expanded = Router::expand_pool(&config);
3208        assert!(
3209            !expanded.is_empty(),
3210            "pool must never be empty after expansion"
3211        );
3212    }
3213
3214    // ── pool round-robin index ────────────────────────────────────────────────
3215
3216    #[serial(cooldown_state)]
3217    #[test]
3218    fn pool_index_initializes_to_zero() {
3219        let config = RouterConfig::default();
3220        let router = Router::new(config);
3221        assert_eq!(router.pool_index, 0);
3222    }
3223
3224    #[serial(cooldown_state)]
3225    #[test]
3226    fn router_pool_non_empty_after_construction() {
3227        let config = RouterConfig::default();
3228        let router = Router::new(config);
3229        assert_ne!(router.router_pool, [] as [(String, String); 0]);
3230    }
3231
3232    /**
3233     * Router construction used to run `opencode models`, and opencode 2.2.1 leaves an
3234     * `opencode serve --service` child behind, so a suite run leaked one server per test
3235     * process. The stub on PATH records any exec, so this fails if discovery comes back
3236     **/
3237    #[cfg(unix)]
3238    #[serial(cooldown_state)]
3239    #[test]
3240    fn building_a_router_never_runs_opencode() {
3241        struct PathRestore(Option<OsString>);
3242        impl Drop for PathRestore {
3243            fn drop(&mut self) {
3244                match &self.0 {
3245                    // SAFETY: nextest runs each test in its own process, so no other test touches the environment
3246                    Some(p) => unsafe { env::set_var("PATH", p) },
3247                    // SAFETY: nextest runs each test in its own process, so no other test touches the environment
3248                    None => unsafe { env::remove_var("PATH") },
3249                }
3250                cmd_cache::reset_for_test();
3251            }
3252        }
3253
3254        let dir = tempfile::tempdir().unwrap();
3255        let marker = dir.path().join("spawned");
3256        let bin_dir = dir.path().join("bin");
3257        fs::create_dir(&bin_dir).unwrap();
3258        let stub = bin_dir.join("opencode");
3259        fs::write(
3260            &stub,
3261            format!(
3262                "#!/bin/sh\necho \"$@\" > '{}'\necho canary-model-free\n",
3263                marker.display()
3264            ),
3265        )
3266        .unwrap();
3267        fs::set_permissions(&stub, Permissions::from_mode(0o755)).unwrap();
3268
3269        let prev_path = env::var_os("PATH");
3270        let mut new_path = bin_dir.as_os_str().to_os_string();
3271        new_path.push(":");
3272        if let Some(ref p) = prev_path {
3273            new_path.push(p);
3274        }
3275        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
3276        unsafe { env::set_var("PATH", &new_path) };
3277        cmd_cache::reset_for_test();
3278        let _restore = PathRestore(prev_path);
3279
3280        // A config that names opencode everywhere discovery reads from
3281        let mut config = RouterConfig {
3282            pool: vec!["opencode:free".to_string()],
3283            fallback: "opencode:free".to_string(),
3284            ..RouterConfig::default()
3285        };
3286        config
3287            .model_map
3288            .entry("simple".to_string())
3289            .or_default()
3290            .insert(
3291                "opencode".to_string(),
3292                vec!["canary-model-free".to_string()],
3293            );
3294
3295        let _router = Router::new(config.clone());
3296        let _test_router = Router::new_for_test(config.clone(), vec!["opencode".to_string()]);
3297        let _pool = Router::expand_pool(&config);
3298        // Discovery refreshes on a background thread, give it room to exec
3299        thread::sleep(Duration::from_millis(300));
3300
3301        assert!(
3302            !marker.exists(),
3303            "building a router ran opencode: {}",
3304            fs::read_to_string(&marker).unwrap_or_default().trim()
3305        );
3306        assert!(
3307            opencode_children().is_empty(),
3308            "building a router left opencode processes: {:?}",
3309            opencode_children()
3310        );
3311    }
3312
3313    /// Commands of this process's direct children that mention opencode
3314    #[cfg(unix)]
3315    fn opencode_children() -> Vec<String> {
3316        let me = process::id().to_string();
3317        let output = Command::new("ps")
3318            .args(["-axo", "ppid=,command="])
3319            .output()
3320            .expect("ps");
3321        String::from_utf8_lossy(&output.stdout)
3322            .lines()
3323            .filter_map(|line| {
3324                let (ppid, cmd) = line.trim().split_once(char::is_whitespace)?;
3325                (ppid == me && cmd.contains("opencode")).then(|| cmd.to_string())
3326            })
3327            .collect()
3328    }
3329
3330    #[serial(cooldown_state)]
3331    #[tokio::test]
3332    async fn reload_resets_pool_index() {
3333        cooldown::reset_global_state().await;
3334        let config = RouterConfig::default();
3335        let mut router = Router::new(config);
3336        router.pool_index = 5;
3337        router.reload_async().await;
3338        assert_eq!(router.pool_index, 0);
3339    }
3340
3341    #[serial(cooldown_state)]
3342    #[test]
3343    fn pool_index_advances_after_failed_attempt() {
3344        let mut router = Router::new(RouterConfig::default());
3345        router.router_pool = vec![
3346            ("claude".to_string(), "haiku".to_string()),
3347            ("codex".to_string(), "gpt-5.2".to_string()),
3348            (
3349                "opencode".to_string(),
3350                "github-copilot/gpt-5-mini".to_string(),
3351            ),
3352        ];
3353        router.pool_index = 0;
3354
3355        router.advance_pool_index_after_attempt(0, router.router_pool.len());
3356
3357        assert_eq!(router.pool_index, 1);
3358    }
3359
3360    #[serial(cooldown_state)]
3361    #[test]
3362    fn pool_index_wraps_after_last_attempt() {
3363        let mut router = Router::new(RouterConfig::default());
3364        router.router_pool = vec![
3365            ("claude".to_string(), "haiku".to_string()),
3366            ("codex".to_string(), "gpt-5.2".to_string()),
3367            (
3368                "opencode".to_string(),
3369                "github-copilot/gpt-5-mini".to_string(),
3370            ),
3371        ];
3372        router.pool_index = 2;
3373
3374        router.advance_pool_index_after_attempt(2, router.router_pool.len());
3375
3376        assert_eq!(router.pool_index, 0);
3377    }
3378
3379    #[serial(cooldown_state)]
3380    #[test]
3381    fn earliest_pool_cooldown_returns_none_when_no_cooldowns() {
3382        let router = Router::new(RouterConfig::default());
3383        assert!(router.earliest_pool_cooldown().is_none());
3384    }
3385
3386    #[serial(cooldown_state)]
3387    #[tokio::test]
3388    async fn earliest_pool_cooldown_returns_earliest_when_set() {
3389        cooldown::reset_global_state().await;
3390        // Use explicit pool with predictable model names to avoid opencode discovery.
3391        let config = RouterConfig {
3392            pool: vec![
3393                "claude:haiku-4-5-20251001".to_string(),
3394                "opencode:haiku-4-5-20251001".to_string(),
3395            ],
3396            ..Default::default()
3397        };
3398        let router = Router::new(config);
3399        set_model_cooldown("claude", "haiku-4-5-20251001", 300, "silence_detected").await; // 5 min
3400        set_model_cooldown("opencode", "haiku-4-5-20251001", 600, "silence_detected").await; // 10 min
3401
3402        let earliest = router.earliest_pool_cooldown();
3403        assert!(earliest.is_some());
3404        let now = chrono::Utc::now().timestamp();
3405        let remaining = earliest.unwrap() - now;
3406        // Should be close to 300 (5 min, the minimum) — allow 5s tolerance for test runtime
3407        assert!((295..=300).contains(&remaining));
3408    }
3409
3410    #[serial(cooldown_state)]
3411    #[tokio::test]
3412    async fn earliest_pool_cooldown_skips_non_pool_entries() {
3413        cooldown::reset_global_state().await;
3414        // Use explicit pool so we can predict what entries exist.
3415        let config = RouterConfig {
3416            pool: vec![
3417                "claude:pool-model-a".to_string(),
3418                "opencode:pool-model-b".to_string(),
3419            ],
3420            ..Default::default()
3421        };
3422        let router = Router::new(config);
3423        // Set cooldown on a non-pool model — should not affect earliest_pool_cooldown
3424        set_model_cooldown("claude", "opus", 999, "silence_detected").await;
3425        // Set cooldown on a pool entry (opencode:pool-model-b)
3426        set_model_cooldown("opencode", "pool-model-b", 300, "silence_detected").await;
3427
3428        let earliest = router.earliest_pool_cooldown();
3429        assert!(earliest.is_some());
3430        let now = chrono::Utc::now().timestamp();
3431        let remaining = earliest.unwrap() - now;
3432        // Should be ~300 (the pool-model-b cooldown), NOT 999 (claude:opus is not in pool)
3433        assert!((295..=300).contains(&remaining));
3434    }
3435
3436    // ---- Pre-emptive health check: degraded agent exclusion ----
3437
3438    #[serial(cooldown_state)]
3439    #[test]
3440    fn degraded_agent_excluded_from_routing() {
3441        let mut config = RouterConfig::default();
3442        config
3443            .model_map
3444            .entry("medium".to_string())
3445            .or_default()
3446            .insert(
3447                "test_degraded_routing".to_string(),
3448                vec!["model-a".to_string()],
3449            );
3450
3451        let mut router = Router::new(config);
3452        router.available_agents = vec!["test_degraded_routing".to_string()];
3453
3454        // Agent is routable before degradation
3455        assert!(router.agent_is_routable("test_degraded_routing", "medium"));
3456
3457        // Mark as degraded
3458        mark_agent_degraded("test_degraded_routing");
3459
3460        // Now excluded from routing
3461        assert!(!router.agent_is_routable("test_degraded_routing", "medium"));
3462
3463        // available_agents_for_complexity returns empty
3464        assert!(
3465            router.available_agents_for_complexity("medium").is_empty(),
3466            "degraded agent should be excluded from available agents"
3467        );
3468
3469        // healthy_agent_count reflects exclusion
3470        assert_eq!(router.healthy_agent_count("medium"), 0);
3471
3472        // Cleanup
3473        clear_agent_degraded("test_degraded_routing");
3474    }
3475
3476    #[serial(cooldown_state)]
3477    #[test]
3478    fn healthy_agents_skips_degraded_but_keeps_healthy() {
3479        let mut config = RouterConfig::default();
3480        for agent in &["agent_healthy", "agent_degraded"] {
3481            config
3482                .model_map
3483                .entry("medium".to_string())
3484                .or_default()
3485                .insert(agent.to_string(), vec!["model-x".to_string()]);
3486        }
3487
3488        let mut router = Router::new(config);
3489        router.available_agents = vec!["agent_healthy".to_string(), "agent_degraded".to_string()];
3490
3491        mark_agent_degraded("agent_degraded");
3492
3493        let candidates = router.available_agents_for_complexity("medium");
3494        assert_eq!(candidates, vec!["agent_healthy".to_string()]);
3495        assert_eq!(router.healthy_agent_count("medium"), 1);
3496
3497        // Cleanup
3498        clear_agent_degraded("agent_degraded");
3499    }
3500
3501    #[serial(cooldown_state)]
3502    #[tokio::test]
3503    async fn refresh_health_marks_degraded_from_rate_limits() {
3504        cooldown::reset_global_state().await;
3505        let store = test_store().await;
3506        let agent = "test_refresh_health_agent";
3507
3508        let mut config = RouterConfig::default();
3509        config
3510            .model_map
3511            .entry("medium".to_string())
3512            .or_default()
3513            .insert(agent.to_string(), vec!["model-z".to_string()]);
3514
3515        let mut router = Router::new(config);
3516        router.available_agents = vec![agent.to_string()];
3517
3518        // Insert rate limit events exceeding default threshold (3)
3519        for _ in 0..4 {
3520            store.record_rate_limit(agent, "rate", None).await.unwrap();
3521        }
3522
3523        router.refresh_health(&store).await;
3524
3525        assert!(
3526            is_agent_degraded(agent),
3527            "agent should be degraded after exceeding rate limit threshold"
3528        );
3529        assert!(
3530            !router.agent_is_routable(agent, "medium"),
3531            "degraded agent should not be routable"
3532        );
3533
3534        // Cleanup
3535        clear_agent_degraded(agent);
3536    }
3537
3538    // ---- route_with_llm candidate filter: agents with all models cooled (#3509) ----
3539
3540    #[serial(cooldown_state)]
3541    #[tokio::test]
3542    async fn agent_has_any_available_model_false_when_only_model_cooled() {
3543        cooldown::reset_global_state().await;
3544        let mut config = RouterConfig::default();
3545        // Agent's only model, shared across every complexity tier it resolves to.
3546        for tier in ["simple", "medium", "complex", "review"] {
3547            config
3548                .model_map
3549                .entry(tier.to_string())
3550                .or_default()
3551                .insert(
3552                    "test_all_cooled".to_string(),
3553                    vec!["only-model".to_string()],
3554                );
3555        }
3556
3557        let mut router = Router::new(config);
3558        router.available_agents = vec!["test_all_cooled".to_string()];
3559
3560        assert!(router.agent_has_any_available_model("test_all_cooled"));
3561
3562        record_model_failure("test_all_cooled", "only-model").await;
3563        assert!(is_model_in_cooldown("test_all_cooled", "only-model"));
3564
3565        assert!(
3566            !router.agent_has_any_available_model("test_all_cooled"),
3567            "agent with its only model cooled across every tier should have no available model"
3568        );
3569    }
3570
3571    #[serial(cooldown_state)]
3572    #[tokio::test]
3573    async fn llm_candidate_excludes_agent_with_all_models_cooled() {
3574        // Regression test for #3509: route_with_llm's candidate filter must exclude an
3575        // agent that has no agent-level cooldown but whose only resolvable model (across
3576        // every complexity tier) is cooled, so it is never handed to the LLM classifier.
3577        cooldown::reset_global_state().await;
3578        let mut config = RouterConfig::default();
3579        for tier in ["simple", "medium", "complex", "review"] {
3580            config
3581                .model_map
3582                .entry(tier.to_string())
3583                .or_default()
3584                .insert("agent_cooled_model".to_string(), vec!["opus".to_string()]);
3585            config
3586                .model_map
3587                .get_mut(tier)
3588                .unwrap()
3589                .insert("agent_healthy".to_string(), vec!["model-x".to_string()]);
3590        }
3591
3592        let mut router = Router::new(config);
3593        router.available_agents = vec![
3594            "agent_cooled_model".to_string(),
3595            "agent_healthy".to_string(),
3596        ];
3597
3598        record_model_failure("agent_cooled_model", "opus").await;
3599        assert!(is_model_in_cooldown("agent_cooled_model", "opus"));
3600        // No agent-level cooldown — the old agent-only filter would still offer it.
3601        assert!(!is_agent_in_cooldown("agent_cooled_model"));
3602
3603        let uncooled_agents: Vec<String> = router
3604            .available_agents
3605            .iter()
3606            .filter(|a| {
3607                !is_agent_in_cooldown(a)
3608                    && !is_agent_degraded(a)
3609                    && router.agent_has_available_model_for_coding_tiers(a)
3610            })
3611            .cloned()
3612            .collect();
3613
3614        assert_eq!(
3615            uncooled_agents,
3616            vec!["agent_healthy".to_string()],
3617            "agent whose only model is cooled must be excluded from the LLM candidate list"
3618        );
3619    }
3620
3621    #[serial(cooldown_state)]
3622    #[tokio::test]
3623    async fn llm_candidate_excludes_agent_with_only_simple_tier_uncooled() {
3624        // Regression test for #3521: an agent whose only healthy tier is `simple`
3625        // (its `medium`/`complex` tiers resolve to the same cooled model) must be
3626        // excluded from the LLM classification candidate list, otherwise the
3627        // classifier can pick it for a `medium`/`complex` task it can't serve,
3628        // wasting the classification call. Mirrors the real-world shape where
3629        // `simple` → sonnet (uncooled) and `medium`/`complex` → opus (cooled).
3630        cooldown::reset_global_state().await;
3631        let mut config = RouterConfig::default();
3632        config
3633            .model_map
3634            .entry("simple".to_string())
3635            .or_default()
3636            .insert("minimax_like".to_string(), vec!["sonnet".to_string()]);
3637        config
3638            .model_map
3639            .entry("medium".to_string())
3640            .or_default()
3641            .insert("minimax_like".to_string(), vec!["opus".to_string()]);
3642        config
3643            .model_map
3644            .entry("complex".to_string())
3645            .or_default()
3646            .insert("minimax_like".to_string(), vec!["opus".to_string()]);
3647        // review must be irrelevant to the coding-tier filter
3648        config
3649            .model_map
3650            .entry("review".to_string())
3651            .or_default()
3652            .insert("minimax_like".to_string(), vec!["opus".to_string()]);
3653        for tier in ["simple", "medium", "complex", "review"] {
3654            config
3655                .model_map
3656                .get_mut(tier)
3657                .unwrap()
3658                .insert("agent_healthy".to_string(), vec!["model-x".to_string()]);
3659        }
3660
3661        let mut router = Router::new(config);
3662        router.available_agents = vec!["minimax_like".to_string(), "agent_healthy".to_string()];
3663
3664        record_model_failure("minimax_like", "opus").await;
3665        assert!(is_model_in_cooldown("minimax_like", "opus"));
3666        // No agent-level cooldown, and the simple tier is healthy, so the loose
3667        // "any tier" check still passes — this is exactly the leak #3511 missed.
3668        assert!(!is_agent_in_cooldown("minimax_like"));
3669        assert!(router.agent_has_any_available_model("minimax_like"));
3670        assert!(!router.agent_has_available_model_for_coding_tiers("minimax_like"));
3671
3672        let uncooled_agents: Vec<String> = router
3673            .available_agents
3674            .iter()
3675            .filter(|a| {
3676                !is_agent_in_cooldown(a)
3677                    && !is_agent_degraded(a)
3678                    && router.agent_has_available_model_for_coding_tiers(a)
3679            })
3680            .cloned()
3681            .collect();
3682
3683        assert_eq!(
3684            uncooled_agents,
3685            vec!["agent_healthy".to_string()],
3686            "agent with only its simple tier uncooled must be excluded from the LLM candidate list"
3687        );
3688    }
3689}