Skip to main content

orch/engine/runner/response_handler/
mod.rs

1//! Success-path response handler — commit, push, PR, token storage.
2//!
3//! Extracted from `runner/mod.rs`. Handles the `Ok(parsed)` arm of the parse
4//! result, including git operations and delegation storage. Also owns
5//! `write_result_json`.
6
7use crate::engine::git::commit;
8use crate::github::types::parse_pr_number_from_url;
9
10use crate::config;
11use crate::engine::agents::parser::AgentResponse;
12use crate::store;
13use crate::store::TaskStore;
14use std::io;
15use std::io::ErrorKind;
16use std::path::Path;
17use std::sync::Arc;
18
19use tokio::fs;
20
21use super::response;
22use crate::cooldown;
23use crate::engine::agents;
24use crate::engine::agents::status_heuristics;
25use crate::engine::git::git_ops;
26use crate::engine::git::push_retry;
27use crate::engine::git::screenshots;
28use crate::engine::git::worktree;
29use crate::github::http::GhHttp;
30use crate::store::Task;
31
32/// Write a structured `result.json` to the attempt directory for debugging.
33#[expect(
34    clippy::too_many_arguments,
35    reason = "each field of result.json is a separate argument"
36)]
37pub async fn write_result_json(
38    attempt_dir: &Path,
39    task_id: &str,
40    agent_name: &str,
41    model_name: Option<&str>,
42    exit_code: i32,
43    new_attempts: u32,
44    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
45    raw_stdout: &str,
46    raw_stderr: &str,
47) {
48    let result_json = match parse_result {
49        Ok(parsed) => {
50            serde_json::json!({
51                "outcome": "success",
52                "agent": agent_name,
53                "model": model_name.unwrap_or("default"),
54                "exit_code": exit_code,
55                "attempt": new_attempts,
56                "status": parsed.response.status,
57                "summary": parsed.response.summary,
58                "input_tokens": parsed.input_tokens,
59                "output_tokens": parsed.output_tokens,
60                "duration_ms": parsed.duration_ms,
61                "files": parsed.response.files,
62                "accomplished": parsed.response.accomplished,
63                "remaining": parsed.response.remaining,
64                "error": parsed.response.error,
65                "learnings": parsed.response.learnings,
66                "delegations": parsed.response.delegations.iter()
67                    .map(|d| serde_json::json!({"title": d.title, "body": d.body}))
68                    .collect::<Vec<_>>(),
69            })
70        }
71        Err(agent_err) => {
72            serde_json::json!({
73                "outcome": "error",
74                "agent": agent_name,
75                "model": model_name.unwrap_or("default"),
76                "exit_code": exit_code,
77                "attempt": new_attempts,
78                "error_class": agents::error_class_name(agent_err),
79                "error_message": agent_err.to_string(),
80                "stderr_tail": agents::patterns::safe_tail(raw_stderr, 2000),
81                "stdout_tail": agents::patterns::safe_tail(raw_stdout, 2000),
82            })
83        }
84    };
85
86    if let Err(e) = fs::write(
87        attempt_dir.join("result.json"),
88        serde_json::to_string_pretty(&result_json).unwrap_or_default(),
89    )
90    .await
91    {
92        tracing::debug!(task_id, ?e, "failed to write result.json");
93    }
94}
95
96/// Input to the pure status-decision function [`classify_final_status`].
97///
98/// The caller is responsible for pre-computing counter values (via store
99/// increments) and populating them here.  No I/O is performed inside the
100/// decision function itself, making it trivially unit-testable.
101#[derive(Default)]
102#[expect(
103    clippy::struct_excessive_bools,
104    reason = "each flag is an independent input to the status decision"
105)]
106struct DecisionInput<'a> {
107    /// Agent-reported status (e.g. `"done"`, `"in_progress"`).
108    agent_status: &'a str,
109    /// Push was attempted and commits existed, but the push error contained a
110    /// `workflow` scope complaint — non-retryable.
111    is_workflow_scope_failure: bool,
112    /// Push failure recovery attempted a rebase but failed (for example due to
113    /// conflicts). This is non-retryable without human intervention.
114    is_rebase_conflict_failure: bool,
115    /// Push was attempted (commits existed) but failed.
116    push_failed: bool,
117    /// Persistent push-failure counter *after* this run's increment.
118    /// Only meaningful when `push_failed` is `true`.
119    push_failures: u64,
120    /// The push failed on a GitHub or network error. A new agent run cannot change that, so the
121    /// engine retries the push with a backoff instead (#4025).
122    is_transient_push_failure: bool,
123    /// A PR already exists (or was just created) for this task.
124    has_pr: bool,
125    /// The agent created sub-task delegations.
126    has_delegations: bool,
127    /// Commits were pushed to the remote branch successfully.
128    has_pushed: bool,
129    /// PR creation failed because the base branch was invalid (even after
130    /// GitHub API fallback). This is a terminal error — the task should be
131    /// blocked rather than re-dispatched.
132    is_pr_base_invalid: bool,
133    /// The task is external and requires a PR to be marked done.
134    /// Always false for internal tasks.
135    requires_pr: bool,
136    /// Persistent no-code-reroute counter *after* this run's increment.
137    no_code_reroutes: u64,
138    /// Maximum no-code reroutes before blocking (from config).
139    max_reroutes: u32,
140    /// True if the agent that just ran is the same as the one that produced
141    /// the previous no-code result. Same-agent loops should be blocked immediately.
142    is_same_agent: bool,
143    /// True when agent_status is "completed". Used to distinguish internal
144    /// completed tasks (mark done) from "done" tasks where the git ops pipeline
145    /// would have detected no-code reroutes. Pre-computed from agent_status
146    /// by the caller so this function stays pure.
147    is_completed_status: bool,
148    /// Agent explicitly returned blocked, but reason appears transient and retryable.
149    is_retryable_blocked: bool,
150    /// The task was re-dispatched to resolve a merge conflict and came back with
151    /// nothing ahead of the default branch, meaning the fix already landed and
152    /// the open PR is superseded. Mark done instead of counting a no-code run.
153    is_superseded_conflict: bool,
154}
155
156/// Determine the final task status from pre-computed state.
157///
158/// This is a pure function — it performs no I/O.  All store increments must be
159/// done by the caller **before** calling this function (so counters reflect the
160/// current run), and all store side-effects (clearing agent/model, writing
161/// last_error) must be applied **after** based on the returned status.
162fn classify_final_status(input: &DecisionInput<'_>) -> String {
163    if input.is_workflow_scope_failure || input.is_rebase_conflict_failure {
164        "blocked".to_string()
165    } else if input.push_failed {
166        if input.is_transient_push_failure && input.push_failures < push_retry::MAX_PUSH_FAILURES {
167            "needs_review".to_string()
168        } else if input.push_failures >= 3 {
169            "blocked".to_string()
170        } else {
171            "new".to_string()
172        }
173    } else if input.agent_status == "done" && input.has_pr {
174        "needs_review".to_string()
175    } else if input.agent_status == "done" && !input.has_pr && input.has_delegations {
176        "blocked".to_string()
177    } else if input.agent_status == "done"
178        && !input.has_pr
179        && input.has_pushed
180        && input.is_pr_base_invalid
181    {
182        // PR creation failed with an invalid base branch (even after GitHub API
183        // fallback).  This is a terminal configuration error — re-dispatching
184        // would just burn tokens on the same failure.
185        "blocked".to_string()
186    } else if input.agent_status == "done" && !input.has_pr && input.has_pushed {
187        "routed".to_string()
188    } else if input.is_superseded_conflict {
189        "done".to_string()
190    } else if input.agent_status == "done" && input.requires_pr {
191        // Same-agent loop detection: if this agent is the same as the one that
192        // produced the previous no-code result, block immediately (#2410, #2686).
193        // Otherwise, block if max reroutes exhausted, else reroute.
194        if input.is_same_agent || input.no_code_reroutes >= u64::from(input.max_reroutes) {
195            "blocked".to_string()
196        } else {
197            "new".to_string()
198        }
199    } else if input.agent_status == "done" && !input.has_pushed {
200        // Only internal tasks reach here — external done+!has_pr+!has_pushed is
201        // always caught by branch 6 (requires_pr = true for external tasks with
202        // !has_pr and done status), so is_external can never be true here.
203        // Internal tasks may legitimately produce no git-visible changes.
204        "done".to_string()
205    } else if input.is_completed_status && input.has_pr {
206        // Agent said "completed" and a PR was created — send to review.
207        "needs_review".to_string()
208    } else if input.is_completed_status && !input.has_pr && input.has_delegations {
209        // Agent said "completed" with delegations but no PR — blocked on children.
210        "blocked".to_string()
211    } else if input.is_completed_status
212        && !input.has_pr
213        && input.has_pushed
214        && input.is_pr_base_invalid
215    {
216        "blocked".to_string()
217    } else if input.is_completed_status && !input.has_pr && input.has_pushed {
218        // Agent said "completed", commits pushed but no PR — re-dispatch for PR.
219        "routed".to_string()
220    } else if input.is_completed_status && input.requires_pr {
221        // Agent said "completed" on external task requiring PR without a PR or pushes.
222        // Same-agent loop detection applies, then reroute or block.
223        if input.is_same_agent || input.no_code_reroutes >= u64::from(input.max_reroutes) {
224            "blocked".to_string()
225        } else {
226            "new".to_string()
227        }
228    } else if input.is_completed_status {
229        // Agent said "completed" on internal task — mark done.
230        // Git ops already ran and detected no commits, so this is a legitimate
231        // completion without code changes.
232        "done".to_string()
233    } else if input.agent_status == "blocked" && input.is_retryable_blocked {
234        "new".to_string()
235    } else if status_heuristics::status_looks_like_descriptive_completion(input.agent_status) {
236        "done".to_string()
237    } else {
238        input.agent_status.to_string()
239    }
240}
241
242// ── Internal context ──────────────────────────────────────────────────────────
243
244/// Bundles store references so helper functions don't repeat four parameters.
245struct StoreCtx<'a> {
246    store: &'a Option<Arc<TaskStore>>,
247    store_id_opt: Option<i64>,
248    repo: &'a str,
249    task_id: &'a str,
250}
251
252impl StoreCtx<'_> {
253    /// Write fields, using the pre-resolved `store_id` when available.
254    async fn set(&self, fields: &[(&str, serde_json::Value)]) {
255        if let Some(store_id) = self.store_id_opt {
256            let _ = store::store_set_by_id(self.store.as_ref(), store_id, fields).await;
257        } else {
258            store::store_set(self.store, self.repo, self.task_id, fields).await;
259        }
260    }
261
262    /// A successful run ends the streak of network errors and timeouts
263    async fn reset_retry_streaks(&self) {
264        self.set(&[
265            ("network_retries", serde_json::json!(0)),
266            ("timeout_retries", serde_json::json!(0)),
267        ])
268        .await;
269    }
270
271    /// Load the full task record.
272    async fn get_task(&self) -> Option<Task> {
273        if let Some(store_id) = self.store_id_opt {
274            store::opt_store_get_task_by_id(self.store, store_id).await
275        } else {
276            store::opt_store_get_task(self.store, self.repo, self.task_id).await
277        }
278    }
279
280    /// Atomically increment a counter field.
281    async fn increment(&self, field: &str) -> anyhow::Result<u64> {
282        if let Some(store_id) = self.store_id_opt {
283            store::store_increment_by_id(self.store, store_id, field).await
284        } else {
285            store::store_increment(self.store, self.repo, self.task_id, field).await
286        }
287    }
288
289    /// Append an activity event to the task timeline.
290    async fn append_activity(
291        &self,
292        event_type: &str,
293        agent: Option<&str>,
294        model: Option<&str>,
295        details: Option<&serde_json::Value>,
296    ) {
297        if let Some(store_id) = self.store_id_opt {
298            if let Some(s) = self.store
299                && let Err(e) = s
300                    .append_activity(store_id, event_type, None, None, agent, model, details)
301                    .await
302            {
303                tracing::warn!(
304                    task_id = self.task_id,
305                    event_type,
306                    error = %e,
307                    "store append_activity failed"
308                );
309            }
310        } else {
311            store::store_log_activity(
312                self.store,
313                self.repo,
314                self.task_id,
315                event_type,
316                None,
317                None,
318                agent,
319                model,
320                details,
321            )
322            .await;
323        }
324    }
325}
326
327// ── Git operation result types ────────────────────────────────────────────────
328
329/// Outcome of the auto-commit → push → PR pipeline.
330#[derive(Default)]
331#[expect(
332    clippy::struct_excessive_bools,
333    reason = "each flag is an independent outcome of the git pipeline"
334)]
335struct GitOpsResult {
336    has_pr: bool,
337    has_pushed: bool,
338    has_commits: bool,
339    /// PR creation failed with an invalid base branch (after all retries
340    /// and the GitHub API fallback).  Used to block the task instead of
341    /// re-dispatching it indefinitely.
342    pr_base_invalid: bool,
343}
344
345/// Push-failure detection result.
346#[expect(
347    clippy::struct_excessive_bools,
348    reason = "each flag is an independent kind of push failure"
349)]
350struct PushFailureState {
351    push_failed: bool,
352    is_workflow_scope_failure: bool,
353    is_rebase_conflict_failure: bool,
354    /// GitHub or network error that the engine retries with a backoff, without an agent run.
355    is_transient_failure: bool,
356    /// Post-increment failure counter (0 when no push was attempted or failed).
357    push_failures: u64,
358    /// Last error stored in the task record (used for workflow-scope detection).
359    stored_last_error: String,
360}
361
362// ── Private git-ops helpers ───────────────────────────────────────────────────
363
364/// Attempt auto-commit; record any error in the store.
365async fn auto_commit_changes(
366    ctx: &StoreCtx<'_>,
367    work_dir: &Path,
368    task_title: &str,
369    agent_name: &str,
370    new_attempts: u32,
371) {
372    if let Err(e) = git_ops::auto_commit(
373        work_dir,
374        ctx.task_id,
375        task_title,
376        agent_name,
377        new_attempts,
378        commit::When::Always,
379    )
380    .await
381    {
382        tracing::error!(task_id = ctx.task_id, error = ?e, "auto commit failed");
383        ctx.set(&[(
384            "last_error",
385            serde_json::json!(format!("auto commit failed: {e}")),
386        )])
387        .await;
388    }
389}
390
391/// Check whether commits exist ahead of the default branch.
392///
393/// When there are no commits, clears any stale push-failure error so that the
394/// review gate does not block an otherwise-approved task.
395async fn check_commits_and_clear_stale_errors(
396    ctx: &StoreCtx<'_>,
397    work_dir: &Path,
398    default_branch: &str,
399) -> bool {
400    let has_commits = git_ops::has_commits_ahead(work_dir, default_branch).await;
401    if !has_commits {
402        tracing::info!(
403            task_id = ctx.task_id,
404            "no commits ahead of default branch, skipping push + PR"
405        );
406        // Clear stale push failure from previous runs.
407        let last_err = ctx
408            .get_task()
409            .await
410            .map(|t| t.last_error)
411            .unwrap_or_default();
412        if last_err.contains("push failed") {
413            ctx.set(&[("last_error", serde_json::json!(""))]).await;
414        }
415    }
416    has_commits
417}
418
419/// Push the branch to the remote and log the activity.
420///
421/// On push failure due to diverged history (non-fast-forward), fetches the remote
422/// branch and rebases local commits on top, then pushes again. If rebase fails
423/// (conflicts), the task is blocked for human intervention.
424///
425/// Returns `PushResult::Success` on success, `PushResult::Failed` if push failed
426/// and recovery was not possible, `PushResult::Skipped` if the push was skipped,
427/// or `PushResult::NoCommits` if the branch has no commits ahead of the default branch
428enum PushResult {
429    Success,
430    Failed,
431    Skipped,         // push_branch returned Ok(false)
432    NoCommits,       // agent made no code changes
433    WorktreeMissing, // retry after rebuilding missing worktree
434}
435
436fn is_missing_path_error(err: &anyhow::Error) -> bool {
437    err.chain().any(|cause| {
438        cause
439            .downcast_ref::<io::Error>()
440            .is_some_and(|ioe| ioe.kind() == ErrorKind::NotFound)
441    }) || err
442        .to_string()
443        .to_ascii_lowercase()
444        .contains("no such file or directory")
445}
446
447async fn recover_missing_worktree_for_push(
448    ctx: &StoreCtx<'_>,
449    wt: &worktree::WorktreeSetup,
450    task_title: &str,
451    agent_name: &str,
452    model_name: Option<&str>,
453) -> anyhow::Result<worktree::WorktreeSetup> {
454    tracing::warn!(
455        task_id = ctx.task_id,
456        worktree = %wt.work_dir.display(),
457        branch = wt.branch,
458        "worktree missing during push; attempting one-time recovery"
459    );
460    ctx.append_activity(
461        "push_recover_worktree",
462        Some(agent_name),
463        model_name,
464        Some(&serde_json::json!({
465            "status": "start",
466            "worktree": wt.work_dir.display().to_string(),
467            "branch": wt.branch,
468        })),
469    )
470    .await;
471
472    let recovered = worktree::setup_worktree(
473        ctx.task_id,
474        task_title,
475        &wt.main_project_dir,
476        ctx.store,
477        ctx.repo,
478    )
479    .await?;
480
481    if !recovered.work_dir.exists() {
482        anyhow::bail!(
483            "recovered worktree path is still missing: {}",
484            recovered.work_dir.display()
485        );
486    }
487
488    ctx.append_activity(
489        "push_recover_worktree",
490        Some(agent_name),
491        model_name,
492        Some(&serde_json::json!({
493            "status": "ok",
494            "worktree": recovered.work_dir.display().to_string(),
495            "branch": recovered.branch,
496        })),
497    )
498    .await;
499
500    Ok(recovered)
501}
502
503/// Push a branch that was just rebased onto its moved remote counterpart.
504///
505/// Separate from the first push attempt so a failure here is reported as orch's own
506/// push failure rather than re-entering the diverged-branch recovery
507async fn push_after_rebase(
508    ctx: &StoreCtx<'_>,
509    work_dir: &Path,
510    branch: &str,
511    default_branch: &str,
512    agent_name: &str,
513    model_name: Option<&str>,
514) -> PushResult {
515    match git_ops::push_branch(work_dir, branch, default_branch).await {
516        Ok(true) => {
517            ctx.append_activity(
518                "push",
519                Some(agent_name),
520                model_name,
521                Some(&serde_json::json!({
522                    "status": "ok",
523                    "branch": branch,
524                    "default_branch": default_branch,
525                    "reason": "pushed_after_rebase",
526                })),
527            )
528            .await;
529            ctx.set(&[
530                ("last_error", serde_json::json!("")),
531                ("push_failures", serde_json::json!(0)),
532            ])
533            .await;
534            PushResult::Success
535        }
536        Ok(false) => {
537            tracing::info!(
538                task_id = ctx.task_id,
539                branch,
540                default_branch,
541                "push skipped after rebase"
542            );
543            ctx.append_activity(
544                "push",
545                Some(agent_name),
546                model_name,
547                Some(&serde_json::json!({
548                    "status": "skipped",
549                    "branch": branch,
550                    "default_branch": default_branch,
551                    "reason": "pushed_after_rebase",
552                })),
553            )
554            .await;
555            PushResult::Skipped
556        }
557        Err(e) => {
558            tracing::error!(
559                task_id = ctx.task_id,
560                branch = branch,
561                error = ?e,
562                "push failed again after rebasing on the remote branch"
563            );
564            ctx.append_activity(
565                "push",
566                Some(agent_name),
567                model_name,
568                Some(&serde_json::json!({
569                    "status": "error",
570                    "branch": branch,
571                    "default_branch": default_branch,
572                    "reason": "pushed_after_rebase",
573                    "error": e.to_string(),
574                })),
575            )
576            .await;
577            ctx.set(&[(
578                "last_error",
579                serde_json::json!(format!("push failed after rebase on remote branch: {e}")),
580            )])
581            .await;
582            PushResult::Failed
583        }
584    }
585}
586
587async fn push_branch_with_log(
588    ctx: &StoreCtx<'_>,
589    work_dir: &Path,
590    branch: &str,
591    default_branch: &str,
592    agent_name: &str,
593    model_name: Option<&str>,
594) -> PushResult {
595    match git_ops::push_branch(work_dir, branch, default_branch).await {
596        Ok(true) => {
597            ctx.append_activity(
598                "push",
599                Some(agent_name),
600                model_name,
601                Some(&serde_json::json!({
602                    "status": "ok",
603                    "branch": branch,
604                    "default_branch": default_branch,
605                })),
606            )
607            .await;
608            // Clear any stale push failure from a previous run so review_and_merge
609            // does not incorrectly block an approved task.
610            ctx.set(&[
611                ("last_error", serde_json::json!("")),
612                ("push_failures", serde_json::json!(0)),
613            ])
614            .await;
615            PushResult::Success
616        }
617        Ok(false) => {
618            tracing::info!(
619                task_id = ctx.task_id,
620                branch,
621                default_branch,
622                "push skipped"
623            );
624            ctx.append_activity(
625                "push",
626                Some(agent_name),
627                model_name,
628                Some(&serde_json::json!({
629                    "status": "skipped",
630                    "branch": branch,
631                    "default_branch": default_branch,
632                })),
633            )
634            .await;
635            PushResult::Skipped
636        }
637        Err(e) => {
638            let err_str = e.to_string();
639            tracing::error!(task_id = ctx.task_id, error = ?e, "push failed");
640
641            if is_missing_path_error(&e) && !work_dir.exists() {
642                tracing::warn!(
643                    task_id = ctx.task_id,
644                    worktree = %work_dir.display(),
645                    "push failed because worktree path disappeared; will attempt recovery"
646                );
647                ctx.append_activity(
648                    "push",
649                    Some(agent_name),
650                    model_name,
651                    Some(&serde_json::json!({
652                        "status": "retry",
653                        "branch": branch,
654                        "default_branch": default_branch,
655                        "reason": "worktree_missing",
656                        "error": err_str,
657                    })),
658                )
659                .await;
660                return PushResult::WorktreeMissing;
661            }
662
663            // Check if this is a non-fast-forward error that we can recover from.
664            if push_error_is_diverged(&err_str) {
665                tracing::info!(
666                    task_id = ctx.task_id,
667                    branch = branch,
668                    "attempting fetch and rebase to recover from diverged branch"
669                );
670
671                // Attempt to fetch and rebase on origin/{branch}.
672                match git_ops::rebase_on_branch(work_dir, branch).await {
673                    Ok(true) => {
674                        // Pushing is orch's step, not the agent's: the commits are already
675                        // written, so push them onto the moved remote branch here. Re-routing
676                        // instead re-ran a finished task until it hit the attempt limit (#3783)
677                        tracing::info!(
678                            task_id = ctx.task_id,
679                            branch = branch,
680                            "rebase succeeded — retrying the push"
681                        );
682                        ctx.append_activity(
683                            "push_rebased",
684                            Some(agent_name),
685                            model_name,
686                            Some(&serde_json::json!({
687                                "status": "rebased",
688                                "branch": branch,
689                                "reason": "diverged_from_remote",
690                            })),
691                        )
692                        .await;
693                        return push_after_rebase(
694                            ctx,
695                            work_dir,
696                            branch,
697                            default_branch,
698                            agent_name,
699                            model_name,
700                        )
701                        .await;
702                    }
703                    Ok(false) => {
704                        // The remote branch already holds every local commit, nothing to push
705                        tracing::info!(
706                            task_id = ctx.task_id,
707                            branch = branch,
708                            "no local commits after fetch — marking as success"
709                        );
710                        ctx.append_activity(
711                            "push",
712                            Some(agent_name),
713                            model_name,
714                            Some(&serde_json::json!({
715                                "status": "ok",
716                                "branch": branch,
717                                "reason": "no_commits_after_fetch",
718                            })),
719                        )
720                        .await;
721                        ctx.set(&[
722                            ("last_error", serde_json::json!("")),
723                            ("push_failures", serde_json::json!(0)),
724                        ])
725                        .await;
726                        return PushResult::Success;
727                    }
728                    Err(rebase_err) if git_ops::is_missing_remote_ref_error(&rebase_err) => {
729                        // The branch never reached the remote, so there is nothing to rebase onto.
730                        // Take the counted retry path instead of the rebase conflict block
731                        tracing::warn!(
732                            task_id = ctx.task_id,
733                            branch = branch,
734                            "remote branch does not exist, skipping rebase recovery"
735                        );
736                        ctx.append_activity(
737                            "push",
738                            Some(agent_name),
739                            model_name,
740                            Some(&serde_json::json!({
741                                "status": "error",
742                                "branch": branch,
743                                "default_branch": default_branch,
744                                "error": err_str,
745                            })),
746                        )
747                        .await;
748                        ctx.set(&[("last_error", serde_json::json!(format!("push failed: {e}")))])
749                            .await;
750                        return PushResult::Failed;
751                    }
752                    Err(rebase_err) => {
753                        // Rebase failed (likely conflicts) — block for human intervention.
754                        tracing::error!(
755                            task_id = ctx.task_id,
756                            branch = branch,
757                            error = ?rebase_err,
758                            "rebase failed — blocking task for human intervention"
759                        );
760                        ctx.append_activity(
761                            "push_rebased",
762                            Some(agent_name),
763                            model_name,
764                            Some(&serde_json::json!({
765                                "status": "error",
766                                "branch": branch,
767                                "error": rebase_err.to_string(),
768                            })),
769                        )
770                        .await;
771                        ctx.set(&[(
772                            "last_error",
773                            serde_json::json!(format!(
774                                "push failed and rebase failed: {rebase_err} — manual resolution required"
775                            )),
776                        )])
777                        .await;
778                        return PushResult::Failed;
779                    }
780                }
781            }
782
783            // Non-recoverable push error — log and return failure.
784            ctx.append_activity(
785                "push",
786                Some(agent_name),
787                model_name,
788                Some(&serde_json::json!({
789                    "status": "error",
790                    "branch": branch,
791                    "default_branch": default_branch,
792                    "error": err_str,
793                })),
794            )
795            .await;
796            ctx.set(&[("last_error", serde_json::json!(format!("push failed: {e}")))])
797                .await;
798            PushResult::Failed
799        }
800    }
801}
802
803/// True when a push error means the remote branch moved. `[remote rejected]` is a server side
804/// failure, only `! [rejected]` marks a divergence
805fn push_error_is_diverged(err_str: &str) -> bool {
806    err_str.contains("non-fast-forward")
807        || err_str.contains("! [rejected]")
808        || err_str.contains("fetch first")
809        || err_str.contains("behind")
810}
811
812/// True when the GitHub client refused the call locally because its rate-limit window is active.
813fn is_local_rate_limit_skip(err_str: &str) -> bool {
814    err_str.contains("rate-limited, skipping call")
815}
816
817/// Create (or find an existing) PR and log the activity.
818///
819/// Returns `(has_pr, has_pushed, pr_base_invalid)`. `has_pushed` may be set to
820/// `false` when a 422 "no commits" GitHub error indicates the branch was
821/// already merged. `pr_base_invalid` is set when the base branch is rejected
822/// by GitHub (even after the API fallback), which is a terminal condition.
823async fn create_pr_with_log(
824    ctx: &StoreCtx<'_>,
825    wt: &worktree::WorktreeSetup,
826    task_title: &str,
827    resp: &AgentResponse,
828    agent_name: &str,
829    model_name: Option<&str>,
830    mut has_pushed: bool,
831) -> (bool, bool, bool) {
832    match git_ops::create_pr_if_needed(
833        &wt.work_dir,
834        &wt.branch,
835        task_title,
836        &resp.summary,
837        &resp.accomplished,
838        &resp.remaining,
839        &resp.files,
840        ctx.task_id,
841        agent_name,
842        model_name,
843        ctx.repo,
844        &wt.default_branch,
845    )
846    .await
847    {
848        Ok(ref url) => {
849            // Save pr_number to the store so the review gate can find it
850            // immediately without racing GitHub's list-API cache (~300 ms lag).
851            // This is set for both newly-created and pre-existing PRs.
852            match parse_pr_number_from_url(url) {
853                Ok(pr_num) => {
854                    if let Err(e) = store::store_set_result(
855                        ctx.store,
856                        ctx.repo,
857                        ctx.task_id,
858                        &[("pr_number", serde_json::json!(pr_num))],
859                    )
860                    .await
861                    {
862                        tracing::error!(
863                            task_id = ctx.task_id,
864                            pr_url = %url,
865                            err = %e,
866                            "CRITICAL: failed to save pr_number to store — downstream review gate may trigger duplicate gh pr create"
867                        );
868                    }
869                }
870                Err(e) => {
871                    tracing::warn!(
872                        task_id = ctx.task_id,
873                        pr_url = %url,
874                        error = %e,
875                        "PR created but failed to parse PR number from URL"
876                    );
877                }
878            }
879            ctx.append_activity(
880                "pr_create",
881                Some(agent_name),
882                model_name,
883                Some(&serde_json::json!({"status": "created", "url": url})),
884            )
885            .await;
886            (true, has_pushed, false)
887        }
888        Err(e) => {
889            let err_str = format!("{e}");
890            tracing::error!(task_id = ctx.task_id, error = ?e, "create PR failed");
891            ctx.append_activity(
892                "pr_create",
893                Some(agent_name),
894                model_name,
895                Some(&serde_json::json!({
896                    "status": "error",
897                    "branch": wt.branch,
898                    "error": err_str.clone(),
899                })),
900            )
901            .await;
902            ctx.set(&[(
903                "last_error",
904                serde_json::json!(format!("create PR failed: {e}")),
905            )])
906            .await;
907            // Distinguish between terminal 422 errors and recoverable ones.
908            // - "No commits between" / "head invalid" → agent made no code changes
909            //   or the branch was already merged.  Clearing has_pushed lets the
910            //   task fall through to the "done" path.
911            // - "base invalid" → the base branch name is wrong.  After the
912            //   GitHub API fallback in create_pr_if_needed also fails, this is a
913            //   terminal configuration error.  We set pr_base_invalid so the
914            //   classifier blocks the task instead of re-dispatching forever.
915            // A GitHub auth error is terminal too: the commits are pushed, so only a token fix helps
916            let mut pr_base_invalid = false;
917            if is_local_rate_limit_skip(&err_str) {
918                // No request was sent and the branch is pushed. Re-running the agent cannot help,
919                // so report the PR as pending and let the review gate create it once calls resume
920                tracing::warn!(
921                    task_id = ctx.task_id,
922                    "PR creation skipped by local GitHub rate limit — review gate will create the PR"
923                );
924                return (true, has_pushed, false);
925            }
926            if agents::patterns::detect_auth_error(&err_str).is_some() {
927                tracing::error!(
928                    task_id = ctx.task_id,
929                    "PR creation failed with GitHub auth error — blocking task"
930                );
931                pr_base_invalid = true;
932            } else if err_str.contains("422") {
933                if err_str.contains("No commits between") || err_str.contains("head") {
934                    tracing::info!(
935                        task_id = ctx.task_id,
936                        "PR creation returned 422/no-commits/head-invalid — agent made no code changes or branch merged, marking done"
937                    );
938                    has_pushed = false;
939                } else if git_ops::is_invalid_base_error(&err_str) {
940                    tracing::error!(
941                        task_id = ctx.task_id,
942                        "PR creation failed with invalid base branch — blocking task"
943                    );
944                    pr_base_invalid = true;
945                }
946            }
947            (false, has_pushed, pr_base_invalid)
948        }
949    }
950}
951
952/// Run the full auto-commit → push → PR pipeline.
953async fn run_git_ops(
954    ctx: &StoreCtx<'_>,
955    wt: &worktree::WorktreeSetup,
956    task_title: &str,
957    resp: &AgentResponse,
958    agent_name: &str,
959    model_name: Option<&str>,
960    new_attempts: u32,
961) -> GitOpsResult {
962    auto_commit_changes(ctx, &wt.work_dir, task_title, agent_name, new_attempts).await;
963
964    let mut has_commits =
965        check_commits_and_clear_stale_errors(ctx, &wt.work_dir, &wt.default_branch).await;
966
967    // Skip push + PR if there are no commits ahead of the default branch.
968    // No-op tasks (e.g. "nothing to execute") produce no commits, so pushing
969    // and creating a PR would just waste API calls and trigger 422 errors.
970    let push_result = if has_commits {
971        push_branch_with_log(
972            ctx,
973            &wt.work_dir,
974            &wt.branch,
975            &wt.default_branch,
976            agent_name,
977            model_name,
978        )
979        .await
980    } else {
981        store::store_log_activity(
982            ctx.store,
983            ctx.repo,
984            ctx.task_id,
985            "push",
986            None,
987            None,
988            Some(agent_name),
989            model_name,
990            Some(&serde_json::json!({
991                "status": "skipped",
992                "reason": "no_commits_ahead",
993                "branch": wt.branch,
994                "default_branch": wt.default_branch,
995            })),
996        )
997        .await;
998        PushResult::NoCommits
999    };
1000    let push_result = if matches!(push_result, PushResult::WorktreeMissing) {
1001        match recover_missing_worktree_for_push(ctx, wt, task_title, agent_name, model_name).await {
1002            Ok(recovered) => {
1003                let wt_for_ops = &recovered;
1004                has_commits = check_commits_and_clear_stale_errors(
1005                    ctx,
1006                    &wt_for_ops.work_dir,
1007                    &wt_for_ops.default_branch,
1008                )
1009                .await;
1010                if has_commits {
1011                    push_branch_with_log(
1012                        ctx,
1013                        &wt_for_ops.work_dir,
1014                        &wt_for_ops.branch,
1015                        &wt_for_ops.default_branch,
1016                        agent_name,
1017                        model_name,
1018                    )
1019                    .await
1020                } else {
1021                    PushResult::NoCommits
1022                }
1023            }
1024            Err(e) => {
1025                tracing::error!(
1026                    task_id = ctx.task_id,
1027                    err = %e,
1028                    "worktree recovery before push failed"
1029                );
1030                ctx.append_activity(
1031                    "push_recover_worktree",
1032                    Some(agent_name),
1033                    model_name,
1034                    Some(&serde_json::json!({
1035                        "status": "error",
1036                        "worktree": wt.work_dir.display().to_string(),
1037                        "branch": wt.branch,
1038                        "error": e.to_string(),
1039                    })),
1040                )
1041                .await;
1042                ctx.set(&[(
1043                    "last_error",
1044                    serde_json::json!(format!(
1045                        "push failed: worktree disappeared and recovery failed: {e}"
1046                    )),
1047                )])
1048                .await;
1049                PushResult::Failed
1050            }
1051        }
1052    } else {
1053        push_result
1054    };
1055
1056    let mut has_pushed = matches!(push_result, PushResult::Success);
1057    let mut has_pr = false;
1058
1059    // Create PR (skip if push failed or repo is unknown)
1060    if has_commits && matches!(push_result, PushResult::Failed) {
1061        tracing::warn!(
1062            task_id = ctx.task_id,
1063            "skipping PR creation due to push failure"
1064        );
1065    } else if matches!(push_result, PushResult::Skipped) {
1066        tracing::info!(task_id = ctx.task_id, "push skipped, skipping PR creation");
1067    } else if matches!(push_result, PushResult::NoCommits) {
1068        tracing::info!(
1069            task_id = ctx.task_id,
1070            "no commits ahead of default branch, skipping push + PR"
1071        );
1072    } else if !has_pushed {
1073        // no commits — already logged "no commits ahead, skipping push + PR" at INFO level above
1074    } else if ctx.repo.is_empty() {
1075        tracing::warn!(
1076            task_id = ctx.task_id,
1077            "skipping PR creation — repo is empty (internal task?)"
1078        );
1079    } else {
1080        let (pr, updated_pushed, pr_base_invalid) = create_pr_with_log(
1081            ctx, wt, task_title, resp, agent_name, model_name, has_pushed,
1082        )
1083        .await;
1084        has_pr = pr;
1085        has_pushed = updated_pushed;
1086        return GitOpsResult {
1087            has_pr,
1088            has_pushed,
1089            has_commits,
1090            pr_base_invalid,
1091        };
1092    }
1093
1094    GitOpsResult {
1095        has_pr,
1096        has_pushed,
1097        has_commits,
1098        pr_base_invalid: false,
1099    }
1100}
1101
1102// ── Private status-computation helpers ───────────────────────────────────────
1103
1104/// Comment the agent's screenshots on the PR. Returns the note for the task summary and channels
1105async fn post_screenshots(
1106    ctx: &StoreCtx<'_>,
1107    work_dir: &Path,
1108    resp: &AgentResponse,
1109) -> Option<String> {
1110    let note = resp.screenshot_note.as_deref().map(str::trim);
1111    let note = note.filter(|n| !n.is_empty());
1112    if resp.screenshots.is_empty() && note.is_none() {
1113        return None;
1114    }
1115    let pr_number = ctx.get_task().await.and_then(|t| t.pr_number);
1116    let (Some(pr_number), false) = (pr_number, ctx.repo.is_empty()) else {
1117        return note.map(String::from);
1118    };
1119    let Ok(pr) = u64::try_from(pr_number) else {
1120        return note.map(String::from);
1121    };
1122
1123    let roots = screenshots::allowed_roots(work_dir).await;
1124    let (images, skipped) = screenshots::prepare(&resp.screenshots, work_dir, &roots, pr);
1125    let commit = if images.is_empty() {
1126        String::new()
1127    } else {
1128        match screenshots::publish(work_dir, &images, pr).await {
1129            Ok(commit) => commit,
1130            Err(e) => {
1131                tracing::warn!(task_id = ctx.task_id, err = %e, "failed to push screenshots");
1132                let body = screenshots::build_unpublished_comment(note, &skipped);
1133                comment_screenshots(ctx, pr, &body).await;
1134                return note.map(String::from);
1135            }
1136        }
1137    };
1138    let body = screenshots::build_comment(ctx.repo, &commit, &images, note, &skipped);
1139    comment_screenshots(ctx, pr, &body).await;
1140    note.map(String::from)
1141}
1142
1143async fn comment_screenshots(ctx: &StoreCtx<'_>, pr: u64, body: &str) {
1144    match GhHttp::new() {
1145        Ok(gh) => {
1146            if let Err(e) = gh.add_comment(ctx.repo, &pr.to_string(), body).await {
1147                tracing::warn!(task_id = ctx.task_id, pr, err = %e, "failed to comment screenshots");
1148            }
1149        }
1150        Err(e) => tracing::warn!(task_id = ctx.task_id, err = %e, "cannot comment screenshots"),
1151    }
1152}
1153
1154/// Comment on and close a PR whose change already landed elsewhere.
1155async fn close_superseded_pr(ctx: &StoreCtx<'_>, pr_number: u64) {
1156    if ctx.repo.is_empty() {
1157        return;
1158    }
1159    match GhHttp::new() {
1160        Ok(gh) => {
1161            let note = "Closing as superseded: the change is already on the default branch, so this branch has no commits ahead of it.";
1162            if let Err(e) = gh.add_comment(ctx.repo, &pr_number.to_string(), note).await {
1163                tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to comment on superseded PR");
1164            }
1165            if let Err(e) = gh.close_pr(ctx.repo, pr_number).await {
1166                tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to close superseded PR");
1167            }
1168        }
1169        Err(e) => {
1170            tracing::warn!(task_id = ctx.task_id, err = %e, "cannot close superseded PR");
1171        }
1172    }
1173    // Dropping the PR lets the blocker refresh read the closed, completed issue with no PR
1174    ctx.set(&[
1175        (
1176            "last_error",
1177            serde_json::json!(
1178                "PR closed as superseded: the fix already landed on the default branch"
1179            ),
1180        ),
1181        ("pr_number", serde_json::json!(null)),
1182    ])
1183    .await;
1184}
1185
1186/// The PR to close when a merge-conflict reroute produced no commits.
1187///
1188/// `merge_conflict_retries > 0` means review_poll sent the task back to resolve a
1189/// conflict. Coming back with nothing ahead of the default branch means another
1190/// PR already landed the same fix, so the open PR is superseded (#3780)
1191fn superseded_conflict_pr(
1192    merge_conflict_retries: i32,
1193    pr_number: Option<i32>,
1194    has_commits: bool,
1195) -> Option<u64> {
1196    if has_commits || merge_conflict_retries <= 0 {
1197        return None;
1198    }
1199    pr_number
1200        .filter(|n| *n > 0)
1201        .and_then(|n| u64::try_from(n).ok())
1202}
1203
1204/// Read push-failure state from the store and increment `push_failures` if needed.
1205async fn detect_push_failure_state(
1206    ctx: &StoreCtx<'_>,
1207    has_commits: bool,
1208    has_pushed: bool,
1209) -> PushFailureState {
1210    // Load stored task once to inspect last_error (avoid repeated DB reads).
1211    let stored_last_error = ctx
1212        .get_task()
1213        .await
1214        .map(|t| t.last_error)
1215        .unwrap_or_default();
1216
1217    let push_failed = !has_pushed && has_commits && stored_last_error.contains("push failed");
1218
1219    // Detect workflow scope errors — these are non-retryable token permission issues.
1220    // Rerouting to a different agent won't help since the same token is used.
1221    let is_workflow_scope_failure = push_failed
1222        && (stored_last_error.contains("workflow` scope")
1223            || stored_last_error.contains("workflow' scope")
1224            || (stored_last_error.contains("refusing to allow")
1225                && stored_last_error.contains("workflow")));
1226
1227    let is_rebase_conflict_failure =
1228        push_failed && stored_last_error.contains("push failed and rebase failed:");
1229
1230    let is_transient_failure = push_failed
1231        && !is_workflow_scope_failure
1232        && !is_rebase_conflict_failure
1233        && git_ops::is_transient_network_error(&stored_last_error);
1234
1235    // Track push failures — block after 3 consecutive failures.
1236    // Workflow-scope failures are non-retryable and blocked immediately; do not
1237    // increment this retry counter for them so that later normal push failures
1238    // are not prematurely blocked.
1239    let push_failures = if push_failed && !is_workflow_scope_failure && !is_rebase_conflict_failure
1240    {
1241        match ctx.increment("push_failures").await {
1242            Ok(v) => v,
1243            Err(e) => {
1244                tracing::warn!(
1245                    task_id = ctx.task_id,
1246                    err = %e,
1247                    "failed to increment push_failures — reading current value from store"
1248                );
1249                // On DB error, read current value to ensure blocking threshold is still reachable
1250                ctx.get_task()
1251                    .await
1252                    .map_or(1, |t| u64::try_from(t.push_failures).unwrap_or(0) + 1)
1253                // assume at least 1 if we can't read either
1254            }
1255        }
1256    } else {
1257        0
1258    };
1259
1260    PushFailureState {
1261        push_failed,
1262        is_workflow_scope_failure,
1263        is_rebase_conflict_failure,
1264        is_transient_failure,
1265        push_failures,
1266        stored_last_error,
1267    }
1268}
1269
1270/// Increment `no_code_reroutes` and log a warning when the agent completed
1271/// without producing code changes on an external task requiring a PR.
1272async fn detect_no_code_reroutes(
1273    ctx: &StoreCtx<'_>,
1274    is_no_code_reroute: bool,
1275    new_attempts: u32,
1276    max_reroutes: u32,
1277) -> u64 {
1278    if !is_no_code_reroute {
1279        return 0;
1280    }
1281    tracing::warn!(
1282        task_id = ctx.task_id,
1283        attempts = new_attempts,
1284        max_reroutes,
1285        "agent reported done but produced no code changes on external task requiring PR"
1286    );
1287    match ctx.increment("no_code_reroutes").await {
1288        Ok(v) => v,
1289        Err(e) => {
1290            tracing::warn!(
1291                task_id = ctx.task_id,
1292                err = %e,
1293                "failed to increment no_code_reroutes — reading current value from store"
1294            );
1295            // On DB error, read current value to ensure blocking threshold is still reachable
1296            ctx.get_task()
1297                .await
1298                .map_or(1, |t| u64::try_from(t.no_code_reroutes).unwrap_or(0) + 1)
1299            // assume at least 1 if we can't read either
1300        }
1301    }
1302}
1303
1304// ── Post-decision side-effect helpers ─────────────────────────────────────────
1305
1306/// Build a human-readable reason string from a "blocked" agent response.
1307///
1308/// Priority: explicit `error` field → `summary` → fallback.
1309/// Appends `remaining` items if present so operators know what was left to do.
1310fn agent_blocked_reason(resp: &AgentResponse) -> String {
1311    let summary_opt = if resp.summary.is_empty() {
1312        None
1313    } else {
1314        Some(resp.summary.as_str())
1315    };
1316    let base = resp
1317        .error
1318        .as_deref()
1319        .filter(|s| !s.is_empty())
1320        .or(summary_opt)
1321        .unwrap_or("agent returned blocked status without a reason");
1322    if resp.remaining.is_empty() {
1323        base.to_string()
1324    } else {
1325        format!("{base}. Remaining: {}", resp.remaining.join("; "))
1326    }
1327}
1328
1329/// True when a blocked response names a denied `git push` and nothing else as the blocker.
1330fn is_denied_push_block(resp: &AgentResponse) -> bool {
1331    let r = agent_blocked_reason(resp).to_lowercase();
1332    r.contains("push")
1333        && [
1334            "denied",
1335            "not allowed",
1336            "permission",
1337            "disallowed",
1338            "approval",
1339        ]
1340        .iter()
1341        .any(|p| r.contains(p))
1342}
1343
1344/// Heuristic classifier for agent-returned blocked reasons.
1345///
1346/// Returns true when the reason looks transient/retryable (network/provider/
1347/// auth-temporary/environment availability issues), and false for likely
1348/// permanent/input/configuration issues.
1349fn is_retryable_blocked_reason(reason: &str) -> bool {
1350    let r = reason.to_lowercase();
1351
1352    let permanent_patterns = [
1353        "not found",
1354        "does not exist",
1355        "invalid",
1356        "malformed",
1357        "syntax error",
1358        "unsupported",
1359        "unimplemented",
1360        "manual intervention required",
1361        "human intervention required",
1362    ];
1363    if permanent_patterns.iter().any(|p| r.contains(p)) {
1364        return false;
1365    }
1366
1367    let transient_patterns = [
1368        "unavailable",
1369        "temporarily unavailable",
1370        "timeout",
1371        "timed out",
1372        "connection reset",
1373        "connection refused",
1374        "network error",
1375        "rate limit",
1376        "try again",
1377        "service down",
1378        "permission denied",
1379        "worktree lock",
1380        "git lock",
1381        "lockfile permission",
1382        "lock permission",
1383        "resource busy",
1384        "could not resolve host",
1385        // Credential providers in headless/tmux sessions can fail transiently
1386        // when GPG agent/passphrase is unavailable.
1387        "gpg decryption fails",
1388        "gpg decryption failed",
1389        "gpg agent",
1390        "no passphrase available",
1391        "passphrase unavailable",
1392        "pass store",
1393        "passwordstoreprovider",
1394        "agentvaultprovider",
1395        "onepasswordprovider",
1396        "decryption failed in this agent session",
1397    ];
1398    transient_patterns.iter().any(|p| r.contains(p))
1399}
1400
1401/// Apply tracing and store writes that depend on the final status decision.
1402#[expect(
1403    clippy::too_many_arguments,
1404    reason = "the decision and its context arrive as separate values"
1405)]
1406async fn apply_post_decision_effects(
1407    ctx: &StoreCtx<'_>,
1408    final_status: &str,
1409    resp_status: &str,
1410    push_state: &PushFailureState,
1411    is_no_code_reroute: bool,
1412    has_pr: bool,
1413    has_pushed: bool,
1414    is_pr_base_invalid: bool,
1415    has_delegations: bool,
1416    is_external: bool,
1417    no_code_reroutes: u64,
1418    max_reroutes: u32,
1419    agent_name: &str,
1420) {
1421    if push_state.is_workflow_scope_failure {
1422        // Non-retryable — block immediately with actionable guidance.
1423        tracing::error!(
1424            task_id = ctx.task_id,
1425            "push failed: token lacks `workflow` OAuth scope — blocking immediately \
1426             (rerouting would not help)"
1427        );
1428        ctx.set(&[(
1429            "last_error",
1430            serde_json::json!(format!(
1431                "push failed: GitHub token lacks `workflow` OAuth scope. \
1432                 The agent modified .github/workflows/ files but the token cannot push them. \
1433                 Fix: add `workflow` scope to your GitHub token, or use a GitHub App for auth. \
1434                 Original error: {}",
1435                push_state.stored_last_error
1436            )),
1437        )])
1438        .await;
1439    } else if push_state.is_rebase_conflict_failure {
1440        tracing::error!(
1441            task_id = ctx.task_id,
1442            "push failed and automatic rebase recovery failed — blocking for human intervention"
1443        );
1444        ctx.set(&[
1445            ("agent", serde_json::json!(null)),
1446            ("model", serde_json::json!(null)),
1447        ])
1448        .await;
1449    } else if push_state.push_failed && final_status == "needs_review" {
1450        // The engine retries the push from the review gate. Keep agent and model, since the
1451        // task never goes back to the router
1452        tracing::warn!(
1453            task_id = ctx.task_id,
1454            push_failures = push_state.push_failures,
1455            "agent done but push failed on a GitHub or network error — engine retries the push"
1456        );
1457    } else if push_state.push_failed {
1458        // Clear agent and model so router picks a different one on reroute (#1604)
1459        ctx.set(&[
1460            ("agent", serde_json::json!(null)),
1461            ("model", serde_json::json!(null)),
1462        ])
1463        .await;
1464        let push_failures = push_state.push_failures;
1465        if push_failures >= 3 {
1466            tracing::error!(
1467                task_id = ctx.task_id,
1468                push_failures,
1469                "push failed {push_failures} times — blocking for human intervention"
1470            );
1471        } else {
1472            tracing::warn!(
1473                task_id = ctx.task_id,
1474                push_failures,
1475                "agent done but push failed ({push_failures}/3) — rerouting to different agent"
1476            );
1477        }
1478    } else if resp_status == "done" && !has_pr && has_delegations {
1479        tracing::info!(
1480            task_id = ctx.task_id,
1481            "agent reported done with delegations but no PR — setting blocked"
1482        );
1483    } else if (resp_status == "done" || resp_status == "completed")
1484        && !has_pr
1485        && has_pushed
1486        && is_pr_base_invalid
1487    {
1488        tracing::error!(
1489            task_id = ctx.task_id,
1490            "PR creation failed with invalid base branch — blocking for human intervention"
1491        );
1492        ctx.set(&[(
1493            "last_error",
1494            serde_json::json!(
1495                "PR creation failed terminally (invalid base branch or GitHub auth error). The agent's commits were pushed successfully. \
1496                 Check the repository default branch and the GitHub token, then create the PR manually or unblock the task."
1497            ),
1498        )])
1499        .await;
1500    } else if resp_status == "done" && !has_pr && has_pushed {
1501        // Push succeeded but PR creation failed after retries.
1502        tracing::warn!(
1503            task_id = ctx.task_id,
1504            "agent done, commits pushed, but PR creation failed — re-dispatching as routed"
1505        );
1506    } else if is_no_code_reroute {
1507        // Record which agent produced this no-code result so the same-agent
1508        // detection on the next run can prevent loop-backs (#2410, #2686).
1509        // Also clear agent/model to force re-routing.
1510
1511        if final_status == "blocked" {
1512            // final_status is "blocked" either because max_reroutes was exhausted
1513            // or because is_same_agent was detected (both cases are handled by
1514            // classify_final_status). Log accordingly.
1515            let prev_no_code_agent = ctx
1516                .get_task()
1517                .await
1518                .map(|t| t.no_code_last_agent)
1519                .unwrap_or_default();
1520            let is_same_agent = !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name;
1521
1522            let msg = if is_same_agent {
1523                tracing::error!(
1524                    task_id = ctx.task_id,
1525                    agent = %agent_name,
1526                    "blocking same-agent no-code loop: agent {} would be selected again",
1527                    agent_name
1528                );
1529                format!(
1530                    "agent {agent_name} completed without code changes twice — same-agent loop detected, blocking for human review"
1531                )
1532            } else {
1533                tracing::error!(
1534                    task_id = ctx.task_id,
1535                    no_code_reroutes,
1536                    max_reroutes,
1537                    "blocking no-code reroute: reached max reroute attempts ({}/{}) for no-code-result",
1538                    no_code_reroutes,
1539                    max_reroutes
1540                );
1541                format!(
1542                    "agent completed without code changes after {no_code_reroutes}/{max_reroutes} reroute attempts on external task requiring PR"
1543                )
1544            };
1545            ctx.set(&[("last_error", serde_json::json!(msg))]).await;
1546        } else {
1547            // Rerouting — no blocking error to record yet.
1548            ctx.set(&[(
1549                "last_error",
1550                serde_json::json!(
1551                    "agent completed without code changes on external task requiring PR"
1552                ),
1553            )])
1554            .await;
1555        }
1556
1557        // Always record which agent produced this no-code result so the router can
1558        // skip it on the next attempt. Also clear agent/model to force re-routing
1559        // (the router will pick a fresh agent, which will be caught by the same-agent
1560        // check on the next round if it's the same agent).
1561        ctx.set(&[
1562            ("no_code_last_agent", serde_json::json!(agent_name)),
1563            ("agent", serde_json::json!(null)),
1564            ("model", serde_json::json!(null)),
1565        ])
1566        .await;
1567    } else if resp_status == "done" && !has_pr && is_external {
1568        // External task with non-code labels (e.g. documentation, research) —
1569        // allowed to be marked done without a PR.
1570        tracing::info!(
1571            task_id = ctx.task_id,
1572            "external task with non-code labels reported done — marking done without PR"
1573        );
1574    } else if resp_status == "done" && !has_pr {
1575        tracing::info!(
1576            task_id = ctx.task_id,
1577            "internal task reported done with no PR — marking done"
1578        );
1579    }
1580}
1581
1582/// Store token usage if both input and output token counts are known, with the cost the agent
1583/// reported for the run.
1584async fn store_token_usage(
1585    ctx: &StoreCtx<'_>,
1586    input_tokens: Option<u64>,
1587    output_tokens: Option<u64>,
1588    cost_usd: Option<f64>,
1589) {
1590    let (Some(input), Some(output)) = (input_tokens, output_tokens) else {
1591        return;
1592    };
1593    if let Some(st) = ctx.store {
1594        if let Some(store_id) = ctx.store_id_opt {
1595            if let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await {
1596                tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1597            }
1598        } else if let Ok(Some(store_id)) = st.resolve_task_id(ctx.repo, ctx.task_id).await
1599            && let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await
1600        {
1601            tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1602        }
1603    }
1604}
1605
1606/// Handle a successful agent response: commit, push, PR, delegations, tokens.
1607///
1608/// Returns `Ok((status, push_failed))` where `status` is the final task status
1609/// string and `push_failed` is `true` when a push was attempted but failed (for
1610/// audit trail classification).
1611#[expect(
1612    clippy::too_many_arguments,
1613    reason = "the runner passes each part of the run result"
1614)]
1615pub async fn handle_success(
1616    task_id: &str,
1617    parsed: agents::ParsedResponse,
1618    wt: &worktree::WorktreeSetup,
1619    task_title: &str,
1620    agent_name: &str,
1621    model_name: Option<&str>,
1622    new_attempts: u32,
1623    repo: &str,
1624    store: &Option<Arc<TaskStore>>,
1625    raw_stdout: &str,
1626) -> anyhow::Result<(String, bool)> {
1627    // Extract token counts before consuming parsed.
1628    let input_tokens = parsed.input_tokens;
1629    let output_tokens = parsed.output_tokens;
1630    let cost_usd = parsed.cost_usd;
1631    let mut resp = parsed.response;
1632
1633    tracing::info!(
1634        task_id,
1635        status = resp.status,
1636        summary = resp.summary,
1637        "agent completed successfully"
1638    );
1639
1640    let push_denied = resp.status == "blocked" && is_denied_push_block(&resp);
1641
1642    // Resolve numeric store_id once so we can reuse it for multiple store ops
1643    // in this hot path and avoid repeated external_id -> store_id SQL lookups.
1644    let store_id_opt = store::resolve_store_id(store, repo, task_id).await;
1645    let ctx = StoreCtx {
1646        store,
1647        store_id_opt,
1648        repo,
1649        task_id,
1650    };
1651
1652    ctx.reset_retry_streaks().await;
1653
1654    // Auto-commit, push, create PR
1655    let git = if resp.status == "done"
1656        || resp.status == "completed"
1657        || resp.status == "in_progress"
1658        || resp.status == "needs_review"
1659        || push_denied
1660    {
1661        run_git_ops(
1662            &ctx,
1663            wt,
1664            task_title,
1665            &resp,
1666            agent_name,
1667            model_name,
1668            new_attempts,
1669        )
1670        .await
1671    } else {
1672        GitOpsResult::default()
1673    };
1674
1675    // The agent's only blocker was the denied push and orch pushed for it, so
1676    // the task continues as if the agent had returned done
1677    if push_denied && (git.has_pr || git.has_pushed) {
1678        tracing::info!(
1679            task_id,
1680            "agent blocked on denied push, orch pushed the branch"
1681        );
1682        resp.status = "done".to_string();
1683    }
1684
1685    let screenshot_note = if git.has_pr {
1686        post_screenshots(&ctx, &wt.work_dir, &resp).await
1687    } else {
1688        None
1689    };
1690
1691    // Store delegations in store if present (processed by run_with_context)
1692    if !resp.delegations.is_empty() {
1693        ctx.set(&[("delegations", serde_json::json!(resp.delegations))])
1694            .await;
1695    }
1696
1697    // Store result in task store
1698    // If agent said "done" and a PR exists, send to review before merge.
1699    // If agent said "done", pushed commits, but PR creation failed — review gate creates PR.
1700    // If agent said "done", no PR, and no delegations — work is complete
1701    // (e.g., review/analysis jobs that create issues but no code changes).
1702    // If agent said "done", no PR, but has delegations — blocked on children.
1703    let has_delegations = !resp.delegations.is_empty();
1704
1705    // Detect push failure, increment counters.
1706    let push_state = detect_push_failure_state(&ctx, git.has_commits, git.has_pushed).await;
1707
1708    // Determine whether this external task can be marked done without a PR.
1709    // External tasks always require a PR before reaching `done` — unless
1710    // commits were successfully pushed (in which case the `has_pushed` branch
1711    // handles routing). The `is_non_code_task` heuristic was removed because
1712    // it relied on agent output and could be fooled: an agent claiming
1713    // "already implemented" or "config-only" would match non-code keywords
1714    // and close the issue without verification.
1715    let is_external = !task_id.starts_with("internal:");
1716    let requires_pr = is_external && !git.has_pr && !resp.status.starts_with("needs_review");
1717
1718    // Preferred config key `workflow.max_reroute_attempts`; fall back to
1719    // `workflow.max_attempts` for backwards compatibility.
1720    let max_reroutes: u32 = config::get("workflow.max_reroute_attempts")
1721        .ok()
1722        .and_then(|s| s.parse().ok())
1723        .or_else(|| {
1724            config::get("workflow.max_attempts")
1725                .ok()
1726                .and_then(|s| s.parse().ok())
1727        })
1728        .unwrap_or(3);
1729
1730    // Determine whether we are entering the no-code-reroute branch (all
1731    // earlier chain conditions are false + done + requires_pr).
1732    let is_no_code_reroute = !push_state.is_workflow_scope_failure
1733        && !push_state.push_failed
1734        && (resp.status == "done" || resp.status == "completed")
1735        && !has_delegations
1736        && !git.has_pushed
1737        && requires_pr;
1738
1739    // A conflict reroute with nothing ahead of the default branch is a landed
1740    // fix, not a no-code run: close the superseded PR and mark the task done.
1741    let superseded_pr = match (is_no_code_reroute, ctx.get_task().await) {
1742        (true, Some(task)) => {
1743            superseded_conflict_pr(task.merge_conflict_retries, task.pr_number, git.has_commits)
1744        }
1745        _ => None,
1746    };
1747    let is_no_code_reroute = is_no_code_reroute && superseded_pr.is_none();
1748
1749    let no_code_reroutes =
1750        detect_no_code_reroutes(&ctx, is_no_code_reroute, new_attempts, max_reroutes).await;
1751
1752    let blocked_reason = if resp.status == "blocked" {
1753        Some(agent_blocked_reason(&resp))
1754    } else {
1755        None
1756    };
1757    let is_retryable_blocked = blocked_reason
1758        .as_deref()
1759        .is_some_and(is_retryable_blocked_reason);
1760
1761    // ── Detect same-agent loop ───────────────────────────────────────────────
1762    //
1763    // If this is a no-code reroute and the agent is the same as the one that
1764    // produced the previous no-code result, flag it for blocking (#2410, #2686).
1765    let is_same_agent = if is_no_code_reroute {
1766        let prev_no_code_agent = ctx
1767            .get_task()
1768            .await
1769            .map(|t| t.no_code_last_agent)
1770            .unwrap_or_default();
1771        !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name
1772    } else {
1773        false
1774    };
1775
1776    // ── Pure status decision ─────────────────────────────────────────────────
1777
1778    let final_status_owned = classify_final_status(&DecisionInput {
1779        agent_status: &resp.status,
1780        is_workflow_scope_failure: push_state.is_workflow_scope_failure,
1781        is_rebase_conflict_failure: push_state.is_rebase_conflict_failure,
1782        push_failed: push_state.push_failed,
1783        push_failures: push_state.push_failures,
1784        is_transient_push_failure: push_state.is_transient_failure,
1785        has_pr: git.has_pr,
1786        has_delegations,
1787        has_pushed: git.has_pushed,
1788        is_pr_base_invalid: git.pr_base_invalid,
1789        requires_pr,
1790        no_code_reroutes,
1791        max_reroutes,
1792        is_same_agent,
1793        is_completed_status: resp.status == "completed",
1794        is_retryable_blocked,
1795        is_superseded_conflict: superseded_pr.is_some(),
1796    });
1797    let final_status = final_status_owned.as_str();
1798
1799    // ── Post-decision side effects (tracing + store updates) ─────────────────
1800
1801    apply_post_decision_effects(
1802        &ctx,
1803        final_status,
1804        &resp.status,
1805        &push_state,
1806        is_no_code_reroute,
1807        git.has_pr,
1808        git.has_pushed,
1809        git.pr_base_invalid,
1810        has_delegations,
1811        is_external,
1812        no_code_reroutes,
1813        max_reroutes,
1814        agent_name,
1815    )
1816    .await;
1817
1818    // When the agent explicitly returned "blocked", persist its explanation into
1819    // last_error so `orch task get` surfaces the reason without requiring manual
1820    // inspection of task_runs.parsed_response.  The apply_post_decision_effects
1821    // branches above only fire on push/no-code scenarios; a raw agent-blocked
1822    // response falls through all of them and would leave last_error empty.
1823    if resp.status == "blocked" {
1824        let reason = blocked_reason.unwrap_or_else(|| agent_blocked_reason(&resp));
1825        if final_status == "new" {
1826            // Retryable external block: cooldown failed agent/model, clear selection,
1827            // and reroute after backoff instead of permanently blocking.
1828            cooldown::record_agent_failure_with_message(agent_name, &reason).await;
1829            if let Some(m) = model_name {
1830                cooldown::record_model_failure(agent_name, m).await;
1831            }
1832            ctx.set(&[
1833                (
1834                    "last_error",
1835                    serde_json::json!(format!(
1836                        "transient blocker (auto-retry scheduled): {reason}"
1837                    )),
1838                ),
1839                ("agent", serde_json::json!(null)),
1840                ("model", serde_json::json!(null)),
1841            ])
1842            .await;
1843            tracing::warn!(
1844                task_id = ctx.task_id,
1845                reason = %reason,
1846                "agent returned retryable blocked status — rerouting as new with cooldown"
1847            );
1848        } else if final_status == "blocked" {
1849            ctx.set(&[("last_error", serde_json::json!(reason))]).await;
1850        }
1851    }
1852
1853    if let Some(pr_number) = superseded_pr {
1854        tracing::info!(
1855            task_id = ctx.task_id,
1856            pr_number,
1857            "conflict reroute found the fix already on the default branch — closing superseded PR"
1858        );
1859        close_superseded_pr(&ctx, pr_number).await;
1860    }
1861
1862    // The summary reaches the channels, so a missing skill or browser goes with it
1863    let summary = match &screenshot_note {
1864        Some(note) => format!("{}\n\nScreenshots: {note}", resp.summary),
1865        None => resp.summary.clone(),
1866    };
1867    ctx.set(&[("summary", serde_json::json!(summary))]).await;
1868
1869    // Store token usage — prefer agent-parsed tokens, fall back to response
1870    store_token_usage(
1871        &ctx,
1872        input_tokens.or(resp.input_tokens),
1873        output_tokens.or(resp.output_tokens),
1874        cost_usd,
1875    )
1876    .await;
1877
1878    // Store learnings for memory (for future retries)
1879    response::store_learnings_from_response(
1880        task_id,
1881        new_attempts,
1882        agent_name,
1883        model_name,
1884        &resp,
1885        resp.error.as_deref(),
1886        store,
1887        repo,
1888        raw_stdout,
1889    )
1890    .await;
1891
1892    // Note: done → in_review transition is handled by the engine
1893    // after triggering the review agent (engine/mod.rs)
1894    Ok((final_status.to_string(), push_state.push_failed))
1895}
1896
1897/// Labels that indicate a task is non-code and can be marked done without a PR.
1898#[cfg(test)]
1899mod tests;