Skip to main content

orch/engine/runner/
mod.rs

1//! Task runner — executes tasks using AI agents.
2//!
3//! Replaces `run_task.sh` with pure Rust. The runner:
4//! 1. Sets up a git worktree for isolation
5//! 2. Builds context (project instructions, comments)
6//! 3. Renders prompts and spawns the agent in tmux
7//! 4. Waits for completion, collects and classifies the response
8//! 5. Handles errors (reroute on limits, fallback agents)
9//! 6. Auto-commits, pushes, and creates PRs
10//! 7. Updates status labels and posts result comments
11//!
12//! Submodules handle the heavy lifting:
13//! - [`task_init`] — guard checks, worktree setup, and invocation building
14//! - [`session`] — tmux session lifecycle and output collection
15//! - [`response_handler`] — success path: commit, push, PR, token storage
16//! - [`fallback`] — error classification and recovery strategies
17
18pub mod agent;
19pub mod agents;
20pub mod commit;
21pub mod context;
22pub mod cow;
23pub mod diff;
24pub mod direct;
25pub mod fallback;
26pub mod git_ops;
27pub mod ndjson;
28#[cfg(test)]
29mod recorded_fixtures;
30pub mod response;
31pub mod response_handler;
32pub mod sandbox;
33pub mod screenshots;
34pub mod session;
35pub mod task_init;
36pub mod worktree;
37
38use crate::backends::{ExternalBackend, ExternalTask, Status};
39use crate::config;
40use crate::cooldown;
41use crate::engine;
42use crate::engine::cleanup;
43use crate::engine::router::RouteResult;
44use crate::engine::tasks;
45use crate::engine::tasks::is_internal_id;
46#[cfg(not(test))]
47use crate::github::http;
48use crate::github::http::GhHttp;
49use crate::home;
50use crate::parser;
51use crate::parser::AgentResponse;
52use crate::parser::Delegation;
53use crate::status_heuristics;
54use crate::store;
55use crate::store::InsertTaskMetric;
56use crate::store::RunTokenUsage;
57use crate::store::TaskStatus;
58use crate::store::TaskStore;
59use crate::tmux::TmuxManager;
60use anyhow::Context;
61use chrono::Utc;
62pub use response::WeightSignal;
63use serde_json::Value;
64use std::collections::HashSet;
65use std::env;
66use std::error;
67use std::fmt;
68use std::fmt::Debug;
69use std::fmt::Formatter;
70use std::path::PathBuf;
71use std::slice;
72use std::sync::Arc;
73use std::time::Duration;
74use tokio::fs;
75use tokio::task;
76
77/// Fully materialized task-run audit data.
78#[derive(Debug, Clone)]
79pub struct RunAudit {
80    pub stdout: String,
81    pub stderr: String,
82    pub parsed_response: String,
83    pub outcome: String,
84    pub error: String,
85    pub input_tokens: u64,
86    pub output_tokens: u64,
87    pub total_cost_usd: f64,
88    pub duration_secs: f64,
89}
90
91/// Result returned by `run()` so callers can persist the audit trail.
92#[derive(Debug, Clone)]
93pub struct RunExecution {
94    pub status: String,
95    pub exit_code: Option<i32>,
96    pub audit: RunAudit,
97}
98
99fn serialize_parsed_response(
100    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
101    raw_stdout: &str,
102) -> String {
103    match parse_result {
104        Ok(parsed) => serde_json::json!({
105            "response": parsed.response,
106            "input_tokens": parsed.input_tokens,
107            "output_tokens": parsed.output_tokens,
108            "cost_usd": parsed.cost_usd,
109            "duration_ms": parsed.duration_ms,
110        })
111        .to_string(),
112        Err(agents::AgentError::InvalidResponse { raw }) => {
113            serde_json::json!({"raw": raw}).to_string()
114        }
115        Err(_) => serde_json::json!({"raw": raw_stdout}).to_string(),
116    }
117}
118
119fn classify_run_outcome(
120    status: &str,
121    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
122    push_failed: bool,
123) -> &'static str {
124    if push_failed {
125        return "push_failed";
126    }
127    match parse_result {
128        Err(agents::AgentError::Timeout { .. }) => "timeout",
129        Err(agents::AgentError::Interrupted { .. }) => "interrupted",
130        // Generic rate-limit patterns (e.g. "usage limit") also match billing-cycle
131        // exhaustion messages, so consult the credit-exhaustion detector first —
132        // otherwise Kimi-style "usage limit for this billing cycle" errors are
133        // stored as a plain "rate_limit" outcome (issue #3529).
134        Err(agents::AgentError::RateLimit { message }) => {
135            cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("rate_limit")
136        }
137        Err(agents::AgentError::Auth { message }) => {
138            cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("failed")
139        }
140        Err(agents::AgentError::InvalidResponse { .. }) => "parse_error",
141        Ok(_)
142            if matches!(
143                status,
144                "done" | "completed" | "in_progress" | "in_review" | "needs_review" | "routed"
145            ) =>
146        {
147            "success"
148        }
149        Ok(_) if status == "blocked" => "blocked",
150        // Non-canonical status that clearly reads as completion — success, not
151        // "unrecognized status" (#3627).
152        Ok(_) if status_heuristics::status_looks_like_descriptive_completion(status) => "success",
153        Err(_) | Ok(_) => "failed",
154    }
155}
156
157fn classify_run_error_type(last_error: &str) -> &'static str {
158    if last_error.is_empty() {
159        // No error: agent completed successfully and created a PR waiting for review
160        "success"
161    } else if last_error.contains("timeout") {
162        "timeout"
163    } else if last_error.contains("interrupted") {
164        "interrupted"
165    } else if last_error.contains("billing cycle") || last_error.contains("monthly quota") {
166        "billing_cycle_exhausted"
167    } else if last_error.contains("rate limit") || last_error.contains("usage limit") {
168        "rate_limit"
169    } else if last_error.contains("auth") {
170        "auth_error"
171    } else if last_error.contains("push failed") {
172        "push_failed"
173    } else if last_error.contains("No commits between") || last_error.contains("no commits") {
174        "no_commits"
175    } else if last_error.contains("create PR failed")
176        || last_error.contains("failed to create pull request")
177        || last_error.contains("pull request creation failed")
178    {
179        "pr_failed"
180    } else if last_error.contains("invalid response") || last_error.contains("parse error") {
181        "parse_error"
182    } else if last_error.contains("exceeded max attempts") {
183        "max_attempts"
184    } else {
185        let lower = last_error.to_ascii_lowercase();
186        if lower.contains("build failed")
187            || lower.contains("tests failed")
188            || lower.contains("test failed")
189            || lower.contains("test suite failed")
190            || lower.contains("lint failed")
191        {
192            "ci_failure"
193        } else {
194            "failed"
195        }
196    }
197}
198
199fn extract_run_tokens(
200    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
201) -> (u64, u64) {
202    match parse_result {
203        Ok(parsed) => (
204            parsed
205                .input_tokens
206                .or(parsed.response.input_tokens)
207                .unwrap_or(0),
208            parsed
209                .output_tokens
210                .or(parsed.response.output_tokens)
211                .unwrap_or(0),
212        ),
213        Err(_) => (0, 0),
214    }
215}
216
217#[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
218fn run_duration_secs(started_at: &chrono::DateTime<Utc>) -> f64 {
219    (Utc::now() - *started_at).num_milliseconds() as f64 / 1000.0
220}
221
222struct RunAuditInput<'a> {
223    task_id: &'a str,
224    status: &'a str,
225    parse_result: &'a Result<agents::ParsedResponse, agents::AgentError>,
226    raw_stdout: &'a str,
227    raw_stderr: &'a str,
228    started_at: &'a chrono::DateTime<Utc>,
229    error_override: Option<String>,
230    elapsed_secs: Option<u64>,
231    push_failed: bool,
232}
233
234fn parse_success_output(
235    task_id: &str,
236    agent_name: &str,
237    agent_runner: &dyn agents::AgentRunner,
238    raw_stdout: &str,
239) -> Result<agents::ParsedResponse, agents::AgentError> {
240    // The last result envelope is the agent's final answer and carries the run's tokens and cost.
241    // Claude writes terminal_reason:completed on every run, so this goes before that shortcut
242    let agent_result = agents::find_agent_result(agent_name, raw_stdout);
243    if let Some(result) = &agent_result
244        && !result.is_error
245        && let Ok(response) = parser::parse(&result.result_text)
246    {
247        return Ok(agents::ParsedResponse {
248            response,
249            input_tokens: result.input_tokens,
250            output_tokens: result.output_tokens,
251            cost_usd: result.cost_usd,
252            duration_ms: result.duration_ms,
253        });
254    }
255
256    // Quick NDJSON terminal_reason:completed shortcut: when the agent
257    // emitted a session envelope that explicitly signals completion we
258    // prefer to interpret that as a successful run (or at least a
259    // soft/empty success) rather than immediately classifying an error
260    // from the trailing process output.  Do not override explicit
261    // in-envelope `is_error: true` signals.
262    if raw_stdout.contains("\"terminal_reason\":\"completed\"")
263        && !raw_stdout.contains("\"is_error\":true")
264    {
265        // Try to recover a structured response from assistant messages first
266        let assistant_text = agents::collect_assistant_messages_text(agent_name, raw_stdout);
267        if !assistant_text.is_empty() {
268            if let Ok(response) = parser::parse(&assistant_text) {
269                tracing::debug!(
270                    task_id,
271                    agent = agent_name,
272                    "found AgentResponse JSON in earlier assistant message (terminal_reason:completed)"
273                );
274                return Ok(agents::ParsedResponse {
275                    response,
276                    input_tokens: None,
277                    output_tokens: None,
278                    cost_usd: None,
279                    duration_ms: None,
280                });
281            }
282            if let Some(response) = agents::synthesize_response_from_text(&assistant_text) {
283                tracing::warn!(
284                    task_id,
285                    agent = agent_name,
286                    "synthesizing response from assistant message due to terminal_reason:completed"
287                );
288                return Ok(agents::ParsedResponse {
289                    response,
290                    input_tokens: None,
291                    output_tokens: None,
292                    cost_usd: None,
293                    duration_ms: None,
294                });
295            }
296        }
297        // If we couldn't recover structured data from earlier assistant
298        // messages, fall through and let the regular NDJSON envelope parsing
299        // / agent-specific parsers handle the terminal_reason case. This
300        // preserves the existing behavior where an empty `result` field
301        // combined with exit != 0 becomes an InvalidResponse that is then
302        // interpreted by parse_session_output (see tests).
303    }
304
305    // 1. Try to use the unified agent result extractor first
306    if let Some(agent_result) = agent_result {
307        // Treat is_error as authoritative for the success path
308        if agent_result.is_error {
309            // Classify the error from the agent's result text rather than
310            // blindly returning AgentFailed — this preserves rate-limit, auth,
311            // and other actionable error types for proper cooldown/reroute.
312            // Without this, e.g. a claude session-limit error with is_error=true
313            // would be downgraded to AgentFailed, losing the RateLimit signal
314            // that the fallback chain needs for UsageLimit recovery (issue #3292).
315            if let Some(e) = agents::patterns::detect_rate_limit(&agent_result.result_text) {
316                return Err(e);
317            }
318            if let Some(e) = agents::patterns::detect_auth_error(&agent_result.result_text) {
319                return Err(e);
320            }
321            if let Some(e) = agents::patterns::detect_model_unavailable(&agent_result.result_text) {
322                return Err(e);
323            }
324            // Grok puts "the wait for background work ran out" in errors[] and
325            // exits 1. That is a timeout, so handle_failover retries
326            let classified = agent_runner.classify_error(1, raw_stdout, "");
327            if matches!(classified, agents::AgentError::Timeout { .. }) {
328                return Err(classified);
329            }
330            return Err(agents::AgentError::AgentFailed {
331                message: agent_result.result_text,
332            });
333        }
334
335        // Strategy 2: scan all earlier assistant messages in the NDJSON
336        // stream for valid AgentResponse JSON. Agents often emit the
337        // JSON in an intermediate turn and then summarise in prose as
338        // their final output, so the `type:result` text may be pure
339        // narrative while a prior assistant turn contains the JSON.
340        let assistant_text = agents::collect_assistant_messages_text(agent_name, raw_stdout);
341        if !assistant_text.is_empty()
342            && let Ok(response) = parser::parse(&assistant_text)
343        {
344            tracing::debug!(
345                task_id,
346                agent = agent_name,
347                "found AgentResponse JSON in earlier assistant message"
348            );
349            return Ok(agents::ParsedResponse {
350                response,
351                input_tokens: agent_result.input_tokens,
352                output_tokens: agent_result.output_tokens,
353                cost_usd: agent_result.cost_usd,
354                duration_ms: agent_result.duration_ms,
355            });
356        }
357
358        // Only fall back to text synthesis when parsing fails
359        if let Some(response) = agents::synthesize_response_from_text(&agent_result.result_text) {
360            tracing::warn!(
361                task_id,
362                agent = agent_name,
363                "parse failed on agent result, synthesizing response from plain text"
364            );
365            return Ok(agents::ParsedResponse {
366                response,
367                input_tokens: agent_result.input_tokens,
368                output_tokens: agent_result.output_tokens,
369                cost_usd: agent_result.cost_usd,
370                duration_ms: agent_result.duration_ms,
371            });
372        }
373
374        // NDJSON envelope fallback: the envelope explicitly reports
375        // success (is_error=false) but the result content is domain
376        // JSON or plain prose that doesn't match AgentResponse schema
377        // and doesn't contain completion keywords.  Rather than
378        // returning InvalidResponse (which causes the task to re-run),
379        // synthesize a minimal "done" response from the result text.
380        //
381        // Guard against kimi/minimax edge case: when terminal_reason=completed
382        // but result text is empty, synthesize returns None, parse_success_output
383        // returns InvalidResponse, and parse_session_output can intercept it
384        // before classify_error. Requiring non-empty result here means the
385        // envelope fallback only fires when we have actual text to report.
386        if !agent_result.is_error
387            && result_envelope_completed(raw_stdout)
388            && !agent_result.result_text.is_empty()
389        {
390            let summary_end = agents::truncate_at_char_boundary(&agent_result.result_text, 500);
391            let summary = agent_result.result_text[..summary_end].to_string();
392            tracing::warn!(
393                task_id,
394                agent = agent_name,
395                "NDJSON envelope indicates success but result lacks AgentResponse \
396                 schema — synthesizing done response"
397            );
398            return Ok(agents::ParsedResponse {
399                response: AgentResponse {
400                    status: "done".to_string(),
401                    summary,
402                    ..Default::default()
403                },
404                input_tokens: agent_result.input_tokens,
405                output_tokens: agent_result.output_tokens,
406                cost_usd: agent_result.cost_usd,
407                duration_ms: agent_result.duration_ms,
408            });
409        }
410    }
411
412    // 2. Fall back to generic agent-specific parser if extraction failed
413    match agent_runner.parse_response(raw_stdout) {
414        Ok(parsed) => Ok(parsed),
415        Err(agents::AgentError::InvalidResponse { raw }) => {
416            if let Some(response) = agents::synthesize_response_from_text(&raw) {
417                tracing::warn!(
418                    task_id,
419                    agent = agent_name,
420                    "parse failed, synthesizing response from plain text"
421                );
422                // Try to extract token metadata from the original raw NDJSON
423                // output (not the truncated/extracted text from the error), so
424                // cost tracking isn't lost for agents that return free-form text.
425                let agent_result = agents::find_agent_result(agent_name, raw_stdout);
426                let input_tokens = agent_result.as_ref().and_then(|r| r.input_tokens);
427                let output_tokens = agent_result.as_ref().and_then(|r| r.output_tokens);
428                let cost_usd = agent_result.as_ref().and_then(|r| r.cost_usd);
429                let duration_ms = agent_result.as_ref().and_then(|r| r.duration_ms);
430                Ok(agents::ParsedResponse {
431                    response,
432                    input_tokens,
433                    output_tokens,
434                    cost_usd,
435                    duration_ms,
436                })
437            } else {
438                Err(agents::AgentError::InvalidResponse { raw })
439            }
440        }
441        Err(err) => Err(err),
442    }
443}
444
445/// Whether the last `type: result` line reports `subtype: success` or
446/// `terminal_reason: completed`. Grok omits `terminal_reason`.
447fn result_envelope_line(raw_stdout: &str) -> Option<serde_json::Value> {
448    raw_stdout
449        .lines()
450        .rev()
451        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
452        .find(|v| v.get("type").and_then(|t| t.as_str()) == Some("result"))
453}
454
455fn has_result_envelope(raw_stdout: &str) -> bool {
456    result_envelope_line(raw_stdout).is_some()
457}
458
459fn result_envelope_completed(raw_stdout: &str) -> bool {
460    result_envelope_line(raw_stdout).is_some_and(|v| {
461        v.get("subtype").and_then(|t| t.as_str()) == Some("success")
462            || v.get("terminal_reason").and_then(|t| t.as_str()) == Some("completed")
463    })
464}
465
466// A timeout kill has no result envelope. Salvage only the wrap-up shape: a successful
467// `git commit`, then only shell calls that all returned ok. Returns the last assistant text
468fn salvage_wrapup(raw: &str) -> Option<String> {
469    // (tool name, command, finished ok) in call order
470    let mut calls: Vec<(String, String, Option<bool>)> = Vec::new();
471    let mut last_text = String::new();
472    for v in raw
473        .lines()
474        .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
475    {
476        let blocks = v.pointer("/message/content").and_then(|c| c.as_array());
477        for b in blocks.into_iter().flatten() {
478            match b.get("type").and_then(|t| t.as_str()) {
479                Some("tool_use") => calls.push((
480                    b["name"].as_str().unwrap_or("").to_string(),
481                    b.pointer("/input/command")
482                        .and_then(|c| c.as_str())
483                        .unwrap_or("")
484                        .to_string(),
485                    None,
486                )),
487                Some("text") if v["type"] == "assistant" => {
488                    last_text = b["text"].as_str().unwrap_or("").to_string();
489                }
490                Some("tool_result") => {
491                    let ok = b.get("is_error").and_then(serde_json::Value::as_bool) != Some(true);
492                    // results arrive in call order, fill the first unanswered call
493                    if let Some(c) = calls.iter_mut().find(|c| c.2.is_none()) {
494                        c.2 = Some(ok);
495                    }
496                }
497                _ => {}
498            }
499        }
500    }
501    let commit = calls
502        .iter()
503        .rposition(|(_, cmd, ok)| cmd.contains("git commit") && *ok == Some(true))?;
504    let tail_ok = calls[commit..].iter().all(|(name, _, ok)| {
505        matches!(name.as_str(), "Bash" | "run_terminal_cmd") && *ok == Some(true)
506    });
507    let lower = last_text.to_lowercase();
508    if !tail_ok || lower.contains("still running") || lower.contains("in progress") {
509        return None;
510    }
511    Some(last_text.chars().take(500).collect())
512}
513
514/**
515 * Tries `parse_success_output` first when stdout is non-empty. If that succeeds,
516 * returns success regardless of exit code. If it fails and `exit_code != 0`,
517 * checks for `"terminal_reason":"completed"` or cost-telemetry-only stdout
518 * (`"costUSD":`) before falling back to `classify_error`, so valid sessions that
519 * exit 1 produce `InvalidResponse` (soft error, re-route) instead of a garbled
520 * `Unknown`/`Auth` error (hard failure with spurious cooldown)
521 **/
522pub fn parse_session_output(
523    task_id: &str,
524    agent_name: &str,
525    agent_runner: &dyn agents::AgentRunner,
526    session_output: &session::SessionOutput,
527) -> Result<agents::ParsedResponse, agents::AgentError> {
528    // Some agents may emit NDJSON/telemetry to stderr instead of stdout. Combine
529    // both streams so parse_success_output can inspect either place for the
530    // terminal_reason/cost telemetry envelope. Only skip parsing when both are
531    // empty so we still attempt recovery when stderr contains the envelope.
532    let combined_output = format!("{}{}", session_output.raw_stdout, session_output.raw_stderr);
533    if !(session_output.raw_stdout.is_empty() && session_output.raw_stderr.is_empty()) {
534        match parse_success_output(task_id, agent_name, agent_runner, &combined_output) {
535            Ok(parsed) => return Ok(parsed),
536            Err(err) => {
537                if session_output.exit_code == 124 {
538                    if let Some(summary) = salvage_wrapup(&combined_output) {
539                        tracing::warn!(
540                            task_id,
541                            agent = agent_name,
542                            "timed out after commit during wrap-up, salvaging as done"
543                        );
544                        return Ok(agents::ParsedResponse {
545                            response: AgentResponse {
546                                status: "done".to_string(),
547                                summary,
548                                ..Default::default()
549                            },
550                            input_tokens: None,
551                            output_tokens: None,
552                            cost_usd: None,
553                            duration_ms: None,
554                        });
555                    }
556                    // timeout(1) killed the process. A cancelled error envelope is the CLI
557                    // reacting to SIGTERM
558                    return Err(agent_runner.classify_error_with_elapsed(
559                        session_output.exit_code,
560                        &session_output.raw_stdout,
561                        &session_output.raw_stderr,
562                        session_output.elapsed_secs,
563                    ));
564                }
565                // If parse_success_output already returned a classified error
566                // (RateLimit, AgentFailed, Timeout, Auth, etc.), propagate it
567                // directly — only InvalidResponse (unparseable output) should
568                // be intercepted by the terminal_reason:completed / cost-telemetry
569                // guard below. Without this, e.g. a claude session-limit error
570                // with terminal_reason=completed would be downgraded from RateLimit
571                // to InvalidResponse → Failed, losing the correct cooldown/reroute.
572                if !matches!(err, agents::AgentError::InvalidResponse { .. }) {
573                    let mut err = err;
574                    if let agents::AgentError::Timeout { elapsed } = &mut err
575                        && let Some(secs) = session_output.elapsed_secs
576                    {
577                        *elapsed = Duration::from_secs(secs);
578                    }
579                    return Err(err);
580                }
581                if session_output.exit_code != 0 {
582                    // kimi/minimax/glm sometimes emit valid NDJSON with
583                    // "terminal_reason":"completed" or cost-only telemetry
584                    // ("costUSD":) but exit 1 due to a post-session hook or
585                    // minor CLI issue. Scanning the tail would just grab JSON
586                    // metadata, producing a garbled error. Detect either
587                    // completion signal and treat as a soft parse error so the
588                    // task re-routes instead of hitting a false cooldown from
589                    // Unknown or Auth error variants. Use the combined output
590                    // (stdout+stderr) so envelopes written to stderr are
591                    // observed.
592                    let combined = &combined_output;
593                    let is_completed_signal =
594                        combined.contains("\"terminal_reason\":\"completed\"");
595                    // GLM emits a cost-telemetry JSON object (containing
596                    // "costUSD":) as its final stdout/stderr line on clean
597                    // exit even when the process exits with code 1. If the
598                    // only content is such telemetry (no is_error=true in the
599                    // envelope), treat it the same as terminal_reason:completed.
600                    let is_cost_telemetry_only = combined.contains("\"costUSD\":")
601                        && !combined.contains("\"is_error\":true");
602                    if is_completed_signal || is_cost_telemetry_only {
603                        let raw_tail = agents::patterns::safe_tail(combined, 300);
604                        return Err(agents::AgentError::InvalidResponse {
605                            raw: raw_tail.to_string(),
606                        });
607                    }
608                    return Err(agent_runner.classify_error_with_elapsed(
609                        session_output.exit_code,
610                        &session_output.raw_stdout,
611                        &session_output.raw_stderr,
612                        session_output.elapsed_secs,
613                    ));
614                }
615                if !has_result_envelope(&combined_output) {
616                    return Err(agents::AgentError::Interrupted {
617                        message: "exited without a result envelope".to_string(),
618                    });
619                }
620                return Err(err);
621            }
622        }
623    }
624
625    if session_output.exit_code != 0 {
626        return Err(agent_runner.classify_error_with_elapsed(
627            session_output.exit_code,
628            &session_output.raw_stdout,
629            &session_output.raw_stderr,
630            session_output.elapsed_secs,
631        ));
632    }
633
634    Err(agents::AgentError::Unknown {
635        exit_code: session_output.exit_code,
636        message: "empty-output-exit0: opencode returned exit 0 with empty stdout".to_string(),
637    })
638}
639
640/// The repo has no project directory: not in the active config, no legacy
641/// `project_dir`, no bare clone. It fails before any agent starts
642#[derive(Debug)]
643pub(crate) struct NoProjectDir {
644    pub(crate) repo: String,
645    pub(crate) bare_clone: PathBuf,
646}
647
648impl NoProjectDir {
649    /// Block reason for a task of this repo
650    pub(crate) const BLOCK_REASON: &str = "project is not configured and has no bare clone";
651}
652
653impl fmt::Display for NoProjectDir {
654    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
655        write!(
656            f,
657            "no resolvable project directory for repo {} — not in active config, no bare clone at {}, no legacy project_dir set",
658            self.repo,
659            self.bare_clone.display()
660        )
661    }
662}
663
664impl error::Error for NoProjectDir {}
665
666/// Task runner configuration.
667pub struct TaskRunner {
668    /// Repository slug (owner/repo)
669    repo: String,
670    /// Path to the orch home directory
671    orch_home: PathBuf,
672    /// Unified task store for run audit trail
673    store: Option<Arc<TaskStore>>,
674}
675
676impl Debug for TaskRunner {
677    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
678        f.debug_struct("TaskRunner")
679            .field("repo", &self.repo)
680            .field("orch_home", &self.orch_home)
681            .finish_non_exhaustive()
682    }
683}
684
685impl TaskRunner {
686    pub fn new(repo: String) -> Self {
687        let orch_home = home::orch_home().unwrap_or_else(|e| {
688            tracing::warn!(error = %e, "orch_home() failed — falling back to /tmp/.orch");
689            PathBuf::from("/tmp").join(".orch")
690        });
691
692        Self {
693            repo,
694            orch_home,
695            store: None,
696        }
697    }
698
699    /// Set the unified task store for run audit trail.
700    #[must_use]
701    pub fn with_store(mut self, store: Arc<TaskStore>) -> Self {
702        self.store = Some(store);
703        self
704    }
705
706    /// Read a field from the task store.
707    async fn get_field(&self, task_id: &str, field: &str) -> Option<String> {
708        let task = store::opt_store_get_task(&self.store, &self.repo, task_id).await?;
709        match field {
710            "route_reason" => Some(task.route_reason),
711            "worktree" => Some(task.worktree),
712            "attempts" => Some(task.attempts.to_string()),
713            "delegations" => serde_json::to_string(&task.delegations).ok(),
714            "summary" => Some(task.summary),
715            "last_error" => Some(task.last_error),
716            "agent" => task.agent,
717            _ => None,
718        }
719    }
720
721    /// Keep a stored fallback on reroute, wipe agent/model when the run's agent is still stored
722    pub(crate) async fn clear_agent_on_reroute_unless_fallback(
723        &self,
724        task_id: &str,
725        ran_agent: &str,
726    ) {
727        let stored = store::opt_store_get_task(&self.store, &self.repo, task_id).await;
728        if Self::reroute_keeps_stored_agent(stored.as_ref(), ran_agent) {
729            tracing::debug!(
730                task_id,
731                "stored fallback agent present, skipping agent/model clear"
732            );
733            return;
734        }
735        if let Err(e) = store::store_set_result(
736            &self.store,
737            &self.repo,
738            task_id,
739            &[
740                ("agent", serde_json::json!("")),
741                ("model", serde_json::json!("")),
742            ],
743        )
744        .await
745        {
746            tracing::warn!(task_id, err = %e, "failed to clear agent/model for reroute in store");
747        }
748    }
749
750    /// True when a fallback is already stored and must survive this reroute
751    fn reroute_keeps_stored_agent(stored: Option<&store::Task>, ran_agent: &str) -> bool {
752        let Some(task) = stored else {
753            return false;
754        };
755        if !matches!(task.status, TaskStatus::InProgress) {
756            return true;
757        }
758        let stored_agent = task.agent.as_deref().unwrap_or("");
759        !stored_agent.is_empty() && stored_agent != ran_agent
760    }
761
762    async fn build_run_audit(&self, input: RunAuditInput<'_>) -> RunAudit {
763        // Filter empty strings so that a blank last_error does not shadow the
764        // actual parse_result error.  Without this, `Option::or(Some(""))` would
765        // return `Some("")` and prevent the `unwrap_or_else` fallback from ever
766        // running, causing task_runs.error to be written as "" even when the
767        // agent returned a classifiable error (fixes issue #2527).
768        let last_error = self
769            .get_field(input.task_id, "last_error")
770            .await
771            .filter(|s| !s.is_empty());
772        let outcome =
773            classify_run_outcome(input.status, input.parse_result, input.push_failed).to_string();
774
775        let error = if outcome == "success" {
776            String::new()
777        } else {
778            // Prefer this run's parsed error over a last_error left by a previous
779            // agent's failover. last_error stays the Err/EarlyReturn fallback (#3851)
780            let error = input
781                .error_override
782                .as_deref()
783                .filter(|s| !s.is_empty())
784                .map(str::to_string)
785                .or_else(|| match input.parse_result {
786                    Ok(parsed) => parsed
787                        .response
788                        .error
789                        .as_deref()
790                        .filter(|s| !s.is_empty())
791                        .map(str::to_string),
792                    Err(_) => None,
793                })
794                .or(last_error)
795                .unwrap_or_else(|| match input.parse_result {
796                    Ok(_) => String::new(),
797                    Err(err) => err.to_string(),
798                });
799
800            if error.is_empty() {
801                if input.status == "blocked" {
802                    match input.parse_result {
803                        Ok(parsed) if !parsed.response.summary.is_empty() => {
804                            parsed.response.summary.clone()
805                        }
806                        _ => "task blocked without explicit error".to_string(),
807                    }
808                } else if matches!(
809                    input.status,
810                    "done"
811                        | "completed"
812                        | "in_progress"
813                        | "in_review"
814                        | "needs_review"
815                        | "routed"
816                        | "new"
817                ) {
818                    // Canonical non-success statuses have no error message (e.g. "routed").
819                    String::new()
820                } else {
821                    // Non-canonical status with no error message — surface the status
822                    // explicitly so operators can identify which statuses need to be
823                    // added to the normalization map in parser.rs.
824                    format!("unrecognized status: {}", input.status)
825                }
826            } else {
827                error
828            }
829        };
830
831        let total_cost_usd = input
832            .parse_result
833            .as_ref()
834            .ok()
835            .and_then(|p| p.cost_usd)
836            .unwrap_or(0.0);
837
838        let (input_tokens, output_tokens) = extract_run_tokens(input.parse_result);
839
840        #[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
841        let duration_secs = input
842            .elapsed_secs
843            .map_or_else(|| run_duration_secs(input.started_at), |s| s as f64);
844
845        RunAudit {
846            stdout: input.raw_stdout.to_string(),
847            stderr: input.raw_stderr.to_string(),
848            parsed_response: serialize_parsed_response(input.parse_result, input.raw_stdout),
849            outcome,
850            error,
851            input_tokens,
852            output_tokens,
853            total_cost_usd,
854            duration_secs,
855        }
856    }
857
858    /// The blocked outcome for a sandbox that cannot start. No agent ran, so none is cooled down
859    async fn sandbox_blocked(&self, task_id: &str, reason: String) -> RunExecution {
860        tracing::error!(task_id, error = %reason, "blocking task");
861        if let Err(e) = store::store_set_result(
862            &self.store,
863            &self.repo,
864            task_id,
865            &[
866                ("last_error", serde_json::json!(reason)),
867                ("block_reason", serde_json::json!(reason)),
868            ],
869        )
870        .await
871        {
872            tracing::warn!(task_id, err = %e, "failed to write the sandbox block_reason");
873        }
874        RunExecution {
875            status: "blocked".to_string(),
876            exit_code: None,
877            audit: RunAudit {
878                stdout: String::new(),
879                stderr: String::new(),
880                parsed_response: String::new(),
881                outcome: "failed".to_string(),
882                error: reason,
883                input_tokens: 0,
884                output_tokens: 0,
885                total_cost_usd: 0.0,
886                duration_secs: 0.0,
887            },
888        }
889    }
890
891    /// Run a task through the full execution pipeline.
892    ///
893    /// Returns `Ok(None)` if the runner guard skipped the task (caller should not
894    /// post stale results). Returns `Ok(Some(status))` with the final task status.
895    pub async fn run(
896        &self,
897        task_id: &str,
898        agent: Option<&str>,
899        model: Option<&str>,
900        backend: Option<&dyn ExternalBackend>,
901        started_at: &chrono::DateTime<Utc>,
902    ) -> anyhow::Result<Option<RunExecution>> {
903        tracing::info!(
904            task_id,
905            agent = agent.unwrap_or("default"),
906            model = model.unwrap_or("default"),
907            "starting task execution"
908        );
909
910        // Check task guards; returns outcome indicating whether to proceed.
911        let attempts = match task_init::check_guards(task_id, &self.repo, &self.store).await {
912            Ok(task_init::GuardOutcome::Proceed(a)) => a,
913            Ok(task_init::GuardOutcome::Skip) => {
914                return Ok(None);
915            }
916            Ok(task_init::GuardOutcome::MaxAttempts) => {
917                // The caller marks the task blocked from the returned status, a task that ran out
918                // of attempts did not finish, so it must never reach done
919                if backend.is_some() {
920                    // If this was label-forced to a specific agent, remove the agent label
921                    // so that /retry can route to a different agent instead of looping.
922                    let route_reason = self
923                        .get_field(task_id, "route_reason")
924                        .await
925                        .unwrap_or_default();
926                    if route_reason.starts_with("label agent:") {
927                        let agent_label = route_reason.trim_start_matches("label ");
928                        let gh = GhHttp::new()?;
929                        match gh.remove_label(&self.repo, task_id, agent_label).await {
930                            Err(e) => {
931                                tracing::warn!(task_id, label = agent_label, err = %e, "failed to remove agent label after max attempts");
932                            }
933                            _ => {
934                                tracing::info!(
935                                    task_id,
936                                    label = agent_label,
937                                    "removed forced agent label after max attempts — /retry will use free routing"
938                                );
939                            }
940                        }
941                    }
942                }
943                return Ok(Some(RunExecution {
944                    status: "blocked".to_string(),
945                    exit_code: None,
946                    audit: RunAudit {
947                        stdout: String::new(),
948                        stderr: String::new(),
949                        parsed_response: String::new(),
950                        outcome: "failed".to_string(),
951                        error: "max attempts reached".to_string(),
952                        input_tokens: 0,
953                        output_tokens: 0,
954                        total_cost_usd: 0.0,
955                        duration_secs: 0.0,
956                    },
957                }));
958            }
959            Err(e) => return Err(e),
960        };
961
962        // Resolve project directory
963        let project_dir = self.resolve_project_dir().await?;
964
965        // Prepare task: worktree, context, prompts, and agent invocation
966        let init = task_init::prepare_task(
967            task_id,
968            agent,
969            model,
970            backend,
971            &self.repo,
972            &project_dir,
973            attempts,
974            &self.store,
975        )
976        .await?;
977
978        // A sandbox that cannot start blocks the task, which never runs without it. It is the
979        // operator's setup that fails, so no agent or model is cooled down
980        if init.invocation.sandbox
981            && let Err(e) = sandbox::argv(
982                &init.invocation.sandbox_scope(),
983                &env::temp_dir().join("orch-sandbox-preflight"),
984            )
985            .await
986        {
987            return Ok(Some(self.sandbox_blocked(task_id, e.to_string()).await));
988        }
989
990        // Run agent session: spawn in tmux, wait for completion, collect output
991        let (tmux, tmux_session, session_output) = session::run_agent_session(
992            task_id,
993            &init.invocation,
994            &init.attempt_dir,
995            &self.orch_home,
996        )
997        .await;
998
999        // The pre-flight policy passed but the one built at spawn did not: block the same way
1000        if let Some(reason) = session_output.sandbox_error.clone() {
1001            return Ok(Some(self.sandbox_blocked(task_id, reason).await));
1002        }
1003
1004        // Touch updated_at immediately after session exit so the stuck-task recovery
1005        // timer resets before response_handler post-processing (git push, PR creation,
1006        // status update) begins.  Without this, a session that ran longer than
1007        // no_session_stuck_timeout (default 10 min) would be re-dispatched by the tick
1008        // while the runner is still writing results.
1009        store::store_touch_updated_at(&self.store, &self.repo, task_id).await;
1010
1011        // If silence detection (tick phase1b) already rerouted this task while the
1012        // session was running, skip all fallback/review processing. Without this check the
1013        // runner would call `fallback::handle_error` on the empty output, exhaust fallback
1014        // agents, and mark the task `needs_review` — overwriting the rerouted status and
1015        // triggering a spurious review cycle.
1016        // Silence detection now sets Routed (with fallback agent) or NeedsReview (no fallback).
1017        // Check for both, plus New for backward compatibility.
1018        if let Some(stored) = store::opt_store_get_task(&self.store, &self.repo, task_id).await {
1019            let silence_reset = matches!(
1020                stored.status,
1021                TaskStatus::New | TaskStatus::Routed | TaskStatus::NeedsReview
1022            );
1023            if silence_reset {
1024                let status_str = stored.status.as_str();
1025                tracing::info!(
1026                    task_id,
1027                    status = status_str,
1028                    "task already reset by the engine — skipping fallback processing"
1029                );
1030                session::cleanup_session(task_id, &tmux, &tmux_session).await;
1031                let silence_err = agents::patterns::classify_from_text(0, "silence detected");
1032                let silence_parse: Result<agents::ParsedResponse, agents::AgentError> =
1033                    Err(silence_err);
1034                let audit = self
1035                    .build_run_audit(RunAuditInput {
1036                        task_id,
1037                        status: status_str,
1038                        parse_result: &silence_parse,
1039                        raw_stdout: &session_output.raw_stdout,
1040                        raw_stderr: &session_output.raw_stderr,
1041                        started_at,
1042                        error_override: Some(format!("task was reset by the engine while the session ran (status {status_str})")),
1043                        elapsed_secs: session_output.elapsed_secs,
1044                        push_failed: false,
1045                    })
1046                    .await;
1047                return Ok(Some(RunExecution {
1048                    status: status_str.to_string(),
1049                    exit_code: Some(session_output.exit_code),
1050                    audit,
1051                }));
1052            }
1053        }
1054
1055        // Log raw output for debugging agent failures
1056        let stdout_len = session_output.raw_stdout.len();
1057        let stderr_len = session_output.raw_stderr.len();
1058        let stdout_tail: String = session_output
1059            .raw_stdout
1060            .chars()
1061            .rev()
1062            .take(500)
1063            .collect::<String>()
1064            .chars()
1065            .rev()
1066            .collect();
1067        let stderr_tail: String = session_output
1068            .raw_stderr
1069            .chars()
1070            .rev()
1071            .take(500)
1072            .collect::<String>()
1073            .chars()
1074            .rev()
1075            .collect();
1076        tracing::info!(
1077            task_id,
1078            exit_code = session_output.exit_code,
1079            stdout_len,
1080            stderr_len,
1081            stdout_tail = %stdout_tail,
1082            stderr_tail = %stderr_tail,
1083            "agent raw output"
1084        );
1085
1086        // Use agent-specific parsing where possible. Previously we only attempted
1087        // parse_success_output when exit_code == 0 which caused runs that emitted
1088        // valid NDJSON but exited non-zero (kimi / minimax) to be classed as
1089        // failures. Try parsing success output first when stdout is present; if
1090        // parsing succeeds treat as success regardless of exit code. Only fall
1091        // back to error classification when parsing fails and the process exit
1092        // code indicates an error.
1093        for window in agents::claude::rate_limit_windows(&session_output.raw_stdout) {
1094            cooldown::record_rate_limit_window(&init.agent_name, &window).await;
1095        }
1096        let agent_runner = agents::get_runner(&init.agent_name);
1097        let parse_result =
1098            parse_session_output(task_id, &init.agent_name, &*agent_runner, &session_output);
1099
1100        // Write structured result.json for deterministic testing and debugging
1101        response_handler::write_result_json(
1102            &init.attempt_dir,
1103            task_id,
1104            &init.agent_name,
1105            init.model_name.as_deref(),
1106            session_output.exit_code,
1107            init.new_attempts,
1108            &parse_result,
1109            &session_output.raw_stdout,
1110            &session_output.raw_stderr,
1111        )
1112        .await;
1113
1114        // Handle outcome: success or error recovery
1115        // `fallback_error` carries the attributed error message from `handle_error()` when
1116        // the Continue path is taken.  It is passed as `error_override` to `build_run_audit`
1117        // so that stale `last_error` values from a previous agent's run are never written
1118        // into the current run's audit record (fixes misattribution bug: task_run shows
1119        // agent=kimi but error="minimax timed out...").
1120        let (final_status, push_failed, fallback_error) = match parse_result {
1121            Ok(ref parsed) => {
1122                let (status, push_failed) = response_handler::handle_success(
1123                    task_id,
1124                    parsed.clone(),
1125                    &init.wt,
1126                    &init.task_title,
1127                    &init.agent_name,
1128                    init.model_name.as_deref(),
1129                    init.new_attempts,
1130                    &self.repo,
1131                    &self.store,
1132                    &session_output.raw_stdout,
1133                )
1134                .await?;
1135                (status, push_failed, None)
1136            }
1137            Err(ref agent_err) => {
1138                match fallback::handle_error(
1139                    task_id,
1140                    agent_err,
1141                    &init.agent_name,
1142                    &*agent_runner,
1143                    init.model_name.as_deref(),
1144                    init.complexity.as_deref(),
1145                    init.new_attempts,
1146                    &self.store,
1147                    &self.repo,
1148                )
1149                .await?
1150                {
1151                    fallback::ErrorHandleResult::EarlyReturn { status } => {
1152                        // Task rerouted — clean up tmux session and env secrets
1153                        session::cleanup_session(task_id, &tmux, &tmux_session).await;
1154                        // The fallback handler already writes a sanitized `last_error`
1155                        // into the store for EarlyReturn paths (reroutes / needs_review).
1156                        // Passing the raw agent_err here would record noisy provider
1157                        // payloads (e.g. full api_retry NDJSON). Leave error_override
1158                        // as None so build_run_audit will prefer the store's last_error
1159                        // (see src/engine/runner/fallback/mod.rs which persists a compact
1160                        // summary for rate-limit and reroute cases).
1161                        let audit = self
1162                            .build_run_audit(RunAuditInput {
1163                                task_id,
1164                                status: &status,
1165                                parse_result: &parse_result,
1166                                raw_stdout: &session_output.raw_stdout,
1167                                raw_stderr: &session_output.raw_stderr,
1168                                started_at,
1169                                error_override: None,
1170                                elapsed_secs: session_output.elapsed_secs,
1171                                push_failed: false,
1172                            })
1173                            .await;
1174                        return Ok(Some(RunExecution {
1175                            status,
1176                            exit_code: Some(session_output.exit_code),
1177                            audit,
1178                        }));
1179                    }
1180                    fallback::ErrorHandleResult::Continue { status, error } => {
1181                        (status, false, Some(error))
1182                    }
1183                }
1184            }
1185        };
1186
1187        // Kill tmux session if still alive
1188        session::cleanup_session(task_id, &tmux, &tmux_session).await;
1189
1190        // For no-op done tasks (agent finished with no code changes and no PR),
1191        // clean up the worktree and branch immediately — tmux session is already
1192        // dead so the tmux guard won't block removal.
1193        if final_status.as_str() == "done"
1194            && let Some(ref st) = self.store
1195            && let Err(e) = cleanup::cleanup_task_worktree(task_id, &self.repo, st).await
1196        {
1197            tracing::warn!(task_id, error = ?e, "worktree cleanup failed after no-op done");
1198        }
1199
1200        // Return final status and the session exit code so callers can record it.
1201        // Use `fallback_error` as error_override when available: it carries the error message
1202        // attributed to the current agent (set by handle_error), preventing stale last_error
1203        // values from a prior run from contaminating this run's audit record.
1204        let audit = self
1205            .build_run_audit(RunAuditInput {
1206                task_id,
1207                status: &final_status,
1208                parse_result: &parse_result,
1209                raw_stdout: &session_output.raw_stdout,
1210                raw_stderr: &session_output.raw_stderr,
1211                started_at,
1212                error_override: fallback_error,
1213                elapsed_secs: session_output.elapsed_secs,
1214                push_failed,
1215            })
1216            .await;
1217
1218        Ok(Some(RunExecution {
1219            status: final_status.clone(),
1220            exit_code: Some(session_output.exit_code),
1221            audit,
1222        }))
1223    }
1224
1225    /// Record task execution metrics to the database.
1226    #[expect(
1227        clippy::too_many_arguments,
1228        reason = "a metric row needs the agent, model, route, timing and outcome together"
1229    )]
1230    async fn record_metrics(
1231        &self,
1232        task_id: &str,
1233        agent_name: &str,
1234        model_name: Option<&str>,
1235        route_result: Option<&RouteResult>,
1236        started_at: &chrono::DateTime<Utc>,
1237        attempts: u32,
1238        final_status: &str,
1239        error_type: Option<&str>,
1240    ) {
1241        let completed_at = Utc::now();
1242        #[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
1243        let duration_seconds = (completed_at - *started_at).num_milliseconds() as f64 / 1000.0;
1244
1245        // Classify outcome based on the final status and optional error_type/last_error
1246        let outcome = match final_status {
1247            "done" | "in_progress" | "in_review" => "success",
1248            "new" => "rerouted",
1249            "needs_review" => classify_run_error_type(error_type.unwrap_or("")),
1250            _ => "unknown",
1251        };
1252
1253        let complexity = route_result.map(|r| r.complexity.clone());
1254        let files_changed = git_ops::count_changed_files(&PathBuf::from(
1255            self.get_field(task_id, "worktree")
1256                .await
1257                .unwrap_or_default(),
1258        ))
1259        .await
1260        .unwrap_or(0);
1261
1262        if let Some(ref store) = self.store {
1263            // Only set error_type for non-success outcomes
1264            let db_error_type: Option<String> = if outcome == "success" {
1265                None
1266            } else {
1267                Some(outcome.to_string())
1268            };
1269
1270            let usage = store::get_token_usage(&self.store, &self.repo, task_id).await;
1271            let total_cost = store::get_reported_cost(&self.store, &self.repo, task_id).await;
1272            let input_tokens = if usage.input_tokens > 0 {
1273                Some(i64::try_from(usage.input_tokens).unwrap_or(i64::MAX))
1274            } else {
1275                None
1276            };
1277            let output_tokens = if usage.output_tokens > 0 {
1278                Some(i64::try_from(usage.output_tokens).unwrap_or(i64::MAX))
1279            } else {
1280                None
1281            };
1282
1283            let metric = InsertTaskMetric {
1284                repo: &self.repo,
1285                task_id,
1286                agent: agent_name,
1287                model: model_name,
1288                complexity: complexity.as_deref(),
1289                outcome,
1290                duration_seconds,
1291                started_at,
1292                completed_at: &completed_at,
1293                attempts: i32::try_from(attempts.saturating_add(1)).unwrap_or(i32::MAX),
1294                files_changed: i32::try_from(files_changed).unwrap_or(i32::MAX),
1295                error_type: db_error_type.as_deref(),
1296                input_tokens,
1297                output_tokens,
1298                total_cost_usd: total_cost,
1299            };
1300
1301            if let Err(e) = store.insert_task_metric(&metric).await {
1302                tracing::error!(task_id, ?e, "failed to record task metrics");
1303            }
1304        }
1305    }
1306
1307    /// Run a task with full engine context (backend, tmux, capture).
1308    ///
1309    /// Called by the engine dispatch loop with richer context.
1310    /// Returns a `WeightSignal` for the engine to feed back to the router.
1311    pub async fn run_with_context(
1312        &self,
1313        task: &ExternalTask,
1314        backend: &Arc<dyn ExternalBackend>,
1315        _tmux: &Arc<TmuxManager>,
1316        route_result: Option<&RouteResult>,
1317    ) -> anyhow::Result<WeightSignal> {
1318        let task_id = &task.id.0;
1319        let agent = route_result.map(|r| r.agent.as_str());
1320        let agent_name = agent.unwrap_or("claude").to_string();
1321        let model = route_result.and_then(|r| r.model.as_deref());
1322
1323        // Record start time for metrics (before any work begins)
1324        let started_at = Utc::now();
1325
1326        // Store task info for prompt building (title/body already in store tasks table)
1327
1328        // Record run start in task_runs audit trail
1329        let run_audit_id = if let Some(ref store) = self.store {
1330            let attempt: i32 = self
1331                .get_field(task_id, "attempts")
1332                .await
1333                .and_then(|s| s.parse().ok())
1334                .unwrap_or(0)
1335                + 1;
1336            match store.resolve_task_id(&self.repo, task_id).await {
1337                Ok(Some(store_id)) => {
1338                    match store
1339                        .start_run(&crate::store::StartRun {
1340                            task_id: store_id,
1341                            attempt,
1342                            run_type: "agent",
1343                            agent: &agent_name,
1344                            model: model.unwrap_or(""),
1345                            command: &format!(
1346                                "{} --model {}",
1347                                agent_name,
1348                                model.unwrap_or("default")
1349                            ),
1350                            prompt: &task.body,
1351                        })
1352                        .await
1353                    {
1354                        Ok(run_id) => Some(run_id),
1355                        Err(e) => {
1356                            tracing::warn!(
1357                                task_id,
1358                                error = %e,
1359                                "failed to record run start in audit trail"
1360                            );
1361                            None
1362                        }
1363                    }
1364                }
1365                _ => None,
1366            }
1367        } else {
1368            None
1369        };
1370
1371        // Run the task.
1372        // Always finalize the run audit row, even on early-return/error paths.
1373        let run_result = match self
1374            .run(task_id, agent, model, Some(&**backend), &started_at)
1375            .await
1376        {
1377            Ok(run_result) => run_result,
1378            Err(e) => {
1379                if let Some(run_id) = run_audit_id
1380                    && let Some(ref store) = self.store
1381                    && let Err(complete_err) = store
1382                        .complete_run(&crate::store::CompleteRun {
1383                            run_id,
1384                            exit_code: Some(-1),
1385                            stdout: "",
1386                            stderr: "",
1387                            parsed: "",
1388                            outcome: "failed",
1389                            error: &e.to_string(),
1390                            tokens: RunTokenUsage::default(),
1391                        })
1392                        .await
1393                {
1394                    tracing::warn!(
1395                        task_id,
1396                        run_id,
1397                        error = %complete_err,
1398                        "failed to record run completion in audit trail after runner error"
1399                    );
1400                }
1401                return Err(e);
1402            }
1403        };
1404
1405        // If the runner guard skipped the task, do not re-post stale data as a new comment.
1406        let (status, exit_code_opt, run_audit) = if let Some(result) = run_result {
1407            (result.status, result.exit_code, result.audit)
1408        } else {
1409            if let Some(run_id) = run_audit_id
1410                && let Some(ref store) = self.store
1411                && let Err(e) = store
1412                    .complete_run(&crate::store::CompleteRun {
1413                        run_id,
1414                        exit_code: Some(-1),
1415                        stdout: "",
1416                        stderr: "",
1417                        parsed: "",
1418                        outcome: "aborted",
1419                        error: "run skipped by guard",
1420                        tokens: RunTokenUsage::default(),
1421                    })
1422                    .await
1423            {
1424                tracing::warn!(
1425                    task_id,
1426                    run_id,
1427                    error = %e,
1428                    "failed to record skipped run completion in audit trail"
1429                );
1430            }
1431            tracing::info!(task_id, "guard skipped task — not posting stale result");
1432            return Ok(WeightSignal::None);
1433        };
1434
1435        // Process delegations if the agent requested subtasks
1436        let delegations_raw = self
1437            .get_field(task_id, "delegations")
1438            .await
1439            .unwrap_or_default();
1440        if !delegations_raw.is_empty() {
1441            match serde_json::from_str::<Vec<Delegation>>(&delegations_raw) {
1442                Ok(delegations) if !delegations.is_empty() => {
1443                    self.process_delegations(task, &delegations, backend)
1444                        .await?;
1445                    if let Err(e) = store::store_set_result(
1446                        &self.store,
1447                        &self.repo,
1448                        task_id,
1449                        &[("delegations", serde_json::json!([]))],
1450                    )
1451                    .await
1452                    {
1453                        tracing::warn!(task_id, err = %e, "failed to clear delegations in store");
1454                    }
1455                }
1456                Ok(_) => {} // empty list, nothing to do
1457                Err(e) => {
1458                    tracing::error!(task_id, error = %e, "corrupt delegations JSON — clearing");
1459                    if let Err(e2) = store::store_set_result(
1460                        &self.store,
1461                        &self.repo,
1462                        task_id,
1463                        &[("delegations", serde_json::json!([]))],
1464                    )
1465                    .await
1466                    {
1467                        tracing::warn!(task_id, err = %e2, "failed to clear corrupt delegations in store");
1468                    }
1469                    if let Err(e2) = store::store_set_result(
1470                        &self.store,
1471                        &self.repo,
1472                        task_id,
1473                        &[(
1474                            "last_error",
1475                            serde_json::json!(format!("delegation parse failed: {e}")),
1476                        )],
1477                    )
1478                    .await
1479                    {
1480                        tracing::warn!(task_id, err = %e2, "failed to write delegation_parse_failed last_error to store");
1481                    }
1482                }
1483            }
1484        }
1485
1486        // Post result to GitHub
1487        let summary = self.get_field(task_id, "summary").await.unwrap_or_default();
1488        let last_error = self
1489            .get_field(task_id, "last_error")
1490            .await
1491            .unwrap_or_default();
1492
1493        // Determine weight signal based on outcome.
1494        // Any reroute ("new"/"routed") should avoid review-gate and go back through
1495        // normal dispatch, regardless of why it was rerouted.
1496        let is_rerouted = status == "new" || status == "routed";
1497        if is_rerouted {
1498            self.clear_agent_on_reroute_unless_fallback(task_id, &agent_name)
1499                .await;
1500        }
1501        // Determine weight signal based on outcome.
1502        // Reroutes should only emit RateLimited when the underlying error is genuinely
1503        // a rate limit (not silence detection, timeouts, parse errors, etc.). This prevents
1504        // false cooldown cascades where non-rate-limit failures are treated as rate limits.
1505        let is_rate_limit_error = classify_run_error_type(&last_error) == "rate_limit";
1506        let weight_signal = if is_rerouted {
1507            if is_rate_limit_error {
1508                WeightSignal::RateLimited {
1509                    agent: agent_name.clone(),
1510                }
1511            } else {
1512                // Non-rate-limit reroutes (silence detection, timeout, parse error): signal
1513                // the engine to keep the task in "new" for re-routing. Using Rerouted (not
1514                // None) prevents tick from converting the silence-reset back to needs_review,
1515                // which would trigger the no-code review shortcut and falsely mark it done.
1516                WeightSignal::Rerouted
1517            }
1518        } else if status == "needs_review" {
1519            // Rate limit errors that escalate to needs_review must NOT reset backoff
1520            // counters (issue #2153).  These errors indicate the agent is genuinely
1521            // unavailable — resetting would wipe the cooldown and cause the next dispatch
1522            // to retry the same rate-limited agent immediately.
1523            //
1524            // Detection: classify_run_error_type() confirms "rate limit" in last_error.
1525            // Reuse the same classifier as `is_rate_limit_error` above rather than a raw
1526            // substring check — billing-cycle exhaustion messages (e.g. Kimi's "usage
1527            // limit for this billing cycle") also contain "usage limit"/"rate limit", so
1528            // a bare substring check would record a rate-limit event into the router's
1529            // health signal for a condition that isn't a genuine rate limit (issue #3529).
1530            let signal = needs_review_signal(&last_error, &agent_name);
1531            match &signal {
1532                WeightSignal::RateLimited { .. } => {
1533                    // Record in the metrics store so the router's health check detects it.
1534                    if let Some(ref store) = self.store
1535                        && let Err(e) = store
1536                            .record_rate_limit(&agent_name, "rate", Some(task_id))
1537                            .await
1538                    {
1539                        tracing::warn!(task_id, agent = %agent_name, err = %e, "failed to persist rate_limit event — router health check may miss this signal");
1540                    }
1541                    // Also record via the cooldown system so model_for_complexity() skips
1542                    // this model.
1543                    cooldown::record_rate_limit(&agent_name, model, &last_error).await;
1544                }
1545                WeightSignal::Success { .. } => {
1546                    // Reset backoff so the next failure starts fresh.
1547                    cooldown::record_agent_success(&agent_name, model.unwrap_or("")).await;
1548                }
1549                _ => {}
1550            }
1551            signal
1552        } else if status == "done" || status == "in_progress" || status == "in_review" {
1553            // Reset exponential backoff counters so the next failure starts fresh.
1554            cooldown::record_agent_success(&agent_name, model.unwrap_or("")).await;
1555            WeightSignal::Success {
1556                agent: agent_name.clone(),
1557            }
1558        } else if status == "blocked" {
1559            WeightSignal::Blocked
1560        } else {
1561            WeightSignal::None
1562        };
1563
1564        // Record metrics
1565        {
1566            let attempts: u32 = self
1567                .get_field(task_id, "attempts")
1568                .await
1569                .and_then(|s| s.parse().ok())
1570                .unwrap_or(0);
1571            self.record_metrics(
1572                task_id,
1573                &agent_name,
1574                model,
1575                route_result,
1576                &started_at,
1577                attempts,
1578                &status,
1579                if last_error.is_empty() {
1580                    None
1581                } else {
1582                    Some(&last_error)
1583                },
1584            )
1585            .await;
1586        }
1587
1588        // Complete run in task_runs audit trail (include exit code from runner when available)
1589        if let Some(run_id) = run_audit_id
1590            && let Some(ref store) = self.store
1591            && let Err(e) = store
1592                .complete_run(&crate::store::CompleteRun {
1593                    run_id,
1594                    exit_code: exit_code_opt,
1595                    stdout: &run_audit.stdout,
1596                    stderr: &run_audit.stderr,
1597                    parsed: &run_audit.parsed_response,
1598                    outcome: &run_audit.outcome,
1599                    error: &run_audit.error,
1600                    tokens: RunTokenUsage {
1601                        input_tokens: run_audit.input_tokens,
1602                        output_tokens: run_audit.output_tokens,
1603                        total_cost_usd: run_audit.total_cost_usd,
1604                        duration_secs: run_audit.duration_secs,
1605                    },
1606                })
1607                .await
1608        {
1609            tracing::warn!(
1610                task_id,
1611                run_id,
1612                error = %e,
1613                "failed to record run completion in audit trail"
1614            );
1615        }
1616
1617        // If task was rerouted (status=routed or new after run), update GitHub agent label
1618        // so the router doesn't re-route back to the same failed agent.
1619        if is_rerouted && !is_internal_id(task_id) {
1620            let new_agent = self.get_field(task_id, "agent").await.unwrap_or_default();
1621            if !new_agent.is_empty() && new_agent != agent_name {
1622                update_agent_label_after_reroute(
1623                    &self.repo,
1624                    task,
1625                    backend,
1626                    &agent_name,
1627                    &new_agent,
1628                )
1629                .await;
1630            }
1631        }
1632
1633        // Internal tasks: skip GitHub status/comment updates — dispatch phase handles status.
1634        if is_internal_id(task_id) {
1635            return Ok(weight_signal);
1636        }
1637
1638        // Update GitHub status
1639        let new_status = match status.as_str() {
1640            "done" => Status::Done,
1641            "in_progress" => Status::InProgress,
1642            "in_review" => Status::InReview,
1643            "blocked" => Status::Blocked,
1644            "routed" => Status::Routed, // Rerouted (agent/model already set)
1645            "new" => Status::New,       // Legacy reroute path
1646            _ => Status::NeedsReview,
1647        };
1648        // Store-first: update SQLite (must succeed), then mirror to backend.
1649        if let Some(ref store) = self.store
1650            && let Ok(Some(store_id)) = store.resolve_task_id(&self.repo, &task.id.0).await
1651        {
1652            store
1653                .update_status(store_id, tasks::status_to_task_status(new_status))
1654                .await
1655                .context("store-first status update failed in runner")?;
1656        }
1657        if let Err(e) = backend.update_status(&task.id, new_status).await {
1658            tracing::warn!(
1659                task_id,
1660                ?new_status,
1661                err = %e,
1662                "failed to mirror runner status to backend — store is authoritative"
1663            );
1664        }
1665
1666        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
1667        let mut comment = if !summary.is_empty() {
1668            format!("[{now}] {status}: {summary}")
1669        } else if !last_error.is_empty() {
1670            format!("[{now}] {status}: {last_error}")
1671        } else {
1672            format!("[{now}] {status}")
1673        };
1674
1675        // Append visible attribution footer (matches PR body style)
1676        let footer = engine::attribution_footer("Created", &agent_name, model);
1677        comment.push_str(&footer);
1678
1679        backend.post_comment(&task.id, &comment).await?;
1680
1681        Ok(weight_signal)
1682    }
1683
1684    /// Process delegations from an agent response.
1685    ///
1686    /// Creates child GitHub issues for each delegation and marks the parent
1687    /// as blocked. The engine's Phase 4 unblock mechanism will re-activate
1688    /// the parent when all children are done.
1689    async fn process_delegations(
1690        &self,
1691        parent_task: &ExternalTask,
1692        delegations: &[Delegation],
1693        backend: &Arc<dyn ExternalBackend>,
1694    ) -> anyhow::Result<()> {
1695        let parent_id = &parent_task.id;
1696
1697        // Fetch existing open tasks once for dedup — prevents creating duplicate
1698        // GitHub issues when the same delegations are produced on repeated runs.
1699        let existing_titles: HashSet<String> = match backend.list_all_tasks().await {
1700            Ok(tasks) => tasks.into_iter().map(|t| t.title).collect(),
1701            Err(e) => {
1702                tracing::warn!(err = %e, "failed to fetch tasks for dedup — will create all");
1703                HashSet::new()
1704            }
1705        };
1706
1707        for delegation in delegations {
1708            // Skip if an issue with the same title already exists
1709            if existing_titles.contains(&delegation.title) {
1710                tracing::info!(
1711                    parent = parent_id.0,
1712                    title = delegation.title,
1713                    "skipping delegation — issue with same title already exists"
1714                );
1715                continue;
1716            }
1717
1718            // Build labels: status:new + any labels from the delegation
1719            let mut labels = delegation.labels.clone();
1720            labels.push("status:new".to_string());
1721
1722            // Build child body with delegation reference
1723            let child_body = format!(
1724                "{}\n\n---\n_Delegated from #{}_{}",
1725                delegation.body,
1726                parent_id.0,
1727                engine::orch_footer()
1728            );
1729
1730            match backend
1731                .create_sub_task(parent_id, &delegation.title, &child_body, &labels)
1732                .await
1733            {
1734                Ok(child_id) => {
1735                    tracing::info!(
1736                        parent = parent_id.0,
1737                        child = child_id.0,
1738                        title = delegation.title,
1739                        "created delegated subtask"
1740                    );
1741                }
1742                Err(e) => {
1743                    tracing::error!(
1744                        parent = parent_id.0,
1745                        title = delegation.title,
1746                        err = %e,
1747                        "failed to create delegated subtask"
1748                    );
1749                }
1750            }
1751        }
1752
1753        // Mark parent as blocked — store-first, then mirror to backend.
1754        if let Some(ref store) = self.store
1755            && let Ok(Some(store_id)) = store.resolve_task_id(&self.repo, &parent_id.0).await
1756        {
1757            store
1758                .update_status(store_id, TaskStatus::Blocked)
1759                .await
1760                .context("store-first: failed to block parent in store")?;
1761        }
1762        if let Err(e) = backend.update_status(parent_id, Status::Blocked).await {
1763            tracing::warn!(
1764                parent = parent_id.0,
1765                err = %e,
1766                "failed to mirror blocked status to backend — store is authoritative"
1767            );
1768        }
1769
1770        // Post summary comment on parent
1771        let summary = delegations
1772            .iter()
1773            .enumerate()
1774            .map(|(i, d)| format!("{}. {}", i + 1, d.title))
1775            .collect::<Vec<_>>()
1776            .join("\n");
1777
1778        backend
1779            .post_comment(
1780                parent_id,
1781                &format!(
1782                    "Delegated {} subtask(s):\n\n{}\n\nParent task is blocked until all subtasks complete.{}",
1783                    delegations.len(),
1784                    summary,
1785                    engine::orch_footer()
1786                ),
1787            )
1788            .await?;
1789
1790        Ok(())
1791    }
1792
1793    /// Resolve the project directory for this repo.
1794    pub(crate) async fn resolve_project_dir(&self) -> anyhow::Result<PathBuf> {
1795        // Explicit env var always wins
1796        if let Ok(dir) = env::var("PROJECT_DIR")
1797            && !dir.is_empty()
1798        {
1799            return Ok(PathBuf::from(dir));
1800        }
1801
1802        // Check projects list in global config — find path for this repo
1803        if let Ok(paths) = config::get_project_paths() {
1804            for path_str in &paths {
1805                let path = PathBuf::from(path_str);
1806                // Check if this project's .orch.yml has matching repo
1807                if let Ok(repo) = config::get_repo_for_project(&path) {
1808                    // Use tokio::fs::metadata for async-safe existence check
1809                    let path_for_check = path.clone();
1810                    if repo == self.repo && fs::metadata(&path_for_check).await.is_ok() {
1811                        return Ok(path);
1812                    }
1813                }
1814            }
1815        }
1816
1817        // Legacy: check config project_dir
1818        if let Ok(dir) = config::get("project_dir")
1819            && !dir.is_empty()
1820        {
1821            let path = PathBuf::from(&dir);
1822            let path_for_check = path.clone();
1823            if fs::metadata(&path_for_check).await.is_ok() {
1824                return Ok(path);
1825            }
1826        }
1827
1828        // Check for bare clone
1829        let parts: Vec<&str> = self.repo.split('/').collect();
1830        if parts.len() == 2 {
1831            let bare = self
1832                .orch_home
1833                .join("projects")
1834                .join(parts[0])
1835                .join(format!("{}.git", parts[1]));
1836            let bare_for_check = bare.clone();
1837            if task::spawn_blocking(move || bare_for_check.exists())
1838                .await
1839                .unwrap_or(false)
1840            {
1841                return Ok(bare);
1842            }
1843        }
1844
1845        // No resolvable project directory: not in active config, no legacy
1846        // project_dir, no bare clone. Falling back to the service's own CWD
1847        // here would silently point worktree creation at an unrelated
1848        // directory (see issue #3416) — surface a clear error instead.
1849        Err(NoProjectDir {
1850            repo: self.repo.clone(),
1851            bare_clone: self
1852                .orch_home
1853                .join("projects")
1854                .join(self.repo.split('/').next().unwrap_or_default())
1855                .join(format!(
1856                    "{}.git",
1857                    self.repo.split('/').nth(1).unwrap_or_default()
1858                )),
1859        }
1860        .into())
1861    }
1862}
1863
1864/// Update the GitHub agent label on an external task when it is rerouted to a new agent.
1865///
1866/// Removes the old `agent:<old_agent>` label, ensures the new `agent:<new_agent>` label exists
1867/// in the repo, then applies it. Returns `true` only when both `ensure_label` (repo label creation)
1868/// and `set_labels` (issue label assignment) succeed. `remove_label` failures are non-fatal.
1869async fn update_agent_label_after_reroute(
1870    #[cfg_attr(
1871        test,
1872        expect(unused_variables, reason = "only the label call outside tests uses it")
1873    )]
1874    repo: &str,
1875    task: &ExternalTask,
1876    backend: &Arc<dyn ExternalBackend>,
1877    old_agent: &str,
1878    new_agent: &str,
1879) -> bool {
1880    let old_label = format!("agent:{old_agent}");
1881    if let Err(e) = backend.remove_label(&task.id, &old_label).await {
1882        tracing::warn!(
1883            task_id = ?task.id,
1884            label = old_label,
1885            error = %e,
1886            "failed to remove old agent label during re-route"
1887        );
1888    }
1889    let new_label = format!("agent:{new_agent}");
1890
1891    // ensure_label creates the repo-level label if missing (best-effort).
1892    // Skipped under #[cfg(test)] to avoid real GitHub API calls.
1893    #[cfg(not(test))]
1894    {
1895        match GhHttp::new() {
1896            Ok(gh) => {
1897                if gh
1898                    .ensure_label(
1899                        repo,
1900                        &new_label,
1901                        http::status_label_color(&new_label),
1902                        &format!("Agent: {new_agent}"),
1903                    )
1904                    .await
1905                    .is_err()
1906                {
1907                    tracing::warn!(
1908                        task_id = ?task.id,
1909                        label = %new_label,
1910                        "ensure_label failed during agent label update after failover"
1911                    );
1912                }
1913            }
1914            Err(e) => {
1915                tracing::warn!(
1916                    task_id = ?task.id,
1917                    err = %e,
1918                    "GhHttp::new() failed — skipping ensure_label"
1919                );
1920            }
1921        }
1922    }
1923
1924    if let Err(e) = backend
1925        .set_labels(&task.id, slice::from_ref(&new_label))
1926        .await
1927    {
1928        tracing::warn!(
1929            task_id = ?task.id,
1930            label = %new_label,
1931            error = %e,
1932            "set_labels failed during agent label update after failover"
1933        );
1934        return false;
1935    }
1936    true
1937}
1938
1939/// Weight signal for a run that ended in `needs_review`. `prepare_task` clears `last_error` at run
1940/// start, so a non-empty value means `handle_error` ended this run
1941fn needs_review_signal(last_error: &str, agent: &str) -> WeightSignal {
1942    let agent = agent.to_string();
1943    if classify_run_error_type(last_error) == "rate_limit" {
1944        WeightSignal::RateLimited { agent }
1945    } else if !last_error.is_empty() {
1946        WeightSignal::Failed { agent }
1947    } else {
1948        WeightSignal::Success { agent }
1949    }
1950}
1951
1952#[cfg(test)]
1953mod tests;