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