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::cooldown;
25use crate::cooldown::{
26    cooldown_until, is_agent_degraded, is_agent_in_cooldown, is_model_in_cooldown,
27    list_degraded_agents, record_agent_success, refresh_degraded_agents, sync_from_kv,
28};
29use crate::engine::agents::opencode;
30use crate::store::WaitingOnDependency;
31use crate::store::{TaskStore, get_task_field_direct, store_log_activity};
32use crate::sys::cmd_cache;
33pub use config::{RouterConfig, parse_pool_entry};
34use llm::{LlmRouter, TIMEOUT_PREFIX};
35use serde::{Deserialize, Serialize};
36use std::fmt;
37use std::fmt::Debug;
38use std::fmt::Formatter;
39use std::sync::Arc;
40use tokio::task;
41pub use weights::AgentWeights;
42
43fn fmt_degraded(degraded: &[String]) -> String {
44    if degraded.is_empty() {
45        String::new()
46    } else {
47        format!(" (degraded: {})", degraded.join(", "))
48    }
49}
50
51/// A turn-cap error comes from the router command line (`--max-turns 1`)
52fn is_max_turns_error(err_msg: &str) -> bool {
53    let lower = err_msg.to_ascii_lowercase();
54    lower.contains("max turns reached") || lower.contains("reached the maximum number of turns")
55}
56
57/// Error returned when all agents/models are in cooldown and routing is temporarily unavailable.
58///
59/// This is a transient error that should not count against `max_route_attempts` since
60/// no agent was actually invoked. The caller should back off and retry later.
61#[derive(Debug, thiserror::Error)]
62pub enum AllAgentsCooledError {
63    #[error("all agents/models in cooldown for {scope}{}", fmt_degraded(.degraded))]
64    AllCooled {
65        scope: String,
66        remaining_secs: Option<u64>,
67        degraded: Vec<String>,
68    },
69}
70
71impl AllAgentsCooledError {
72    /// Create a new error for the given scope, naming currently degraded agents
73    pub fn new(scope: String, remaining_secs: Option<u64>) -> Self {
74        Self::AllCooled {
75            scope,
76            remaining_secs,
77            degraded: list_degraded_agents()
78                .into_iter()
79                .map(|(agent, _reason)| agent)
80                .collect(),
81        }
82    }
83
84    // LLM bypass helpers moved to `impl Router` so they can access Router fields.
85
86    /// Get the scope of the cooldown (e.g., "medium", "all agents", "router pool").
87    pub fn scope(&self) -> &str {
88        match self {
89            Self::AllCooled { scope, .. } => scope,
90        }
91    }
92
93    /// Remaining cooldown duration in seconds when available.
94    pub fn remaining_secs(&self) -> Option<u64> {
95        match self {
96            Self::AllCooled { remaining_secs, .. } => *remaining_secs,
97        }
98    }
99
100    /// Agents currently marked degraded, shown by `orch cooldown list`
101    pub fn degraded(&self) -> &[String] {
102        match self {
103            Self::AllCooled { degraded, .. } => degraded,
104        }
105    }
106}
107
108/// Typed error returned by [`get_route_result`].
109#[derive(Debug, thiserror::Error)]
110pub enum RouteResultError {
111    /// The task has no agent field — it needs to be re-routed.
112    #[error("no agent configured for task {task_id}")]
113    NoAgent { task_id: String },
114    /// Any other failure (store lookup, SQL, etc.).
115    #[error(transparent)]
116    Other(#[from] anyhow::Error),
117}
118
119/// Result of routing a task to an agent.
120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
121pub struct RouteResult {
122    /// The selected agent: "claude", "codex", or "opencode"
123    pub agent: String,
124    /// Optional model suggestion, e.g., "claude-sonnet-4-6", "claude-opus-4-6", "o3"
125    pub model: Option<String>,
126    /// Complexity level: "simple", "medium", or "complex"
127    pub complexity: String,
128    /// Fibonacci effort estimate (1, 2, 3, 5, 8, 13, or 21). 0 means not provided.
129    pub estimate: u8,
130    /// Why this agent was selected
131    pub reason: String,
132    /// Specialized agent profile (role, tools, constraints)
133    pub profile: AgentProfile,
134    /// Optional warning about routing decision
135    pub warning: Option<String>,
136}
137
138/// Specialized agent profile for a task.
139#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
140pub struct AgentProfile {
141    /// Role name, e.g., "backend specialist"
142    pub role: String,
143    /// Tools allowed for this task
144    pub tools: Vec<String>,
145    /// Constraints for this task
146    pub constraints: Vec<String>,
147    /// The model/effort choice associated with this route, cleared on failover.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub execution: Option<config::NamedProfile>,
150}
151
152impl AgentProfile {
153    /// Build the default "general" profile from router config.
154    pub fn default_from_config(config: &RouterConfig) -> Self {
155        Self {
156            role: "general".to_string(),
157            tools: config.allowed_tools.clone(),
158            constraints: vec![],
159            execution: None,
160        }
161    }
162}
163
164impl RouteResult {
165    /// The model for the task's tier, or one from the nearest tier with a free model. The warning
166    /// names the tier used when it differs, so the switch shows in the route activity
167    pub(crate) fn resolve_model(
168        config: &RouterConfig,
169        agent: &str,
170        complexity: &str,
171        task_id: &str,
172    ) -> (Option<String>, Option<String>) {
173        match config.model_for_complexity_or_adjacent(agent, complexity, task_id) {
174            Some((model, tier)) if tier != complexity => {
175                let warning =
176                    format!("no available {complexity} model for {agent}; using {tier} tier");
177                (Some(model), Some(warning))
178            }
179            Some((model, _)) => (Some(model), None),
180            None => (None, None),
181        }
182    }
183
184    /// Build a standard route result from the three task-specific values.
185    ///
186    /// Fills `profile` and `warning` with router-config defaults so call sites
187    /// only need to supply what varies per task.
188    pub fn from_config(
189        agent: String,
190        complexity: String,
191        reason: String,
192        config: &RouterConfig,
193        task_id: &str,
194    ) -> Self {
195        let (model, warning) = Self::resolve_model(config, &agent, &complexity, task_id);
196        Self {
197            agent,
198            model,
199            complexity,
200            estimate: 0,
201            reason,
202            profile: AgentProfile::default_from_config(config),
203            warning,
204        }
205    }
206}
207
208/// The agent router.
209#[expect(
210    clippy::struct_field_names,
211    reason = "the router holds sub-routers whose names say which backend they use"
212)]
213pub struct Router {
214    /// Router configuration
215    pub config: RouterConfig,
216    /// Available agents discovered at runtime
217    pub available_agents: Vec<String>,
218    /// Per-agent rate limit weights (used when weighted_round_robin is enabled)
219    pub weights: AgentWeights,
220    /// LLM routing subsystem (wrapped in Arc so callers can clone a handle
221    /// without holding the router RwLock across async operations)
222    llm_router: Arc<LlmRouter>,
223    /// Ollama router for local routing (contains reusable reqwest::Client)
224    ollama_router: Option<ollama::OllamaRouter>,
225    /// Round-robin index for task routing
226    pub(crate) rr_index: usize,
227    /// Last agent routed to (for distribution tracking)
228    pub(crate) last_agent: Option<String>,
229    /// Round-robin index for review agent selection
230    pub(crate) review_rr_index: usize,
231    /// Expanded pool of (agent, model) pairs for router LLM round-robin.
232    /// `opencode:free` entries are expanded at construction time.
233    pub(crate) router_pool: Vec<(String, String)>,
234    /// Current round-robin index into router_pool
235    pub(crate) pool_index: usize,
236}
237
238impl Debug for Router {
239    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
240        f.debug_struct("Router")
241            .field("config", &self.config)
242            .field("available_agents", &self.available_agents)
243            .field("weights", &self.weights)
244            .field("ollama_router", &self.ollama_router)
245            .field("rr_index", &self.rr_index)
246            .field("last_agent", &self.last_agent)
247            .field("review_rr_index", &self.review_rr_index)
248            .field("router_pool", &self.router_pool)
249            .field("pool_index", &self.pool_index)
250            .finish_non_exhaustive()
251    }
252}
253
254impl Router {
255    pub fn available_agent_count(&self) -> usize {
256        self.available_agents.len()
257    }
258
259    /// Agents are installed but every review agent is cooled down or degraded
260    pub fn review_agents_all_cooled(&self) -> bool {
261        !self.available_agents.is_empty() && self.healthy_agent_count("review") == 0
262    }
263
264    pub fn has_routable_review_agent(&self) -> bool {
265        !self.available_agents.is_empty() && self.healthy_agent_count("review") > 0
266    }
267
268    pub fn model_for_complexity(
269        &self,
270        agent: &str,
271        complexity: &str,
272        task_id: &str,
273    ) -> Option<String> {
274        self.config.model_for_complexity(agent, complexity, task_id)
275    }
276
277    /// Create a new router with the given configuration.
278    pub fn new(config: RouterConfig) -> Self {
279        let available_agents = Self::discover_agents(&config.agents);
280        let weights = config.agent_weights(&available_agents);
281        let router_pool = Self::expand_pool(&config);
282        tracing::info!(
283            pool = ?router_pool,
284            fallback = %config.effective_fallback(),
285            "router LLM pool initialized"
286        );
287        // Prime only when this config names opencode, so a default or claude-only
288        // router never runs `opencode models`
289        if config.uses_opencode() {
290            opencode::prime_free_model_cache();
291        }
292        let ollama_router = if config.mode == "local" {
293            Some(ollama::OllamaRouter::new(&config))
294        } else {
295            None
296        };
297        Self {
298            config,
299            available_agents,
300            weights,
301            llm_router: Arc::new(LlmRouter::new()),
302            ollama_router,
303            rr_index: 0,
304            last_agent: None,
305            review_rr_index: 0,
306            router_pool,
307            pool_index: 0,
308        }
309    }
310
311    /// Create a router with default configuration loaded from files.
312    pub fn from_config() -> Self {
313        Self::new(RouterConfig::from_config())
314    }
315
316    /// Create a router with a forced agent list, bypassing CLI discovery.
317    /// Only for use in unit tests.
318    #[cfg(test)]
319    pub(crate) fn new_for_test(config: RouterConfig, available_agents: Vec<String>) -> Self {
320        let mut weights = AgentWeights {
321            base_weights: config.weights.clone(),
322            ..Default::default()
323        };
324        weights.ensure_agents(&available_agents);
325        let router_pool = Self::expand_pool(&config);
326        Self {
327            config,
328            available_agents,
329            weights,
330            llm_router: Arc::new(LlmRouter::new()),
331            ollama_router: None,
332            rr_index: 0,
333            last_agent: None,
334            review_rr_index: 0,
335            router_pool,
336            pool_index: 0,
337        }
338    }
339
340    fn advance_pool_index_after_attempt(&mut self, idx: usize, pool_len: usize) {
341        debug_assert!(pool_len > 0, "router pool must not be empty");
342        self.pool_index = (idx + 1) % pool_len;
343    }
344
345    /// Discover available agent CLIs in PATH.
346    /// Checks all agents from the configured list.
347    fn discover_agents(configured_agents: &[String]) -> Vec<String> {
348        let mut agents = Vec::new();
349        for agent in configured_agents {
350            if cmd_cache::command_exists(agent) {
351                agents.push(agent.clone());
352            }
353        }
354        agents
355    }
356
357    /// Expand the router LLM pool, resolving `opencode:free` to discovered free models.
358    ///
359    /// - Entries other than `opencode:free` are parsed as `agent:model` and added as-is.
360    /// - `opencode:free` is expanded by running `opencode models | grep free` at startup.
361    /// - If `opencode` is not installed or the command fails, the entry is skipped.
362    /// - If the expanded pool is empty, falls back to a single entry from `effective_fallback()`.
363    fn expand_pool(config: &RouterConfig) -> Vec<(String, String)> {
364        let raw_pool = config.effective_pool();
365        let mut expanded: Vec<(String, String)> = Vec::new();
366
367        for entry in &raw_pool {
368            if entry == "opencode:free" {
369                let free_models = Self::discover_free_opencode_models();
370                if free_models.is_empty() {
371                    tracing::debug!("opencode:free expanded to nothing — skipping");
372                } else {
373                    tracing::debug!(models = ?free_models, "opencode:free expanded");
374                    for model in free_models {
375                        expanded.push(("opencode".to_string(), model));
376                    }
377                }
378            } else {
379                let (agent, model) = parse_pool_entry(entry);
380                expanded.push((agent, model));
381            }
382        }
383
384        if expanded.is_empty() {
385            // All entries were opencode:free and opencode isn't installed — use fallback
386            let (agent, model) = parse_pool_entry(&config.effective_fallback());
387            tracing::debug!(
388                agent = %agent, model = %model,
389                "pool empty after expansion, using fallback as sole pool entry"
390            );
391            expanded.push((agent, model));
392        }
393
394        expanded
395    }
396
397    /// Async version of expand_pool which may query the opencode CLI without
398    /// blocking the Tokio runtime.
399    async fn expand_pool_async(config: &RouterConfig) -> Vec<(String, String)> {
400        let raw_pool = config.effective_pool();
401        let mut expanded: Vec<(String, String)> = Vec::new();
402
403        for entry in &raw_pool {
404            if entry == "opencode:free" {
405                let free_models = Self::discover_free_opencode_models_async().await;
406                if free_models.is_empty() {
407                    tracing::debug!("opencode:free expanded to nothing — skipping (async)");
408                } else {
409                    tracing::debug!(models = ?free_models, "opencode:free expanded (async)");
410                    for model in free_models {
411                        expanded.push(("opencode".to_string(), model));
412                    }
413                }
414            } else {
415                let (agent, model) = parse_pool_entry(entry);
416                expanded.push((agent, model));
417            }
418        }
419
420        if expanded.is_empty() {
421            // All entries were opencode:free and opencode isn't installed — use fallback
422            let (agent, model) = parse_pool_entry(&config.effective_fallback());
423            tracing::debug!(
424                agent = %agent, model = %model,
425                "pool empty after async expansion, using fallback as sole pool entry"
426            );
427            expanded.push((agent, model));
428        }
429
430        expanded
431    }
432
433    /// Async reload that uses async pool expansion to avoid blocking the runtime
434    /// when discovering opencode free models.
435    pub async fn reload_async(&mut self) {
436        let new_config = RouterConfig::from_config();
437        let new_agents = Self::discover_agents(&new_config.agents);
438        let new_pool = Self::expand_pool_async(&new_config).await;
439        tracing::info!(
440            mode = %new_config.mode,
441            agents = ?new_agents,
442            fallback = %new_config.fallback_executor,
443            weighted_rr = new_config.weighted_round_robin,
444            pool = ?new_pool,
445            "router reloaded (async)"
446        );
447        self.config = new_config;
448        self.available_agents.clone_from(&new_agents);
449        // Ensure new agents have weight entries (preserves existing weights)
450        self.weights.ensure_agents(&new_agents);
451        self.router_pool = new_pool;
452        self.pool_index = 0;
453        // Reinitialize Ollama router if mode changed to local
454        self.ollama_router = if self.config.mode == "local" {
455            Some(ollama::OllamaRouter::new(&self.config))
456        } else {
457            None
458        };
459    }
460
461    fn discover_free_opencode_models() -> Vec<String> {
462        opencode::discover_free_opencode_models()
463    }
464
465    async fn discover_free_opencode_models_async() -> Vec<String> {
466        task::spawn_blocking(Self::discover_free_opencode_models)
467            .await
468            .unwrap_or_default()
469    }
470
471    /// Run the pre-emptive health check, refreshing the degraded-agent set.
472    ///
473    /// Queries the `rate_limits` table for recent events and combines with
474    /// cooldown state to mark agents as degraded before routing attempts them.
475    pub async fn refresh_health(&self, store: &Arc<TaskStore>) {
476        // KV is the source of truth for cooldowns. Reconcile the in-memory map
477        // from KV every tick so external mutations (e.g. `orch cooldown clear`
478        // from a separate CLI process) actually take effect on the running
479        // service. Without this, the engine keeps stale entries until they
480        // expire on their own, producing the "all agents cooled" log with
481        // `orch cooldown list` simultaneously reporting "No active cooldowns".
482        sync_from_kv(store).await;
483
484        let agents = self.available_agents.clone();
485        let model_checker = |agent: &str| -> bool { self.agent_has_any_available_model(agent) };
486        refresh_degraded_agents(
487            store,
488            &agents,
489            &model_checker,
490            config::health_check_window_hours(),
491            config::degraded_rate_limit_threshold(),
492        )
493        .await;
494    }
495
496    /// Check if an agent is available.
497    pub fn is_agent_available(&self, agent: &str) -> bool {
498        self.available_agents.contains(&agent.to_string())
499    }
500
501    /// True if the agent has at least one uncooled model across any complexity
502    /// tier. Used where the eventual complexity isn't known yet (e.g. before
503    /// LLM classification), so we can't check a single tier.
504    fn agent_has_any_available_model(&self, agent: &str) -> bool {
505        ["simple", "medium", "complex", "review"]
506            .iter()
507            .any(|comp| self.config.has_available_model_for_complexity(agent, comp))
508    }
509
510    /// True if the agent has an available (uncooled) model for the `medium`
511    /// and `complex` tiers — the tiers real coding tasks are classified into
512    /// by the LLM classifier. Used to pre-filter the candidate list handed to
513    /// that classifier so an agent whose healthy tiers are only `simple` isn't
514    /// offered: the classifier can't be constrained to `simple`, so offering
515    /// such an agent produces a near-certain wasted classification call whenever
516    /// it picks `medium`/`complex` (issue #3521). `review` is not a candidate
517    /// outcome of initial classification and is deliberately excluded.
518    fn agent_has_available_model_for_coding_tiers(&self, agent: &str) -> bool {
519        ["medium", "complex"]
520            .iter()
521            .all(|comp| self.config.has_available_model_for_complexity(agent, comp))
522    }
523
524    fn agent_is_routable(&self, agent: &str, complexity: &str) -> bool {
525        if !self.is_agent_available(agent) {
526            return false;
527        }
528        if is_agent_in_cooldown(agent) {
529            tracing::debug!(agent, "agent skipped: in cooldown");
530            return false;
531        }
532        if is_agent_degraded(agent) {
533            tracing::debug!(agent, "agent skipped: degraded (pre-emptive health check)");
534            return false;
535        }
536        // If weighted routing is used, consider the agent degraded when its
537        // weight has decayed below the threshold. This avoids
538        // proactively routing to agents that recently hit many rate limits.
539        if self.config.weighted_round_robin {
540            let weight = self.weights.get_weight(agent);
541            if weight < config::SKIP_LIMITED_THRESHOLD {
542                tracing::debug!(
543                    agent,
544                    weight,
545                    "agent considered degraded by weight threshold, skipping"
546                );
547                return false;
548            }
549        }
550        if !self
551            .config
552            .has_available_model_in_any_tier(agent, complexity)
553        {
554            tracing::debug!(agent, complexity, "agent skipped: no available model");
555            return false;
556        }
557        true
558    }
559
560    fn available_agents_for_complexity(&self, complexity: &str) -> Vec<String> {
561        self.available_agents
562            .iter()
563            .filter(|agent| self.agent_is_routable(agent, complexity))
564            .cloned()
565            .collect()
566    }
567
568    /// Count of healthy (routable) agents for a given complexity.
569    /// Returns the number of agents that are available, not in cooldown, and have an available model.
570    pub fn healthy_agent_count(&self, complexity: &str) -> usize {
571        self.available_agents_for_complexity(complexity).len()
572    }
573
574    /// Check if the system is in degraded mode (fewer than threshold healthy agents).
575    /// Uses "simple" complexity as the baseline since it has the widest model support.
576    pub fn is_degraded(&self, threshold: usize) -> bool {
577        self.healthy_agent_count("simple") < threshold
578    }
579
580    pub fn earliest_cooldown_until(&self, complexity: Option<&str>) -> Option<i64> {
581        let mut earliest: Option<i64> = None;
582
583        for agent in &self.available_agents {
584            if let Some(until) = cooldown_until(agent) {
585                earliest = Some(earliest.map_or(until, |current| current.min(until)));
586            }
587
588            if let Some(comp) = complexity
589                && let Some(pool) = self.config.model_pool_for_complexity(agent, comp)
590            {
591                for model in pool {
592                    let key = format!("{agent}:{model}");
593                    if let Some(until) = cooldown_until(&key) {
594                        earliest = Some(earliest.map_or(until, |current| current.min(until)));
595                    }
596                }
597            }
598        }
599
600        earliest
601    }
602
603    /// Find the earliest cooldown expiration among the router LLM pool entries.
604    ///
605    /// Returns `Some(earliest_ts)` if at least one pool model is on cooldown,
606    /// or `None` if no pool model has a cooldown.
607    fn earliest_pool_cooldown(&self) -> Option<i64> {
608        let mut earliest: Option<i64> = None;
609        for (agent, model) in &self.router_pool {
610            let key = format!("{agent}:{model}");
611            if let Some(until) = cooldown_until(&key) {
612                earliest = Some(earliest.map_or(until, |current| current.min(until)));
613            }
614        }
615        earliest
616    }
617
618    fn wait_for_cooldown(&self, complexity: Option<&str>) -> anyhow::Result<()> {
619        // If any cooldowns are present, return an error immediately so the
620        // caller (the tick loop) can skip this task and retry on the next tick.
621        // Sleeping inside the router blocks the entire tick loop for the
622        // cooldown duration which starves other tasks. The engine tick already
623        // retries every `tick_interval` (default 10s), so allow the tick loop
624        // to drive retries instead of sleeping here.
625        let now = chrono::Utc::now().timestamp();
626        let Some(earliest) = self.earliest_cooldown_until(complexity) else {
627            // All agents are degraded but none have a timed cooldown entry
628            // (e.g. over-threshold rate limiting without explicit cooldown duration).
629            // Log at warn and return an error so the tick skips this task and retries after backoff.
630            tracing::warn!(
631                scope = complexity.unwrap_or("all agents"),
632                "all agents degraded (no cooldown timestamp available) — skipping task, will retry after backoff"
633            );
634            // Return an error similar to the cooldown case to trigger backoff in the tick loop
635            return Err(AllAgentsCooledError::new(
636                complexity.unwrap_or("all agents").to_string(),
637                None,
638            )
639            .into());
640        };
641
642        let remaining = earliest.saturating_sub(now);
643        if remaining > 0 {
644            let scope_str = complexity.unwrap_or("all agents").to_string();
645            tracing::warn!(
646                remaining_secs = remaining,
647                scope = %scope_str,
648                "all agents/models cooled — routing is unavailable until cooldown expires; failing fast to let tick retry"
649            );
650            // Return a domain error indicating all candidates are cooled so the
651            // caller can handle it (tick will skip this task and retry later).
652            return Err(AllAgentsCooledError::new(scope_str, u64::try_from(remaining).ok()).into());
653        }
654
655        Ok(())
656    }
657
658    /// Get the first available agent.
659    /// Pick next agent via round-robin (for review or other non-task routing).
660    /// Pick the next review agent, optionally excluding one (e.g. the task's original agent).
661    /// Falls back to the first candidate whenever every candidate is excluded (#3645).
662    pub fn next_round_robin_agent(&mut self, exclude: &[&str], complexity: &str) -> Option<String> {
663        // Use available_agents_for_complexity which already filters using agent_is_routable,
664        // eliminating duplicate cooldown/degraded/model checks.
665        let candidates = self.available_agents_for_complexity(complexity);
666        if candidates.is_empty() {
667            return None;
668        }
669        let idx = self.review_rr_index;
670        let n = candidates.len();
671
672        // Try to find an agent that isn't excluded
673        let agent = (0..n)
674            .map(|offset| &candidates[(idx + offset) % n])
675            .find(|a| !exclude.contains(&a.as_str()))
676            .cloned()
677            // Fallback: use the first available candidate (even if excluded)
678            .or_else(|| candidates.first().cloned())?;
679
680        self.review_rr_index = (idx + 1) % candidates.len().max(1);
681        Some(agent)
682    }
683
684    /// If the selected agent matches `no_code_last_agent` for this task, filter it
685    /// out of the candidates and return the filtered list. Used to prevent the
686    /// same agent from being selected twice in a row after a no-code failure (#2410).
687    async fn skip_no_code_agent(
688        &self,
689        store: &Arc<TaskStore>,
690        repo: &str,
691        task_id: &str,
692        candidates: &[String],
693    ) -> Option<Vec<String>> {
694        let no_code_agent = get_task_field_direct(store, repo, task_id, "no_code_last_agent")
695            .await
696            .unwrap_or_else(|| {
697                tracing::warn!(
698                    task_id,
699                    "no_code_last_agent DB read returned None — loop detection may be impaired"
700                );
701                String::new()
702            });
703        if no_code_agent.is_empty() || !candidates.iter().any(|a| a == &no_code_agent) {
704            return None;
705        }
706        let filtered: Vec<String> = candidates
707            .iter()
708            .filter(|a| a.as_str() != no_code_agent)
709            .cloned()
710            .collect();
711        if filtered.is_empty() {
712            tracing::warn!(
713                task_id,
714                no_code_agent = %no_code_agent,
715                "all available agents are the no-code agent — cannot skip"
716            );
717            return None;
718        }
719        tracing::info!(
720            task_id,
721            skipped = %no_code_agent,
722            remaining = ?filtered,
723            "skipping no-code agent, routing to alternative"
724        );
725        Some(filtered)
726    }
727
728    /// Route a task to the best agent.
729    ///
730    /// Routing logic (in priority order):
731    /// 1. Check for `agent:*` label — use that agent directly
732    /// 2. If weighted_round_robin enabled, select by capacity-weighted probability
733    /// 3. If round_robin mode, cycle through agents (stateful)
734    /// 4. Call LLM classifier for intelligent routing
735    /// 5. After max_route_attempts LLM failures, fall back to round-robin
736    pub async fn route(
737        &mut self,
738        task: &ExternalTask,
739        store: &Arc<TaskStore>,
740        repo: &str,
741    ) -> anyhow::Result<RouteResult> {
742        // NOTE: refresh_health() is called once per tick in tick_route_tasks()
743        // before the routing loop, not per-task. Do not re-add it here.
744
745        // Hold the task before any classification, label override, or fallback.
746        // A waiting task must not increment route_attempts.
747        match store.resolve_id_by_external(repo, &task.id.0).await {
748            Ok(Some(id)) => match store.block_claim_if_waiting(id).await {
749                Ok(Some(blockers)) => {
750                    return Err(WaitingOnDependency { blockers }.into());
751                }
752                Ok(None) => {}
753                Err(err) => return Err(err),
754            },
755            Ok(None) => {}
756            Err(err) => return Err(err),
757        }
758
759        loop {
760            // 1. Check store agent field first (set by failover, authoritative over labels)
761            // Use a lightweight lookup to avoid deserializing the full Task row when
762            // only the `agent` column is needed. This avoids two full-row loads
763            // per routing pass (resolve_task_id + get) and significantly reduces
764            // CPU work on busy instances.
765            let store_agent = match store.get_agent_by_external_id(repo, &task.id.0).await {
766                Ok(Some(agent)) => {
767                    // Router enforces that the agent string matches a configured agent
768                    if !agent.is_empty() && self.config.has_agent(&agent) {
769                        Some(agent)
770                    } else {
771                        None
772                    }
773                }
774                Ok(None) => None,
775                Err(e) => {
776                    tracing::warn!(
777                        repo,
778                        task_id = %task.id.0,
779                        err = %e,
780                        "failed to fetch stored agent, falling back to label/LLM routing"
781                    );
782                    None
783                }
784            };
785
786            // Named profiles select a route after dependencies and stored recovery.
787            if store_agent.is_none()
788                && let Some(result) = self.route_profile(task)?
789            {
790                self.log_route_activity(store, repo, &task.id.0, &result, None)
791                    .await;
792                return Ok(result);
793            }
794
795            // 2. Fall back to explicit agent label
796            let resolved_agent = store_agent.or_else(|| {
797                strategies::extract_agent_from_labels(&self.config.agents, &task.labels)
798            });
799
800            if let Some(agent) = resolved_agent {
801                let complexity = strategies::extract_complexity_from_labels(&task.labels);
802                // If agent appears routable (not in agent-wide cooldown and has
803                // available models or no model_map configured), check whether
804                // we actually have a concrete model to dispatch. If the
805                // resolved label maps to no model (None), we fall through to
806                // the standard routing logic so the router LLM can pick a
807                // proper agent/model, instead of dispatching with an empty
808                // model which causes some agents (e.g. opencode) to exit
809                // silently.
810                if self.agent_is_routable(&agent, &complexity) {
811                    let (model, tier_warning) =
812                        RouteResult::resolve_model(&self.config, &agent, &complexity, &task.id.0);
813
814                    // Only dispatch label overrides when we have a concrete
815                    // model to send to the executor. Dispatching with an
816                    // empty model led to silent exits for some agents
817                    // (notably opencode). If no concrete model is available
818                    // for the labeled agent, fall through to the standard
819                    // routing logic so the LLM or round-robin can pick an
820                    // appropriate agent/model.
821                    if model.is_some() {
822                        tracing::debug!(
823                            task_id = %task.id.0,
824                            agent = %agent,
825                            complexity = %complexity,
826                            "routed via label"
827                        );
828                        let mut result = RouteResult::from_config(
829                            agent.clone(),
830                            complexity.clone(),
831                            format!("label agent:{agent}"),
832                            &self.config,
833                            &task.id.0,
834                        );
835                        // Label routing uses agent-specific role and the
836                        // resolved model (may differ from from_config's default).
837                        result.profile.role = format!("{agent} specialist");
838                        result.model = model.clone();
839                        result.warning = tier_warning;
840                        self.log_route_activity(store, repo, &task.id.0, &result, None)
841                            .await;
842                        return Ok(result);
843                    }
844                    // No concrete model found for the labeled agent — do
845                    // not honor the label override. Fall through to the
846                    // standard routing logic so another agent or the LLM
847                    // can be chosen with a valid model.
848                    tracing::warn!(task_id = %task.id.0, agent = %agent, "label agent has no available model — falling through to LLM routing");
849                }
850
851                let candidates = self.available_agents_for_complexity(&complexity);
852                if candidates.is_empty() {
853                    self.wait_for_cooldown(Some(&complexity))?;
854                    continue;
855                }
856                // Label target is cooled or lacked model; fall through to standard routing.
857            }
858
859            let complexity = strategies::extract_complexity_from_labels(&task.labels);
860
861            // Check if any agents have available models for this complexity
862            let mut candidates = self.available_agents_for_complexity(&complexity);
863            if candidates.is_empty() {
864                self.wait_for_cooldown(Some(&complexity))?;
865                continue;
866            }
867
868            // Skip the no-code agent if one is recorded for this task (#2410).
869            // If all available agents are filtered out, we fall through to
870            // LLM routing with no constraints (LLM will pick the same agent but
871            // the response_handler will block it immediately via same-agent check).
872            if let Some(filtered) = self
873                .skip_no_code_agent(store, repo, &task.id.0, &candidates)
874                .await
875            {
876                candidates = filtered;
877            }
878
879            // 2. Weighted round-robin — capacity-based selection
880            if self.config.weighted_round_robin {
881                let result = strategies::route_via_weighted_round_robin(
882                    &candidates,
883                    &self.weights,
884                    &self.config,
885                    task,
886                    &mut self.last_agent,
887                )?;
888                self.log_route_activity(store, repo, &task.id.0, &result, None)
889                    .await;
890                return Ok(result);
891            }
892
893            // 3. Round-robin mode — use stateful round-robin
894            if self.config.mode == "round_robin" || self.config.mode == "profile" {
895                tracing::debug!(task_id = %task.id.0, "routing via round-robin mode");
896                let result = strategies::route_via_round_robin_stateful(
897                    &candidates,
898                    &self.config,
899                    task,
900                    &mut self.rr_index,
901                    &mut self.last_agent,
902                )?;
903                self.log_route_activity(store, repo, &task.id.0, &result, None)
904                    .await;
905                return Ok(result);
906            }
907
908            // 4. Local Ollama routing
909            if self.config.mode == "local" {
910                tracing::debug!(task_id = %task.id.0, ollama_url = %self.config.ollama_url, "routing via local Ollama");
911                let ollama_router = self
912                    .ollama_router
913                    .as_ref()
914                    .expect("ollama_router must be initialized in Router::new when mode=local");
915                match ollama_router.route(task, &self.config).await {
916                    Ok(result) => {
917                        self.log_route_activity(store, repo, &task.id.0, &result, None)
918                            .await;
919                        return Ok(result);
920                    }
921                    Err(e) => {
922                        tracing::warn!(
923                            task_id = %task.id.0,
924                            error = %e,
925                            "Ollama routing failed, falling back to round-robin"
926                        );
927                        let result = strategies::route_via_round_robin_stateful(
928                            &candidates,
929                            &self.config,
930                            task,
931                            &mut self.rr_index,
932                            &mut self.last_agent,
933                        )?;
934                        self.log_route_activity(store, repo, &task.id.0, &result, None)
935                            .await;
936                        return Ok(result);
937                    }
938                }
939            }
940
941            // 5. LLM-based routing with retry tracking
942            let route_attempts = self.get_route_attempts(&task.id.0, store, repo).await;
943
944            if route_attempts >= self.config.max_route_attempts {
945                tracing::warn!(
946                    task_id = %task.id.0,
947                    attempts = route_attempts,
948                    max = self.config.max_route_attempts,
949                    "max LLM route attempts reached, falling back to round-robin"
950                );
951                let candidates = self.available_agents_for_complexity(&complexity);
952                if candidates.is_empty() {
953                    self.wait_for_cooldown(Some(&complexity))?;
954                    continue;
955                }
956                let result = strategies::route_via_round_robin_stateful(
957                    &candidates,
958                    &self.config,
959                    task,
960                    &mut self.rr_index,
961                    &mut self.last_agent,
962                )?;
963                self.log_route_activity(store, repo, &task.id.0, &result, None)
964                    .await;
965                return Ok(result);
966            }
967
968            // Log routing start (before await)
969            tracing::debug!(task_id = %task.id.0, "starting LLM routing");
970
971            match self.route_with_llm(task, repo).await {
972                Ok(result) => {
973                    let candidates = self.available_agents_for_complexity(&result.complexity);
974                    if candidates.is_empty() {
975                        self.wait_for_cooldown(Some(&result.complexity))?;
976                        continue;
977                    }
978
979                    // If the LLM selected the no-code agent, filter it out and
980                    // pick an alternative (#2410). Re-use the existing fallback logic.
981                    let no_code_agent =
982                         get_task_field_direct(store, repo, &task.id.0, "no_code_last_agent")
983                             .await
984                             .unwrap_or_else(|| {
985                                 tracing::warn!(task_id = %task.id.0, "no_code_last_agent DB read returned None — loop detection may be impaired");
986                                 String::new()
987                             });
988                    if result.agent == no_code_agent {
989                        // Pick the first agent that isn't the no-code agent.
990                        let fallback_agent = candidates
991                            .iter()
992                            .find(|a| a.as_str() != no_code_agent)
993                            .cloned()
994                            .unwrap_or_else(|| candidates[0].clone());
995                        if fallback_agent.as_str() == no_code_agent {
996                            tracing::warn!(
997                                task_id = %task.id.0,
998                                no_code_agent = %no_code_agent,
999                                complexity = %result.complexity,
1000                                "all available agents are the no-code agent — waiting for another agent"
1001                            );
1002                            self.wait_for_cooldown(Some(&result.complexity))?;
1003                            continue;
1004                        }
1005                        tracing::info!(
1006                            task_id = %task.id.0,
1007                            llm_selected = %result.agent,
1008                            skipped = %no_code_agent,
1009                            fallback = %fallback_agent,
1010                            "LLM selected the no-code agent — routing to alternative"
1011                        );
1012                        let (fallback_model, _) = RouteResult::resolve_model(
1013                            &self.config,
1014                            &fallback_agent,
1015                            &result.complexity,
1016                            &task.id.0,
1017                        );
1018
1019                        self.set_route_attempts(&task.id.0, 0, store, repo).await;
1020                        let result = RouteResult {
1021                            agent: fallback_agent.clone(),
1022                            model: fallback_model,
1023                            complexity: result.complexity.clone(),
1024                            estimate: result.estimate,
1025                            reason: format!(
1026                                "LLM selected no-code agent {}; routed to {}",
1027                                result.agent, fallback_agent
1028                            ),
1029                            profile: result.profile.clone(),
1030                            warning: Some(format!(
1031                                "LLM selected no-code agent {}; used fallback {}",
1032                                result.agent, fallback_agent
1033                            )),
1034                        };
1035                        self.log_route_activity(store, repo, &task.id.0, &result, None)
1036                            .await;
1037                        return Ok(result);
1038                    }
1039
1040                    let model_cooled = result
1041                        .model
1042                        .as_deref()
1043                        .is_some_and(|model| is_model_in_cooldown(&result.agent, model));
1044                    if !candidates.contains(&result.agent) || model_cooled {
1045                        let fallback_agent = candidates
1046                            .iter()
1047                            .find(|agent| *agent != &result.agent)
1048                            .cloned()
1049                            .unwrap_or_else(|| candidates[0].clone());
1050                        let (fallback_model, _) = RouteResult::resolve_model(
1051                            &self.config,
1052                            &fallback_agent,
1053                            &result.complexity,
1054                            &task.id.0,
1055                        );
1056
1057                        // If the fallback model is None and the fallback agent is the
1058                        // same as the LLM-selected agent, it means all models for the
1059                        // only available agent are cooled. In that case, wait for
1060                        // cooldowns instead of returning a RouteResult with
1061                        // model: None which would be dispatched incorrectly.
1062                        if fallback_model.is_none() && fallback_agent == result.agent {
1063                            tracing::warn!(
1064                                task_id = %task.id.0,
1065                                agent = %result.agent,
1066                                complexity = %result.complexity,
1067                                "LLM-selected model(s) are cooled for the only available agent; waiting for cooldown"
1068                            );
1069                            self.wait_for_cooldown(Some(&result.complexity))?;
1070                            continue;
1071                        }
1072
1073                        // Distinguish logging and reasons when we actually switch
1074                        // agents vs when we keep the same agent but pick a
1075                        // different (non-cooled) model.
1076                        if fallback_agent == result.agent {
1077                            tracing::warn!(
1078                                task_id = %task.id.0,
1079                                agent = %result.agent,
1080                                complexity = %result.complexity,
1081                                "LLM-selected model was cooled; selecting an alternative model for the same agent"
1082                            );
1083                        } else {
1084                            tracing::warn!(
1085                                task_id = %task.id.0,
1086                                agent = %result.agent,
1087                                fallback = %fallback_agent,
1088                                complexity = %result.complexity,
1089                                "LLM selected cooled agent/model; rerouting to available agent"
1090                            );
1091                        }
1092
1093                        // Reset attempts on success
1094                        self.set_route_attempts(&task.id.0, 0, store, repo).await;
1095
1096                        let reason = if fallback_agent == result.agent {
1097                            format!(
1098                                "LLM selected cooled model; using same agent {fallback_agent} with different model"
1099                            )
1100                        } else {
1101                            format!("LLM selected cooled agent/model; rerouted to {fallback_agent}")
1102                        };
1103
1104                        let result = RouteResult {
1105                            agent: fallback_agent.clone(),
1106                            model: fallback_model,
1107                            complexity: result.complexity.clone(),
1108                            estimate: result.estimate,
1109                            reason: reason.clone(),
1110                            profile: result.profile.clone(),
1111                            warning: Some(if fallback_agent == result.agent {
1112                                "LLM-selected model was cooled; selected alternative model for same agent"
1113                                    .to_string()
1114                            } else {
1115                                "LLM-selected agent/model was cooled; rerouted to available agent"
1116                                    .to_string()
1117                            }),
1118                        };
1119                        self.log_route_activity(store, repo, &task.id.0, &result, None)
1120                            .await;
1121                        return Ok(result);
1122                    }
1123
1124                    // Reset attempts on success
1125                    self.set_route_attempts(&task.id.0, 0, store, repo).await;
1126                    tracing::info!(
1127                        task_id = %task.id.0,
1128                        agent = %result.agent,
1129                        complexity = %result.complexity,
1130                        "routed via LLM"
1131                    );
1132                    self.log_route_activity(store, repo, &task.id.0, &result, None)
1133                        .await;
1134                    return Ok(result);
1135                }
1136                Err(e) => {
1137                    if let Some(err) = e.downcast_ref::<AllAgentsCooledError>() {
1138                        let scope = err.scope();
1139                        tracing::warn!(scope = %scope, "router cooldown gate tripped");
1140                        // "router pool" scope means all router LLM pool entries were pre-cooled.
1141                        // Pass None so wait_for_cooldown queries all agent+model cooldowns generically
1142                        // (no complexity-specific pool lookup, which would fail for "router pool").
1143                        let scope_opt = match scope {
1144                            "all agents" | "router pool" => None,
1145                            _ => Some(scope),
1146                        };
1147                        self.wait_for_cooldown(scope_opt)?;
1148                        continue;
1149                    }
1150
1151                    let new_attempts = route_attempts + 1;
1152                    self.set_route_attempts(&task.id.0, new_attempts, store, repo)
1153                        .await;
1154                    tracing::warn!(
1155                        task_id = %task.id.0,
1156                        error = %e,
1157                        error_chain = ?e,
1158                        attempt = new_attempts,
1159                        max = self.config.max_route_attempts,
1160                        "LLM routing failed"
1161                    );
1162
1163                    if new_attempts >= self.config.max_route_attempts {
1164                        tracing::info!(
1165                            task_id = %task.id.0,
1166                            "falling back to round-robin after {} failed attempts",
1167                            new_attempts
1168                        );
1169                        let candidates = self.available_agents_for_complexity(&complexity);
1170                        if candidates.is_empty() {
1171                            self.wait_for_cooldown(Some(&complexity))?;
1172                            continue;
1173                        }
1174                        let result = strategies::route_via_round_robin_stateful(
1175                            &candidates,
1176                            &self.config,
1177                            task,
1178                            &mut self.rr_index,
1179                            &mut self.last_agent,
1180                        )?;
1181                        self.log_route_activity(store, repo, &task.id.0, &result, None)
1182                            .await;
1183                        return Ok(result);
1184                    }
1185
1186                    let candidates = self.available_agents_for_complexity(&complexity);
1187                    if candidates.is_empty() {
1188                        self.wait_for_cooldown(Some(&complexity))?;
1189                        continue;
1190                    }
1191                    let result = strategies::route_via_fallback(
1192                        &candidates,
1193                        &self.config,
1194                        task,
1195                        Some(&self.weights),
1196                    )?;
1197                    self.log_route_activity(store, repo, &task.id.0, &result, None)
1198                        .await;
1199                    return Ok(result);
1200                }
1201            }
1202        }
1203    }
1204
1205    /// Get the number of LLM routing attempts for a task from the store.
1206    async fn get_route_attempts(&self, task_id: &str, store: &Arc<TaskStore>, repo: &str) -> u32 {
1207        match store.resolve_task_id(repo, task_id).await {
1208            Ok(Some(store_id)) => store
1209                .get(store_id)
1210                .await
1211                .map_or(0, |t| u32::try_from(t.route_attempts).unwrap_or(0)),
1212            _ => 0,
1213        }
1214    }
1215
1216    /// Set the number of LLM routing attempts for a task in the store.
1217    async fn set_route_attempts(
1218        &self,
1219        task_id: &str,
1220        attempts: u32,
1221        store: &Arc<TaskStore>,
1222        repo: &str,
1223    ) {
1224        if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
1225            && let Err(e) = store
1226                .set_fields(store_id, &[("route_attempts", serde_json::json!(attempts))])
1227                .await
1228        {
1229            tracing::warn!(task_id, error = %e, "failed to store route_attempts");
1230        }
1231    }
1232
1233    /// Log a route event to task activity timeline.
1234    async fn log_route_activity(
1235        &self,
1236        store: &Arc<TaskStore>,
1237        repo: &str,
1238        task_id: &str,
1239        result: &RouteResult,
1240        from_agent: Option<&str>,
1241    ) {
1242        let details = serde_json::json!({
1243            "reason": result.reason,
1244            "complexity": result.complexity,
1245            "role": result.profile.role,
1246            "warning": result.warning,
1247        });
1248        let event_type = if from_agent.is_some() {
1249            "rerouted"
1250        } else {
1251            "routed"
1252        };
1253        store_log_activity(
1254            &Some(Arc::clone(store)),
1255            repo,
1256            task_id,
1257            event_type,
1258            None,
1259            Some("routed"),
1260            Some(&result.agent),
1261            result.model.as_deref(),
1262            Some(&details),
1263        )
1264        .await;
1265    }
1266
1267    /// Route using LLM classification with pool round-robin.
1268    ///
1269    /// Iterates through `router_pool` (skipping cooled entries) until one succeeds.
1270    /// On full exhaustion, tries the configured fallback. If the fallback also fails,
1271    /// returns the last error (the caller falls back to round-robin agent selection).
1272    async fn route_with_llm(
1273        &mut self,
1274        task: &ExternalTask,
1275        repo: &str,
1276    ) -> anyhow::Result<RouteResult> {
1277        // Filter out cooled and degraded agents, and agents without an available
1278        // model for the coding tiers (`medium`/`complex`) that real tasks are
1279        // classified into, so the LLM only sees candidates that could actually
1280        // be dispatched for whatever complexity it picks. An agent whose only
1281        // healthy tier is `simple` is excluded too: the classifier can't be
1282        // constrained to `simple`, so leaving such an agent in would waste the
1283        // call whenever it picks `medium`/`complex` (issue #3521).
1284        // Fall back to the full list if all agents are cooled/degraded.
1285        // Cloned to avoid borrow conflict with &mut self in the loop.
1286        let uncooled_agents: Vec<String> = self
1287            .available_agents
1288            .iter()
1289            .filter(|a| {
1290                !is_agent_in_cooldown(a)
1291                    && !is_agent_degraded(a)
1292                    && self.agent_has_available_model_for_coding_tiers(a)
1293            })
1294            .cloned()
1295            .collect();
1296        if uncooled_agents.is_empty() {
1297            return Err(AllAgentsCooledError::new("all agents".to_string(), None).into());
1298        }
1299        let llm_agents = uncooled_agents;
1300
1301        let pool = self.router_pool.clone();
1302        let n = pool.len();
1303        let start = self.pool_index;
1304        let mut last_err: Option<anyhow::Error> = None;
1305        let mut attempted_any = false;
1306
1307        // Try pool entries in round-robin order, skipping cooled ones
1308        for i in 0..n {
1309            let idx = (start + i) % n;
1310            let (agent, model) = &pool[idx];
1311            let model_str = model.as_str();
1312
1313            if cooldown::is_model_in_cooldown(agent, model_str) {
1314                tracing::debug!(agent, model = model_str, "pool entry on cooldown, skipping");
1315                continue;
1316            }
1317
1318            // At least one pool entry was available to attempt
1319            attempted_any = true;
1320
1321            let model_opt = if model_str.is_empty() {
1322                None
1323            } else {
1324                Some(model_str)
1325            };
1326
1327            match self
1328                .llm_router
1329                .route_with_llm_using(
1330                    task,
1331                    &llm_agents,
1332                    &self.config,
1333                    &mut self.last_agent,
1334                    repo,
1335                    agent,
1336                    model_opt,
1337                )
1338                .await
1339            {
1340                Ok(result) => {
1341                    // Advance index so the next call starts at the next pool entry
1342                    self.advance_pool_index_after_attempt(idx, n);
1343                    tracing::debug!(
1344                        agent,
1345                        model = model_str,
1346                        pool_idx = idx,
1347                        "router LLM pool entry succeeded"
1348                    );
1349                    record_agent_success(agent, model_str).await;
1350                    return Ok(result);
1351                }
1352                Err(e) => {
1353                    let err_msg = e.to_string();
1354                    let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1355                    if is_timeout {
1356                        // Advance pool index so the next tick starts at the next entry,
1357                        // then return immediately. Continuing to try further pool entries
1358                        // in the same tick would accumulate multiple timeout windows and
1359                        // stall the tick loop for minutes (issue #3187).
1360                        //
1361                        // Also record a standard cooldown, same as the non-timeout branch,
1362                        // so a chronically-timing-out entry is skipped by is_model_in_cooldown
1363                        // on future ticks instead of burning the full timeout window again
1364                        // every time round-robin reaches it (issue #3422).
1365                        self.advance_pool_index_after_attempt(idx, n);
1366                        tracing::warn!(
1367                            agent,
1368                            model = model_str,
1369                            next_pool_idx = self.pool_index,
1370                            "router LLM pool entry timed out — recording cooldown, will retry next tick"
1371                        );
1372                        cooldown::record_model_failure(agent, model_str).await;
1373                        return Err(e);
1374                    }
1375                    if is_max_turns_error(&err_msg) {
1376                        tracing::warn!(
1377                            agent,
1378                            model = model_str,
1379                            error = %e,
1380                            "pool entry hit max turns — trying next without cooldown"
1381                        );
1382                    } else {
1383                        tracing::warn!(
1384                            agent,
1385                            model = model_str,
1386                            error = %e,
1387                            "pool entry failed, recording cooldown and trying next"
1388                        );
1389                        if !cooldown::record_credit_exhaustion_from_message(
1390                            agent,
1391                            Some(model_str),
1392                            &err_msg,
1393                        )
1394                        .await
1395                        {
1396                            cooldown::record_model_failure(agent, model_str).await;
1397                        }
1398                    }
1399                    last_err = Some(e);
1400                    self.advance_pool_index_after_attempt(idx, n);
1401                }
1402            }
1403        }
1404
1405        // If every pool entry was pre-cooled (nothing was attempted), do not
1406        // immediately exhaust the pool again — fail fast and let the tick loop
1407        // retry on the next cycle instead of cascading failures.
1408        // However, we should still try the fallback if configured.
1409        if !attempted_any {
1410            let now = chrono::Utc::now().timestamp();
1411            let earliest = self.earliest_pool_cooldown();
1412            if let Some(until) = earliest {
1413                // Pool entries exist but are all cooled - we'll try fallback below
1414                let remaining = until.saturating_sub(now);
1415                tracing::warn!(
1416                    remaining_secs = remaining,
1417                    pool = ?pool,
1418                    "all router LLM pool entries on cooldown — will try fallback"
1419                );
1420                // Continue to fallback logic instead of returning early
1421            } else {
1422                // No pool cooldowns found either — this means the pool was empty
1423                // or every entry was filtered out for some other reason.
1424                return Err(last_err
1425                    .unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")));
1426            }
1427        }
1428
1429        // All pool entries failed or were cooled — try the configured fallback
1430        let fallback = self.config.effective_fallback();
1431        let (fb_agent, fb_model) = parse_pool_entry(&fallback);
1432        let fb_model_str = fb_model.as_str();
1433
1434        // Only try fallback if it wasn't already in the pool (avoid double-try)
1435        let fallback_already_tried = pool.iter().any(|(a, m)| a == &fb_agent && m == &fb_model);
1436
1437        if !fallback_already_tried && !cooldown::is_model_in_cooldown(&fb_agent, fb_model_str) {
1438            tracing::info!(
1439                agent = %fb_agent,
1440                model = %fb_model_str,
1441                "all pool entries exhausted — trying fallback router LLM"
1442            );
1443            let fb_model_opt = if fb_model_str.is_empty() {
1444                None
1445            } else {
1446                Some(fb_model_str)
1447            };
1448            match self
1449                .llm_router
1450                .route_with_llm_using(
1451                    task,
1452                    &llm_agents,
1453                    &self.config,
1454                    &mut self.last_agent,
1455                    repo,
1456                    &fb_agent,
1457                    fb_model_opt,
1458                )
1459                .await
1460            {
1461                Ok(result) => {
1462                    record_agent_success(&fb_agent, fb_model_str).await;
1463                    return Ok(result);
1464                }
1465                Err(e) => {
1466                    let err_msg = e.to_string();
1467                    let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1468                    if is_timeout {
1469                        // Cool down on timeout like pool entries (#3422), else a
1470                        // chronically-timing-out fallback burns the full timeout window every tick (#3616)
1471                        cooldown::record_model_failure(&fb_agent, fb_model_str).await;
1472                        tracing::warn!(
1473                            agent = %fb_agent,
1474                            model = %fb_model_str,
1475                            "fallback router LLM timed out — returning immediately to unblock tick loop"
1476                        );
1477                        return Err(e);
1478                    }
1479                    tracing::warn!(
1480                        agent = %fb_agent,
1481                        model = %fb_model_str,
1482                        error = %e,
1483                        "fallback router LLM also failed"
1484                    );
1485                    if !is_max_turns_error(&err_msg) {
1486                        cooldown::record_model_failure(&fb_agent, fb_model_str).await;
1487                    }
1488                    last_err = Some(e);
1489                }
1490            }
1491        }
1492
1493        Err(last_err.unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")))
1494    }
1495
1496    /// Record a rate limit event for an agent, reducing its routing weight.
1497    ///
1498    /// Called by the engine when an agent returns a 429/rate limit error.
1499    pub fn record_rate_limit(&mut self, agent: &str) {
1500        self.weights.record_rate_limit(agent);
1501    }
1502
1503    /// Record a successful task completion, restoring agent weight.
1504    pub fn record_success(&mut self, agent: &str) {
1505        self.weights.record_success(agent);
1506    }
1507
1508    /// Tick weight recovery for all agents.
1509    ///
1510    /// Called periodically by the engine to gradually restore weights
1511    /// as rate limit windows expire.
1512    pub fn tick_weight_recovery(&mut self) {
1513        self.weights.tick_recovery();
1514    }
1515
1516    /// Store routing result in the task store.
1517    pub async fn store_route_result(
1518        &self,
1519        task_id: &str,
1520        result: &RouteResult,
1521        store: &Arc<TaskStore>,
1522        repo: &str,
1523    ) -> anyhow::Result<()> {
1524        if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await {
1525            store
1526                .set_fields(
1527                    store_id,
1528                    &[
1529                        ("agent", serde_json::json!(result.agent)),
1530                        ("complexity", serde_json::json!(result.complexity)),
1531                        ("route_reason", serde_json::json!(result.reason)),
1532                        (
1533                            "agent_profile",
1534                            serde_json::json!(serde_json::to_string(&result.profile)?),
1535                        ),
1536                        (
1537                            "model",
1538                            serde_json::json!(result.model.as_deref().unwrap_or("")),
1539                        ),
1540                    ],
1541                )
1542                .await?;
1543        }
1544        Ok(())
1545    }
1546}
1547
1548/// Retrieve routing result from the task store.
1549pub async fn get_route_result(
1550    store: &Arc<TaskStore>,
1551    repo: &str,
1552    task_id: &str,
1553) -> Result<RouteResult, RouteResultError> {
1554    let store_id = store
1555        .resolve_task_id(repo, task_id)
1556        .await
1557        .map_err(RouteResultError::Other)?
1558        .ok_or_else(|| {
1559            RouteResultError::Other(anyhow::anyhow!("task {task_id} not found in store"))
1560        })?;
1561    let task = store.get(store_id).await.map_err(RouteResultError::Other)?;
1562
1563    let agent = task
1564        .agent
1565        .clone()
1566        .filter(|a| !a.is_empty())
1567        .ok_or_else(|| RouteResultError::NoAgent {
1568            task_id: task_id.to_string(),
1569        })?;
1570
1571    let complexity = if task.complexity.is_empty() {
1572        "medium".to_string()
1573    } else {
1574        task.complexity.clone()
1575    };
1576
1577    let reason = task.route_reason.clone();
1578    let model = task.model.clone().filter(|m| !m.is_empty());
1579    // Only a profile route's model/effort choice is restored; every other route
1580    // keeps the default profile, as before. Recovery that changed the agent or
1581    // model invalidates the stored choice.
1582    let profile = AgentProfile {
1583        execution: serde_json::from_str::<AgentProfile>(&task.agent_profile)
1584            .ok()
1585            .and_then(|stored| stored.execution)
1586            .filter(|p| p.matches_route(&agent, model.as_deref())),
1587        ..AgentProfile::default()
1588    };
1589
1590    // Validate that the stored model is valid for the resolved agent.
1591    // Agent-specific aliases (e.g. "opus") can leak across agents during
1592    // failover, so we verify against the router's model pools (#1604).
1593    let config = RouterConfig::from_config();
1594    let model = model.filter(|m| {
1595        let complexities = ["simple", "medium", "complex", "review"];
1596        // Collect all model pools configured for this agent across complexity tiers.
1597        let all_pools: Vec<Vec<String>> = complexities
1598            .iter()
1599            .filter_map(|comp| config.model_pool_for_complexity(&agent, comp))
1600            .collect();
1601        // If the agent has no model pools configured, we can't validate — pass through.
1602        if all_pools.is_empty() {
1603            return true;
1604        }
1605        let valid = all_pools.iter().any(|pool| pool.contains(m))
1606            || profile
1607                .execution
1608                .as_ref()
1609                .is_some_and(|p| p.matches_route(&agent, Some(m)));
1610        if !valid {
1611            tracing::warn!(
1612                task_id,
1613                agent,
1614                model = %m,
1615                "discarding stale model: not in agent's model pools"
1616            );
1617        }
1618        valid
1619    });
1620
1621    // A stale model is replaced by the agent's model for the task's complexity, an empty
1622    // model would reach the agent as `--model ""`. last_error keeps the reason (#2527)
1623    let original_model = task.model.clone().filter(|m| !m.is_empty());
1624    let mut model = model;
1625    if original_model.is_some() && model.is_none() {
1626        model = config.model_for_complexity(&agent, &complexity, task_id);
1627        let stale_model = original_model.as_deref().unwrap_or("unknown");
1628        let stale_err = format!(
1629            "stale model discarded: {stale_model} not in {agent} model pools, using {}",
1630            model.as_deref().unwrap_or("the agent default")
1631        );
1632        if let Err(e) = store
1633            .set_fields(
1634                store_id,
1635                &[
1636                    (
1637                        "model",
1638                        serde_json::json!(model.clone().unwrap_or_default()),
1639                    ),
1640                    ("last_error", serde_json::json!(stale_err)),
1641                ],
1642            )
1643            .await
1644        {
1645            // Log the error so transient DB failures are visible and diagnosable.
1646            tracing::warn!(task_id = %task_id, error = %e, "failed to clear stale model from store — will retry on next dispatch");
1647        }
1648    }
1649
1650    Ok(RouteResult {
1651        agent,
1652        model,
1653        complexity,
1654        estimate: 0,
1655        reason,
1656        profile,
1657        warning: None,
1658    })
1659}
1660
1661#[cfg(test)]
1662#[expect(
1663    clippy::float_cmp,
1664    reason = "the weights are stored constants, so they compare exactly"
1665)]
1666mod tests;