Skip to main content

orch/engine/runner/
response_handler.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::config;
8use crate::parser::AgentResponse;
9use crate::store;
10use crate::store::TaskStore;
11use std::io;
12use std::io::ErrorKind;
13use std::path::Path;
14use std::sync::Arc;
15
16use tokio::fs;
17
18use super::{agents, git_ops, response, screenshots, worktree};
19use crate::engine::cooldown;
20use crate::engine::push_retry;
21use crate::engine::review;
22use crate::github::http::GhHttp;
23use crate::status_heuristics;
24use crate::store::Task;
25
26/// Write a structured `result.json` to the attempt directory for debugging.
27#[expect(
28    clippy::too_many_arguments,
29    reason = "each field of result.json is a separate argument"
30)]
31pub async fn write_result_json(
32    attempt_dir: &Path,
33    task_id: &str,
34    agent_name: &str,
35    model_name: Option<&str>,
36    exit_code: i32,
37    new_attempts: u32,
38    parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
39    raw_stdout: &str,
40    raw_stderr: &str,
41) {
42    let result_json = match parse_result {
43        Ok(parsed) => {
44            serde_json::json!({
45                "outcome": "success",
46                "agent": agent_name,
47                "model": model_name.unwrap_or("default"),
48                "exit_code": exit_code,
49                "attempt": new_attempts,
50                "status": parsed.response.status,
51                "summary": parsed.response.summary,
52                "input_tokens": parsed.input_tokens,
53                "output_tokens": parsed.output_tokens,
54                "duration_ms": parsed.duration_ms,
55                "files": parsed.response.files,
56                "accomplished": parsed.response.accomplished,
57                "remaining": parsed.response.remaining,
58                "error": parsed.response.error,
59                "learnings": parsed.response.learnings,
60                "delegations": parsed.response.delegations.iter()
61                    .map(|d| serde_json::json!({"title": d.title, "body": d.body}))
62                    .collect::<Vec<_>>(),
63            })
64        }
65        Err(agent_err) => {
66            serde_json::json!({
67                "outcome": "error",
68                "agent": agent_name,
69                "model": model_name.unwrap_or("default"),
70                "exit_code": exit_code,
71                "attempt": new_attempts,
72                "error_class": agents::error_class_name(agent_err),
73                "error_message": agent_err.to_string(),
74                "stderr_tail": agents::patterns::safe_tail(raw_stderr, 2000),
75                "stdout_tail": agents::patterns::safe_tail(raw_stdout, 2000),
76            })
77        }
78    };
79
80    if let Err(e) = fs::write(
81        attempt_dir.join("result.json"),
82        serde_json::to_string_pretty(&result_json).unwrap_or_default(),
83    )
84    .await
85    {
86        tracing::debug!(task_id, ?e, "failed to write result.json");
87    }
88}
89
90/// Input to the pure status-decision function [`classify_final_status`].
91///
92/// The caller is responsible for pre-computing counter values (via store
93/// increments) and populating them here.  No I/O is performed inside the
94/// decision function itself, making it trivially unit-testable.
95#[derive(Default)]
96#[expect(
97    clippy::struct_excessive_bools,
98    reason = "each flag is an independent input to the status decision"
99)]
100struct DecisionInput<'a> {
101    /// Agent-reported status (e.g. `"done"`, `"in_progress"`).
102    agent_status: &'a str,
103    /// Push was attempted and commits existed, but the push error contained a
104    /// `workflow` scope complaint — non-retryable.
105    is_workflow_scope_failure: bool,
106    /// Push failure recovery attempted a rebase but failed (for example due to
107    /// conflicts). This is non-retryable without human intervention.
108    is_rebase_conflict_failure: bool,
109    /// Push was attempted (commits existed) but failed.
110    push_failed: bool,
111    /// Persistent push-failure counter *after* this run's increment.
112    /// Only meaningful when `push_failed` is `true`.
113    push_failures: u64,
114    /// The push failed on a GitHub or network error. A new agent run cannot change that, so the
115    /// engine retries the push with a backoff instead (#4025).
116    is_transient_push_failure: bool,
117    /// A PR already exists (or was just created) for this task.
118    has_pr: bool,
119    /// The agent created sub-task delegations.
120    has_delegations: bool,
121    /// Commits were pushed to the remote branch successfully.
122    has_pushed: bool,
123    /// PR creation failed because the base branch was invalid (even after
124    /// GitHub API fallback). This is a terminal error — the task should be
125    /// blocked rather than re-dispatched.
126    is_pr_base_invalid: bool,
127    /// The task is external and requires a PR to be marked done.
128    /// Always false for internal tasks.
129    requires_pr: bool,
130    /// Persistent no-code-reroute counter *after* this run's increment.
131    no_code_reroutes: u64,
132    /// Maximum no-code reroutes before blocking (from config).
133    max_reroutes: u32,
134    /// True if the agent that just ran is the same as the one that produced
135    /// the previous no-code result. Same-agent loops should be blocked immediately.
136    is_same_agent: bool,
137    /// True when agent_status is "completed". Used to distinguish internal
138    /// completed tasks (mark done) from "done" tasks where the git ops pipeline
139    /// would have detected no-code reroutes. Pre-computed from agent_status
140    /// by the caller so this function stays pure.
141    is_completed_status: bool,
142    /// Agent explicitly returned blocked, but reason appears transient and retryable.
143    is_retryable_blocked: bool,
144    /// The task was re-dispatched to resolve a merge conflict and came back with
145    /// nothing ahead of the default branch, meaning the fix already landed and
146    /// the open PR is superseded. Mark done instead of counting a no-code run.
147    is_superseded_conflict: bool,
148}
149
150/// Determine the final task status from pre-computed state.
151///
152/// This is a pure function — it performs no I/O.  All store increments must be
153/// done by the caller **before** calling this function (so counters reflect the
154/// current run), and all store side-effects (clearing agent/model, writing
155/// last_error) must be applied **after** based on the returned status.
156fn classify_final_status(input: &DecisionInput<'_>) -> String {
157    if input.is_workflow_scope_failure || input.is_rebase_conflict_failure {
158        "blocked".to_string()
159    } else if input.push_failed {
160        if input.is_transient_push_failure && input.push_failures < push_retry::MAX_PUSH_FAILURES {
161            "needs_review".to_string()
162        } else if input.push_failures >= 3 {
163            "blocked".to_string()
164        } else {
165            "new".to_string()
166        }
167    } else if input.agent_status == "done" && input.has_pr {
168        "needs_review".to_string()
169    } else if input.agent_status == "done" && !input.has_pr && input.has_delegations {
170        "blocked".to_string()
171    } else if input.agent_status == "done"
172        && !input.has_pr
173        && input.has_pushed
174        && input.is_pr_base_invalid
175    {
176        // PR creation failed with an invalid base branch (even after GitHub API
177        // fallback).  This is a terminal configuration error — re-dispatching
178        // would just burn tokens on the same failure.
179        "blocked".to_string()
180    } else if input.agent_status == "done" && !input.has_pr && input.has_pushed {
181        "routed".to_string()
182    } else if input.is_superseded_conflict {
183        "done".to_string()
184    } else if input.agent_status == "done" && input.requires_pr {
185        // Same-agent loop detection: if this agent is the same as the one that
186        // produced the previous no-code result, block immediately (#2410, #2686).
187        // Otherwise, block if max reroutes exhausted, else reroute.
188        if input.is_same_agent || input.no_code_reroutes >= u64::from(input.max_reroutes) {
189            "blocked".to_string()
190        } else {
191            "new".to_string()
192        }
193    } else if input.agent_status == "done" && !input.has_pushed {
194        // Only internal tasks reach here — external done+!has_pr+!has_pushed is
195        // always caught by branch 6 (requires_pr = true for external tasks with
196        // !has_pr and done status), so is_external can never be true here.
197        // Internal tasks may legitimately produce no git-visible changes.
198        "done".to_string()
199    } else if input.is_completed_status && input.has_pr {
200        // Agent said "completed" and a PR was created — send to review.
201        "needs_review".to_string()
202    } else if input.is_completed_status && !input.has_pr && input.has_delegations {
203        // Agent said "completed" with delegations but no PR — blocked on children.
204        "blocked".to_string()
205    } else if input.is_completed_status
206        && !input.has_pr
207        && input.has_pushed
208        && input.is_pr_base_invalid
209    {
210        "blocked".to_string()
211    } else if input.is_completed_status && !input.has_pr && input.has_pushed {
212        // Agent said "completed", commits pushed but no PR — re-dispatch for PR.
213        "routed".to_string()
214    } else if input.is_completed_status && input.requires_pr {
215        // Agent said "completed" on external task requiring PR without a PR or pushes.
216        // Same-agent loop detection applies, then reroute or block.
217        if input.is_same_agent || input.no_code_reroutes >= u64::from(input.max_reroutes) {
218            "blocked".to_string()
219        } else {
220            "new".to_string()
221        }
222    } else if input.is_completed_status {
223        // Agent said "completed" on internal task — mark done.
224        // Git ops already ran and detected no commits, so this is a legitimate
225        // completion without code changes.
226        "done".to_string()
227    } else if input.agent_status == "blocked" && input.is_retryable_blocked {
228        "new".to_string()
229    } else if status_heuristics::status_looks_like_descriptive_completion(input.agent_status) {
230        "done".to_string()
231    } else {
232        input.agent_status.to_string()
233    }
234}
235
236// ── Internal context ──────────────────────────────────────────────────────────
237
238/// Bundles store references so helper functions don't repeat four parameters.
239struct StoreCtx<'a> {
240    store: &'a Option<Arc<TaskStore>>,
241    store_id_opt: Option<i64>,
242    repo: &'a str,
243    task_id: &'a str,
244}
245
246impl StoreCtx<'_> {
247    /// Write fields, using the pre-resolved `store_id` when available.
248    async fn set(&self, fields: &[(&str, serde_json::Value)]) {
249        if let Some(store_id) = self.store_id_opt {
250            let _ = store::store_set_by_id(self.store.as_ref(), store_id, fields).await;
251        } else {
252            store::store_set(self.store, self.repo, self.task_id, fields).await;
253        }
254    }
255
256    /// A successful run ends the streak of network errors and timeouts
257    async fn reset_retry_streaks(&self) {
258        self.set(&[
259            ("network_retries", serde_json::json!(0)),
260            ("timeout_retries", serde_json::json!(0)),
261        ])
262        .await;
263    }
264
265    /// Load the full task record.
266    async fn get_task(&self) -> Option<Task> {
267        if let Some(store_id) = self.store_id_opt {
268            store::opt_store_get_task_by_id(self.store, store_id).await
269        } else {
270            store::opt_store_get_task(self.store, self.repo, self.task_id).await
271        }
272    }
273
274    /// Atomically increment a counter field.
275    async fn increment(&self, field: &str) -> anyhow::Result<u64> {
276        if let Some(store_id) = self.store_id_opt {
277            store::store_increment_by_id(self.store, store_id, field).await
278        } else {
279            store::store_increment(self.store, self.repo, self.task_id, field).await
280        }
281    }
282
283    /// Append an activity event to the task timeline.
284    async fn append_activity(
285        &self,
286        event_type: &str,
287        agent: Option<&str>,
288        model: Option<&str>,
289        details: Option<&serde_json::Value>,
290    ) {
291        if let Some(store_id) = self.store_id_opt {
292            if let Some(s) = self.store
293                && let Err(e) = s
294                    .append_activity(store_id, event_type, None, None, agent, model, details)
295                    .await
296            {
297                tracing::warn!(
298                    task_id = self.task_id,
299                    event_type,
300                    error = %e,
301                    "store append_activity failed"
302                );
303            }
304        } else {
305            store::store_log_activity(
306                self.store,
307                self.repo,
308                self.task_id,
309                event_type,
310                None,
311                None,
312                agent,
313                model,
314                details,
315            )
316            .await;
317        }
318    }
319}
320
321// ── Git operation result types ────────────────────────────────────────────────
322
323/// Outcome of the auto-commit → push → PR pipeline.
324#[derive(Default)]
325#[expect(
326    clippy::struct_excessive_bools,
327    reason = "each flag is an independent outcome of the git pipeline"
328)]
329struct GitOpsResult {
330    has_pr: bool,
331    has_pushed: bool,
332    has_commits: bool,
333    /// PR creation failed with an invalid base branch (after all retries
334    /// and the GitHub API fallback).  Used to block the task instead of
335    /// re-dispatching it indefinitely.
336    pr_base_invalid: bool,
337}
338
339/// Push-failure detection result.
340#[expect(
341    clippy::struct_excessive_bools,
342    reason = "each flag is an independent kind of push failure"
343)]
344struct PushFailureState {
345    push_failed: bool,
346    is_workflow_scope_failure: bool,
347    is_rebase_conflict_failure: bool,
348    /// GitHub or network error that the engine retries with a backoff, without an agent run.
349    is_transient_failure: bool,
350    /// Post-increment failure counter (0 when no push was attempted or failed).
351    push_failures: u64,
352    /// Last error stored in the task record (used for workflow-scope detection).
353    stored_last_error: String,
354}
355
356// ── Private git-ops helpers ───────────────────────────────────────────────────
357
358/// Attempt auto-commit; record any error in the store.
359async fn auto_commit_changes(
360    ctx: &StoreCtx<'_>,
361    work_dir: &Path,
362    task_title: &str,
363    agent_name: &str,
364    new_attempts: u32,
365) {
366    if let Err(e) = git_ops::auto_commit(
367        work_dir,
368        ctx.task_id,
369        task_title,
370        agent_name,
371        new_attempts,
372        super::commit::When::Always,
373    )
374    .await
375    {
376        tracing::error!(task_id = ctx.task_id, error = ?e, "auto commit failed");
377        ctx.set(&[(
378            "last_error",
379            serde_json::json!(format!("auto commit failed: {e}")),
380        )])
381        .await;
382    }
383}
384
385/// Check whether commits exist ahead of the default branch.
386///
387/// When there are no commits, clears any stale push-failure error so that the
388/// review gate does not block an otherwise-approved task.
389async fn check_commits_and_clear_stale_errors(
390    ctx: &StoreCtx<'_>,
391    work_dir: &Path,
392    default_branch: &str,
393) -> bool {
394    let has_commits = git_ops::has_commits_ahead(work_dir, default_branch).await;
395    if !has_commits {
396        tracing::info!(
397            task_id = ctx.task_id,
398            "no commits ahead of default branch, skipping push + PR"
399        );
400        // Clear stale push failure from previous runs.
401        let last_err = ctx
402            .get_task()
403            .await
404            .map(|t| t.last_error)
405            .unwrap_or_default();
406        if last_err.contains("push failed") {
407            ctx.set(&[("last_error", serde_json::json!(""))]).await;
408        }
409    }
410    has_commits
411}
412
413/// Push the branch to the remote and log the activity.
414///
415/// On push failure due to diverged history (non-fast-forward), fetches the remote
416/// branch and rebases local commits on top, then pushes again. If rebase fails
417/// (conflicts), the task is blocked for human intervention.
418///
419/// Returns `PushResult::Success` on success, `PushResult::Failed` if push failed
420/// and recovery was not possible, or `PushResult::NoCommits` if the branch has no
421/// commits ahead of the default branch
422enum PushResult {
423    Success,
424    Failed,
425    NoCommits,       // agent made no code changes
426    WorktreeMissing, // retry after rebuilding missing worktree
427}
428
429fn is_missing_path_error(err: &anyhow::Error) -> bool {
430    err.chain().any(|cause| {
431        cause
432            .downcast_ref::<io::Error>()
433            .is_some_and(|ioe| ioe.kind() == ErrorKind::NotFound)
434    }) || err
435        .to_string()
436        .to_ascii_lowercase()
437        .contains("no such file or directory")
438}
439
440async fn recover_missing_worktree_for_push(
441    ctx: &StoreCtx<'_>,
442    wt: &worktree::WorktreeSetup,
443    task_title: &str,
444    agent_name: &str,
445    model_name: Option<&str>,
446) -> anyhow::Result<worktree::WorktreeSetup> {
447    tracing::warn!(
448        task_id = ctx.task_id,
449        worktree = %wt.work_dir.display(),
450        branch = wt.branch,
451        "worktree missing during push; attempting one-time recovery"
452    );
453    ctx.append_activity(
454        "push_recover_worktree",
455        Some(agent_name),
456        model_name,
457        Some(&serde_json::json!({
458            "status": "start",
459            "worktree": wt.work_dir.display().to_string(),
460            "branch": wt.branch,
461        })),
462    )
463    .await;
464
465    let recovered = worktree::setup_worktree(
466        ctx.task_id,
467        task_title,
468        &wt.main_project_dir,
469        ctx.store,
470        ctx.repo,
471    )
472    .await?;
473
474    if !recovered.work_dir.exists() {
475        anyhow::bail!(
476            "recovered worktree path is still missing: {}",
477            recovered.work_dir.display()
478        );
479    }
480
481    ctx.append_activity(
482        "push_recover_worktree",
483        Some(agent_name),
484        model_name,
485        Some(&serde_json::json!({
486            "status": "ok",
487            "worktree": recovered.work_dir.display().to_string(),
488            "branch": recovered.branch,
489        })),
490    )
491    .await;
492
493    Ok(recovered)
494}
495
496/// Push a branch that was just rebased onto its moved remote counterpart.
497///
498/// Separate from the first push attempt so a failure here is reported as orch's own
499/// push failure rather than re-entering the diverged-branch recovery
500async fn push_after_rebase(
501    ctx: &StoreCtx<'_>,
502    work_dir: &Path,
503    branch: &str,
504    default_branch: &str,
505    agent_name: &str,
506    model_name: Option<&str>,
507) -> PushResult {
508    match git_ops::push_branch(work_dir, branch, default_branch).await {
509        Ok(_) => {
510            ctx.append_activity(
511                "push",
512                Some(agent_name),
513                model_name,
514                Some(&serde_json::json!({
515                    "status": "ok",
516                    "branch": branch,
517                    "default_branch": default_branch,
518                    "reason": "pushed_after_rebase",
519                })),
520            )
521            .await;
522            ctx.set(&[
523                ("last_error", serde_json::json!("")),
524                ("push_failures", serde_json::json!(0)),
525            ])
526            .await;
527            PushResult::Success
528        }
529        Err(e) => {
530            tracing::error!(
531                task_id = ctx.task_id,
532                branch = branch,
533                error = ?e,
534                "push failed again after rebasing on the remote branch"
535            );
536            ctx.append_activity(
537                "push",
538                Some(agent_name),
539                model_name,
540                Some(&serde_json::json!({
541                    "status": "error",
542                    "branch": branch,
543                    "default_branch": default_branch,
544                    "reason": "pushed_after_rebase",
545                    "error": e.to_string(),
546                })),
547            )
548            .await;
549            ctx.set(&[(
550                "last_error",
551                serde_json::json!(format!("push failed after rebase on remote branch: {e}")),
552            )])
553            .await;
554            PushResult::Failed
555        }
556    }
557}
558
559async fn push_branch_with_log(
560    ctx: &StoreCtx<'_>,
561    work_dir: &Path,
562    branch: &str,
563    default_branch: &str,
564    agent_name: &str,
565    model_name: Option<&str>,
566) -> PushResult {
567    match git_ops::push_branch(work_dir, branch, default_branch).await {
568        Ok(_) => {
569            ctx.append_activity(
570                "push",
571                Some(agent_name),
572                model_name,
573                Some(&serde_json::json!({
574                    "status": "ok",
575                    "branch": branch,
576                    "default_branch": default_branch,
577                })),
578            )
579            .await;
580            // Clear any stale push failure from a previous run so review_and_merge
581            // does not incorrectly block an approved task.
582            ctx.set(&[
583                ("last_error", serde_json::json!("")),
584                ("push_failures", serde_json::json!(0)),
585            ])
586            .await;
587            PushResult::Success
588        }
589        Err(e) => {
590            let err_str = e.to_string();
591            tracing::error!(task_id = ctx.task_id, error = ?e, "push failed");
592
593            if is_missing_path_error(&e) && !work_dir.exists() {
594                tracing::warn!(
595                    task_id = ctx.task_id,
596                    worktree = %work_dir.display(),
597                    "push failed because worktree path disappeared; will attempt recovery"
598                );
599                ctx.append_activity(
600                    "push",
601                    Some(agent_name),
602                    model_name,
603                    Some(&serde_json::json!({
604                        "status": "retry",
605                        "branch": branch,
606                        "default_branch": default_branch,
607                        "reason": "worktree_missing",
608                        "error": err_str,
609                    })),
610                )
611                .await;
612                return PushResult::WorktreeMissing;
613            }
614
615            // Check if this is a non-fast-forward error that we can recover from.
616            if push_error_is_diverged(&err_str) {
617                tracing::info!(
618                    task_id = ctx.task_id,
619                    branch = branch,
620                    "attempting fetch and rebase to recover from diverged branch"
621                );
622
623                // Attempt to fetch and rebase on origin/{branch}.
624                match git_ops::rebase_on_branch(work_dir, branch).await {
625                    Ok(true) => {
626                        // Pushing is orch's step, not the agent's: the commits are already
627                        // written, so push them onto the moved remote branch here. Re-routing
628                        // instead re-ran a finished task until it hit the attempt limit (#3783)
629                        tracing::info!(
630                            task_id = ctx.task_id,
631                            branch = branch,
632                            "rebase succeeded — retrying the push"
633                        );
634                        ctx.append_activity(
635                            "push_rebased",
636                            Some(agent_name),
637                            model_name,
638                            Some(&serde_json::json!({
639                                "status": "rebased",
640                                "branch": branch,
641                                "reason": "diverged_from_remote",
642                            })),
643                        )
644                        .await;
645                        return push_after_rebase(
646                            ctx,
647                            work_dir,
648                            branch,
649                            default_branch,
650                            agent_name,
651                            model_name,
652                        )
653                        .await;
654                    }
655                    Ok(false) => {
656                        // The remote branch already holds every local commit, nothing to push
657                        tracing::info!(
658                            task_id = ctx.task_id,
659                            branch = branch,
660                            "no local commits after fetch — marking as success"
661                        );
662                        ctx.append_activity(
663                            "push",
664                            Some(agent_name),
665                            model_name,
666                            Some(&serde_json::json!({
667                                "status": "ok",
668                                "branch": branch,
669                                "reason": "no_commits_after_fetch",
670                            })),
671                        )
672                        .await;
673                        ctx.set(&[
674                            ("last_error", serde_json::json!("")),
675                            ("push_failures", serde_json::json!(0)),
676                        ])
677                        .await;
678                        return PushResult::Success;
679                    }
680                    Err(rebase_err) if git_ops::is_missing_remote_ref_error(&rebase_err) => {
681                        // The branch never reached the remote, so there is nothing to rebase onto.
682                        // Take the counted retry path instead of the rebase conflict block
683                        tracing::warn!(
684                            task_id = ctx.task_id,
685                            branch = branch,
686                            "remote branch does not exist, skipping rebase recovery"
687                        );
688                        ctx.append_activity(
689                            "push",
690                            Some(agent_name),
691                            model_name,
692                            Some(&serde_json::json!({
693                                "status": "error",
694                                "branch": branch,
695                                "default_branch": default_branch,
696                                "error": err_str,
697                            })),
698                        )
699                        .await;
700                        ctx.set(&[("last_error", serde_json::json!(format!("push failed: {e}")))])
701                            .await;
702                        return PushResult::Failed;
703                    }
704                    Err(rebase_err) => {
705                        // Rebase failed (likely conflicts) — block for human intervention.
706                        tracing::error!(
707                            task_id = ctx.task_id,
708                            branch = branch,
709                            error = ?rebase_err,
710                            "rebase failed — blocking task for human intervention"
711                        );
712                        ctx.append_activity(
713                            "push_rebased",
714                            Some(agent_name),
715                            model_name,
716                            Some(&serde_json::json!({
717                                "status": "error",
718                                "branch": branch,
719                                "error": rebase_err.to_string(),
720                            })),
721                        )
722                        .await;
723                        ctx.set(&[(
724                            "last_error",
725                            serde_json::json!(format!(
726                                "push failed and rebase failed: {rebase_err} — manual resolution required"
727                            )),
728                        )])
729                        .await;
730                        return PushResult::Failed;
731                    }
732                }
733            }
734
735            // Non-recoverable push error — log and return failure.
736            ctx.append_activity(
737                "push",
738                Some(agent_name),
739                model_name,
740                Some(&serde_json::json!({
741                    "status": "error",
742                    "branch": branch,
743                    "default_branch": default_branch,
744                    "error": err_str,
745                })),
746            )
747            .await;
748            ctx.set(&[("last_error", serde_json::json!(format!("push failed: {e}")))])
749                .await;
750            PushResult::Failed
751        }
752    }
753}
754
755/// True when a push error means the remote branch moved. `[remote rejected]` is a server side
756/// failure, only `! [rejected]` marks a divergence
757fn push_error_is_diverged(err_str: &str) -> bool {
758    err_str.contains("non-fast-forward")
759        || err_str.contains("! [rejected]")
760        || err_str.contains("fetch first")
761        || err_str.contains("behind")
762}
763
764/// True when the GitHub client refused the call locally because its rate-limit window is active.
765fn is_local_rate_limit_skip(err_str: &str) -> bool {
766    err_str.contains("rate-limited, skipping call")
767}
768
769/// Create (or find an existing) PR and log the activity.
770///
771/// Returns `(has_pr, has_pushed, pr_base_invalid)`. `has_pushed` may be set to
772/// `false` when a 422 "no commits" GitHub error indicates the branch was
773/// already merged. `pr_base_invalid` is set when the base branch is rejected
774/// by GitHub (even after the API fallback), which is a terminal condition.
775async fn create_pr_with_log(
776    ctx: &StoreCtx<'_>,
777    wt: &worktree::WorktreeSetup,
778    task_title: &str,
779    resp: &AgentResponse,
780    agent_name: &str,
781    model_name: Option<&str>,
782    mut has_pushed: bool,
783) -> (bool, bool, bool) {
784    match git_ops::create_pr_if_needed(
785        &wt.work_dir,
786        &wt.branch,
787        task_title,
788        &resp.summary,
789        &resp.accomplished,
790        &resp.remaining,
791        &resp.files,
792        ctx.task_id,
793        agent_name,
794        model_name,
795        ctx.repo,
796        &wt.default_branch,
797    )
798    .await
799    {
800        Ok(ref url) => {
801            // Save pr_number to the store so the review gate can find it
802            // immediately without racing GitHub's list-API cache (~300 ms lag).
803            // This is set for both newly-created and pre-existing PRs.
804            match review::parse_pr_number_from_url(url) {
805                Ok(pr_num) => {
806                    if let Err(e) = store::store_set_result(
807                        ctx.store,
808                        ctx.repo,
809                        ctx.task_id,
810                        &[("pr_number", serde_json::json!(pr_num))],
811                    )
812                    .await
813                    {
814                        tracing::error!(
815                            task_id = ctx.task_id,
816                            pr_url = %url,
817                            err = %e,
818                            "CRITICAL: failed to save pr_number to store — downstream review gate may trigger duplicate gh pr create"
819                        );
820                    }
821                }
822                Err(e) => {
823                    tracing::warn!(
824                        task_id = ctx.task_id,
825                        pr_url = %url,
826                        error = %e,
827                        "PR created but failed to parse PR number from URL"
828                    );
829                }
830            }
831            ctx.append_activity(
832                "pr_create",
833                Some(agent_name),
834                model_name,
835                Some(&serde_json::json!({"status": "created", "url": url})),
836            )
837            .await;
838            (true, has_pushed, false)
839        }
840        Err(e) => {
841            let err_str = format!("{e}");
842            tracing::error!(task_id = ctx.task_id, error = ?e, "create PR failed");
843            ctx.append_activity(
844                "pr_create",
845                Some(agent_name),
846                model_name,
847                Some(&serde_json::json!({
848                    "status": "error",
849                    "branch": wt.branch,
850                    "error": err_str.clone(),
851                })),
852            )
853            .await;
854            ctx.set(&[(
855                "last_error",
856                serde_json::json!(format!("create PR failed: {e}")),
857            )])
858            .await;
859            // Distinguish between terminal 422 errors and recoverable ones.
860            // - "No commits between" / "head invalid" → agent made no code changes
861            //   or the branch was already merged.  Clearing has_pushed lets the
862            //   task fall through to the "done" path.
863            // - "base invalid" → the base branch name is wrong.  After the
864            //   GitHub API fallback in create_pr_if_needed also fails, this is a
865            //   terminal configuration error.  We set pr_base_invalid so the
866            //   classifier blocks the task instead of re-dispatching forever.
867            // A GitHub auth error is terminal too: the commits are pushed, so only a token fix helps
868            let mut pr_base_invalid = false;
869            if is_local_rate_limit_skip(&err_str) {
870                // No request was sent and the branch is pushed. Re-running the agent cannot help,
871                // so report the PR as pending and let the review gate create it once calls resume
872                tracing::warn!(
873                    task_id = ctx.task_id,
874                    "PR creation skipped by local GitHub rate limit — review gate will create the PR"
875                );
876                return (true, has_pushed, false);
877            }
878            if agents::patterns::detect_auth_error(&err_str).is_some() {
879                tracing::error!(
880                    task_id = ctx.task_id,
881                    "PR creation failed with GitHub auth error — blocking task"
882                );
883                pr_base_invalid = true;
884            } else if err_str.contains("422") {
885                if err_str.contains("No commits between") || err_str.contains("head") {
886                    tracing::info!(
887                        task_id = ctx.task_id,
888                        "PR creation returned 422/no-commits/head-invalid — agent made no code changes or branch merged, marking done"
889                    );
890                    has_pushed = false;
891                } else if git_ops::is_invalid_base_error(&err_str) {
892                    tracing::error!(
893                        task_id = ctx.task_id,
894                        "PR creation failed with invalid base branch — blocking task"
895                    );
896                    pr_base_invalid = true;
897                }
898            }
899            (false, has_pushed, pr_base_invalid)
900        }
901    }
902}
903
904/// Run the full auto-commit → push → PR pipeline.
905async fn run_git_ops(
906    ctx: &StoreCtx<'_>,
907    wt: &worktree::WorktreeSetup,
908    task_title: &str,
909    resp: &AgentResponse,
910    agent_name: &str,
911    model_name: Option<&str>,
912    new_attempts: u32,
913) -> GitOpsResult {
914    auto_commit_changes(ctx, &wt.work_dir, task_title, agent_name, new_attempts).await;
915
916    let mut has_commits =
917        check_commits_and_clear_stale_errors(ctx, &wt.work_dir, &wt.default_branch).await;
918
919    // Skip push + PR if there are no commits ahead of the default branch.
920    // No-op tasks (e.g. "nothing to execute") produce no commits, so pushing
921    // and creating a PR would just waste API calls and trigger 422 errors.
922    let push_result = if has_commits {
923        push_branch_with_log(
924            ctx,
925            &wt.work_dir,
926            &wt.branch,
927            &wt.default_branch,
928            agent_name,
929            model_name,
930        )
931        .await
932    } else {
933        store::store_log_activity(
934            ctx.store,
935            ctx.repo,
936            ctx.task_id,
937            "push",
938            None,
939            None,
940            Some(agent_name),
941            model_name,
942            Some(&serde_json::json!({
943                "status": "skipped",
944                "reason": "no_commits_ahead",
945                "branch": wt.branch,
946                "default_branch": wt.default_branch,
947            })),
948        )
949        .await;
950        PushResult::NoCommits
951    };
952    let push_result = if matches!(push_result, PushResult::WorktreeMissing) {
953        match recover_missing_worktree_for_push(ctx, wt, task_title, agent_name, model_name).await {
954            Ok(recovered) => {
955                let wt_for_ops = &recovered;
956                has_commits = check_commits_and_clear_stale_errors(
957                    ctx,
958                    &wt_for_ops.work_dir,
959                    &wt_for_ops.default_branch,
960                )
961                .await;
962                if has_commits {
963                    push_branch_with_log(
964                        ctx,
965                        &wt_for_ops.work_dir,
966                        &wt_for_ops.branch,
967                        &wt_for_ops.default_branch,
968                        agent_name,
969                        model_name,
970                    )
971                    .await
972                } else {
973                    PushResult::NoCommits
974                }
975            }
976            Err(e) => {
977                tracing::error!(
978                    task_id = ctx.task_id,
979                    err = %e,
980                    "worktree recovery before push failed"
981                );
982                ctx.append_activity(
983                    "push_recover_worktree",
984                    Some(agent_name),
985                    model_name,
986                    Some(&serde_json::json!({
987                        "status": "error",
988                        "worktree": wt.work_dir.display().to_string(),
989                        "branch": wt.branch,
990                        "error": e.to_string(),
991                    })),
992                )
993                .await;
994                ctx.set(&[(
995                    "last_error",
996                    serde_json::json!(format!(
997                        "push failed: worktree disappeared and recovery failed: {e}"
998                    )),
999                )])
1000                .await;
1001                PushResult::Failed
1002            }
1003        }
1004    } else {
1005        push_result
1006    };
1007
1008    let mut has_pushed = matches!(push_result, PushResult::Success);
1009    let mut has_pr = false;
1010
1011    // Create PR (skip if push failed or repo is unknown)
1012    if has_commits && matches!(push_result, PushResult::Failed) {
1013        tracing::warn!(
1014            task_id = ctx.task_id,
1015            "skipping PR creation due to push failure"
1016        );
1017    } else if matches!(push_result, PushResult::NoCommits) {
1018        tracing::info!(
1019            task_id = ctx.task_id,
1020            "no commits ahead of default branch, skipping push + PR"
1021        );
1022    } else if !has_pushed {
1023        // no commits — already logged "no commits ahead, skipping push + PR" at INFO level above
1024    } else if ctx.repo.is_empty() {
1025        tracing::warn!(
1026            task_id = ctx.task_id,
1027            "skipping PR creation — repo is empty (internal task?)"
1028        );
1029    } else {
1030        let (pr, updated_pushed, pr_base_invalid) = create_pr_with_log(
1031            ctx, wt, task_title, resp, agent_name, model_name, has_pushed,
1032        )
1033        .await;
1034        has_pr = pr;
1035        has_pushed = updated_pushed;
1036        return GitOpsResult {
1037            has_pr,
1038            has_pushed,
1039            has_commits,
1040            pr_base_invalid,
1041        };
1042    }
1043
1044    GitOpsResult {
1045        has_pr,
1046        has_pushed,
1047        has_commits,
1048        pr_base_invalid: false,
1049    }
1050}
1051
1052// ── Private status-computation helpers ───────────────────────────────────────
1053
1054/// Comment the agent's screenshots on the PR. Returns the note for the task summary and channels
1055async fn post_screenshots(
1056    ctx: &StoreCtx<'_>,
1057    work_dir: &Path,
1058    resp: &AgentResponse,
1059) -> Option<String> {
1060    let note = resp.screenshot_note.as_deref().map(str::trim);
1061    let note = note.filter(|n| !n.is_empty());
1062    if resp.screenshots.is_empty() && note.is_none() {
1063        return None;
1064    }
1065    let pr_number = ctx.get_task().await.and_then(|t| t.pr_number);
1066    let (Some(pr_number), false) = (pr_number, ctx.repo.is_empty()) else {
1067        return note.map(String::from);
1068    };
1069    let Ok(pr) = u64::try_from(pr_number) else {
1070        return note.map(String::from);
1071    };
1072
1073    let roots = screenshots::allowed_roots(work_dir).await;
1074    let (images, skipped) = screenshots::prepare(&resp.screenshots, work_dir, &roots, pr);
1075    let commit = if images.is_empty() {
1076        String::new()
1077    } else {
1078        match screenshots::publish(work_dir, &images, pr).await {
1079            Ok(commit) => commit,
1080            Err(e) => {
1081                tracing::warn!(task_id = ctx.task_id, err = %e, "failed to push screenshots");
1082                let body = screenshots::build_unpublished_comment(note, &skipped);
1083                comment_screenshots(ctx, pr, &body).await;
1084                return note.map(String::from);
1085            }
1086        }
1087    };
1088    let body = screenshots::build_comment(ctx.repo, &commit, &images, note, &skipped);
1089    comment_screenshots(ctx, pr, &body).await;
1090    note.map(String::from)
1091}
1092
1093async fn comment_screenshots(ctx: &StoreCtx<'_>, pr: u64, body: &str) {
1094    match GhHttp::new() {
1095        Ok(gh) => {
1096            if let Err(e) = gh.add_comment(ctx.repo, &pr.to_string(), body).await {
1097                tracing::warn!(task_id = ctx.task_id, pr, err = %e, "failed to comment screenshots");
1098            }
1099        }
1100        Err(e) => tracing::warn!(task_id = ctx.task_id, err = %e, "cannot comment screenshots"),
1101    }
1102}
1103
1104/// Comment on and close a PR whose change already landed elsewhere.
1105async fn close_superseded_pr(ctx: &StoreCtx<'_>, pr_number: u64) {
1106    if ctx.repo.is_empty() {
1107        return;
1108    }
1109    match GhHttp::new() {
1110        Ok(gh) => {
1111            let note = "Closing as superseded: the change is already on the default branch, so this branch has no commits ahead of it.";
1112            if let Err(e) = gh.add_comment(ctx.repo, &pr_number.to_string(), note).await {
1113                tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to comment on superseded PR");
1114            }
1115            if let Err(e) = gh.close_pr(ctx.repo, pr_number).await {
1116                tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to close superseded PR");
1117            }
1118        }
1119        Err(e) => {
1120            tracing::warn!(task_id = ctx.task_id, err = %e, "cannot close superseded PR");
1121        }
1122    }
1123    // Dropping the PR lets the blocker refresh read the closed, completed issue with no PR
1124    ctx.set(&[
1125        (
1126            "last_error",
1127            serde_json::json!(
1128                "PR closed as superseded: the fix already landed on the default branch"
1129            ),
1130        ),
1131        ("pr_number", serde_json::json!(null)),
1132    ])
1133    .await;
1134}
1135
1136/// The PR to close when a merge-conflict reroute produced no commits.
1137///
1138/// `merge_conflict_retries > 0` means review_poll sent the task back to resolve a
1139/// conflict. Coming back with nothing ahead of the default branch means another
1140/// PR already landed the same fix, so the open PR is superseded (#3780)
1141fn superseded_conflict_pr(
1142    merge_conflict_retries: i32,
1143    pr_number: Option<i32>,
1144    has_commits: bool,
1145) -> Option<u64> {
1146    if has_commits || merge_conflict_retries <= 0 {
1147        return None;
1148    }
1149    pr_number
1150        .filter(|n| *n > 0)
1151        .and_then(|n| u64::try_from(n).ok())
1152}
1153
1154/// Read push-failure state from the store and increment `push_failures` if needed.
1155async fn detect_push_failure_state(
1156    ctx: &StoreCtx<'_>,
1157    has_commits: bool,
1158    has_pushed: bool,
1159) -> PushFailureState {
1160    // Load stored task once to inspect last_error (avoid repeated DB reads).
1161    let stored_last_error = ctx
1162        .get_task()
1163        .await
1164        .map(|t| t.last_error)
1165        .unwrap_or_default();
1166
1167    let push_failed = !has_pushed && has_commits && stored_last_error.contains("push failed");
1168
1169    // Detect workflow scope errors — these are non-retryable token permission issues.
1170    // Rerouting to a different agent won't help since the same token is used.
1171    let is_workflow_scope_failure = push_failed
1172        && (stored_last_error.contains("workflow` scope")
1173            || stored_last_error.contains("workflow' scope")
1174            || (stored_last_error.contains("refusing to allow")
1175                && stored_last_error.contains("workflow")));
1176
1177    let is_rebase_conflict_failure =
1178        push_failed && stored_last_error.contains("push failed and rebase failed:");
1179
1180    let is_transient_failure = push_failed
1181        && !is_workflow_scope_failure
1182        && !is_rebase_conflict_failure
1183        && git_ops::is_transient_network_error(&stored_last_error);
1184
1185    // Track push failures — block after 3 consecutive failures.
1186    // Workflow-scope failures are non-retryable and blocked immediately; do not
1187    // increment this retry counter for them so that later normal push failures
1188    // are not prematurely blocked.
1189    let push_failures = if push_failed && !is_workflow_scope_failure && !is_rebase_conflict_failure
1190    {
1191        match ctx.increment("push_failures").await {
1192            Ok(v) => v,
1193            Err(e) => {
1194                tracing::warn!(
1195                    task_id = ctx.task_id,
1196                    err = %e,
1197                    "failed to increment push_failures — reading current value from store"
1198                );
1199                // On DB error, read current value to ensure blocking threshold is still reachable
1200                ctx.get_task()
1201                    .await
1202                    .map_or(1, |t| u64::try_from(t.push_failures).unwrap_or(0) + 1)
1203                // assume at least 1 if we can't read either
1204            }
1205        }
1206    } else {
1207        0
1208    };
1209
1210    PushFailureState {
1211        push_failed,
1212        is_workflow_scope_failure,
1213        is_rebase_conflict_failure,
1214        is_transient_failure,
1215        push_failures,
1216        stored_last_error,
1217    }
1218}
1219
1220/// Increment `no_code_reroutes` and log a warning when the agent completed
1221/// without producing code changes on an external task requiring a PR.
1222async fn detect_no_code_reroutes(
1223    ctx: &StoreCtx<'_>,
1224    is_no_code_reroute: bool,
1225    new_attempts: u32,
1226    max_reroutes: u32,
1227) -> u64 {
1228    if !is_no_code_reroute {
1229        return 0;
1230    }
1231    tracing::warn!(
1232        task_id = ctx.task_id,
1233        attempts = new_attempts,
1234        max_reroutes,
1235        "agent reported done but produced no code changes on external task requiring PR"
1236    );
1237    match ctx.increment("no_code_reroutes").await {
1238        Ok(v) => v,
1239        Err(e) => {
1240            tracing::warn!(
1241                task_id = ctx.task_id,
1242                err = %e,
1243                "failed to increment no_code_reroutes — reading current value from store"
1244            );
1245            // On DB error, read current value to ensure blocking threshold is still reachable
1246            ctx.get_task()
1247                .await
1248                .map_or(1, |t| u64::try_from(t.no_code_reroutes).unwrap_or(0) + 1)
1249            // assume at least 1 if we can't read either
1250        }
1251    }
1252}
1253
1254// ── Post-decision side-effect helpers ─────────────────────────────────────────
1255
1256/// Build a human-readable reason string from a "blocked" agent response.
1257///
1258/// Priority: explicit `error` field → `summary` → fallback.
1259/// Appends `remaining` items if present so operators know what was left to do.
1260fn agent_blocked_reason(resp: &AgentResponse) -> String {
1261    let summary_opt = if resp.summary.is_empty() {
1262        None
1263    } else {
1264        Some(resp.summary.as_str())
1265    };
1266    let base = resp
1267        .error
1268        .as_deref()
1269        .filter(|s| !s.is_empty())
1270        .or(summary_opt)
1271        .unwrap_or("agent returned blocked status without a reason");
1272    if resp.remaining.is_empty() {
1273        base.to_string()
1274    } else {
1275        format!("{base}. Remaining: {}", resp.remaining.join("; "))
1276    }
1277}
1278
1279/// True when a blocked response names a denied `git push` and nothing else as the blocker.
1280fn is_denied_push_block(resp: &AgentResponse) -> bool {
1281    let r = agent_blocked_reason(resp).to_lowercase();
1282    r.contains("push")
1283        && [
1284            "denied",
1285            "not allowed",
1286            "permission",
1287            "disallowed",
1288            "approval",
1289        ]
1290        .iter()
1291        .any(|p| r.contains(p))
1292}
1293
1294/// Heuristic classifier for agent-returned blocked reasons.
1295///
1296/// Returns true when the reason looks transient/retryable (network/provider/
1297/// auth-temporary/environment availability issues), and false for likely
1298/// permanent/input/configuration issues.
1299fn is_retryable_blocked_reason(reason: &str) -> bool {
1300    let r = reason.to_lowercase();
1301
1302    let permanent_patterns = [
1303        "not found",
1304        "does not exist",
1305        "invalid",
1306        "malformed",
1307        "syntax error",
1308        "unsupported",
1309        "unimplemented",
1310        "manual intervention required",
1311        "human intervention required",
1312    ];
1313    if permanent_patterns.iter().any(|p| r.contains(p)) {
1314        return false;
1315    }
1316
1317    let transient_patterns = [
1318        "unavailable",
1319        "temporarily unavailable",
1320        "timeout",
1321        "timed out",
1322        "connection reset",
1323        "connection refused",
1324        "network error",
1325        "rate limit",
1326        "try again",
1327        "service down",
1328        "permission denied",
1329        "worktree lock",
1330        "git lock",
1331        "lockfile permission",
1332        "lock permission",
1333        "resource busy",
1334        "could not resolve host",
1335        // Credential providers in headless/tmux sessions can fail transiently
1336        // when GPG agent/passphrase is unavailable.
1337        "gpg decryption fails",
1338        "gpg decryption failed",
1339        "gpg agent",
1340        "no passphrase available",
1341        "passphrase unavailable",
1342        "pass store",
1343        "passwordstoreprovider",
1344        "agentvaultprovider",
1345        "onepasswordprovider",
1346        "decryption failed in this agent session",
1347    ];
1348    transient_patterns.iter().any(|p| r.contains(p))
1349}
1350
1351/// Apply tracing and store writes that depend on the final status decision.
1352#[expect(
1353    clippy::too_many_arguments,
1354    reason = "the decision and its context arrive as separate values"
1355)]
1356async fn apply_post_decision_effects(
1357    ctx: &StoreCtx<'_>,
1358    final_status: &str,
1359    resp_status: &str,
1360    push_state: &PushFailureState,
1361    is_no_code_reroute: bool,
1362    has_pr: bool,
1363    has_pushed: bool,
1364    is_pr_base_invalid: bool,
1365    has_delegations: bool,
1366    is_external: bool,
1367    no_code_reroutes: u64,
1368    max_reroutes: u32,
1369    agent_name: &str,
1370) {
1371    if push_state.is_workflow_scope_failure {
1372        // Non-retryable — block immediately with actionable guidance.
1373        tracing::error!(
1374            task_id = ctx.task_id,
1375            "push failed: token lacks `workflow` OAuth scope — blocking immediately \
1376             (rerouting would not help)"
1377        );
1378        ctx.set(&[(
1379            "last_error",
1380            serde_json::json!(format!(
1381                "push failed: GitHub token lacks `workflow` OAuth scope. \
1382                 The agent modified .github/workflows/ files but the token cannot push them. \
1383                 Fix: add `workflow` scope to your GitHub token, or use a GitHub App for auth. \
1384                 Original error: {}",
1385                push_state.stored_last_error
1386            )),
1387        )])
1388        .await;
1389    } else if push_state.is_rebase_conflict_failure {
1390        tracing::error!(
1391            task_id = ctx.task_id,
1392            "push failed and automatic rebase recovery failed — blocking for human intervention"
1393        );
1394        ctx.set(&[
1395            ("agent", serde_json::json!(null)),
1396            ("model", serde_json::json!(null)),
1397        ])
1398        .await;
1399    } else if push_state.push_failed && final_status == "needs_review" {
1400        // The engine retries the push from the review gate. Keep agent and model, since the
1401        // task never goes back to the router
1402        tracing::warn!(
1403            task_id = ctx.task_id,
1404            push_failures = push_state.push_failures,
1405            "agent done but push failed on a GitHub or network error — engine retries the push"
1406        );
1407    } else if push_state.push_failed {
1408        // Clear agent and model so router picks a different one on reroute (#1604)
1409        ctx.set(&[
1410            ("agent", serde_json::json!(null)),
1411            ("model", serde_json::json!(null)),
1412        ])
1413        .await;
1414        let push_failures = push_state.push_failures;
1415        if push_failures >= 3 {
1416            tracing::error!(
1417                task_id = ctx.task_id,
1418                push_failures,
1419                "push failed {push_failures} times — blocking for human intervention"
1420            );
1421        } else {
1422            tracing::warn!(
1423                task_id = ctx.task_id,
1424                push_failures,
1425                "agent done but push failed ({push_failures}/3) — rerouting to different agent"
1426            );
1427        }
1428    } else if resp_status == "done" && !has_pr && has_delegations {
1429        tracing::info!(
1430            task_id = ctx.task_id,
1431            "agent reported done with delegations but no PR — setting blocked"
1432        );
1433    } else if (resp_status == "done" || resp_status == "completed")
1434        && !has_pr
1435        && has_pushed
1436        && is_pr_base_invalid
1437    {
1438        tracing::error!(
1439            task_id = ctx.task_id,
1440            "PR creation failed with invalid base branch — blocking for human intervention"
1441        );
1442        ctx.set(&[(
1443            "last_error",
1444            serde_json::json!(
1445                "PR creation failed terminally (invalid base branch or GitHub auth error). The agent's commits were pushed successfully. \
1446                 Check the repository default branch and the GitHub token, then create the PR manually or unblock the task."
1447            ),
1448        )])
1449        .await;
1450    } else if resp_status == "done" && !has_pr && has_pushed {
1451        // Push succeeded but PR creation failed after retries.
1452        tracing::warn!(
1453            task_id = ctx.task_id,
1454            "agent done, commits pushed, but PR creation failed — re-dispatching as routed"
1455        );
1456    } else if is_no_code_reroute {
1457        // Record which agent produced this no-code result so the same-agent
1458        // detection on the next run can prevent loop-backs (#2410, #2686).
1459        // Also clear agent/model to force re-routing.
1460
1461        if final_status == "blocked" {
1462            // final_status is "blocked" either because max_reroutes was exhausted
1463            // or because is_same_agent was detected (both cases are handled by
1464            // classify_final_status). Log accordingly.
1465            let prev_no_code_agent = ctx
1466                .get_task()
1467                .await
1468                .map(|t| t.no_code_last_agent)
1469                .unwrap_or_default();
1470            let is_same_agent = !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name;
1471
1472            let msg = if is_same_agent {
1473                tracing::error!(
1474                    task_id = ctx.task_id,
1475                    agent = %agent_name,
1476                    "blocking same-agent no-code loop: agent {} would be selected again",
1477                    agent_name
1478                );
1479                format!(
1480                    "agent {agent_name} completed without code changes twice — same-agent loop detected, blocking for human review"
1481                )
1482            } else {
1483                tracing::error!(
1484                    task_id = ctx.task_id,
1485                    no_code_reroutes,
1486                    max_reroutes,
1487                    "blocking no-code reroute: reached max reroute attempts ({}/{}) for no-code-result",
1488                    no_code_reroutes,
1489                    max_reroutes
1490                );
1491                format!(
1492                    "agent completed without code changes after {no_code_reroutes}/{max_reroutes} reroute attempts on external task requiring PR"
1493                )
1494            };
1495            ctx.set(&[("last_error", serde_json::json!(msg))]).await;
1496        } else {
1497            // Rerouting — no blocking error to record yet.
1498            ctx.set(&[(
1499                "last_error",
1500                serde_json::json!(
1501                    "agent completed without code changes on external task requiring PR"
1502                ),
1503            )])
1504            .await;
1505        }
1506
1507        // Always record which agent produced this no-code result so the router can
1508        // skip it on the next attempt. Also clear agent/model to force re-routing
1509        // (the router will pick a fresh agent, which will be caught by the same-agent
1510        // check on the next round if it's the same agent).
1511        ctx.set(&[
1512            ("no_code_last_agent", serde_json::json!(agent_name)),
1513            ("agent", serde_json::json!(null)),
1514            ("model", serde_json::json!(null)),
1515        ])
1516        .await;
1517    } else if resp_status == "done" && !has_pr && is_external {
1518        // External task with non-code labels (e.g. documentation, research) —
1519        // allowed to be marked done without a PR.
1520        tracing::info!(
1521            task_id = ctx.task_id,
1522            "external task with non-code labels reported done — marking done without PR"
1523        );
1524    } else if resp_status == "done" && !has_pr {
1525        tracing::info!(
1526            task_id = ctx.task_id,
1527            "internal task reported done with no PR — marking done"
1528        );
1529    }
1530}
1531
1532/// Store token usage if both input and output token counts are known, with the cost the agent
1533/// reported for the run.
1534async fn store_token_usage(
1535    ctx: &StoreCtx<'_>,
1536    input_tokens: Option<u64>,
1537    output_tokens: Option<u64>,
1538    cost_usd: Option<f64>,
1539) {
1540    let (Some(input), Some(output)) = (input_tokens, output_tokens) else {
1541        return;
1542    };
1543    if let Some(st) = ctx.store {
1544        if let Some(store_id) = ctx.store_id_opt {
1545            if let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await {
1546                tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1547            }
1548        } else if let Ok(Some(store_id)) = st.resolve_task_id(ctx.repo, ctx.task_id).await
1549            && let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await
1550        {
1551            tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1552        }
1553    }
1554}
1555
1556/// Handle a successful agent response: commit, push, PR, delegations, tokens.
1557///
1558/// Returns `Ok((status, push_failed))` where `status` is the final task status
1559/// string and `push_failed` is `true` when a push was attempted but failed (for
1560/// audit trail classification).
1561#[expect(
1562    clippy::too_many_arguments,
1563    reason = "the runner passes each part of the run result"
1564)]
1565pub async fn handle_success(
1566    task_id: &str,
1567    parsed: agents::ParsedResponse,
1568    wt: &worktree::WorktreeSetup,
1569    task_title: &str,
1570    agent_name: &str,
1571    model_name: Option<&str>,
1572    new_attempts: u32,
1573    repo: &str,
1574    store: &Option<Arc<TaskStore>>,
1575    raw_stdout: &str,
1576) -> anyhow::Result<(String, bool)> {
1577    // Extract token counts before consuming parsed.
1578    let input_tokens = parsed.input_tokens;
1579    let output_tokens = parsed.output_tokens;
1580    let cost_usd = parsed.cost_usd;
1581    let mut resp = parsed.response;
1582
1583    tracing::info!(
1584        task_id,
1585        status = resp.status,
1586        summary = resp.summary,
1587        "agent completed successfully"
1588    );
1589
1590    let push_denied = resp.status == "blocked" && is_denied_push_block(&resp);
1591
1592    // Resolve numeric store_id once so we can reuse it for multiple store ops
1593    // in this hot path and avoid repeated external_id -> store_id SQL lookups.
1594    let store_id_opt = store::resolve_store_id(store, repo, task_id).await;
1595    let ctx = StoreCtx {
1596        store,
1597        store_id_opt,
1598        repo,
1599        task_id,
1600    };
1601
1602    ctx.reset_retry_streaks().await;
1603
1604    // Auto-commit, push, create PR
1605    let git = if resp.status == "done"
1606        || resp.status == "completed"
1607        || resp.status == "in_progress"
1608        || resp.status == "needs_review"
1609        || push_denied
1610    {
1611        run_git_ops(
1612            &ctx,
1613            wt,
1614            task_title,
1615            &resp,
1616            agent_name,
1617            model_name,
1618            new_attempts,
1619        )
1620        .await
1621    } else {
1622        GitOpsResult::default()
1623    };
1624
1625    // The agent's only blocker was the denied push and orch pushed for it, so
1626    // the task continues as if the agent had returned done
1627    if push_denied && (git.has_pr || git.has_pushed) {
1628        tracing::info!(
1629            task_id,
1630            "agent blocked on denied push, orch pushed the branch"
1631        );
1632        resp.status = "done".to_string();
1633    }
1634
1635    let screenshot_note = if git.has_pr {
1636        post_screenshots(&ctx, &wt.work_dir, &resp).await
1637    } else {
1638        None
1639    };
1640
1641    // Store delegations in store if present (processed by run_with_context)
1642    if !resp.delegations.is_empty() {
1643        ctx.set(&[("delegations", serde_json::json!(resp.delegations))])
1644            .await;
1645    }
1646
1647    // Store result in task store
1648    // If agent said "done" and a PR exists, send to review before merge.
1649    // If agent said "done", pushed commits, but PR creation failed — review gate creates PR.
1650    // If agent said "done", no PR, and no delegations — work is complete
1651    // (e.g., review/analysis jobs that create issues but no code changes).
1652    // If agent said "done", no PR, but has delegations — blocked on children.
1653    let has_delegations = !resp.delegations.is_empty();
1654
1655    // Detect push failure, increment counters.
1656    let push_state = detect_push_failure_state(&ctx, git.has_commits, git.has_pushed).await;
1657
1658    // Determine whether this external task can be marked done without a PR.
1659    // External tasks always require a PR before reaching `done` — unless
1660    // commits were successfully pushed (in which case the `has_pushed` branch
1661    // handles routing). The `is_non_code_task` heuristic was removed because
1662    // it relied on agent output and could be fooled: an agent claiming
1663    // "already implemented" or "config-only" would match non-code keywords
1664    // and close the issue without verification.
1665    let is_external = !task_id.starts_with("internal:");
1666    let requires_pr = is_external && !git.has_pr && !resp.status.starts_with("needs_review");
1667
1668    // Preferred config key `workflow.max_reroute_attempts`; fall back to
1669    // `workflow.max_attempts` for backwards compatibility.
1670    let max_reroutes: u32 = config::get("workflow.max_reroute_attempts")
1671        .ok()
1672        .and_then(|s| s.parse().ok())
1673        .or_else(|| {
1674            config::get("workflow.max_attempts")
1675                .ok()
1676                .and_then(|s| s.parse().ok())
1677        })
1678        .unwrap_or(3);
1679
1680    // Determine whether we are entering the no-code-reroute branch (all
1681    // earlier chain conditions are false + done + requires_pr).
1682    let is_no_code_reroute = !push_state.is_workflow_scope_failure
1683        && !push_state.push_failed
1684        && (resp.status == "done" || resp.status == "completed")
1685        && !has_delegations
1686        && !git.has_pushed
1687        && requires_pr;
1688
1689    // A conflict reroute with nothing ahead of the default branch is a landed
1690    // fix, not a no-code run: close the superseded PR and mark the task done.
1691    let superseded_pr = match (is_no_code_reroute, ctx.get_task().await) {
1692        (true, Some(task)) => {
1693            superseded_conflict_pr(task.merge_conflict_retries, task.pr_number, git.has_commits)
1694        }
1695        _ => None,
1696    };
1697    let is_no_code_reroute = is_no_code_reroute && superseded_pr.is_none();
1698
1699    let no_code_reroutes =
1700        detect_no_code_reroutes(&ctx, is_no_code_reroute, new_attempts, max_reroutes).await;
1701
1702    let blocked_reason = if resp.status == "blocked" {
1703        Some(agent_blocked_reason(&resp))
1704    } else {
1705        None
1706    };
1707    let is_retryable_blocked = blocked_reason
1708        .as_deref()
1709        .is_some_and(is_retryable_blocked_reason);
1710
1711    // ── Detect same-agent loop ───────────────────────────────────────────────
1712    //
1713    // If this is a no-code reroute and the agent is the same as the one that
1714    // produced the previous no-code result, flag it for blocking (#2410, #2686).
1715    let is_same_agent = if is_no_code_reroute {
1716        let prev_no_code_agent = ctx
1717            .get_task()
1718            .await
1719            .map(|t| t.no_code_last_agent)
1720            .unwrap_or_default();
1721        !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name
1722    } else {
1723        false
1724    };
1725
1726    // ── Pure status decision ─────────────────────────────────────────────────
1727
1728    let final_status_owned = classify_final_status(&DecisionInput {
1729        agent_status: &resp.status,
1730        is_workflow_scope_failure: push_state.is_workflow_scope_failure,
1731        is_rebase_conflict_failure: push_state.is_rebase_conflict_failure,
1732        push_failed: push_state.push_failed,
1733        push_failures: push_state.push_failures,
1734        is_transient_push_failure: push_state.is_transient_failure,
1735        has_pr: git.has_pr,
1736        has_delegations,
1737        has_pushed: git.has_pushed,
1738        is_pr_base_invalid: git.pr_base_invalid,
1739        requires_pr,
1740        no_code_reroutes,
1741        max_reroutes,
1742        is_same_agent,
1743        is_completed_status: resp.status == "completed",
1744        is_retryable_blocked,
1745        is_superseded_conflict: superseded_pr.is_some(),
1746    });
1747    let final_status = final_status_owned.as_str();
1748
1749    // ── Post-decision side effects (tracing + store updates) ─────────────────
1750
1751    apply_post_decision_effects(
1752        &ctx,
1753        final_status,
1754        &resp.status,
1755        &push_state,
1756        is_no_code_reroute,
1757        git.has_pr,
1758        git.has_pushed,
1759        git.pr_base_invalid,
1760        has_delegations,
1761        is_external,
1762        no_code_reroutes,
1763        max_reroutes,
1764        agent_name,
1765    )
1766    .await;
1767
1768    // When the agent explicitly returned "blocked", persist its explanation into
1769    // last_error so `orch task get` surfaces the reason without requiring manual
1770    // inspection of task_runs.parsed_response.  The apply_post_decision_effects
1771    // branches above only fire on push/no-code scenarios; a raw agent-blocked
1772    // response falls through all of them and would leave last_error empty.
1773    if resp.status == "blocked" {
1774        let reason = blocked_reason.unwrap_or_else(|| agent_blocked_reason(&resp));
1775        if final_status == "new" {
1776            // Retryable external block: cooldown failed agent/model, clear selection,
1777            // and reroute after backoff instead of permanently blocking.
1778            cooldown::record_agent_failure_with_message(agent_name, &reason).await;
1779            if let Some(m) = model_name {
1780                cooldown::record_model_failure(agent_name, m).await;
1781            }
1782            ctx.set(&[
1783                (
1784                    "last_error",
1785                    serde_json::json!(format!(
1786                        "transient blocker (auto-retry scheduled): {reason}"
1787                    )),
1788                ),
1789                ("agent", serde_json::json!(null)),
1790                ("model", serde_json::json!(null)),
1791            ])
1792            .await;
1793            tracing::warn!(
1794                task_id = ctx.task_id,
1795                reason = %reason,
1796                "agent returned retryable blocked status — rerouting as new with cooldown"
1797            );
1798        } else if final_status == "blocked" {
1799            ctx.set(&[("last_error", serde_json::json!(reason))]).await;
1800        }
1801    }
1802
1803    if let Some(pr_number) = superseded_pr {
1804        tracing::info!(
1805            task_id = ctx.task_id,
1806            pr_number,
1807            "conflict reroute found the fix already on the default branch — closing superseded PR"
1808        );
1809        close_superseded_pr(&ctx, pr_number).await;
1810    }
1811
1812    // The summary reaches the channels, so a missing skill or browser goes with it
1813    let summary = match &screenshot_note {
1814        Some(note) => format!("{}\n\nScreenshots: {note}", resp.summary),
1815        None => resp.summary.clone(),
1816    };
1817    ctx.set(&[("summary", serde_json::json!(summary))]).await;
1818
1819    // Store token usage — prefer agent-parsed tokens, fall back to response
1820    store_token_usage(
1821        &ctx,
1822        input_tokens.or(resp.input_tokens),
1823        output_tokens.or(resp.output_tokens),
1824        cost_usd,
1825    )
1826    .await;
1827
1828    // Store learnings for memory (for future retries)
1829    response::store_learnings_from_response(
1830        task_id,
1831        new_attempts,
1832        agent_name,
1833        model_name,
1834        &resp,
1835        resp.error.as_deref(),
1836        store,
1837        repo,
1838        raw_stdout,
1839    )
1840    .await;
1841
1842    // Note: done → in_review transition is handled by the engine
1843    // after triggering the review agent (engine/mod.rs)
1844    Ok((final_status.to_string(), push_state.push_failed))
1845}
1846
1847/// Labels that indicate a task is non-code and can be marked done without a PR.
1848#[cfg(test)]
1849mod tests {
1850    use std::fs as std_fs;
1851    use std::process::Command;
1852
1853    use super::*;
1854    use crate::store::NewTask;
1855
1856    /// A successful run between timeouts restarts the count, so only timeouts in a row block a task
1857    #[tokio::test]
1858    async fn successful_run_resets_timeout_retries() {
1859        let store = Some(Arc::new(TaskStore::open_memory().await.unwrap()));
1860        let id = store
1861            .as_ref()
1862            .unwrap()
1863            .create_internal("owner/repo", "t", "b", "test", "", None)
1864            .await
1865            .unwrap();
1866        let task_id = format!("internal:{id}");
1867        let ctx = StoreCtx {
1868            store: &store,
1869            store_id_opt: None,
1870            repo: "owner/repo",
1871            task_id: &task_id,
1872        };
1873
1874        ctx.increment("timeout_retries").await.unwrap();
1875        ctx.increment("network_retries").await.unwrap();
1876        ctx.reset_retry_streaks().await;
1877        ctx.increment("timeout_retries").await.unwrap();
1878        ctx.increment("timeout_retries").await.unwrap();
1879
1880        let task = ctx.get_task().await.unwrap();
1881        assert_eq!(task.timeout_retries, 2);
1882        assert_eq!(task.network_retries, 0);
1883        assert_ne!(task.status.as_str(), "blocked");
1884    }
1885
1886    #[test]
1887    fn local_rate_limit_skip_is_detected() {
1888        assert!(is_local_rate_limit_skip(
1889            "GitHub API error: GitHub REST API rate-limited, skipping call for 236s"
1890        ));
1891        assert!(!is_local_rate_limit_skip(
1892            "GitHub API POST failed (502): Bad Gateway"
1893        ));
1894    }
1895
1896    /// Helper: run git in `dir`, panicking on failure
1897    fn git(dir: &Path, args: &[&str]) {
1898        let out = Command::new("git")
1899            .current_dir(dir)
1900            .args(args)
1901            .output()
1902            .unwrap_or_else(|e| panic!("git {args:?} failed to start: {e}"));
1903        assert!(
1904            out.status.success(),
1905            "git {args:?} failed:\nstdout: {}\nstderr: {}",
1906            String::from_utf8_lossy(&out.stdout),
1907            String::from_utf8_lossy(&out.stderr)
1908        );
1909    }
1910
1911    fn init_clone(remote: &Path, dir: &Path) {
1912        git(dir, &["clone", remote.to_str().unwrap(), "."]);
1913        git(dir, &["config", "user.email", "t@t.com"]);
1914        git(dir, &["config", "user.name", "T"]);
1915        git(dir, &["config", "commit.gpgsign", "false"]);
1916    }
1917
1918    #[test]
1919    fn remote_rejected_failure_is_not_diverged() {
1920        let err = "remote: fatal error in commit_refs\n ! [remote rejected] b -> b (failure)";
1921        assert!(!push_error_is_diverged(err));
1922        assert!(push_error_is_diverged("! [rejected] b -> b (fetch first)"));
1923        assert!(push_error_is_diverged(
1924            "! [rejected] b -> b (non-fast-forward)"
1925        ));
1926    }
1927
1928    /**
1929     * Someone rebased the PR branch from another clone and force-pushed it, so orch's
1930     * push is rejected with a stale lease. Pushing is orch's own step: it must rebase
1931     * onto the moved branch and push again, never hand finished work back to the agent
1932     * as a fresh attempt (#3783)
1933     **/
1934    #[tokio::test]
1935    async fn push_rejected_after_remote_rebase_is_pushed_not_rerouted() {
1936        let remote = tempfile::tempdir().unwrap();
1937        git(remote.path(), &["init", "--bare", "-b", "main"]);
1938
1939        // orch's worktree: main, then a feature branch with the task's commit
1940        let work = tempfile::tempdir().unwrap();
1941        init_clone(remote.path(), work.path());
1942        std_fs::write(work.path().join("README.md"), "base").unwrap();
1943        git(work.path(), &["add", "."]);
1944        git(work.path(), &["commit", "-m", "init"]);
1945        git(work.path(), &["push", "origin", "HEAD:main"]);
1946        git(work.path(), &["checkout", "-b", "feat"]);
1947        std_fs::write(work.path().join("fix.txt"), "the fix").unwrap();
1948        git(work.path(), &["add", "."]);
1949        git(work.path(), &["commit", "-m", "apply the fix"]);
1950        git(work.path(), &["push", "-u", "origin", "feat"]);
1951
1952        // Another clone rewrites the same change and force-pushes it
1953        let other = tempfile::tempdir().unwrap();
1954        init_clone(remote.path(), other.path());
1955        git(other.path(), &["checkout", "feat"]);
1956        git(
1957            other.path(),
1958            &["commit", "--amend", "-m", "apply the fix (rebased)"],
1959        );
1960        git(other.path(), &["push", "--force", "origin", "feat"]);
1961
1962        // orch now has an unpushed commit of its own on top of the stale branch
1963        std_fs::write(work.path().join("more.txt"), "follow-up").unwrap();
1964        git(work.path(), &["add", "."]);
1965        git(work.path(), &["commit", "-m", "follow-up"]);
1966
1967        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1968        let store_id = store
1969            .create_internal("owner/repo", "Push recovery", "", "task", "3783", None)
1970            .await
1971            .unwrap();
1972        let task_id = format!("internal:{store_id}");
1973        let store_opt = Some(Arc::clone(&store));
1974        let ctx = StoreCtx {
1975            store: &store_opt,
1976            store_id_opt: Some(store_id),
1977            repo: "owner/repo",
1978            task_id: &task_id,
1979        };
1980
1981        let result =
1982            push_branch_with_log(&ctx, work.path(), "feat", "main", "claude", Some("opus")).await;
1983
1984        assert!(
1985            matches!(result, PushResult::Success),
1986            "orch must land the push itself after adopting the moved remote branch"
1987        );
1988
1989        let task = store.get(store_id).await.unwrap();
1990        assert!(
1991            task.last_error.is_empty(),
1992            "a recovered push must leave no error behind, got: {}",
1993            task.last_error
1994        );
1995        assert_eq!(task.push_failures, 0, "recovery is not a push failure");
1996
1997        // push_branch recovers the stale lease itself, so the log below is the proof: the
1998        // follow-up commit is on the remote, on top of the rebased history
1999        let log = Command::new("git")
2000            .current_dir(work.path())
2001            .args(["log", "--oneline", "origin/feat"])
2002            .output()
2003            .unwrap();
2004        let log = String::from_utf8_lossy(&log.stdout);
2005        assert!(
2006            log.contains("follow-up"),
2007            "remote must carry the task's commit: {log}"
2008        );
2009        assert!(
2010            log.contains("apply the fix (rebased)"),
2011            "orch must adopt the rebased remote history, not re-push its own: {log}"
2012        );
2013        assert!(
2014            !log.contains("apply the fix\n"),
2015            "the superseded commit must not come back: {log}"
2016        );
2017    }
2018
2019    #[test]
2020    fn missing_path_error_detects_io_not_found() {
2021        let err = anyhow::Error::from(io::Error::new(
2022            ErrorKind::NotFound,
2023            "simulated missing path",
2024        ));
2025        assert!(is_missing_path_error(&err));
2026    }
2027
2028    #[test]
2029    fn missing_path_error_detects_message_fallback() {
2030        let err = anyhow::anyhow!("push failed: No such file or directory (os error 2)");
2031        assert!(is_missing_path_error(&err));
2032    }
2033
2034    #[test]
2035    fn superseded_conflict_pr_requires_conflict_reroute_and_no_commits() {
2036        // Conflict reroute, nothing ahead of the default branch → close the PR.
2037        assert_eq!(superseded_conflict_pr(1, Some(42), false), Some(42));
2038        // Commits exist → the agent did work, keep the PR.
2039        assert_eq!(superseded_conflict_pr(1, Some(42), true), None);
2040        // No conflict reroute → an ordinary no-code run.
2041        assert_eq!(superseded_conflict_pr(0, Some(42), false), None);
2042        // No PR to close.
2043        assert_eq!(superseded_conflict_pr(1, None, false), None);
2044    }
2045
2046    /// End-to-end: a conflict reroute that comes back with zero commits ahead of
2047    /// the default branch closes the superseded PR and marks the task done,
2048    /// instead of blocking it as a same-agent no-code loop (#3780).
2049    #[tokio::test]
2050    async fn conflict_reroute_with_no_commits_closes_pr_and_marks_done() {
2051        fn git(dir: &Path, args: &[&str]) {
2052            let ok = Command::new("git")
2053                .args(args)
2054                .current_dir(dir)
2055                .env("GIT_AUTHOR_NAME", "t")
2056                .env("GIT_AUTHOR_EMAIL", "t@example.com")
2057                .env("GIT_COMMITTER_NAME", "t")
2058                .env("GIT_COMMITTER_EMAIL", "t@example.com")
2059                .output()
2060                .expect("git runs")
2061                .status
2062                .success();
2063            assert!(ok, "git {args:?} failed");
2064        }
2065
2066        // A worktree whose branch has nothing ahead of origin/main — the state
2067        // the agent leaves behind when the fix already landed on the base.
2068        let dir = tempfile::tempdir().unwrap();
2069        let origin = dir.path().join("origin.git");
2070        std_fs::create_dir(&origin).unwrap();
2071        git(&origin, &["init", "--bare", "-b", "main"]);
2072        let work_dir = dir.path().join("work");
2073        std_fs::create_dir(&work_dir).unwrap();
2074        git(&work_dir, &["init", "-b", "main"]);
2075        git(
2076            &work_dir,
2077            &["remote", "add", "origin", &origin.display().to_string()],
2078        );
2079        std_fs::write(work_dir.join("a.txt"), "a").unwrap();
2080        git(&work_dir, &["add", "-A"]);
2081        git(&work_dir, &["commit", "-m", "init"]);
2082        git(&work_dir, &["push", "-u", "origin", "main"]);
2083        git(&work_dir, &["checkout", "-b", "fix-branch"]);
2084
2085        let wt = worktree::WorktreeSetup {
2086            work_dir: work_dir.clone(),
2087            branch: "fix-branch".to_string(),
2088            default_branch: "main".to_string(),
2089            main_project_dir: work_dir.clone(),
2090        };
2091
2092        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2093        let store_id = store
2094            .create(&NewTask {
2095                external_id: Some("3772".to_string()),
2096                repo: "owner/repo".to_string(),
2097                origin: "github".to_string(),
2098                title: "Fix the thing".to_string(),
2099                body: String::new(),
2100                source: "manual".to_string(),
2101                source_id: String::new(),
2102                author: "bot".to_string(),
2103                url: String::new(),
2104                labels: vec![],
2105                parent_id: None,
2106            })
2107            .await
2108            .unwrap();
2109        store
2110            .set_fields(store_id, &[("pr_number", serde_json::json!(42))])
2111            .await
2112            .unwrap();
2113        // review_poll rerouted this task to resolve a merge conflict.
2114        store
2115            .increment(store_id, "merge_conflict_retries")
2116            .await
2117            .unwrap();
2118        // A previous no-code run by the same agent — without the superseded
2119        // check this run would block the task as a same-agent loop.
2120        store
2121            .set_fields(
2122                store_id,
2123                &[("no_code_last_agent", serde_json::json!("claude"))],
2124            )
2125            .await
2126            .unwrap();
2127
2128        let parsed = agents::ParsedResponse {
2129            response: AgentResponse {
2130                status: "done".to_string(),
2131                summary: "the fix is already on main".to_string(),
2132                ..Default::default()
2133            },
2134            input_tokens: None,
2135            output_tokens: None,
2136            cost_usd: None,
2137            duration_ms: None,
2138        };
2139
2140        let (final_status, push_failed) = handle_success(
2141            "3772",
2142            parsed,
2143            &wt,
2144            "Fix the thing",
2145            "claude",
2146            Some("sonnet"),
2147            1,
2148            "owner/repo",
2149            &Some(Arc::clone(&store)),
2150            "",
2151        )
2152        .await
2153        .unwrap();
2154
2155        assert_eq!(
2156            final_status, "done",
2157            "a superseded conflict reroute must end done, not blocked"
2158        );
2159        assert!(!push_failed);
2160
2161        let task = store.get(store_id).await.unwrap();
2162        assert!(
2163            task.last_error.contains("superseded"),
2164            "the close attempt must be recorded on the task: {}",
2165            task.last_error
2166        );
2167        assert_eq!(
2168            task.pr_number, None,
2169            "a superseded PR must not stay on the task, the blocker refresh would read it as closed unmerged"
2170        );
2171    }
2172
2173    /// A conflict reroute with zero commits ahead marks the task done instead of
2174    /// blocking it as a same-agent no-code loop (#3780).
2175    #[test]
2176    fn classify_superseded_conflict_marks_done() {
2177        let status = classify_final_status(&DecisionInput {
2178            agent_status: "done",
2179            requires_pr: true,
2180            is_same_agent: true,
2181            is_superseded_conflict: true,
2182            ..Default::default()
2183        });
2184        assert_eq!(status, "done");
2185    }
2186
2187    // ── classify_final_status — one test per decision branch ─────────────────
2188
2189    /// Branch 1: workflow-scope push failure → block immediately (non-retryable).
2190    #[test]
2191    fn classify_workflow_scope_failure_blocks() {
2192        let status = classify_final_status(&DecisionInput {
2193            is_workflow_scope_failure: true,
2194            push_failed: true,
2195            push_failures: 1,
2196            ..Default::default()
2197        });
2198        assert_eq!(status, "blocked");
2199    }
2200
2201    /// Branch 1b: automatic rebase recovery failed (conflicts) → block immediately.
2202    #[test]
2203    fn classify_rebase_conflict_failure_blocks() {
2204        let status = classify_final_status(&DecisionInput {
2205            is_rebase_conflict_failure: true,
2206            push_failed: true,
2207            ..Default::default()
2208        });
2209        assert_eq!(status, "blocked");
2210    }
2211
2212    /// Branch 2a: push failed, < 3 times → reroute with "new".
2213    #[test]
2214    fn classify_push_failed_under_threshold_reroutes() {
2215        let status = classify_final_status(&DecisionInput {
2216            push_failed: true,
2217            push_failures: 2, // < 3
2218            ..Default::default()
2219        });
2220        assert_eq!(status, "new");
2221    }
2222
2223    #[test]
2224    fn denied_push_block_detected() {
2225        let resp = |s: &str| AgentResponse {
2226            status: "blocked".to_string(),
2227            summary: s.to_string(),
2228            ..Default::default()
2229        };
2230        assert!(is_denied_push_block(&resp(
2231            "Work committed, but `git push -u origin HEAD` was denied"
2232        )));
2233        assert!(is_denied_push_block(&resp(
2234            "It is not pushed: `git push --force-with-lease` needs approval that this session could not get."
2235        )));
2236        assert!(is_denied_push_block(&resp(
2237            "`git push --force-with-lease` was denied because this session cannot get approval"
2238        )));
2239        assert!(is_denied_push_block(&resp("The push requires approval")));
2240        assert!(!is_denied_push_block(&resp("Missing API key")));
2241    }
2242
2243    /// Branch 2b: push failed >= 3 times → block for human intervention.
2244    #[test]
2245    fn classify_push_failed_at_threshold_blocks() {
2246        let status = classify_final_status(&DecisionInput {
2247            push_failed: true,
2248            push_failures: 3, // >= 3
2249            ..Default::default()
2250        });
2251        assert_eq!(status, "blocked");
2252    }
2253
2254    /// A GitHub-side push failure never reaches the router, the engine retries the push (#4025).
2255    #[test]
2256    fn classify_transient_push_failure_waits_for_the_engine_retry() {
2257        for push_failures in 1..push_retry::MAX_PUSH_FAILURES {
2258            let status = classify_final_status(&DecisionInput {
2259                push_failed: true,
2260                is_transient_push_failure: true,
2261                push_failures,
2262                ..Default::default()
2263            });
2264            assert_eq!(status, "needs_review", "push_failures={push_failures}");
2265        }
2266    }
2267
2268    #[test]
2269    fn classify_transient_push_failure_blocks_after_the_last_retry() {
2270        let status = classify_final_status(&DecisionInput {
2271            push_failed: true,
2272            is_transient_push_failure: true,
2273            push_failures: push_retry::MAX_PUSH_FAILURES,
2274            ..Default::default()
2275        });
2276        assert_eq!(status, "blocked");
2277    }
2278
2279    /// Branch 3: done + PR exists → send to review.
2280    #[test]
2281    fn classify_done_with_pr_goes_to_needs_review() {
2282        let status = classify_final_status(&DecisionInput {
2283            agent_status: "done",
2284            has_pr: true,
2285            ..Default::default()
2286        });
2287        assert_eq!(status, "needs_review");
2288    }
2289
2290    /// Branch 4: done + delegations, no PR → block (waiting on child tasks).
2291    #[test]
2292    fn classify_done_with_delegations_no_pr_blocks() {
2293        let status = classify_final_status(&DecisionInput {
2294            agent_status: "done",
2295            has_delegations: true,
2296            ..Default::default()
2297        });
2298        assert_eq!(status, "blocked");
2299    }
2300
2301    /// Branch 5: done + commits pushed but PR creation failed → re-dispatch.
2302    #[test]
2303    fn classify_done_pushed_no_pr_reroutes_for_pr_creation() {
2304        let status = classify_final_status(&DecisionInput {
2305            agent_status: "done",
2306            has_pushed: true,
2307            ..Default::default()
2308        });
2309        assert_eq!(status, "routed");
2310    }
2311
2312    /// Branch 5b: done + pushed + PR base invalid → block (terminal error).
2313    #[test]
2314    fn classify_done_pushed_pr_base_invalid_blocks() {
2315        let status = classify_final_status(&DecisionInput {
2316            agent_status: "done",
2317            has_pushed: true,
2318            is_pr_base_invalid: true,
2319            ..Default::default()
2320        });
2321        assert_eq!(status, "blocked");
2322    }
2323
2324    /// Branch 5c: completed + pushed + PR base invalid → block (terminal error).
2325    #[test]
2326    fn classify_completed_pushed_pr_base_invalid_blocks() {
2327        let status = classify_final_status(&DecisionInput {
2328            agent_status: "completed",
2329            is_completed_status: true,
2330            has_pushed: true,
2331            is_pr_base_invalid: true,
2332            ..Default::default()
2333        });
2334        assert_eq!(status, "blocked");
2335    }
2336
2337    /// Branch 6a: done + requires_pr, under max reroutes → reroute.
2338    #[test]
2339    fn classify_done_requires_pr_under_max_reroutes() {
2340        let status = classify_final_status(&DecisionInput {
2341            agent_status: "done",
2342            requires_pr: true,
2343            no_code_reroutes: 1,
2344            max_reroutes: 3,
2345            is_same_agent: false,
2346            ..Default::default()
2347        });
2348        assert_eq!(status, "new");
2349    }
2350
2351    /// Branch 6a edge: same agent on no-code reroute → block immediately.
2352    #[test]
2353    fn classify_done_requires_pr_same_agent_blocks_immediately() {
2354        let status = classify_final_status(&DecisionInput {
2355            agent_status: "done",
2356            requires_pr: true,
2357            no_code_reroutes: 1,
2358            max_reroutes: 3,
2359            is_same_agent: true, // Same agent would be selected again
2360            ..Default::default()
2361        });
2362        assert_eq!(status, "blocked");
2363    }
2364
2365    /// Branch 6b: done + requires_pr, at max reroutes → block.
2366    #[test]
2367    fn classify_done_requires_pr_at_max_reroutes_blocks() {
2368        let status = classify_final_status(&DecisionInput {
2369            agent_status: "done",
2370            requires_pr: true,
2371            no_code_reroutes: 3,
2372            max_reroutes: 3,
2373            is_same_agent: false,
2374            ..Default::default()
2375        });
2376        assert_eq!(status, "blocked");
2377    }
2378
2379    /// Branch 6b edge: exceeding max also blocks.
2380    #[test]
2381    fn classify_done_requires_pr_exceeds_max_reroutes_blocks() {
2382        let status = classify_final_status(&DecisionInput {
2383            agent_status: "done",
2384            requires_pr: true,
2385            no_code_reroutes: 5,
2386            max_reroutes: 3,
2387            is_same_agent: false,
2388            ..Default::default()
2389        });
2390        assert_eq!(status, "blocked");
2391    }
2392
2393    /// Same agent on external task requiring PR → block immediately (not wait for max).
2394    #[test]
2395    fn classify_done_external_no_pushed_same_agent_blocks_immediately() {
2396        let status = classify_final_status(&DecisionInput {
2397            agent_status: "done",
2398            requires_pr: true, // always true for external tasks with !has_pr + done
2399            no_code_reroutes: 0,
2400            max_reroutes: 3,
2401            is_same_agent: true,
2402            ..Default::default()
2403        });
2404        assert_eq!(status, "blocked");
2405    }
2406
2407    /// External task with no pushed commits: reroute (agent must produce commits
2408    /// before the issue can be closed). This was the source of issue #1898 — an
2409    /// agent claiming "already implemented" without any code changes would
2410    /// previously match non-code keywords and close the issue falsely.
2411    ///
2412    /// External tasks with done+!has_pr+!has_pushed always have requires_pr=true
2413    /// (see handle_success), so they are caught by branch 6, not branch 7.
2414    #[test]
2415    fn classify_done_external_no_pushed_commits_reroutes() {
2416        let status = classify_final_status(&DecisionInput {
2417            agent_status: "done",
2418            has_pushed: false,
2419            requires_pr: true, // always true for external tasks with !has_pr + done
2420            no_code_reroutes: 0,
2421            max_reroutes: 3,
2422            is_same_agent: false,
2423            ..Default::default()
2424        });
2425        assert_eq!(status, "new");
2426    }
2427
2428    /// Internal task with no pushed commits may still be marked done — internal
2429    /// tasks may produce no git-visible changes.
2430    #[test]
2431    fn classify_done_internal_task_no_pr_is_done() {
2432        let status = classify_final_status(&DecisionInput {
2433            agent_status: "done",
2434            has_pushed: false,
2435            requires_pr: false,
2436            ..Default::default()
2437        });
2438        assert_eq!(status, "done");
2439    }
2440
2441    /// Pass-through: non-"done" status is returned unchanged.
2442    #[test]
2443    fn classify_non_done_status_passes_through() {
2444        for status_str in &["in_progress", "needs_review", "blocked"] {
2445            let result = classify_final_status(&DecisionInput {
2446                agent_status: status_str,
2447                ..Default::default()
2448            });
2449            assert_eq!(
2450                result, *status_str,
2451                "status '{status_str}' should pass through unchanged"
2452            );
2453        }
2454    }
2455
2456    /// Descriptive completion text should normalize to done.
2457    #[test]
2458    fn classify_descriptive_completion_status_normalizes_to_done() {
2459        let status = classify_final_status(&DecisionInput {
2460            agent_status: "Trading scan complete. Nothing to trade.",
2461            ..Default::default()
2462        });
2463        assert_eq!(status, "done");
2464    }
2465
2466    /// Do not normalize to done when completion-like text includes failure cues.
2467    #[test]
2468    fn classify_descriptive_completion_with_failure_cues_does_not_normalize() {
2469        let status = classify_final_status(&DecisionInput {
2470            agent_status: "completed but failed to push branch due to error",
2471            ..Default::default()
2472        });
2473        assert_eq!(status, "completed but failed to push branch due to error");
2474    }
2475
2476    /// push_failed takes precedence over done+has_pr (push failure detected first).
2477    #[test]
2478    fn classify_push_failed_takes_precedence_over_has_pr() {
2479        let status = classify_final_status(&DecisionInput {
2480            agent_status: "done",
2481            has_pr: true,
2482            push_failed: true,
2483            push_failures: 1,
2484            ..Default::default()
2485        });
2486        // push_failed branch runs before done+has_pr check
2487        assert_eq!(status, "new");
2488    }
2489
2490    /// workflow_scope_failure takes precedence over push_failed < 3.
2491    #[test]
2492    fn classify_workflow_scope_failure_takes_precedence_over_push_reroute() {
2493        let status = classify_final_status(&DecisionInput {
2494            is_workflow_scope_failure: true,
2495            push_failed: true,
2496            push_failures: 1, // would normally reroute
2497            ..Default::default()
2498        });
2499        assert_eq!(status, "blocked");
2500    }
2501
2502    // ── "completed" status tests ────────────────────────────────────────────────
2503
2504    /// "completed" + has_pr → needs_review.
2505    #[test]
2506    fn classify_completed_with_pr_goes_to_needs_review() {
2507        let status = classify_final_status(&DecisionInput {
2508            agent_status: "completed",
2509            has_pr: true,
2510            is_completed_status: true,
2511            ..Default::default()
2512        });
2513        assert_eq!(status, "needs_review");
2514    }
2515
2516    /// "completed" + delegations, no PR → blocked.
2517    #[test]
2518    fn classify_completed_with_delegations_no_pr_blocks() {
2519        let status = classify_final_status(&DecisionInput {
2520            agent_status: "completed",
2521            has_delegations: true,
2522            is_completed_status: true,
2523            ..Default::default()
2524        });
2525        assert_eq!(status, "blocked");
2526    }
2527
2528    /// "completed" + pushed, no PR → routed for PR creation.
2529    #[test]
2530    fn classify_completed_pushed_no_pr_reroutes_for_pr_creation() {
2531        let status = classify_final_status(&DecisionInput {
2532            agent_status: "completed",
2533            has_pushed: true,
2534            is_completed_status: true,
2535            ..Default::default()
2536        });
2537        assert_eq!(status, "routed");
2538    }
2539
2540    /// "completed" + external task requiring PR, under max reroutes → reroute.
2541    #[test]
2542    fn classify_completed_requires_pr_under_max_reroutes() {
2543        let status = classify_final_status(&DecisionInput {
2544            agent_status: "completed",
2545            requires_pr: true,
2546            no_code_reroutes: 1,
2547            max_reroutes: 3,
2548            is_completed_status: true,
2549            is_same_agent: false,
2550            ..Default::default()
2551        });
2552        assert_eq!(status, "new");
2553    }
2554
2555    /// "completed" + external task, at max reroutes → block.
2556    #[test]
2557    fn classify_completed_requires_pr_at_max_reroutes_blocks() {
2558        let status = classify_final_status(&DecisionInput {
2559            agent_status: "completed",
2560            requires_pr: true,
2561            no_code_reroutes: 3,
2562            max_reroutes: 3,
2563            is_completed_status: true,
2564            is_same_agent: false,
2565            ..Default::default()
2566        });
2567        assert_eq!(status, "blocked");
2568    }
2569
2570    /// "completed" + external task, same agent on no-code reroute → block immediately.
2571    #[test]
2572    fn classify_completed_same_agent_blocks_immediately() {
2573        let status = classify_final_status(&DecisionInput {
2574            agent_status: "completed",
2575            requires_pr: true,
2576            no_code_reroutes: 1,
2577            max_reroutes: 3,
2578            is_completed_status: true,
2579            is_same_agent: true,
2580            ..Default::default()
2581        });
2582        assert_eq!(status, "blocked");
2583    }
2584
2585    /// "completed" on internal task (no requires_pr) → mark done.
2586    #[test]
2587    fn classify_completed_internal_task_is_done() {
2588        let status = classify_final_status(&DecisionInput {
2589            agent_status: "completed",
2590            requires_pr: false,
2591            is_completed_status: true,
2592            ..Default::default()
2593        });
2594        assert_eq!(status, "done");
2595    }
2596
2597    // ── agent_blocked_reason — regression tests for issue #3012 ──────────────
2598
2599    /// Agent explicitly returned blocked with an error field — use error as reason.
2600    #[test]
2601    fn agent_blocked_reason_prefers_error_field() {
2602        let resp = AgentResponse {
2603            status: "blocked".to_string(),
2604            error: Some("CDP endpoint not reachable".to_string()),
2605            summary: "Could not complete research".to_string(),
2606            remaining: vec!["Run x-twitter-brave with reachable endpoint".to_string()],
2607            ..Default::default()
2608        };
2609        let reason = agent_blocked_reason(&resp);
2610        assert!(
2611            reason.contains("CDP endpoint not reachable"),
2612            "reason: {reason}"
2613        );
2614        assert!(reason.contains("Remaining:"), "reason: {reason}");
2615        assert!(reason.contains("x-twitter-brave"), "reason: {reason}");
2616    }
2617
2618    /// No error field — falls back to summary.
2619    #[test]
2620    fn agent_blocked_reason_falls_back_to_summary() {
2621        let resp = AgentResponse {
2622            status: "blocked".to_string(),
2623            error: None,
2624            summary: "Could not access required data sources in sandboxed environment".to_string(),
2625            remaining: vec![],
2626            ..Default::default()
2627        };
2628        let reason = agent_blocked_reason(&resp);
2629        assert_eq!(
2630            reason,
2631            "Could not access required data sources in sandboxed environment"
2632        );
2633    }
2634
2635    /// No error or summary — returns generic fallback.
2636    #[test]
2637    fn agent_blocked_reason_generic_fallback() {
2638        let resp = AgentResponse {
2639            status: "blocked".to_string(),
2640            ..Default::default()
2641        };
2642        let reason = agent_blocked_reason(&resp);
2643        assert_eq!(reason, "agent returned blocked status without a reason");
2644    }
2645
2646    /// Agent-returned "blocked" status passes through classify_final_status unchanged.
2647    #[test]
2648    fn classify_agent_blocked_passes_through() {
2649        let status = classify_final_status(&DecisionInput {
2650            agent_status: "blocked",
2651            ..Default::default()
2652        });
2653        assert_eq!(status, "blocked");
2654    }
2655
2656    #[test]
2657    fn classify_retryable_agent_blocked_reroutes() {
2658        let status = classify_final_status(&DecisionInput {
2659            agent_status: "blocked",
2660            is_retryable_blocked: true,
2661            ..Default::default()
2662        });
2663        assert_eq!(status, "new");
2664    }
2665
2666    #[test]
2667    fn retryable_blocked_reason_detects_transient_patterns() {
2668        assert!(is_retryable_blocked_reason(
2669            "Twitter access unavailable: service timed out"
2670        ));
2671        assert!(is_retryable_blocked_reason(
2672            "final commit blocked by git worktree lock permission error"
2673        ));
2674        assert!(is_retryable_blocked_reason(
2675            "could not commit due a worktree git lock permission error"
2676        ));
2677        assert!(is_retryable_blocked_reason(
2678            "git lockfile permission restrictions in this environment"
2679        ));
2680        assert!(is_retryable_blocked_reason(
2681            "API rate limit hit, try again later"
2682        ));
2683        assert!(is_retryable_blocked_reason(
2684            "Credential bean/hyperliquid-address exists in the pass store but GPG decryption fails in this agent session — no passphrase available."
2685        ));
2686        assert!(is_retryable_blocked_reason(
2687            "credential resolution failed via PasswordStoreProvider; AgentVaultProvider unavailable"
2688        ));
2689    }
2690
2691    #[test]
2692    fn retryable_blocked_reason_rejects_permanent_patterns() {
2693        assert!(!is_retryable_blocked_reason(
2694            "invalid request payload: malformed JSON"
2695        ));
2696        assert!(!is_retryable_blocked_reason(
2697            "resource not found in repository"
2698        ));
2699    }
2700}