Skip to main content

orch/engine/runner/
mod.rs

1//! Task runner — executes tasks using AI agents.
2//!
3//! Replaces `run_task.sh` with pure Rust. The runner:
4//! 1. Sets up a git worktree for isolation
5//! 2. Builds context (project instructions, comments)
6//! 3. Renders prompts and spawns the agent in tmux
7//! 4. Waits for completion, collects and classifies the response
8//! 5. Handles errors (reroute on limits, fallback agents)
9//! 6. Auto-commits, pushes, and creates PRs
10//! 7. Updates status labels and posts result comments
11//!
12//! Submodules handle the heavy lifting:
13//! - [`task_init`] — guard checks, worktree setup, and invocation building
14//! - [`session`] — tmux session lifecycle and output collection
15//! - [`response_handler`] — success path: commit, push, PR, token storage
16//! - [`fallback`] — error classification and recovery strategies
17
18pub mod agent;
19pub mod context;
20pub mod fallback;
21pub mod ndjson;
22#[cfg(test)]
23mod recorded_fixtures;
24pub mod response;
25pub mod response_handler;
26pub mod sandbox;
27pub mod session;
28pub mod task_init;
29pub mod template;
30
31use crate::engine::git::diff;
32
33use crate::backends::{ExternalBackend, ExternalTask, Status};
34use crate::config;
35use crate::cooldown;
36use crate::engine;
37use crate::engine::agents;
38use crate::engine::agents::parser;
39use crate::engine::agents::parser::AgentResponse;
40use crate::engine::agents::parser::Delegation;
41use crate::engine::agents::status_heuristics;
42use crate::engine::git::cleanup;
43use crate::engine::router::RouteResult;
44use crate::engine::tasks;
45use crate::engine::tasks::is_internal_id;
46#[cfg(not(test))]
47use crate::github::http;
48use crate::github::http::GhHttp;
49use crate::store;
50use crate::store::InsertTaskMetric;
51use crate::store::RunTokenUsage;
52use crate::store::TaskStatus;
53use crate::store::TaskStore;
54use crate::sys::home;
55use crate::sys::tmux::TmuxManager;
56use anyhow::Context;
57use chrono::Utc;
58pub use response::WeightSignal;
59use serde_json::Value;
60use std::collections::HashSet;
61use std::env;
62use std::error;
63use std::fmt;
64use std::fmt::Debug;
65use std::fmt::Formatter;
66use std::path::PathBuf;
67use std::slice;
68use std::sync::Arc;
69use std::time::Duration;
70use tokio::fs;
71use tokio::task;
72
73/// Fully materialized task-run audit data.
74#[derive(Debug, Clone)]
75pub struct RunAudit {
76    pub stdout: String,
77    pub stderr: String,
78    pub parsed_response: String,
79    pub outcome: String,
80    pub error: String,
81    pub input_tokens: u64,
82    pub output_tokens: u64,
83    pub total_cost_usd: f64,
84    pub duration_secs: f64,
85}
86
87/// Result returned by `run()` so callers can persist the audit trail.
88#[derive(Debug, Clone)]
89pub struct RunExecution {
90    pub status: String,
91    pub exit_code: Option<i32>,
92    pub audit: RunAudit,
93}
94
95fn serialize_parsed_response(
96    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
97    raw_stdout: &str,
98) -> String {
99    match parse_result {
100        Ok(parsed) => serde_json::json!({
101            "response": parsed.response,
102            "input_tokens": parsed.input_tokens,
103            "output_tokens": parsed.output_tokens,
104            "cost_usd": parsed.cost_usd,
105            "duration_ms": parsed.duration_ms,
106        })
107        .to_string(),
108        Err(agents::AgentError::InvalidResponse { raw }) => {
109            serde_json::json!({"raw": raw}).to_string()
110        }
111        Err(_) => serde_json::json!({"raw": raw_stdout}).to_string(),
112    }
113}
114
115fn classify_run_outcome(
116    status: &str,
117    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
118    push_failed: bool,
119) -> &'static str {
120    if push_failed {
121        return "push_failed";
122    }
123    match parse_result {
124        Err(agents::AgentError::Timeout { .. }) => "timeout",
125        Err(agents::AgentError::Interrupted { .. }) => "interrupted",
126        // Generic rate-limit patterns (e.g. "usage limit") also match billing-cycle
127        // exhaustion messages, so consult the credit-exhaustion detector first —
128        // otherwise Kimi-style "usage limit for this billing cycle" errors are
129        // stored as a plain "rate_limit" outcome (issue #3529).
130        Err(agents::AgentError::RateLimit { message }) => {
131            cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("rate_limit")
132        }
133        Err(agents::AgentError::Auth { message }) => {
134            cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("failed")
135        }
136        Err(agents::AgentError::InvalidResponse { .. }) => "parse_error",
137        Ok(_)
138            if matches!(
139                status,
140                "done" | "completed" | "in_progress" | "in_review" | "needs_review" | "routed"
141            ) =>
142        {
143            "success"
144        }
145        Ok(_) if status == "blocked" => "blocked",
146        // Non-canonical status that clearly reads as completion — success, not
147        // "unrecognized status" (#3627).
148        Ok(_) if status_heuristics::status_looks_like_descriptive_completion(status) => "success",
149        Err(_) | Ok(_) => "failed",
150    }
151}
152
153fn classify_run_error_type(last_error: &str) -> &'static str {
154    if last_error.is_empty() {
155        // No error: agent completed successfully and created a PR waiting for review
156        "success"
157    } else if last_error.contains("timeout") {
158        "timeout"
159    } else if last_error.contains("interrupted") {
160        "interrupted"
161    } else if last_error.contains("billing cycle") || last_error.contains("monthly quota") {
162        "billing_cycle_exhausted"
163    } else if last_error.contains("rate limit") || last_error.contains("usage limit") {
164        "rate_limit"
165    } else if last_error.contains("auth") {
166        "auth_error"
167    } else if last_error.contains("push failed") {
168        "push_failed"
169    } else if last_error.contains("No commits between") || last_error.contains("no commits") {
170        "no_commits"
171    } else if last_error.contains("create PR failed")
172        || last_error.contains("failed to create pull request")
173        || last_error.contains("pull request creation failed")
174    {
175        "pr_failed"
176    } else if last_error.contains("invalid response") || last_error.contains("parse error") {
177        "parse_error"
178    } else if last_error.contains("exceeded max attempts") {
179        "max_attempts"
180    } else {
181        let lower = last_error.to_ascii_lowercase();
182        if lower.contains("build failed")
183            || lower.contains("tests failed")
184            || lower.contains("test failed")
185            || lower.contains("test suite failed")
186            || lower.contains("lint failed")
187        {
188            "ci_failure"
189        } else {
190            "failed"
191        }
192    }
193}
194
195fn extract_run_tokens(
196    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
197) -> (u64, u64) {
198    match parse_result {
199        Ok(parsed) => (
200            parsed
201                .input_tokens
202                .or(parsed.response.input_tokens)
203                .unwrap_or(0),
204            parsed
205                .output_tokens
206                .or(parsed.response.output_tokens)
207                .unwrap_or(0),
208        ),
209        Err(_) => (0, 0),
210    }
211}
212
213#[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
214fn run_duration_secs(started_at: &chrono::DateTime<Utc>) -> f64 {
215    (Utc::now() - *started_at).num_milliseconds() as f64 / 1000.0
216}
217
218struct RunAuditInput<'a> {
219    task_id: &'a str,
220    status: &'a str,
221    parse_result: &'a Result<agents::ParsedResponse, agents::AgentError>,
222    raw_stdout: &'a str,
223    raw_stderr: &'a str,
224    started_at: &'a chrono::DateTime<Utc>,
225    error_override: Option<String>,
226    elapsed_secs: Option<u64>,
227    push_failed: bool,
228}
229
230fn parse_success_output(
231    task_id: &str,
232    agent_name: &str,
233    agent_runner: &dyn agents::AgentRunner,
234    raw_stdout: &str,
235) -> Result<agents::ParsedResponse, agents::AgentError> {
236    // The last result envelope is the agent's final answer and carries the run's tokens and cost.
237    // Claude writes terminal_reason:completed on every run, so this goes before that shortcut
238    let agent_result = agent_runner.find_result(raw_stdout);
239    if let Some(result) = &agent_result
240        && !result.is_error
241        && let Ok(response) = parser::parse(&result.result_text)
242    {
243        return Ok(agents::ParsedResponse {
244            response,
245            input_tokens: result.input_tokens,
246            output_tokens: result.output_tokens,
247            cost_usd: result.cost_usd,
248            duration_ms: result.duration_ms,
249        });
250    }
251
252    // Quick NDJSON terminal_reason:completed shortcut: when the agent
253    // emitted a session envelope that explicitly signals completion we
254    // prefer to interpret that as a successful run (or at least a
255    // soft/empty success) rather than immediately classifying an error
256    // from the trailing process output.  Do not override explicit
257    // in-envelope `is_error: true` signals.
258    if raw_stdout.contains("\"terminal_reason\":\"completed\"")
259        && !raw_stdout.contains("\"is_error\":true")
260    {
261        // Try to recover a structured response from assistant messages first
262        let assistant_text = agents::collect_assistant_messages_text(agent_name, raw_stdout);
263        if !assistant_text.is_empty() {
264            if let Ok(response) = parser::parse(&assistant_text) {
265                tracing::debug!(
266                    task_id,
267                    agent = agent_name,
268                    "found AgentResponse JSON in earlier assistant message (terminal_reason:completed)"
269                );
270                return Ok(agents::ParsedResponse {
271                    response,
272                    input_tokens: None,
273                    output_tokens: None,
274                    cost_usd: None,
275                    duration_ms: None,
276                });
277            }
278            if let Some(response) = agents::synthesize_response_from_text(&assistant_text) {
279                tracing::warn!(
280                    task_id,
281                    agent = agent_name,
282                    "synthesizing response from assistant message due to terminal_reason:completed"
283                );
284                return Ok(agents::ParsedResponse {
285                    response,
286                    input_tokens: None,
287                    output_tokens: None,
288                    cost_usd: None,
289                    duration_ms: None,
290                });
291            }
292        }
293        // If we couldn't recover structured data from earlier assistant
294        // messages, fall through and let the regular NDJSON envelope parsing
295        // / agent-specific parsers handle the terminal_reason case. This
296        // preserves the existing behavior where an empty `result` field
297        // combined with exit != 0 becomes an InvalidResponse that is then
298        // interpreted by parse_session_output (see tests).
299    }
300
301    // 1. Try to use the unified agent result extractor first
302    if let Some(agent_result) = agent_result {
303        // Treat is_error as authoritative for the success path
304        if agent_result.is_error {
305            // Classify the error from the agent's result text rather than
306            // blindly returning AgentFailed — this preserves rate-limit, auth,
307            // and other actionable error types for proper cooldown/reroute.
308            // Without this, e.g. a claude session-limit error with is_error=true
309            // would be downgraded to AgentFailed, losing the RateLimit signal
310            // that the fallback chain needs for UsageLimit recovery (issue #3292).
311            if let Some(e) = agents::patterns::detect_rate_limit(&agent_result.result_text) {
312                return Err(e);
313            }
314            if let Some(e) = agents::patterns::detect_auth_error(&agent_result.result_text) {
315                return Err(e);
316            }
317            if let Some(e) = agents::patterns::detect_model_unavailable(&agent_result.result_text) {
318                return Err(e);
319            }
320            // Grok puts "the wait for background work ran out" in errors[] and
321            // exits 1. That is a timeout, so handle_failover retries
322            let classified = agent_runner.classify_error(1, raw_stdout, "");
323            if matches!(classified, agents::AgentError::Timeout { .. }) {
324                return Err(classified);
325            }
326            return Err(agents::AgentError::AgentFailed {
327                message: agent_result.result_text,
328            });
329        }
330
331        // Strategy 2: scan all earlier assistant messages in the NDJSON
332        // stream for valid AgentResponse JSON. Agents often emit the
333        // JSON in an intermediate turn and then summarise in prose as
334        // their final output, so the `type:result` text may be pure
335        // narrative while a prior assistant turn contains the JSON.
336        let assistant_text = agents::collect_assistant_messages_text(agent_name, raw_stdout);
337        if !assistant_text.is_empty()
338            && let Ok(response) = parser::parse(&assistant_text)
339        {
340            tracing::debug!(
341                task_id,
342                agent = agent_name,
343                "found AgentResponse JSON in earlier assistant message"
344            );
345            return Ok(agents::ParsedResponse {
346                response,
347                input_tokens: agent_result.input_tokens,
348                output_tokens: agent_result.output_tokens,
349                cost_usd: agent_result.cost_usd,
350                duration_ms: agent_result.duration_ms,
351            });
352        }
353
354        // Only fall back to text synthesis when parsing fails
355        if let Some(response) = agents::synthesize_response_from_text(&agent_result.result_text) {
356            tracing::warn!(
357                task_id,
358                agent = agent_name,
359                "parse failed on agent result, synthesizing response from plain text"
360            );
361            return Ok(agents::ParsedResponse {
362                response,
363                input_tokens: agent_result.input_tokens,
364                output_tokens: agent_result.output_tokens,
365                cost_usd: agent_result.cost_usd,
366                duration_ms: agent_result.duration_ms,
367            });
368        }
369
370        // NDJSON envelope fallback: the envelope explicitly reports
371        // success (is_error=false) but the result content is domain
372        // JSON or plain prose that doesn't match AgentResponse schema
373        // and doesn't contain completion keywords.  Rather than
374        // returning InvalidResponse (which causes the task to re-run),
375        // synthesize a minimal "done" response from the result text.
376        //
377        // Guard against kimi/minimax edge case: when terminal_reason=completed
378        // but result text is empty, synthesize returns None, parse_success_output
379        // returns InvalidResponse, and parse_session_output can intercept it
380        // before classify_error. Requiring non-empty result here means the
381        // envelope fallback only fires when we have actual text to report.
382        if !agent_result.is_error
383            && result_envelope_completed(raw_stdout)
384            && !agent_result.result_text.is_empty()
385        {
386            let summary = agents::truncate_str(&agent_result.result_text, 500).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 = agent_runner.find_result(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            // `orch task move` gave the task to another node, which now owns its status and agent
1015            if self.store.as_ref().is_some_and(|s| s.moved_away(&stored)) {
1016                tracing::info!(
1017                    task_id,
1018                    node = stored.owner_node.as_deref().unwrap_or("-"),
1019                    "the task moved to another node, dropping this run"
1020                );
1021                session::cleanup_session(task_id, &tmux, &tmux_session).await;
1022                return Ok(None);
1023            }
1024
1025            let silence_reset = matches!(
1026                stored.status,
1027                TaskStatus::New | TaskStatus::Routed | TaskStatus::NeedsReview
1028            );
1029            if silence_reset {
1030                let status_str = stored.status.as_str();
1031                tracing::info!(
1032                    task_id,
1033                    status = status_str,
1034                    "task already reset by the engine — skipping fallback processing"
1035                );
1036                session::cleanup_session(task_id, &tmux, &tmux_session).await;
1037                let silence_err = agents::patterns::classify_from_text(0, "silence detected");
1038                let silence_parse: Result<agents::ParsedResponse, agents::AgentError> =
1039                    Err(silence_err);
1040                let audit = self
1041                    .build_run_audit(RunAuditInput {
1042                        task_id,
1043                        status: status_str,
1044                        parse_result: &silence_parse,
1045                        raw_stdout: &session_output.raw_stdout,
1046                        raw_stderr: &session_output.raw_stderr,
1047                        started_at,
1048                        error_override: Some(format!("task was reset by the engine while the session ran (status {status_str})")),
1049                        elapsed_secs: session_output.elapsed_secs,
1050                        push_failed: false,
1051                    })
1052                    .await;
1053                return Ok(Some(RunExecution {
1054                    status: status_str.to_string(),
1055                    exit_code: Some(session_output.exit_code),
1056                    audit,
1057                }));
1058            }
1059        }
1060
1061        // Log raw output for debugging agent failures
1062        let stdout_len = session_output.raw_stdout.len();
1063        let stderr_len = session_output.raw_stderr.len();
1064        let stdout_tail: String = session_output
1065            .raw_stdout
1066            .chars()
1067            .rev()
1068            .take(500)
1069            .collect::<String>()
1070            .chars()
1071            .rev()
1072            .collect();
1073        let stderr_tail: String = session_output
1074            .raw_stderr
1075            .chars()
1076            .rev()
1077            .take(500)
1078            .collect::<String>()
1079            .chars()
1080            .rev()
1081            .collect();
1082        tracing::info!(
1083            task_id,
1084            exit_code = session_output.exit_code,
1085            stdout_len,
1086            stderr_len,
1087            stdout_tail = %stdout_tail,
1088            stderr_tail = %stderr_tail,
1089            "agent raw output"
1090        );
1091
1092        // Use agent-specific parsing where possible. Previously we only attempted
1093        // parse_success_output when exit_code == 0 which caused runs that emitted
1094        // valid NDJSON but exited non-zero (kimi / minimax) to be classed as
1095        // failures. Try parsing success output first when stdout is present; if
1096        // parsing succeeds treat as success regardless of exit code. Only fall
1097        // back to error classification when parsing fails and the process exit
1098        // code indicates an error.
1099        for window in agents::claude::rate_limit_windows(&session_output.raw_stdout) {
1100            cooldown::record_rate_limit_window(&init.agent_name, &window).await;
1101        }
1102        let agent_runner = agents::get_runner(&init.agent_name);
1103        let parse_result =
1104            parse_session_output(task_id, &init.agent_name, &*agent_runner, &session_output);
1105
1106        // Write structured result.json for deterministic testing and debugging
1107        response_handler::write_result_json(
1108            &init.attempt_dir,
1109            task_id,
1110            &init.agent_name,
1111            init.model_name.as_deref(),
1112            session_output.exit_code,
1113            init.new_attempts,
1114            &parse_result,
1115            &session_output.raw_stdout,
1116            &session_output.raw_stderr,
1117        )
1118        .await;
1119
1120        // Handle outcome: success or error recovery
1121        // `fallback_error` carries the attributed error message from `handle_error()` when
1122        // the Continue path is taken.  It is passed as `error_override` to `build_run_audit`
1123        // so that stale `last_error` values from a previous agent's run are never written
1124        // into the current run's audit record (fixes misattribution bug: task_run shows
1125        // agent=kimi but error="minimax timed out...").
1126        let (final_status, push_failed, fallback_error) = match parse_result {
1127            Ok(ref parsed) => {
1128                let (status, push_failed) = response_handler::handle_success(
1129                    task_id,
1130                    parsed.clone(),
1131                    &init.wt,
1132                    &init.task_title,
1133                    &init.agent_name,
1134                    init.model_name.as_deref(),
1135                    init.new_attempts,
1136                    &self.repo,
1137                    &self.store,
1138                    &session_output.raw_stdout,
1139                )
1140                .await?;
1141                (status, push_failed, None)
1142            }
1143            Err(ref agent_err) => {
1144                match fallback::handle_error(
1145                    task_id,
1146                    agent_err,
1147                    &init.agent_name,
1148                    &*agent_runner,
1149                    init.model_name.as_deref(),
1150                    init.complexity.as_deref(),
1151                    init.new_attempts,
1152                    &self.store,
1153                    &self.repo,
1154                )
1155                .await?
1156                {
1157                    fallback::ErrorHandleResult::EarlyReturn { status } => {
1158                        // Task rerouted — clean up tmux session and env secrets
1159                        session::cleanup_session(task_id, &tmux, &tmux_session).await;
1160                        // The fallback handler already writes a sanitized `last_error`
1161                        // into the store for EarlyReturn paths (reroutes / needs_review).
1162                        // Passing the raw agent_err here would record noisy provider
1163                        // payloads (e.g. full api_retry NDJSON). Leave error_override
1164                        // as None so build_run_audit will prefer the store's last_error
1165                        // (see src/engine/runner/fallback/mod.rs which persists a compact
1166                        // summary for rate-limit and reroute cases).
1167                        let audit = self
1168                            .build_run_audit(RunAuditInput {
1169                                task_id,
1170                                status: &status,
1171                                parse_result: &parse_result,
1172                                raw_stdout: &session_output.raw_stdout,
1173                                raw_stderr: &session_output.raw_stderr,
1174                                started_at,
1175                                error_override: None,
1176                                elapsed_secs: session_output.elapsed_secs,
1177                                push_failed: false,
1178                            })
1179                            .await;
1180                        return Ok(Some(RunExecution {
1181                            status,
1182                            exit_code: Some(session_output.exit_code),
1183                            audit,
1184                        }));
1185                    }
1186                    fallback::ErrorHandleResult::Continue { status, error } => {
1187                        (status, false, Some(error))
1188                    }
1189                }
1190            }
1191        };
1192
1193        // Kill tmux session if still alive
1194        session::cleanup_session(task_id, &tmux, &tmux_session).await;
1195
1196        // For no-op done tasks (agent finished with no code changes and no PR),
1197        // clean up the worktree and branch immediately — tmux session is already
1198        // dead so the tmux guard won't block removal.
1199        if final_status.as_str() == "done"
1200            && let Some(ref st) = self.store
1201            && let Err(e) = cleanup::cleanup_task_worktree(task_id, &self.repo, st).await
1202        {
1203            tracing::warn!(task_id, error = ?e, "worktree cleanup failed after no-op done");
1204        }
1205
1206        // Return final status and the session exit code so callers can record it.
1207        // Use `fallback_error` as error_override when available: it carries the error message
1208        // attributed to the current agent (set by handle_error), preventing stale last_error
1209        // values from a prior run from contaminating this run's audit record.
1210        let audit = self
1211            .build_run_audit(RunAuditInput {
1212                task_id,
1213                status: &final_status,
1214                parse_result: &parse_result,
1215                raw_stdout: &session_output.raw_stdout,
1216                raw_stderr: &session_output.raw_stderr,
1217                started_at,
1218                error_override: fallback_error,
1219                elapsed_secs: session_output.elapsed_secs,
1220                push_failed,
1221            })
1222            .await;
1223
1224        Ok(Some(RunExecution {
1225            status: final_status.clone(),
1226            exit_code: Some(session_output.exit_code),
1227            audit,
1228        }))
1229    }
1230
1231    /// Record task execution metrics to the database.
1232    #[expect(
1233        clippy::too_many_arguments,
1234        reason = "a metric row needs the agent, model, route, timing and outcome together"
1235    )]
1236    async fn record_metrics(
1237        &self,
1238        task_id: &str,
1239        agent_name: &str,
1240        model_name: Option<&str>,
1241        route_result: Option<&RouteResult>,
1242        started_at: &chrono::DateTime<Utc>,
1243        attempts: u32,
1244        final_status: &str,
1245        error_type: Option<&str>,
1246    ) {
1247        let completed_at = Utc::now();
1248        #[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
1249        let duration_seconds = (completed_at - *started_at).num_milliseconds() as f64 / 1000.0;
1250
1251        // Classify outcome based on the final status and optional error_type/last_error
1252        let outcome = match final_status {
1253            "done" | "in_progress" | "in_review" => "success",
1254            "new" => "rerouted",
1255            "needs_review" => classify_run_error_type(error_type.unwrap_or("")),
1256            _ => "unknown",
1257        };
1258
1259        let complexity = route_result.map(|r| r.complexity.clone());
1260        let files_changed = diff::count_changed_files(&PathBuf::from(
1261            self.get_field(task_id, "worktree")
1262                .await
1263                .unwrap_or_default(),
1264        ))
1265        .await
1266        .unwrap_or(0);
1267
1268        if let Some(ref store) = self.store {
1269            // Only set error_type for non-success outcomes
1270            let db_error_type: Option<String> = if outcome == "success" {
1271                None
1272            } else {
1273                Some(outcome.to_string())
1274            };
1275
1276            let usage = store::get_token_usage(&self.store, &self.repo, task_id).await;
1277            let total_cost = store::get_reported_cost(&self.store, &self.repo, task_id).await;
1278            let input_tokens = if usage.input_tokens > 0 {
1279                Some(i64::try_from(usage.input_tokens).unwrap_or(i64::MAX))
1280            } else {
1281                None
1282            };
1283            let output_tokens = if usage.output_tokens > 0 {
1284                Some(i64::try_from(usage.output_tokens).unwrap_or(i64::MAX))
1285            } else {
1286                None
1287            };
1288
1289            let metric = InsertTaskMetric {
1290                repo: &self.repo,
1291                task_id,
1292                agent: agent_name,
1293                model: model_name,
1294                complexity: complexity.as_deref(),
1295                outcome,
1296                duration_seconds,
1297                started_at,
1298                completed_at: &completed_at,
1299                attempts: i32::try_from(attempts.saturating_add(1)).unwrap_or(i32::MAX),
1300                files_changed: i32::try_from(files_changed).unwrap_or(i32::MAX),
1301                error_type: db_error_type.as_deref(),
1302                input_tokens,
1303                output_tokens,
1304                total_cost_usd: total_cost,
1305            };
1306
1307            if let Err(e) = store.insert_task_metric(&metric).await {
1308                tracing::error!(task_id, ?e, "failed to record task metrics");
1309            }
1310        }
1311    }
1312
1313    /// Run a task with full engine context (backend, tmux, capture).
1314    ///
1315    /// Called by the engine dispatch loop with richer context.
1316    /// Returns a `WeightSignal` for the engine to feed back to the router.
1317    pub async fn run_with_context(
1318        &self,
1319        task: &ExternalTask,
1320        backend: &Arc<dyn ExternalBackend>,
1321        _tmux: &Arc<TmuxManager>,
1322        route_result: Option<&RouteResult>,
1323    ) -> anyhow::Result<WeightSignal> {
1324        let task_id = &task.id.0;
1325        let agent = route_result.map(|r| r.agent.as_str());
1326        let agent_name = agent.unwrap_or("claude").to_string();
1327        let model = route_result.and_then(|r| r.model.as_deref());
1328
1329        // Record start time for metrics (before any work begins)
1330        let started_at = Utc::now();
1331
1332        // Store task info for prompt building (title/body already in store tasks table)
1333
1334        // Record run start in task_runs audit trail
1335        let run_audit_id = if let Some(ref store) = self.store {
1336            let attempt: i32 = self
1337                .get_field(task_id, "attempts")
1338                .await
1339                .and_then(|s| s.parse().ok())
1340                .unwrap_or(0)
1341                + 1;
1342            match store.resolve_task_id(&self.repo, task_id).await {
1343                Ok(Some(store_id)) => {
1344                    match store
1345                        .start_run(&crate::store::StartRun {
1346                            task_id: store_id,
1347                            attempt,
1348                            run_type: "agent",
1349                            agent: &agent_name,
1350                            model: model.unwrap_or(""),
1351                            command: &format!(
1352                                "{} --model {}",
1353                                agent_name,
1354                                model.unwrap_or("default")
1355                            ),
1356                            prompt: &task.body,
1357                        })
1358                        .await
1359                    {
1360                        Ok(run_id) => Some(run_id),
1361                        Err(e) => {
1362                            tracing::warn!(
1363                                task_id,
1364                                error = %e,
1365                                "failed to record run start in audit trail"
1366                            );
1367                            None
1368                        }
1369                    }
1370                }
1371                _ => None,
1372            }
1373        } else {
1374            None
1375        };
1376
1377        // Run the task.
1378        // Always finalize the run audit row, even on early-return/error paths.
1379        let run_result = match self
1380            .run(task_id, agent, model, Some(&**backend), &started_at)
1381            .await
1382        {
1383            Ok(run_result) => run_result,
1384            Err(e) => {
1385                if let Some(run_id) = run_audit_id
1386                    && let Some(ref store) = self.store
1387                    && let Err(complete_err) = store
1388                        .complete_run(&crate::store::CompleteRun {
1389                            run_id,
1390                            exit_code: Some(-1),
1391                            stdout: "",
1392                            stderr: "",
1393                            parsed: "",
1394                            outcome: "failed",
1395                            error: &e.to_string(),
1396                            tokens: RunTokenUsage::default(),
1397                        })
1398                        .await
1399                {
1400                    tracing::warn!(
1401                        task_id,
1402                        run_id,
1403                        error = %complete_err,
1404                        "failed to record run completion in audit trail after runner error"
1405                    );
1406                }
1407                return Err(e);
1408            }
1409        };
1410
1411        // If the runner guard skipped the task, do not re-post stale data as a new comment.
1412        let (status, exit_code_opt, run_audit) = if let Some(result) = run_result {
1413            (result.status, result.exit_code, result.audit)
1414        } else {
1415            if let Some(run_id) = run_audit_id
1416                && let Some(ref store) = self.store
1417                && let Err(e) = store
1418                    .complete_run(&crate::store::CompleteRun {
1419                        run_id,
1420                        exit_code: Some(-1),
1421                        stdout: "",
1422                        stderr: "",
1423                        parsed: "",
1424                        outcome: "aborted",
1425                        error: "run skipped by guard",
1426                        tokens: RunTokenUsage::default(),
1427                    })
1428                    .await
1429            {
1430                tracing::warn!(
1431                    task_id,
1432                    run_id,
1433                    error = %e,
1434                    "failed to record skipped run completion in audit trail"
1435                );
1436            }
1437            tracing::info!(task_id, "guard skipped task — not posting stale result");
1438            return Ok(WeightSignal::None);
1439        };
1440
1441        // Process delegations if the agent requested subtasks
1442        let delegations_raw = self
1443            .get_field(task_id, "delegations")
1444            .await
1445            .unwrap_or_default();
1446        if !delegations_raw.is_empty() {
1447            match serde_json::from_str::<Vec<Delegation>>(&delegations_raw) {
1448                Ok(delegations) if !delegations.is_empty() => {
1449                    self.process_delegations(task, &delegations, backend)
1450                        .await?;
1451                    if let Err(e) = store::store_set_result(
1452                        &self.store,
1453                        &self.repo,
1454                        task_id,
1455                        &[("delegations", serde_json::json!([]))],
1456                    )
1457                    .await
1458                    {
1459                        tracing::warn!(task_id, err = %e, "failed to clear delegations in store");
1460                    }
1461                }
1462                Ok(_) => {} // empty list, nothing to do
1463                Err(e) => {
1464                    tracing::error!(task_id, error = %e, "corrupt delegations JSON — clearing");
1465                    if let Err(e2) = store::store_set_result(
1466                        &self.store,
1467                        &self.repo,
1468                        task_id,
1469                        &[("delegations", serde_json::json!([]))],
1470                    )
1471                    .await
1472                    {
1473                        tracing::warn!(task_id, err = %e2, "failed to clear corrupt delegations in store");
1474                    }
1475                    if let Err(e2) = store::store_set_result(
1476                        &self.store,
1477                        &self.repo,
1478                        task_id,
1479                        &[(
1480                            "last_error",
1481                            serde_json::json!(format!("delegation parse failed: {e}")),
1482                        )],
1483                    )
1484                    .await
1485                    {
1486                        tracing::warn!(task_id, err = %e2, "failed to write delegation_parse_failed last_error to store");
1487                    }
1488                }
1489            }
1490        }
1491
1492        // Post result to GitHub
1493        let summary = self.get_field(task_id, "summary").await.unwrap_or_default();
1494        let last_error = self
1495            .get_field(task_id, "last_error")
1496            .await
1497            .unwrap_or_default();
1498
1499        // Determine weight signal based on outcome.
1500        // Any reroute ("new"/"routed") should avoid review-gate and go back through
1501        // normal dispatch, regardless of why it was rerouted.
1502        let is_rerouted = status == "new" || status == "routed";
1503        if is_rerouted {
1504            self.clear_agent_on_reroute_unless_fallback(task_id, &agent_name)
1505                .await;
1506        }
1507        // Determine weight signal based on outcome.
1508        // Reroutes should only emit RateLimited when the underlying error is genuinely
1509        // a rate limit (not silence detection, timeouts, parse errors, etc.). This prevents
1510        // false cooldown cascades where non-rate-limit failures are treated as rate limits.
1511        let is_rate_limit_error = classify_run_error_type(&last_error) == "rate_limit";
1512        let weight_signal = if is_rerouted {
1513            if is_rate_limit_error {
1514                WeightSignal::RateLimited {
1515                    agent: agent_name.clone(),
1516                }
1517            } else {
1518                // Non-rate-limit reroutes (silence detection, timeout, parse error): signal
1519                // the engine to keep the task in "new" for re-routing. Using Rerouted (not
1520                // None) prevents tick from converting the silence-reset back to needs_review,
1521                // which would trigger the no-code review shortcut and falsely mark it done.
1522                WeightSignal::Rerouted
1523            }
1524        } else if status == "needs_review" {
1525            // Rate limit errors that escalate to needs_review must NOT reset backoff
1526            // counters (issue #2153).  These errors indicate the agent is genuinely
1527            // unavailable — resetting would wipe the cooldown and cause the next dispatch
1528            // to retry the same rate-limited agent immediately.
1529            //
1530            // Detection: classify_run_error_type() confirms "rate limit" in last_error.
1531            // Reuse the same classifier as `is_rate_limit_error` above rather than a raw
1532            // substring check — billing-cycle exhaustion messages (e.g. Kimi's "usage
1533            // limit for this billing cycle") also contain "usage limit"/"rate limit", so
1534            // a bare substring check would record a rate-limit event into the router's
1535            // health signal for a condition that isn't a genuine rate limit (issue #3529).
1536            let signal = needs_review_signal(&last_error, &agent_name);
1537            match &signal {
1538                WeightSignal::RateLimited { .. } => {
1539                    // Record in the metrics store so the router's health check detects it.
1540                    if let Some(ref store) = self.store
1541                        && let Err(e) = store
1542                            .record_rate_limit(&agent_name, "rate", Some(task_id))
1543                            .await
1544                    {
1545                        tracing::warn!(task_id, agent = %agent_name, err = %e, "failed to persist rate_limit event — router health check may miss this signal");
1546                    }
1547                    // Also record via the cooldown system so model_for_complexity() skips
1548                    // this model.
1549                    cooldown::record_rate_limit(&agent_name, model, &last_error).await;
1550                }
1551                WeightSignal::Success { .. } => {
1552                    // Reset backoff so the next failure starts fresh.
1553                    cooldown::record_agent_success(&agent_name, model.unwrap_or("")).await;
1554                }
1555                _ => {}
1556            }
1557            signal
1558        } else if status == "done" || status == "in_progress" || status == "in_review" {
1559            // Reset exponential backoff counters so the next failure starts fresh.
1560            cooldown::record_agent_success(&agent_name, model.unwrap_or("")).await;
1561            WeightSignal::Success {
1562                agent: agent_name.clone(),
1563            }
1564        } else if status == "blocked" {
1565            WeightSignal::Blocked
1566        } else {
1567            WeightSignal::None
1568        };
1569
1570        // Record metrics
1571        {
1572            let attempts: u32 = self
1573                .get_field(task_id, "attempts")
1574                .await
1575                .and_then(|s| s.parse().ok())
1576                .unwrap_or(0);
1577            self.record_metrics(
1578                task_id,
1579                &agent_name,
1580                model,
1581                route_result,
1582                &started_at,
1583                attempts,
1584                &status,
1585                if last_error.is_empty() {
1586                    None
1587                } else {
1588                    Some(&last_error)
1589                },
1590            )
1591            .await;
1592        }
1593
1594        // Complete run in task_runs audit trail (include exit code from runner when available)
1595        if let Some(run_id) = run_audit_id
1596            && let Some(ref store) = self.store
1597            && let Err(e) = store
1598                .complete_run(&crate::store::CompleteRun {
1599                    run_id,
1600                    exit_code: exit_code_opt,
1601                    stdout: &run_audit.stdout,
1602                    stderr: &run_audit.stderr,
1603                    parsed: &run_audit.parsed_response,
1604                    outcome: &run_audit.outcome,
1605                    error: &run_audit.error,
1606                    tokens: RunTokenUsage {
1607                        input_tokens: run_audit.input_tokens,
1608                        output_tokens: run_audit.output_tokens,
1609                        total_cost_usd: run_audit.total_cost_usd,
1610                        duration_secs: run_audit.duration_secs,
1611                    },
1612                })
1613                .await
1614        {
1615            tracing::warn!(
1616                task_id,
1617                run_id,
1618                error = %e,
1619                "failed to record run completion in audit trail"
1620            );
1621        }
1622
1623        // If task was rerouted (status=routed or new after run), update GitHub agent label
1624        // so the router doesn't re-route back to the same failed agent.
1625        if is_rerouted && !is_internal_id(task_id) {
1626            let new_agent = self.get_field(task_id, "agent").await.unwrap_or_default();
1627            if !new_agent.is_empty() && new_agent != agent_name {
1628                update_agent_label_after_reroute(
1629                    &self.repo,
1630                    task,
1631                    backend,
1632                    &agent_name,
1633                    &new_agent,
1634                )
1635                .await;
1636            }
1637        }
1638
1639        // Internal tasks: skip GitHub status/comment updates — dispatch phase handles status.
1640        if is_internal_id(task_id) {
1641            return Ok(weight_signal);
1642        }
1643
1644        // Update GitHub status
1645        let new_status = match status.as_str() {
1646            "done" => Status::Done,
1647            "in_progress" => Status::InProgress,
1648            "in_review" => Status::InReview,
1649            "blocked" => Status::Blocked,
1650            "routed" => Status::Routed, // Rerouted (agent/model already set)
1651            "new" => Status::New,       // Legacy reroute path
1652            _ => Status::NeedsReview,
1653        };
1654        // Store-first: update SQLite (must succeed), then mirror to backend.
1655        if let Some(ref store) = self.store
1656            && let Ok(Some(store_id)) = store.resolve_task_id(&self.repo, &task.id.0).await
1657        {
1658            store
1659                .update_status(store_id, tasks::status_to_task_status(new_status))
1660                .await
1661                .context("store-first status update failed in runner")?;
1662        }
1663        if let Err(e) = backend.update_status(&task.id, new_status).await {
1664            tracing::warn!(
1665                task_id,
1666                ?new_status,
1667                err = %e,
1668                "failed to mirror runner status to backend — store is authoritative"
1669            );
1670        }
1671
1672        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
1673        let mut comment = if !summary.is_empty() {
1674            format!("[{now}] {status}: {summary}")
1675        } else if !last_error.is_empty() {
1676            format!("[{now}] {status}: {last_error}")
1677        } else {
1678            format!("[{now}] {status}")
1679        };
1680
1681        // Append visible attribution footer (matches PR body style)
1682        let footer = engine::attribution_footer("Created", &agent_name, model);
1683        comment.push_str(&footer);
1684
1685        backend.post_comment(&task.id, &comment).await?;
1686
1687        Ok(weight_signal)
1688    }
1689
1690    /// Process delegations from an agent response.
1691    ///
1692    /// Creates child GitHub issues for each delegation and marks the parent
1693    /// as blocked. The engine's Phase 4 unblock mechanism will re-activate
1694    /// the parent when all children are done.
1695    async fn process_delegations(
1696        &self,
1697        parent_task: &ExternalTask,
1698        delegations: &[Delegation],
1699        backend: &Arc<dyn ExternalBackend>,
1700    ) -> anyhow::Result<()> {
1701        let parent_id = &parent_task.id;
1702
1703        // Fetch existing open tasks once for dedup — prevents creating duplicate
1704        // GitHub issues when the same delegations are produced on repeated runs.
1705        let existing_titles: HashSet<String> = match backend.list_all_tasks().await {
1706            Ok(tasks) => tasks.into_iter().map(|t| t.title).collect(),
1707            Err(e) => {
1708                tracing::warn!(err = %e, "failed to fetch tasks for dedup — will create all");
1709                HashSet::new()
1710            }
1711        };
1712
1713        for delegation in delegations {
1714            // Skip if an issue with the same title already exists
1715            if existing_titles.contains(&delegation.title) {
1716                tracing::info!(
1717                    parent = parent_id.0,
1718                    title = delegation.title,
1719                    "skipping delegation — issue with same title already exists"
1720                );
1721                continue;
1722            }
1723
1724            // Build labels: status:new + any labels from the delegation
1725            let mut labels = delegation.labels.clone();
1726            labels.push("status:new".to_string());
1727
1728            // Build child body with delegation reference
1729            let child_body = format!(
1730                "{}\n\n---\n_Delegated from #{}_{}",
1731                delegation.body,
1732                parent_id.0,
1733                engine::orch_footer()
1734            );
1735
1736            match backend
1737                .create_sub_task(parent_id, &delegation.title, &child_body, &labels)
1738                .await
1739            {
1740                Ok(child_id) => {
1741                    tracing::info!(
1742                        parent = parent_id.0,
1743                        child = child_id.0,
1744                        title = delegation.title,
1745                        "created delegated subtask"
1746                    );
1747                }
1748                Err(e) => {
1749                    tracing::error!(
1750                        parent = parent_id.0,
1751                        title = delegation.title,
1752                        err = %e,
1753                        "failed to create delegated subtask"
1754                    );
1755                }
1756            }
1757        }
1758
1759        // Mark parent as blocked — store-first, then mirror to backend.
1760        if let Some(ref store) = self.store
1761            && let Ok(Some(store_id)) = store.resolve_task_id(&self.repo, &parent_id.0).await
1762        {
1763            store
1764                .update_status(store_id, TaskStatus::Blocked)
1765                .await
1766                .context("store-first: failed to block parent in store")?;
1767        }
1768        if let Err(e) = backend.update_status(parent_id, Status::Blocked).await {
1769            tracing::warn!(
1770                parent = parent_id.0,
1771                err = %e,
1772                "failed to mirror blocked status to backend — store is authoritative"
1773            );
1774        }
1775
1776        // Post summary comment on parent
1777        let summary = delegations
1778            .iter()
1779            .enumerate()
1780            .map(|(i, d)| format!("{}. {}", i + 1, d.title))
1781            .collect::<Vec<_>>()
1782            .join("\n");
1783
1784        backend
1785            .post_comment(
1786                parent_id,
1787                &format!(
1788                    "Delegated {} subtask(s):\n\n{}\n\nParent task is blocked until all subtasks complete.{}",
1789                    delegations.len(),
1790                    summary,
1791                    engine::orch_footer()
1792                ),
1793            )
1794            .await?;
1795
1796        Ok(())
1797    }
1798
1799    /// Resolve the project directory for this repo.
1800    pub(crate) async fn resolve_project_dir(&self) -> anyhow::Result<PathBuf> {
1801        // Explicit env var always wins
1802        if let Ok(dir) = env::var("PROJECT_DIR")
1803            && !dir.is_empty()
1804        {
1805            return Ok(PathBuf::from(dir));
1806        }
1807
1808        // Check projects list in global config — find path for this repo
1809        if let Ok(paths) = config::get_project_paths() {
1810            for path_str in &paths {
1811                let path = PathBuf::from(path_str);
1812                // Check if this project's .orch.yml has matching repo
1813                if let Ok(repo) = config::get_repo_for_project(&path) {
1814                    // Use tokio::fs::metadata for async-safe existence check
1815                    let path_for_check = path.clone();
1816                    if repo == self.repo && fs::metadata(&path_for_check).await.is_ok() {
1817                        return Ok(path);
1818                    }
1819                }
1820            }
1821        }
1822
1823        // Legacy: check config project_dir
1824        if let Ok(dir) = config::get("project_dir")
1825            && !dir.is_empty()
1826        {
1827            let path = PathBuf::from(&dir);
1828            let path_for_check = path.clone();
1829            if fs::metadata(&path_for_check).await.is_ok() {
1830                return Ok(path);
1831            }
1832        }
1833
1834        // Check for bare clone
1835        let parts: Vec<&str> = self.repo.split('/').collect();
1836        if parts.len() == 2 {
1837            let bare = self
1838                .orch_home
1839                .join("projects")
1840                .join(parts[0])
1841                .join(format!("{}.git", parts[1]));
1842            let bare_for_check = bare.clone();
1843            if task::spawn_blocking(move || bare_for_check.exists())
1844                .await
1845                .unwrap_or(false)
1846            {
1847                return Ok(bare);
1848            }
1849        }
1850
1851        // No resolvable project directory: not in active config, no legacy
1852        // project_dir, no bare clone. Falling back to the service's own CWD
1853        // here would silently point worktree creation at an unrelated
1854        // directory (see issue #3416) — surface a clear error instead.
1855        Err(NoProjectDir {
1856            repo: self.repo.clone(),
1857            bare_clone: self
1858                .orch_home
1859                .join("projects")
1860                .join(self.repo.split('/').next().unwrap_or_default())
1861                .join(format!(
1862                    "{}.git",
1863                    self.repo.split('/').nth(1).unwrap_or_default()
1864                )),
1865        }
1866        .into())
1867    }
1868}
1869
1870/// Update the GitHub agent label on an external task when it is rerouted to a new agent.
1871///
1872/// Removes the old `agent:<old_agent>` label, ensures the new `agent:<new_agent>` label exists
1873/// in the repo, then applies it. Returns `true` only when both `ensure_label` (repo label creation)
1874/// and `set_labels` (issue label assignment) succeed. `remove_label` failures are non-fatal.
1875async fn update_agent_label_after_reroute(
1876    #[cfg_attr(
1877        test,
1878        expect(unused_variables, reason = "only the label call outside tests uses it")
1879    )]
1880    repo: &str,
1881    task: &ExternalTask,
1882    backend: &Arc<dyn ExternalBackend>,
1883    old_agent: &str,
1884    new_agent: &str,
1885) -> bool {
1886    let old_label = format!("agent:{old_agent}");
1887    if let Err(e) = backend.remove_label(&task.id, &old_label).await {
1888        tracing::warn!(
1889            task_id = ?task.id,
1890            label = old_label,
1891            error = %e,
1892            "failed to remove old agent label during re-route"
1893        );
1894    }
1895    let new_label = format!("agent:{new_agent}");
1896
1897    // ensure_label creates the repo-level label if missing (best-effort).
1898    // Skipped under #[cfg(test)] to avoid real GitHub API calls.
1899    #[cfg(not(test))]
1900    {
1901        match GhHttp::new() {
1902            Ok(gh) => {
1903                if gh
1904                    .ensure_label(
1905                        repo,
1906                        &new_label,
1907                        http::status_label_color(&new_label),
1908                        &format!("Agent: {new_agent}"),
1909                    )
1910                    .await
1911                    .is_err()
1912                {
1913                    tracing::warn!(
1914                        task_id = ?task.id,
1915                        label = %new_label,
1916                        "ensure_label failed during agent label update after failover"
1917                    );
1918                }
1919            }
1920            Err(e) => {
1921                tracing::warn!(
1922                    task_id = ?task.id,
1923                    err = %e,
1924                    "GhHttp::new() failed — skipping ensure_label"
1925                );
1926            }
1927        }
1928    }
1929
1930    if let Err(e) = backend
1931        .set_labels(&task.id, slice::from_ref(&new_label))
1932        .await
1933    {
1934        tracing::warn!(
1935            task_id = ?task.id,
1936            label = %new_label,
1937            error = %e,
1938            "set_labels failed during agent label update after failover"
1939        );
1940        return false;
1941    }
1942    true
1943}
1944
1945/// Weight signal for a run that ended in `needs_review`. `prepare_task` clears `last_error` at run
1946/// start, so a non-empty value means `handle_error` ended this run
1947fn needs_review_signal(last_error: &str, agent: &str) -> WeightSignal {
1948    let agent = agent.to_string();
1949    if classify_run_error_type(last_error) == "rate_limit" {
1950        WeightSignal::RateLimited { agent }
1951    } else if !last_error.is_empty() {
1952        WeightSignal::Failed { agent }
1953    } else {
1954        WeightSignal::Success { agent }
1955    }
1956}
1957
1958#[cfg(test)]
1959mod tests;