Skip to main content

orch/engine/runner/response/
mod.rs

1//! Response collection + error classification.
2//!
3//! After the agent finishes (tmux session ends), this module:
4//! 1. Reads the output file
5//! 2. Parses the response JSON
6//! 3. Classifies errors (timeout, usage limit, auth, tooling)
7//! 4. Determines next action (success, reroute, needs_review)
8
9pub use crate::github::types::ReviewIssue;
10use crate::store;
11use crate::store::TaskStore;
12use std::collections::HashSet;
13use std::collections::hash_map::DefaultHasher;
14use std::fs;
15use std::fs::File;
16use std::hash::Hash;
17use std::hash::Hasher;
18use std::io::Read;
19use std::io::Seek;
20use std::io::SeekFrom;
21use std::path::{Path, PathBuf};
22use std::result;
23use std::sync::Arc;
24use std::thread;
25use std::time::Duration;
26use std::time::SystemTime;
27
28use tokio::fs as tokio_fs;
29use tokio::task;
30use tokio::time;
31// Cooldown tracking is implemented in `crate::cooldown` (shared with the router).
32use crate::config as app_config;
33pub use crate::cooldown::{
34    clear_expired_cooldowns, is_agent_in_cooldown, is_model_in_cooldown,
35    record_agent_failure_with_message, record_model_failure, set_agent_cooldown,
36};
37use crate::engine;
38use crate::engine::agents::parser::AgentResponse;
39use crate::engine::router::config;
40use crate::engine::runner::ndjson;
41use crate::store::MemoryEntry;
42use crate::store::Task;
43use crate::sys::cmd_cache;
44use crate::sys::home;
45
46const JITTER_FACTOR: f64 = 0.3;
47
48/// Maximum output file size to read (10 MB).
49/// Prevents runaway outputs from consuming excessive memory.
50const MAX_OUTPUT_SIZE_BYTES: u64 = 10 * 1024 * 1024;
51
52/// Read a file with a size limit, returning truncated content if the file is too large.
53///
54/// This prevents runaway agent outputs from causing memory issues. If the file
55/// exceeds the limit, reads from the end of the file to capture the most recent
56/// output (which is typically where the result or error message is).
57fn read_file_with_limit<P: AsRef<Path>>(path: P, max_bytes: u64) -> anyhow::Result<String> {
58    let path = path.as_ref();
59    let metadata = fs::metadata(path)?;
60
61    if !metadata.is_file() {
62        anyhow::bail!("not a file: {}", path.display());
63    }
64
65    let file_size = metadata.len();
66
67    // If file is within limits, read the whole thing
68    if file_size <= max_bytes {
69        return fs::read_to_string(path).map_err(Into::into);
70    }
71
72    // File is too large - read from the end to get the most recent output
73    let mut file = File::open(path)?;
74    let start_pos = file_size.saturating_sub(max_bytes);
75    file.seek(SeekFrom::Start(start_pos))?;
76
77    let mut buffer = Vec::with_capacity(usize::try_from(max_bytes).unwrap_or(0));
78    file.read_to_end(&mut buffer)?;
79
80    // Try to convert to UTF-8, replacing invalid sequences
81    let content = String::from_utf8_lossy(&buffer);
82
83    // Log a warning about truncation
84    tracing::warn!(
85        path = %path.display(),
86        file_size = file_size,
87        max_bytes = max_bytes,
88        "output file truncated: exceeded size limit"
89    );
90
91    Ok(content.into_owned())
92}
93
94/// Calculate exponential backoff with jitter for fallback retries.
95/// Uses retry count from the reroute chain to determine the delay.
96///
97/// Delay = min(base * 2^retry_count, max) * (1 + jitter)
98pub(crate) fn calculate_backoff_delay(retry_count: usize) -> u64 {
99    let base_delay = config::retry_base_delay_ms();
100    let max_delay = config::retry_max_delay_ms();
101
102    // Exponential: base * 2^retry_count
103    let exponential =
104        base_delay * (2_u64.saturating_pow(u32::try_from(retry_count).unwrap_or(u32::MAX)));
105    let capped = exponential.min(max_delay);
106
107    // Add jitter: ±30% using a hash-based pseudo-random value.
108    // Mix system time (nanoseconds) with thread ID so concurrent retries on
109    // different threads get different delays even when called in the same
110    // microsecond, avoiding the thundering-herd problem.
111    #[expect(
112        clippy::cast_precision_loss,
113        clippy::cast_possible_truncation,
114        clippy::cast_sign_loss,
115        reason = "a jitter range in milliseconds, far below 2^52 and never negative"
116    )]
117    let jitter_range = (capped as f64 * JITTER_FACTOR) as u64;
118    let jitter = {
119        let mut h = DefaultHasher::new();
120        SystemTime::now().hash(&mut h);
121        thread::current().id().hash(&mut h);
122        h.finish() % (jitter_range * 2 + 1)
123    };
124
125    capped.saturating_sub(jitter_range) + jitter
126}
127
128fn fallback_retry_count(task: Option<&Task>) -> usize {
129    task.map_or(0, |t| {
130        let chain_retry_count = t
131            .limit_reroute_chain
132            .split(',')
133            .filter(|entry| !entry.is_empty())
134            .count();
135        let network_retry_count = usize::try_from(t.network_retries).unwrap_or(0);
136        chain_retry_count.max(network_retry_count)
137    })
138}
139
140/// Wait with exponential backoff before retrying with a fallback agent.
141/// Returns the delay applied in milliseconds.
142pub async fn wait_for_fallback_backoff(
143    task_id: &str,
144    store: &Option<Arc<TaskStore>>,
145    repo: &str,
146) -> u64 {
147    let task = store::opt_store_get_task(store, repo, task_id).await;
148
149    // Normal failover uses reroute chain length. NetworkError retries bypass
150    // failover, so track their own streak and use whichever retry source is larger.
151    let retry_count = fallback_retry_count(task.as_ref());
152
153    let delay = calculate_backoff_delay(retry_count);
154
155    if delay > 0 {
156        tracing::debug!(
157            task_id,
158            retry_count = retry_count,
159            delay_ms = delay,
160            "fallback backoff: waiting before retry"
161        );
162        time::sleep(Duration::from_millis(delay)).await;
163    }
164
165    delay
166}
167
168/// Outcome signal for the engine to update router weights.
169///
170/// Returned by the task runner so the engine can feed rate limit and
171/// success signals back to the router's weighted round-robin implementation.
172#[derive(Debug, Clone)]
173pub enum WeightSignal {
174    /// Agent completed a task successfully.
175    Success { agent: String },
176    /// Agent hit a rate limit / usage limit.
177    RateLimited { agent: String },
178    /// The run failed (timeout, no fallback, exhausted agents) and ended in `needs_review`.
179    /// Never read as a completed run, so the no-PR shortcut cannot mark the task done.
180    Failed { agent: String },
181    /// Task is blocked on child tasks (delegations). Do not trigger review agent.
182    Blocked,
183    /// Task was rerouted (silence detection, timeout, parse error) — reset to new for re-routing.
184    /// Distinct from None so the engine never converts a silent-reset task into needs_review.
185    Rerouted,
186    /// No weight-relevant signal (guard skipped task, unrecognised status, etc.)
187    None,
188}
189
190/// Read the agent's output file, trying multiple locations.
191///
192/// Checks per-task attempt directory first, then legacy flat paths.
193/// Output is truncated to `MAX_OUTPUT_SIZE_BYTES` to prevent runaway memory usage.
194pub async fn read_output_file(task_id: &str, primary_path: &Path, repo: &str) -> String {
195    // Primary: explicit output file (already points to attempt dir)
196    if let Some(content) = task::spawn_blocking({
197        let p = primary_path.to_path_buf();
198        move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
199    })
200    .await
201    .ok()
202    .and_then(result::Result::ok)
203        && !content.is_empty()
204    {
205        return content;
206    }
207
208    // Fallback: check all attempt dirs for this task (newest first)
209    if let Ok(task_dir) = home::task_dir_async(repo, task_id).await {
210        let attempts_dir = task_dir.join("attempts");
211        // Use async metadata for is_dir check
212        if tokio_fs::metadata(&attempts_dir)
213            .await
214            .is_ok_and(|m| m.is_dir())
215        {
216            let mut attempt_nums: Vec<u32> = task::spawn_blocking({
217                let a = attempts_dir.clone();
218                move || {
219                    match fs::read_dir(&a) {
220                        Ok(entries) => {
221                            let mut nums = Vec::new();
222                            for entry in entries {
223                                match entry {
224                                    Ok(e) => {
225                                        if let Some(n) =
226                                            e.file_name().to_str().and_then(|n| n.parse().ok())
227                                        {
228                                            nums.push(n);
229                                        }
230                                    }
231                                    Err(e) => tracing::warn!(
232                                        path = %a.display(),
233                                        err = %e,
234                                        "error reading attempt dir entry in output fallback"
235                                    ),
236                                }
237                            }
238                            nums
239                        }
240                        Err(e) => {
241                            tracing::warn!(path = %a.display(), err = %e, "failed to read attempts dir in output fallback");
242                            Vec::new()
243                        }
244                    }
245                }
246            })
247            .await
248            .unwrap_or_default();
249
250            attempt_nums.sort_unstable_by(|a, b| b.cmp(a)); // newest first
251            for n in attempt_nums {
252                let p = attempts_dir.join(n.to_string()).join("output.json");
253                if let Some(content) = task::spawn_blocking({
254                    let p = p.clone();
255                    move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
256                })
257                .await
258                .ok()
259                .and_then(result::Result::ok)
260                    && !content.is_empty()
261                {
262                    tracing::info!(task_id, path = %p.display(), "read output from attempt dir");
263                    return content;
264                }
265            }
266        }
267    }
268
269    // Legacy fallback locations
270    let state_dir = home::state_dir().unwrap_or_else(|_| PathBuf::from("/tmp"));
271
272    let mut fallbacks = vec![
273        PathBuf::from(format!("/tmp/output-{task_id}.json")),
274        state_dir.join(format!("output-{task_id}.json")),
275    ];
276
277    if let Ok(legacy_path) = home::state_file(&format!("output-{task_id}.json"))
278        && !fallbacks.contains(&legacy_path)
279    {
280        fallbacks.push(legacy_path);
281    }
282
283    for path in &fallbacks {
284        if let Some(content) = task::spawn_blocking({
285            let p = path.clone();
286            move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
287        })
288        .await
289        .ok()
290        .and_then(result::Result::ok)
291            && !content.is_empty()
292        {
293            tracing::info!(task_id, path = %path.display(), "read output from legacy fallback");
294            return content;
295        }
296    }
297
298    String::new()
299}
300
301/// Pick a fallback agent, avoiding agents already in the reroute chain and agents in cooldown.
302pub fn pick_fallback_agent(
303    current_agent: &str,
304    chain: &str,
305    available_agents: &[String],
306) -> Option<String> {
307    // Clear expired cooldowns first
308    clear_expired_cooldowns();
309
310    let chain_set: HashSet<&str> = if chain.is_empty() {
311        HashSet::new()
312    } else {
313        chain.split(',').collect()
314    };
315
316    // Prefer agents that are not in cooldown and are not heavily degraded
317    // from recent rate-limits. This prevents immediate failover to agents
318    // that have been heavily penalized and likely to fail as well.
319    for agent in available_agents {
320        if agent == current_agent || chain_set.contains(agent.as_str()) {
321            continue;
322        }
323        if is_agent_in_cooldown(agent) {
324            continue;
325        }
326        // Weight-based filtering was removed from this module because it used
327        // a default-constructed AgentWeights (dead code that always returned
328        // true). Keep failover behavior simple here: prefer the first agent
329        // that is not in cooldown and not in the reroute chain. If we later
330        // expose the router's AgentWeights snapshot to this module we can add
331        // weight-based avoidance back in a non-dead way.
332        return Some(agent.clone());
333    }
334
335    None
336}
337
338/// Retryable error types that should trigger agent failover.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub enum RetryableError {
341    /// Agent timed out.
342    Timeout,
343    /// Run exited without a result envelope
344    Interrupted,
345    /// Usage/rate limit hit.
346    UsageLimit,
347    /// Auth/billing error.
348    AuthError,
349    /// General failure (non-retryable but we still try fallback agents).
350    Failed,
351    /// Missing tooling - fallback might help if another agent has the tool.
352    MissingTooling,
353    /// A specific model was unavailable (e.g. "Model not found"). The agent
354    /// itself is fine — only the model is in cooldown. Failover may still pick
355    /// a different agent, but we must not bump the agent-level failure counter.
356    ModelUnavailable,
357}
358
359impl RetryableError {
360    /// Return a short classified string for this error type.
361    /// Used in DB rate-limit metrics and test assertions.
362    pub fn type_str(self) -> &'static str {
363        match self {
364            RetryableError::Timeout => "timeout",
365            RetryableError::Interrupted => "interrupted",
366            RetryableError::UsageLimit => "rate_limit",
367            RetryableError::AuthError => "auth_error",
368            RetryableError::ModelUnavailable => "model_unavailable",
369            RetryableError::Failed | RetryableError::MissingTooling => "failed",
370        }
371    }
372}
373
374/// Next task status from [`handle_failover`], plus the fallback agent when one was stored
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct FailoverOutcome {
377    /// Task status to apply: `new`, `blocked`, or `needs_review`
378    pub status: String,
379    /// Fallback agent written to the task when failover switched
380    pub next_agent: Option<String>,
381}
382
383impl FailoverOutcome {
384    fn with_status(status: impl Into<String>) -> Self {
385        Self {
386            status: status.into(),
387            next_agent: None,
388        }
389    }
390
391    fn switched(next_agent: String) -> Self {
392        Self {
393            status: "new".to_string(),
394            next_agent: Some(next_agent),
395        }
396    }
397}
398
399/**
400 * Handle failover for any retryable error type. Status is "new" on reroute (or
401 * retryable exhaustion), "blocked" on hard exhaustion, "needs_review" when no
402 * fallback agents are available. `next_agent` is set when a fallback was stored
403 * so the next route prefers it over an `agent:*` label. `credit_recorded` means
404 * the caller already ran `record_credit_exhaustion`; the generic `failure_count:`
405 * counter must not be bumped here or the next ordinary failure starts at the
406 * extended backoff tier (issue #3652). Rate-limit event DB recording is done by
407 * the caller (mod.rs)
408 **/
409pub async fn handle_failover(
410    task_id: &str,
411    agent_name: &str,
412    error_type: RetryableError,
413    error_message: &str,
414    credit_recorded: bool,
415    store: &Option<Arc<TaskStore>>,
416    repo: &str,
417) -> FailoverOutcome {
418    // Get the reroute chain
419    let chain = get_reroute_chain(task_id, store, repo).await;
420    let chain = update_reroute_chain(task_id, agent_name, &chain, store, repo).await;
421
422    if error_type == RetryableError::Timeout
423        && let Some(status) =
424            block_after_repeated_timeouts(task_id, error_message, store, repo).await
425    {
426        return FailoverOutcome::with_status(status);
427    }
428
429    // Get all available agents
430    let available: Vec<String> = engine::configured_agents()
431        .into_iter()
432        .filter(|a| cmd_cache::command_exists(a))
433        .collect();
434
435    // Check if we've exhausted all agents (build chain_set once)
436    let chain_set: HashSet<&str> = if chain.is_empty() {
437        HashSet::new()
438    } else {
439        chain.split(',').collect()
440    };
441    let is_exhausted = available.iter().all(|a| chain_set.contains(a.as_str()));
442
443    if is_exhausted {
444        // Retryable failures (rate limits, quota, model unavailable) will resolve once
445        // cooldowns expire — reset to "new" so the router picks it up again then.
446        // Hard failures (generic agent crash, missing tooling) won't improve on retry;
447        // block immediately with a clear reason rather than wasting 63 minutes in the
448        // review-refire loop before getting a misleading "review agent rebroadcast" message.
449        let is_retryable = matches!(
450            error_type,
451            RetryableError::UsageLimit
452                | RetryableError::AuthError
453                | RetryableError::ModelUnavailable
454                | RetryableError::Timeout
455                | RetryableError::Interrupted
456        );
457        let next_status = if is_retryable { "new" } else { "blocked" };
458
459        tracing::warn!(
460            task_id,
461            agent = agent_name,
462            error_type = ?error_type,
463            next_status,
464            "all agents exhausted"
465        );
466
467        let mut store_fields: Vec<(&str, serde_json::Value)> = Vec::new();
468
469        if is_retryable {
470            // Clear reroute chain so the next dispatch builds a fresh one rather than
471            // immediately seeing "all agents in chain" and exhausting again.
472            let msg = format!("{error_message} (all agents exhausted, will retry when available)");
473            store_fields.push(("last_error", serde_json::json!(msg)));
474            store_fields.push(("limit_reroute_chain", serde_json::json!("")));
475        } else {
476            let msg = format!("{error_message} (all agents exhausted)");
477            let block_reason = format!(
478                "all agents exhausted: {} — {}",
479                error_type.type_str(),
480                error_message
481            );
482            store_fields.push(("last_error", serde_json::json!(msg)));
483            store_fields.push(("block_reason", serde_json::json!(block_reason)));
484        }
485
486        if let Err(e) = store::store_set_result(store, repo, task_id, &store_fields).await {
487            tracing::warn!(task_id, err = %e, "failed to write agents_exhausted fields to store");
488        }
489
490        // Log reroute activity for exhausted agents
491        let details = serde_json::json!({
492            "failure_reason": error_type.type_str(),
493            "error_message": error_message,
494            "chain": chain,
495            "agents_exhausted": true,
496            "is_retryable": is_retryable,
497        });
498        store::store_log_activity(
499            store,
500            repo,
501            task_id,
502            "rerouted",
503            Some("in_progress"),
504            Some(next_status),
505            None::<&str>,
506            None::<&str>,
507            Some(&details),
508        )
509        .await;
510
511        return FailoverOutcome::with_status(next_status);
512    }
513
514    // Pick a fallback agent
515    if let Some(next) = pick_fallback_agent(agent_name, &chain, &available) {
516        tracing::info!(
517            task_id,
518            from = agent_name,
519            to = next,
520            error_type = ?error_type,
521            "failover: switching to fallback agent"
522        );
523
524        // Timeouts and interrupts are not agent faults, skip the agent cooldown
525        if !matches!(
526            error_type,
527            RetryableError::MissingTooling
528                | RetryableError::ModelUnavailable
529                | RetryableError::Timeout
530                | RetryableError::Interrupted
531        ) {
532            // Credit errors skip the generic counter (already counted via
533            // credit_failure_count); the 120s cooldown below still applies
534            if !credit_recorded {
535                record_agent_failure_with_message(agent_name, error_message).await;
536            }
537
538            // Apply brief 120s cooldown on the failed agent so the router skips it
539            // on the next routing attempt. This prevents the router from immediately
540            // re-selecting the same agent after clearing both agent and model (#1492).
541            // Also skipped for ModelUnavailable: the agent is healthy.
542            set_agent_cooldown(agent_name, 120).await;
543        }
544
545        // Store the fallback agent so the next route prefers it over an agent:* label
546        // Clear the model so routing picks one that the fallback agent can run
547        let msg = format!("{error_message}, switching to {next} for re-route");
548        if let Err(e) = store::store_set_result(
549            store,
550            repo,
551            task_id,
552            &[
553                ("agent", serde_json::json!(next)),
554                ("model", serde_json::json!("")),
555                ("last_error", serde_json::json!(msg)),
556            ],
557        )
558        .await
559        {
560            tracing::warn!(task_id, err = %e, "failed to write failover agent to store");
561        }
562
563        // Apply exponential backoff with jitter before retry.
564        // Return "new" (not "routed") so the task goes through Phase 3a routing
565        // again. This ensures the router actually re-selects a compatible agent+model
566        // via model_for_complexity() instead of bypassing routing and defaulting to
567        // claude in the dispatch loop (#1604).
568        wait_for_fallback_backoff(task_id, store, repo).await;
569
570        // Log reroute activity for successful failover
571        let details = serde_json::json!({
572            "failure_reason": error_type.type_str(),
573            "error_message": error_message,
574            "from_agent": agent_name,
575            "to_agent": next,
576            "chain": chain,
577        });
578        store::store_log_activity(
579            store,
580            repo,
581            task_id,
582            "rerouted",
583            Some("in_progress"),
584            Some("new"),
585            Some(&next),
586            None::<&str>,
587            Some(&details),
588        )
589        .await;
590
591        return FailoverOutcome::switched(next);
592    }
593
594    // No fallback available
595    tracing::warn!(task_id, agent = agent_name, "no fallback agents available");
596
597    let is_retryable = matches!(
598        error_type,
599        RetryableError::UsageLimit
600            | RetryableError::AuthError
601            | RetryableError::ModelUnavailable
602            | RetryableError::Timeout
603            | RetryableError::Interrupted
604    );
605
606    // Timeouts and interrupts are not agent faults, skip the agent cooldown
607    if !matches!(
608        error_type,
609        RetryableError::MissingTooling
610            | RetryableError::ModelUnavailable
611            | RetryableError::Timeout
612            | RetryableError::Interrupted
613    ) && !credit_recorded
614    {
615        record_agent_failure_with_message(agent_name, error_message).await;
616    }
617
618    if is_retryable {
619        // The other agents are in cooldown, so wait out the backoff and let the router
620        // pick the task up again. A fresh chain keeps the next run from seeing every agent as tried
621        wait_for_fallback_backoff(task_id, store, repo).await;
622
623        let msg = format!("{error_message} (no fallback agents, will retry)");
624        if let Err(e) = store::store_set_result(
625            store,
626            repo,
627            task_id,
628            &[
629                ("last_error", serde_json::json!(msg)),
630                ("limit_reroute_chain", serde_json::json!("")),
631            ],
632        )
633        .await
634        {
635            tracing::warn!(task_id, err = %e, "failed to write no_fallback retry fields to store");
636        }
637
638        let details = serde_json::json!({
639            "failure_reason": error_type.type_str(),
640            "error_message": error_message,
641            "chain": chain,
642            "no_fallback_available": true,
643            "is_retryable": true,
644        });
645        store::store_log_activity(
646            store,
647            repo,
648            task_id,
649            "rerouted",
650            Some("in_progress"),
651            Some("new"),
652            None::<&str>,
653            None::<&str>,
654            Some(&details),
655        )
656        .await;
657
658        return FailoverOutcome::with_status("new");
659    }
660
661    let msg = format!("{error_message}, no fallback agents");
662    if let Err(e) = store::store_set_result(
663        store,
664        repo,
665        task_id,
666        &[("last_error", serde_json::json!(msg))],
667    )
668    .await
669    {
670        tracing::warn!(task_id, err = %e, "failed to write no_fallback last_error to store");
671    }
672
673    // Log reroute activity for no fallback available
674    let details = serde_json::json!({
675        "failure_reason": error_type.type_str(),
676        "error_message": error_message,
677        "chain": chain,
678        "no_fallback_available": true,
679    });
680    store::store_log_activity(
681        store,
682        repo,
683        task_id,
684        "rerouted",
685        Some("in_progress"),
686        Some("needs_review"),
687        None::<&str>,
688        None::<&str>,
689        Some(&details),
690    )
691    .await;
692
693    FailoverOutcome::with_status("needs_review")
694}
695
696/// Count a timeout against the task. Returns "blocked" once the task has timed out
697/// `workflow.max_timeout_retries` times (default 3), so a task that always times out does not loop
698pub async fn block_after_repeated_timeouts(
699    task_id: &str,
700    error_message: &str,
701    store: &Option<Arc<TaskStore>>,
702    repo: &str,
703) -> Option<String> {
704    let max: i64 = app_config::get("workflow.max_timeout_retries")
705        .ok()
706        .and_then(|v| v.parse().ok())
707        .unwrap_or(3);
708    let count = match store::store_increment(store, repo, task_id, "timeout_retries").await {
709        Ok(count) => i64::try_from(count).unwrap_or(i64::MAX),
710        Err(e) => {
711            tracing::warn!(task_id, err = %e, "failed to increment timeout_retries");
712            return None;
713        }
714    };
715    if count < max {
716        return None;
717    }
718
719    let block_reason = format!("timed out {count} times");
720    tracing::warn!(
721        task_id,
722        count,
723        max,
724        "timeout retries exhausted, blocking task"
725    );
726    if let Err(e) = store::store_set_result(
727        store,
728        repo,
729        task_id,
730        &[
731            (
732                "last_error",
733                serde_json::json!(format!("{error_message} ({block_reason})")),
734            ),
735            ("block_reason", serde_json::json!(block_reason)),
736            ("limit_reroute_chain", serde_json::json!("")),
737        ],
738    )
739    .await
740    {
741        tracing::warn!(task_id, err = %e, "failed to write timeout block fields to store");
742    }
743    let details = serde_json::json!({
744        "failure_reason": "timeout",
745        "error_message": error_message,
746        "timeout_retries": count,
747    });
748    store::store_log_activity(
749        store,
750        repo,
751        task_id,
752        "rerouted",
753        Some("in_progress"),
754        Some("blocked"),
755        None::<&str>,
756        None::<&str>,
757        Some(&details),
758    )
759    .await;
760    Some("blocked".to_string())
761}
762
763/// Get the reroute chain from store.
764pub async fn get_reroute_chain(
765    task_id: &str,
766    store: &Option<Arc<TaskStore>>,
767    repo: &str,
768) -> String {
769    store::opt_store_get_task(store, repo, task_id)
770        .await
771        .map(|t| t.limit_reroute_chain)
772        .unwrap_or_default()
773        .trim()
774        .to_string()
775}
776
777/// Update the reroute chain in store.
778pub async fn update_reroute_chain(
779    task_id: &str,
780    current_agent: &str,
781    existing_chain: &str,
782    store: &Option<Arc<TaskStore>>,
783    repo: &str,
784) -> String {
785    let mut chain = existing_chain.to_string();
786    if chain.is_empty() {
787        chain = current_agent.to_string();
788    } else if !chain.split(',').any(|a| a == current_agent) {
789        chain = format!("{chain},{current_agent}");
790    }
791
792    if let Err(e) = store::store_set_result(
793        store,
794        repo,
795        task_id,
796        &[("limit_reroute_chain", serde_json::json!(chain))],
797    )
798    .await
799    {
800        tracing::warn!(task_id, err = %e, "failed to write limit_reroute_chain to store");
801    }
802    chain
803}
804
805/// Review response from the review agent.
806#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
807pub struct ReviewResponse {
808    /// Decision: "approve" | "request_changes"
809    pub decision: String,
810    /// Detailed review feedback.
811    pub notes: String,
812    /// Test results: "pass" | "fail" | "skipped"
813    pub test_results: Option<String>,
814    /// List of issues found.
815    pub issues: Vec<ReviewIssue>,
816}
817
818/// Parse a review response from already-unwrapped text.
819///
820/// Expects the raw result text (already extracted from the agent envelope
821/// by the agent-specific parser). Tries direct JSON parse, then markdown
822/// code block extraction.
823pub fn parse_review_response(text: &str) -> anyhow::Result<ReviewResponse> {
824    let resp = parse_review_json(text)?;
825    if matches!(resp.decision.as_str(), "approve" | "request_changes") {
826        return Ok(resp);
827    }
828
829    // Weak models echo the prompt template ("approve|request_changes"), strip it so it
830    // does not match the "request_changes" keyword
831    let stripped = text.replace("approve|request_changes", "");
832    infer_review_response_from_text(&stripped)
833        .ok_or_else(|| anyhow::anyhow!("invalid review decision: {}", resp.decision))
834}
835
836fn parse_review_json(text: &str) -> anyhow::Result<ReviewResponse> {
837    // Try direct JSON parse
838    if let Ok(resp) = serde_json::from_str::<ReviewResponse>(text) {
839        return Ok(resp);
840    }
841
842    // Try extracting JSON from markdown code blocks
843    if let Some(json_str) = extract_json_block(text)
844        && let Ok(resp) = serde_json::from_str::<ReviewResponse>(&json_str)
845    {
846        return Ok(resp);
847    }
848
849    if let Some(resp) = extract_review_response_object(text) {
850        return Ok(resp);
851    }
852
853    anyhow::bail!("failed to parse review response")
854}
855
856fn infer_review_response_from_text(text: &str) -> Option<ReviewResponse> {
857    let lower = text.to_ascii_lowercase();
858    let has_changes_requested =
859        lower.contains("changes requested") || lower.contains("request_changes");
860    if has_changes_requested {
861        return Some(ReviewResponse {
862            decision: "request_changes".to_string(),
863            notes: "Inferred decision from plain-text review output.".to_string(),
864            test_results: None,
865            issues: Vec::new(),
866        });
867    }
868
869    // Approval only from an explicit decision token. "approved" and CI-evidence
870    // phrases ("all checks passed") are not a decision, a negation list cannot cover them
871    let positive_approval = lower
872        .split(|c: char| !c.is_ascii_alphabetic())
873        .any(|word| word == "lgtm")
874        || lower.contains("decision is `approve`")
875        || lower.contains("decision: `approve`")
876        || lower.contains("decision is approve")
877        || lower.contains("decision: approve");
878    if positive_approval {
879        return Some(ReviewResponse {
880            decision: "approve".to_string(),
881            notes: "Inferred decision from plain-text review output.".to_string(),
882            test_results: None,
883            issues: Vec::new(),
884        });
885    }
886
887    None
888}
889
890/// Public entry point for keyword-based review response inference.
891///
892/// Used by `review.rs` when `parse_review_response` fails on the extracted text.
893pub fn infer_review_response(text: &str) -> Option<ReviewResponse> {
894    infer_review_response_from_text(text)
895}
896
897/// Extract the first valid JSON object from markdown code blocks.
898///
899/// Searches for ```json blocks and returns the first one whose content
900/// starts with `{`, skipping non-JSON code blocks.
901fn extract_json_block(text: &str) -> Option<String> {
902    let mut search_from = 0;
903    while let Some(start) = text[search_from..].find("```json") {
904        let abs_start = search_from + start;
905        let after_tag = abs_start + "```json".len();
906        let Some(rest) = text[after_tag..].strip_prefix('\n') else {
907            search_from = after_tag;
908            continue;
909        };
910        let content_start = text.len() - rest.len();
911        let Some(end_offset) = rest.find("```") else {
912            search_from = content_start;
913            continue;
914        };
915        let end = content_start + end_offset;
916        let content = text[content_start..end].trim();
917        if content.starts_with('{') {
918            return Some(content.to_string());
919        }
920        search_from = end + 3;
921    }
922    None
923}
924
925/// Extract a ReviewResponse JSON object from arbitrary text.
926///
927/// Scans for balanced JSON objects and tries to parse them as ReviewResponse.
928fn extract_review_response_object(text: &str) -> Option<ReviewResponse> {
929    let mut start: Option<usize> = None;
930    let mut depth: i32 = 0;
931    let mut in_string = false;
932    let mut escape = false;
933
934    for (idx, ch) in text.char_indices() {
935        if start.is_some() {
936            if in_string {
937                if escape {
938                    escape = false;
939                } else if ch == '\\' {
940                    escape = true;
941                } else if ch == '"' {
942                    in_string = false;
943                }
944                continue;
945            }
946
947            match ch {
948                '"' => in_string = true,
949                '{' => depth += 1,
950                '}' => {
951                    depth -= 1;
952                    if depth == 0 {
953                        debug_assert!(
954                            start.is_some(),
955                            "start must be Some when depth returns to 0"
956                        );
957                        let start_idx = start.unwrap_or(0);
958                        let candidate = &text[start_idx..=idx];
959                        if let Ok(resp) = serde_json::from_str::<ReviewResponse>(candidate) {
960                            return Some(resp);
961                        }
962                        start = None;
963                    }
964                }
965                _ => {}
966            }
967            continue;
968        }
969
970        if ch == '{' {
971            start = Some(idx);
972            depth = 1;
973            in_string = false;
974            escape = false;
975        }
976    }
977
978    None
979}
980
981/// Extract learnings and store as memory for future attempts.
982#[expect(
983    clippy::too_many_arguments,
984    reason = "a memory entry records the task, attempt, agent, model and outcome"
985)]
986pub async fn store_learnings_from_response(
987    task_id: &str,
988    attempt: u32,
989    agent: &str,
990    model: Option<&str>,
991    response: &AgentResponse,
992    error: Option<&str>,
993    store: &Option<Arc<TaskStore>>,
994    repo: &str,
995    raw_stdout: &str,
996) {
997    // Use agent self-reported files; fall back to NDJSON tool-call extraction when empty.
998    let files_modified = if response.files.is_empty() {
999        let extracted = ndjson::extract_files_changed(raw_stdout);
1000        if !extracted.is_empty() {
1001            tracing::debug!(
1002                task_id,
1003                count = extracted.len(),
1004                "files_modified: fell back to NDJSON extraction (agent reported none)"
1005            );
1006        }
1007        extracted
1008    } else {
1009        response.files.clone()
1010    };
1011
1012    // Build the memory entry
1013    let entry = MemoryEntry {
1014        attempt,
1015        agent: agent.to_string(),
1016        model: model.map(String::from),
1017        learnings: response.learnings.clone(),
1018        error: error.map(String::from),
1019        files_modified,
1020        approach: response.summary.clone(),
1021        timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1022    };
1023
1024    if let Some(st) = store
1025        && let Ok(Some(store_id)) = st.resolve_task_id(repo, task_id).await
1026    {
1027        match st.append_memory(store_id, &entry).await {
1028            Err(e) => {
1029                tracing::warn!(task_id, error = ?e, "failed to store memory");
1030            }
1031            _ => {
1032                tracing::debug!(task_id, attempt, "stored memory for attempt");
1033            }
1034        }
1035    }
1036}
1037
1038/// Store a memory entry for a failed attempt (without a full AgentResponse).
1039pub async fn store_failure_memory(
1040    task_id: &str,
1041    attempt: u32,
1042    agent: &str,
1043    model: Option<&str>,
1044    error: &str,
1045    store: &Option<Arc<TaskStore>>,
1046    repo: &str,
1047) {
1048    let entry = MemoryEntry {
1049        attempt,
1050        agent: agent.to_string(),
1051        model: model.map(String::from),
1052        learnings: vec![],
1053        error: Some(error.to_string()),
1054        files_modified: vec![],
1055        approach: String::new(),
1056        timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1057    };
1058
1059    if let Some(st) = store
1060        && let Ok(Some(store_id)) = st.resolve_task_id(repo, task_id).await
1061    {
1062        match st.append_memory(store_id, &entry).await {
1063            Err(e) => {
1064                tracing::warn!(task_id, error = ?e, "failed to store failure memory");
1065            }
1066            _ => {
1067                tracing::debug!(task_id, attempt, "stored failure memory");
1068            }
1069        }
1070    }
1071}
1072
1073#[cfg(test)]
1074mod tests;