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