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;