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