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