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