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