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