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                return note.map(String::from);
1083            }
1084        }
1085    };
1086    let body = screenshots::build_comment(ctx.repo, &commit, &images, note, &skipped);
1087    match GhHttp::new() {
1088        Ok(gh) => {
1089            if let Err(e) = gh.add_comment(ctx.repo, &pr.to_string(), &body).await {
1090                tracing::warn!(task_id = ctx.task_id, pr, err = %e, "failed to comment screenshots");
1091            }
1092        }
1093        Err(e) => tracing::warn!(task_id = ctx.task_id, err = %e, "cannot comment screenshots"),
1094    }
1095    note.map(String::from)
1096}
1097
1098/// Comment on and close a PR whose change already landed elsewhere.
1099async fn close_superseded_pr(ctx: &StoreCtx<'_>, pr_number: u64) {
1100    if ctx.repo.is_empty() {
1101        return;
1102    }
1103    match GhHttp::new() {
1104        Ok(gh) => {
1105            let note = "Closing as superseded: the change is already on the default branch, so this branch has no commits ahead of it.";
1106            if let Err(e) = gh.add_comment(ctx.repo, &pr_number.to_string(), note).await {
1107                tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to comment on superseded PR");
1108            }
1109            if let Err(e) = gh.close_pr(ctx.repo, pr_number).await {
1110                tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to close superseded PR");
1111            }
1112        }
1113        Err(e) => {
1114            tracing::warn!(task_id = ctx.task_id, err = %e, "cannot close superseded PR");
1115        }
1116    }
1117    // Dropping the PR lets the blocker refresh read the closed, completed issue with no PR
1118    ctx.set(&[
1119        (
1120            "last_error",
1121            serde_json::json!(
1122                "PR closed as superseded: the fix already landed on the default branch"
1123            ),
1124        ),
1125        ("pr_number", serde_json::json!(null)),
1126    ])
1127    .await;
1128}
1129
1130/// The PR to close when a merge-conflict reroute produced no commits.
1131///
1132/// `merge_conflict_retries > 0` means review_poll sent the task back to resolve a
1133/// conflict. Coming back with nothing ahead of the default branch means another
1134/// PR already landed the same fix, so the open PR is superseded (#3780)
1135fn superseded_conflict_pr(
1136    merge_conflict_retries: i32,
1137    pr_number: Option<i32>,
1138    has_commits: bool,
1139) -> Option<u64> {
1140    if has_commits || merge_conflict_retries <= 0 {
1141        return None;
1142    }
1143    pr_number
1144        .filter(|n| *n > 0)
1145        .and_then(|n| u64::try_from(n).ok())
1146}
1147
1148/// Read push-failure state from the store and increment `push_failures` if needed.
1149async fn detect_push_failure_state(
1150    ctx: &StoreCtx<'_>,
1151    has_commits: bool,
1152    has_pushed: bool,
1153) -> PushFailureState {
1154    // Load stored task once to inspect last_error (avoid repeated DB reads).
1155    let stored_last_error = ctx
1156        .get_task()
1157        .await
1158        .map(|t| t.last_error)
1159        .unwrap_or_default();
1160
1161    let push_failed = !has_pushed && has_commits && stored_last_error.contains("push failed");
1162
1163    // Detect workflow scope errors — these are non-retryable token permission issues.
1164    // Rerouting to a different agent won't help since the same token is used.
1165    let is_workflow_scope_failure = push_failed
1166        && (stored_last_error.contains("workflow` scope")
1167            || stored_last_error.contains("workflow' scope")
1168            || (stored_last_error.contains("refusing to allow")
1169                && stored_last_error.contains("workflow")));
1170
1171    let is_rebase_conflict_failure =
1172        push_failed && stored_last_error.contains("push failed and rebase failed:");
1173
1174    let is_transient_failure = push_failed
1175        && !is_workflow_scope_failure
1176        && !is_rebase_conflict_failure
1177        && git_ops::is_transient_network_error(&stored_last_error);
1178
1179    // Track push failures — block after 3 consecutive failures.
1180    // Workflow-scope failures are non-retryable and blocked immediately; do not
1181    // increment this retry counter for them so that later normal push failures
1182    // are not prematurely blocked.
1183    let push_failures = if push_failed && !is_workflow_scope_failure && !is_rebase_conflict_failure
1184    {
1185        match ctx.increment("push_failures").await {
1186            Ok(v) => v,
1187            Err(e) => {
1188                tracing::warn!(
1189                    task_id = ctx.task_id,
1190                    err = %e,
1191                    "failed to increment push_failures — reading current value from store"
1192                );
1193                // On DB error, read current value to ensure blocking threshold is still reachable
1194                ctx.get_task()
1195                    .await
1196                    .map_or(1, |t| u64::try_from(t.push_failures).unwrap_or(0) + 1)
1197                // assume at least 1 if we can't read either
1198            }
1199        }
1200    } else {
1201        0
1202    };
1203
1204    PushFailureState {
1205        push_failed,
1206        is_workflow_scope_failure,
1207        is_rebase_conflict_failure,
1208        is_transient_failure,
1209        push_failures,
1210        stored_last_error,
1211    }
1212}
1213
1214/// Increment `no_code_reroutes` and log a warning when the agent completed
1215/// without producing code changes on an external task requiring a PR.
1216async fn detect_no_code_reroutes(
1217    ctx: &StoreCtx<'_>,
1218    is_no_code_reroute: bool,
1219    new_attempts: u32,
1220    max_reroutes: u32,
1221) -> u64 {
1222    if !is_no_code_reroute {
1223        return 0;
1224    }
1225    tracing::warn!(
1226        task_id = ctx.task_id,
1227        attempts = new_attempts,
1228        max_reroutes,
1229        "agent reported done but produced no code changes on external task requiring PR"
1230    );
1231    match ctx.increment("no_code_reroutes").await {
1232        Ok(v) => v,
1233        Err(e) => {
1234            tracing::warn!(
1235                task_id = ctx.task_id,
1236                err = %e,
1237                "failed to increment no_code_reroutes — reading current value from store"
1238            );
1239            // On DB error, read current value to ensure blocking threshold is still reachable
1240            ctx.get_task()
1241                .await
1242                .map_or(1, |t| u64::try_from(t.no_code_reroutes).unwrap_or(0) + 1)
1243            // assume at least 1 if we can't read either
1244        }
1245    }
1246}
1247
1248// ── Post-decision side-effect helpers ─────────────────────────────────────────
1249
1250/// Build a human-readable reason string from a "blocked" agent response.
1251///
1252/// Priority: explicit `error` field → `summary` → fallback.
1253/// Appends `remaining` items if present so operators know what was left to do.
1254fn agent_blocked_reason(resp: &AgentResponse) -> String {
1255    let summary_opt = if resp.summary.is_empty() {
1256        None
1257    } else {
1258        Some(resp.summary.as_str())
1259    };
1260    let base = resp
1261        .error
1262        .as_deref()
1263        .filter(|s| !s.is_empty())
1264        .or(summary_opt)
1265        .unwrap_or("agent returned blocked status without a reason");
1266    if resp.remaining.is_empty() {
1267        base.to_string()
1268    } else {
1269        format!("{base}. Remaining: {}", resp.remaining.join("; "))
1270    }
1271}
1272
1273/// True when a blocked response names a denied `git push` and nothing else as the blocker.
1274fn is_denied_push_block(resp: &AgentResponse) -> bool {
1275    let r = agent_blocked_reason(resp).to_lowercase();
1276    r.contains("push")
1277        && [
1278            "denied",
1279            "not allowed",
1280            "permission",
1281            "disallowed",
1282            "approval",
1283        ]
1284        .iter()
1285        .any(|p| r.contains(p))
1286}
1287
1288/// Heuristic classifier for agent-returned blocked reasons.
1289///
1290/// Returns true when the reason looks transient/retryable (network/provider/
1291/// auth-temporary/environment availability issues), and false for likely
1292/// permanent/input/configuration issues.
1293fn is_retryable_blocked_reason(reason: &str) -> bool {
1294    let r = reason.to_lowercase();
1295
1296    let permanent_patterns = [
1297        "not found",
1298        "does not exist",
1299        "invalid",
1300        "malformed",
1301        "syntax error",
1302        "unsupported",
1303        "unimplemented",
1304        "manual intervention required",
1305        "human intervention required",
1306    ];
1307    if permanent_patterns.iter().any(|p| r.contains(p)) {
1308        return false;
1309    }
1310
1311    let transient_patterns = [
1312        "unavailable",
1313        "temporarily unavailable",
1314        "timeout",
1315        "timed out",
1316        "connection reset",
1317        "connection refused",
1318        "network error",
1319        "rate limit",
1320        "try again",
1321        "service down",
1322        "permission denied",
1323        "worktree lock",
1324        "git lock",
1325        "lockfile permission",
1326        "lock permission",
1327        "resource busy",
1328        "could not resolve host",
1329        // Credential providers in headless/tmux sessions can fail transiently
1330        // when GPG agent/passphrase is unavailable.
1331        "gpg decryption fails",
1332        "gpg decryption failed",
1333        "gpg agent",
1334        "no passphrase available",
1335        "passphrase unavailable",
1336        "pass store",
1337        "passwordstoreprovider",
1338        "agentvaultprovider",
1339        "onepasswordprovider",
1340        "decryption failed in this agent session",
1341    ];
1342    transient_patterns.iter().any(|p| r.contains(p))
1343}
1344
1345/// Apply tracing and store writes that depend on the final status decision.
1346#[expect(
1347    clippy::too_many_arguments,
1348    reason = "the decision and its context arrive as separate values"
1349)]
1350async fn apply_post_decision_effects(
1351    ctx: &StoreCtx<'_>,
1352    final_status: &str,
1353    resp_status: &str,
1354    push_state: &PushFailureState,
1355    is_no_code_reroute: bool,
1356    has_pr: bool,
1357    has_pushed: bool,
1358    is_pr_base_invalid: bool,
1359    has_delegations: bool,
1360    is_external: bool,
1361    no_code_reroutes: u64,
1362    max_reroutes: u32,
1363    agent_name: &str,
1364) {
1365    if push_state.is_workflow_scope_failure {
1366        // Non-retryable — block immediately with actionable guidance.
1367        tracing::error!(
1368            task_id = ctx.task_id,
1369            "push failed: token lacks `workflow` OAuth scope — blocking immediately \
1370             (rerouting would not help)"
1371        );
1372        ctx.set(&[(
1373            "last_error",
1374            serde_json::json!(format!(
1375                "push failed: GitHub token lacks `workflow` OAuth scope. \
1376                 The agent modified .github/workflows/ files but the token cannot push them. \
1377                 Fix: add `workflow` scope to your GitHub token, or use a GitHub App for auth. \
1378                 Original error: {}",
1379                push_state.stored_last_error
1380            )),
1381        )])
1382        .await;
1383    } else if push_state.is_rebase_conflict_failure {
1384        tracing::error!(
1385            task_id = ctx.task_id,
1386            "push failed and automatic rebase recovery failed — blocking for human intervention"
1387        );
1388        ctx.set(&[
1389            ("agent", serde_json::json!(null)),
1390            ("model", serde_json::json!(null)),
1391        ])
1392        .await;
1393    } else if push_state.push_failed && final_status == "needs_review" {
1394        // The engine retries the push from the review gate. Keep agent and model, since the
1395        // task never goes back to the router
1396        tracing::warn!(
1397            task_id = ctx.task_id,
1398            push_failures = push_state.push_failures,
1399            "agent done but push failed on a GitHub or network error — engine retries the push"
1400        );
1401    } else if push_state.push_failed {
1402        // Clear agent and model so router picks a different one on reroute (#1604)
1403        ctx.set(&[
1404            ("agent", serde_json::json!(null)),
1405            ("model", serde_json::json!(null)),
1406        ])
1407        .await;
1408        let push_failures = push_state.push_failures;
1409        if push_failures >= 3 {
1410            tracing::error!(
1411                task_id = ctx.task_id,
1412                push_failures,
1413                "push failed {push_failures} times — blocking for human intervention"
1414            );
1415        } else {
1416            tracing::warn!(
1417                task_id = ctx.task_id,
1418                push_failures,
1419                "agent done but push failed ({push_failures}/3) — rerouting to different agent"
1420            );
1421        }
1422    } else if resp_status == "done" && !has_pr && has_delegations {
1423        tracing::info!(
1424            task_id = ctx.task_id,
1425            "agent reported done with delegations but no PR — setting blocked"
1426        );
1427    } else if (resp_status == "done" || resp_status == "completed")
1428        && !has_pr
1429        && has_pushed
1430        && is_pr_base_invalid
1431    {
1432        tracing::error!(
1433            task_id = ctx.task_id,
1434            "PR creation failed with invalid base branch — blocking for human intervention"
1435        );
1436        ctx.set(&[(
1437            "last_error",
1438            serde_json::json!(
1439                "PR creation failed terminally (invalid base branch or GitHub auth error). The agent's commits were pushed successfully. \
1440                 Check the repository default branch and the GitHub token, then create the PR manually or unblock the task."
1441            ),
1442        )])
1443        .await;
1444    } else if resp_status == "done" && !has_pr && has_pushed {
1445        // Push succeeded but PR creation failed after retries.
1446        tracing::warn!(
1447            task_id = ctx.task_id,
1448            "agent done, commits pushed, but PR creation failed — re-dispatching as routed"
1449        );
1450    } else if is_no_code_reroute {
1451        // Record which agent produced this no-code result so the same-agent
1452        // detection on the next run can prevent loop-backs (#2410, #2686).
1453        // Also clear agent/model to force re-routing.
1454
1455        if final_status == "blocked" {
1456            // final_status is "blocked" either because max_reroutes was exhausted
1457            // or because is_same_agent was detected (both cases are handled by
1458            // classify_final_status). Log accordingly.
1459            let prev_no_code_agent = ctx
1460                .get_task()
1461                .await
1462                .map(|t| t.no_code_last_agent)
1463                .unwrap_or_default();
1464            let is_same_agent = !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name;
1465
1466            let msg = if is_same_agent {
1467                tracing::error!(
1468                    task_id = ctx.task_id,
1469                    agent = %agent_name,
1470                    "blocking same-agent no-code loop: agent {} would be selected again",
1471                    agent_name
1472                );
1473                format!(
1474                    "agent {agent_name} completed without code changes twice — same-agent loop detected, blocking for human review"
1475                )
1476            } else {
1477                tracing::error!(
1478                    task_id = ctx.task_id,
1479                    no_code_reroutes,
1480                    max_reroutes,
1481                    "blocking no-code reroute: reached max reroute attempts ({}/{}) for no-code-result",
1482                    no_code_reroutes,
1483                    max_reroutes
1484                );
1485                format!(
1486                    "agent completed without code changes after {no_code_reroutes}/{max_reroutes} reroute attempts on external task requiring PR"
1487                )
1488            };
1489            ctx.set(&[("last_error", serde_json::json!(msg))]).await;
1490        } else {
1491            // Rerouting — no blocking error to record yet.
1492            ctx.set(&[(
1493                "last_error",
1494                serde_json::json!(
1495                    "agent completed without code changes on external task requiring PR"
1496                ),
1497            )])
1498            .await;
1499        }
1500
1501        // Always record which agent produced this no-code result so the router can
1502        // skip it on the next attempt. Also clear agent/model to force re-routing
1503        // (the router will pick a fresh agent, which will be caught by the same-agent
1504        // check on the next round if it's the same agent).
1505        ctx.set(&[
1506            ("no_code_last_agent", serde_json::json!(agent_name)),
1507            ("agent", serde_json::json!(null)),
1508            ("model", serde_json::json!(null)),
1509        ])
1510        .await;
1511    } else if resp_status == "done" && !has_pr && is_external {
1512        // External task with non-code labels (e.g. documentation, research) —
1513        // allowed to be marked done without a PR.
1514        tracing::info!(
1515            task_id = ctx.task_id,
1516            "external task with non-code labels reported done — marking done without PR"
1517        );
1518    } else if resp_status == "done" && !has_pr {
1519        tracing::info!(
1520            task_id = ctx.task_id,
1521            "internal task reported done with no PR — marking done"
1522        );
1523    }
1524}
1525
1526/// Store token usage if both input and output token counts are known, with the cost the agent
1527/// reported for the run.
1528async fn store_token_usage(
1529    ctx: &StoreCtx<'_>,
1530    input_tokens: Option<u64>,
1531    output_tokens: Option<u64>,
1532    cost_usd: Option<f64>,
1533) {
1534    let (Some(input), Some(output)) = (input_tokens, output_tokens) else {
1535        return;
1536    };
1537    if let Some(st) = ctx.store {
1538        if let Some(store_id) = ctx.store_id_opt {
1539            if let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await {
1540                tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1541            }
1542        } else if let Ok(Some(store_id)) = st.resolve_task_id(ctx.repo, ctx.task_id).await
1543            && let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await
1544        {
1545            tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1546        }
1547    }
1548}
1549
1550/// Handle a successful agent response: commit, push, PR, delegations, tokens.
1551///
1552/// Returns `Ok((status, push_failed))` where `status` is the final task status
1553/// string and `push_failed` is `true` when a push was attempted but failed (for
1554/// audit trail classification).
1555#[expect(
1556    clippy::too_many_arguments,
1557    reason = "the runner passes each part of the run result"
1558)]
1559pub async fn handle_success(
1560    task_id: &str,
1561    parsed: agents::ParsedResponse,
1562    wt: &worktree::WorktreeSetup,
1563    task_title: &str,
1564    agent_name: &str,
1565    model_name: Option<&str>,
1566    new_attempts: u32,
1567    repo: &str,
1568    store: &Option<Arc<TaskStore>>,
1569    raw_stdout: &str,
1570) -> anyhow::Result<(String, bool)> {
1571    // Extract token counts before consuming parsed.
1572    let input_tokens = parsed.input_tokens;
1573    let output_tokens = parsed.output_tokens;
1574    let cost_usd = parsed.cost_usd;
1575    let mut resp = parsed.response;
1576
1577    tracing::info!(
1578        task_id,
1579        status = resp.status,
1580        summary = resp.summary,
1581        "agent completed successfully"
1582    );
1583
1584    let push_denied = resp.status == "blocked" && is_denied_push_block(&resp);
1585
1586    // Resolve numeric store_id once so we can reuse it for multiple store ops
1587    // in this hot path and avoid repeated external_id -> store_id SQL lookups.
1588    let store_id_opt = store::resolve_store_id(store, repo, task_id).await;
1589    let ctx = StoreCtx {
1590        store,
1591        store_id_opt,
1592        repo,
1593        task_id,
1594    };
1595
1596    ctx.reset_retry_streaks().await;
1597
1598    // Auto-commit, push, create PR
1599    let git = if resp.status == "done"
1600        || resp.status == "completed"
1601        || resp.status == "in_progress"
1602        || resp.status == "needs_review"
1603        || push_denied
1604    {
1605        run_git_ops(
1606            &ctx,
1607            wt,
1608            task_title,
1609            &resp,
1610            agent_name,
1611            model_name,
1612            new_attempts,
1613        )
1614        .await
1615    } else {
1616        GitOpsResult::default()
1617    };
1618
1619    // The agent's only blocker was the denied push and orch pushed for it, so
1620    // the task continues as if the agent had returned done
1621    if push_denied && (git.has_pr || git.has_pushed) {
1622        tracing::info!(
1623            task_id,
1624            "agent blocked on denied push, orch pushed the branch"
1625        );
1626        resp.status = "done".to_string();
1627    }
1628
1629    let screenshot_note = if git.has_pr {
1630        post_screenshots(&ctx, &wt.work_dir, &resp).await
1631    } else {
1632        None
1633    };
1634
1635    // Store delegations in store if present (processed by run_with_context)
1636    if !resp.delegations.is_empty() {
1637        ctx.set(&[("delegations", serde_json::json!(resp.delegations))])
1638            .await;
1639    }
1640
1641    // Store result in task store
1642    // If agent said "done" and a PR exists, send to review before merge.
1643    // If agent said "done", pushed commits, but PR creation failed — review gate creates PR.
1644    // If agent said "done", no PR, and no delegations — work is complete
1645    // (e.g., review/analysis jobs that create issues but no code changes).
1646    // If agent said "done", no PR, but has delegations — blocked on children.
1647    let has_delegations = !resp.delegations.is_empty();
1648
1649    // Detect push failure, increment counters.
1650    let push_state = detect_push_failure_state(&ctx, git.has_commits, git.has_pushed).await;
1651
1652    // Determine whether this external task can be marked done without a PR.
1653    // External tasks always require a PR before reaching `done` — unless
1654    // commits were successfully pushed (in which case the `has_pushed` branch
1655    // handles routing). The `is_non_code_task` heuristic was removed because
1656    // it relied on agent output and could be fooled: an agent claiming
1657    // "already implemented" or "config-only" would match non-code keywords
1658    // and close the issue without verification.
1659    let is_external = !task_id.starts_with("internal:");
1660    let requires_pr = is_external && !git.has_pr && !resp.status.starts_with("needs_review");
1661
1662    // Preferred config key `workflow.max_reroute_attempts`; fall back to
1663    // `workflow.max_attempts` for backwards compatibility.
1664    let max_reroutes: u32 = config::get("workflow.max_reroute_attempts")
1665        .ok()
1666        .and_then(|s| s.parse().ok())
1667        .or_else(|| {
1668            config::get("workflow.max_attempts")
1669                .ok()
1670                .and_then(|s| s.parse().ok())
1671        })
1672        .unwrap_or(3);
1673
1674    // Determine whether we are entering the no-code-reroute branch (all
1675    // earlier chain conditions are false + done + requires_pr).
1676    let is_no_code_reroute = !push_state.is_workflow_scope_failure
1677        && !push_state.push_failed
1678        && (resp.status == "done" || resp.status == "completed")
1679        && !has_delegations
1680        && !git.has_pushed
1681        && requires_pr;
1682
1683    // A conflict reroute with nothing ahead of the default branch is a landed
1684    // fix, not a no-code run: close the superseded PR and mark the task done.
1685    let superseded_pr = match (is_no_code_reroute, ctx.get_task().await) {
1686        (true, Some(task)) => {
1687            superseded_conflict_pr(task.merge_conflict_retries, task.pr_number, git.has_commits)
1688        }
1689        _ => None,
1690    };
1691    let is_no_code_reroute = is_no_code_reroute && superseded_pr.is_none();
1692
1693    let no_code_reroutes =
1694        detect_no_code_reroutes(&ctx, is_no_code_reroute, new_attempts, max_reroutes).await;
1695
1696    let blocked_reason = if resp.status == "blocked" {
1697        Some(agent_blocked_reason(&resp))
1698    } else {
1699        None
1700    };
1701    let is_retryable_blocked = blocked_reason
1702        .as_deref()
1703        .is_some_and(is_retryable_blocked_reason);
1704
1705    // ── Detect same-agent loop ───────────────────────────────────────────────
1706    //
1707    // If this is a no-code reroute and the agent is the same as the one that
1708    // produced the previous no-code result, flag it for blocking (#2410, #2686).
1709    let is_same_agent = if is_no_code_reroute {
1710        let prev_no_code_agent = ctx
1711            .get_task()
1712            .await
1713            .map(|t| t.no_code_last_agent)
1714            .unwrap_or_default();
1715        !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name
1716    } else {
1717        false
1718    };
1719
1720    // ── Pure status decision ─────────────────────────────────────────────────
1721
1722    let final_status_owned = classify_final_status(&DecisionInput {
1723        agent_status: &resp.status,
1724        is_workflow_scope_failure: push_state.is_workflow_scope_failure,
1725        is_rebase_conflict_failure: push_state.is_rebase_conflict_failure,
1726        push_failed: push_state.push_failed,
1727        push_failures: push_state.push_failures,
1728        is_transient_push_failure: push_state.is_transient_failure,
1729        has_pr: git.has_pr,
1730        has_delegations,
1731        has_pushed: git.has_pushed,
1732        is_pr_base_invalid: git.pr_base_invalid,
1733        requires_pr,
1734        no_code_reroutes,
1735        max_reroutes,
1736        is_same_agent,
1737        is_completed_status: resp.status == "completed",
1738        is_retryable_blocked,
1739        is_superseded_conflict: superseded_pr.is_some(),
1740    });
1741    let final_status = final_status_owned.as_str();
1742
1743    // ── Post-decision side effects (tracing + store updates) ─────────────────
1744
1745    apply_post_decision_effects(
1746        &ctx,
1747        final_status,
1748        &resp.status,
1749        &push_state,
1750        is_no_code_reroute,
1751        git.has_pr,
1752        git.has_pushed,
1753        git.pr_base_invalid,
1754        has_delegations,
1755        is_external,
1756        no_code_reroutes,
1757        max_reroutes,
1758        agent_name,
1759    )
1760    .await;
1761
1762    // When the agent explicitly returned "blocked", persist its explanation into
1763    // last_error so `orch task get` surfaces the reason without requiring manual
1764    // inspection of task_runs.parsed_response.  The apply_post_decision_effects
1765    // branches above only fire on push/no-code scenarios; a raw agent-blocked
1766    // response falls through all of them and would leave last_error empty.
1767    if resp.status == "blocked" {
1768        let reason = blocked_reason.unwrap_or_else(|| agent_blocked_reason(&resp));
1769        if final_status == "new" {
1770            // Retryable external block: cooldown failed agent/model, clear selection,
1771            // and reroute after backoff instead of permanently blocking.
1772            cooldown::record_agent_failure_with_message(agent_name, &reason).await;
1773            if let Some(m) = model_name {
1774                cooldown::record_model_failure(agent_name, m).await;
1775            }
1776            ctx.set(&[
1777                (
1778                    "last_error",
1779                    serde_json::json!(format!(
1780                        "transient blocker (auto-retry scheduled): {reason}"
1781                    )),
1782                ),
1783                ("agent", serde_json::json!(null)),
1784                ("model", serde_json::json!(null)),
1785            ])
1786            .await;
1787            tracing::warn!(
1788                task_id = ctx.task_id,
1789                reason = %reason,
1790                "agent returned retryable blocked status — rerouting as new with cooldown"
1791            );
1792        } else if final_status == "blocked" {
1793            ctx.set(&[("last_error", serde_json::json!(reason))]).await;
1794        }
1795    }
1796
1797    if let Some(pr_number) = superseded_pr {
1798        tracing::info!(
1799            task_id = ctx.task_id,
1800            pr_number,
1801            "conflict reroute found the fix already on the default branch — closing superseded PR"
1802        );
1803        close_superseded_pr(&ctx, pr_number).await;
1804    }
1805
1806    // The summary reaches the channels, so a missing skill or browser goes with it
1807    let summary = match &screenshot_note {
1808        Some(note) => format!("{}\n\nScreenshots: {note}", resp.summary),
1809        None => resp.summary.clone(),
1810    };
1811    ctx.set(&[("summary", serde_json::json!(summary))]).await;
1812
1813    // Store token usage — prefer agent-parsed tokens, fall back to response
1814    store_token_usage(
1815        &ctx,
1816        input_tokens.or(resp.input_tokens),
1817        output_tokens.or(resp.output_tokens),
1818        cost_usd,
1819    )
1820    .await;
1821
1822    // Store learnings for memory (for future retries)
1823    response::store_learnings_from_response(
1824        task_id,
1825        new_attempts,
1826        agent_name,
1827        model_name,
1828        &resp,
1829        resp.error.as_deref(),
1830        store,
1831        repo,
1832        raw_stdout,
1833    )
1834    .await;
1835
1836    // Note: done → in_review transition is handled by the engine
1837    // after triggering the review agent (engine/mod.rs)
1838    Ok((final_status.to_string(), push_state.push_failed))
1839}
1840
1841/// Labels that indicate a task is non-code and can be marked done without a PR.
1842#[cfg(test)]
1843mod tests {
1844    use std::fs as std_fs;
1845    use std::process::Command;
1846
1847    use super::*;
1848    use crate::store::NewTask;
1849
1850    /// A successful run between timeouts restarts the count, so only timeouts in a row block a task
1851    #[tokio::test]
1852    async fn successful_run_resets_timeout_retries() {
1853        let store = Some(Arc::new(TaskStore::open_memory().await.unwrap()));
1854        let id = store
1855            .as_ref()
1856            .unwrap()
1857            .create_internal("owner/repo", "t", "b", "test", "", None)
1858            .await
1859            .unwrap();
1860        let task_id = format!("internal:{id}");
1861        let ctx = StoreCtx {
1862            store: &store,
1863            store_id_opt: None,
1864            repo: "owner/repo",
1865            task_id: &task_id,
1866        };
1867
1868        ctx.increment("timeout_retries").await.unwrap();
1869        ctx.increment("network_retries").await.unwrap();
1870        ctx.reset_retry_streaks().await;
1871        ctx.increment("timeout_retries").await.unwrap();
1872        ctx.increment("timeout_retries").await.unwrap();
1873
1874        let task = ctx.get_task().await.unwrap();
1875        assert_eq!(task.timeout_retries, 2);
1876        assert_eq!(task.network_retries, 0);
1877        assert_ne!(task.status.as_str(), "blocked");
1878    }
1879
1880    #[test]
1881    fn local_rate_limit_skip_is_detected() {
1882        assert!(is_local_rate_limit_skip(
1883            "GitHub API error: GitHub REST API rate-limited, skipping call for 236s"
1884        ));
1885        assert!(!is_local_rate_limit_skip(
1886            "GitHub API POST failed (502): Bad Gateway"
1887        ));
1888    }
1889
1890    /// Helper: run git in `dir`, panicking on failure
1891    fn git(dir: &Path, args: &[&str]) {
1892        let out = Command::new("git")
1893            .current_dir(dir)
1894            .args(args)
1895            .output()
1896            .unwrap_or_else(|e| panic!("git {args:?} failed to start: {e}"));
1897        assert!(
1898            out.status.success(),
1899            "git {args:?} failed:\nstdout: {}\nstderr: {}",
1900            String::from_utf8_lossy(&out.stdout),
1901            String::from_utf8_lossy(&out.stderr)
1902        );
1903    }
1904
1905    fn init_clone(remote: &Path, dir: &Path) {
1906        git(dir, &["clone", remote.to_str().unwrap(), "."]);
1907        git(dir, &["config", "user.email", "t@t.com"]);
1908        git(dir, &["config", "user.name", "T"]);
1909        git(dir, &["config", "commit.gpgsign", "false"]);
1910    }
1911
1912    #[test]
1913    fn remote_rejected_failure_is_not_diverged() {
1914        let err = "remote: fatal error in commit_refs\n ! [remote rejected] b -> b (failure)";
1915        assert!(!push_error_is_diverged(err));
1916        assert!(push_error_is_diverged("! [rejected] b -> b (fetch first)"));
1917        assert!(push_error_is_diverged(
1918            "! [rejected] b -> b (non-fast-forward)"
1919        ));
1920    }
1921
1922    /**
1923     * Someone rebased the PR branch from another clone and force-pushed it, so orch's
1924     * push is rejected with a stale lease. Pushing is orch's own step: it must rebase
1925     * onto the moved branch and push again, never hand finished work back to the agent
1926     * as a fresh attempt (#3783)
1927     **/
1928    #[tokio::test]
1929    async fn push_rejected_after_remote_rebase_is_pushed_not_rerouted() {
1930        let remote = tempfile::tempdir().unwrap();
1931        git(remote.path(), &["init", "--bare", "-b", "main"]);
1932
1933        // orch's worktree: main, then a feature branch with the task's commit
1934        let work = tempfile::tempdir().unwrap();
1935        init_clone(remote.path(), work.path());
1936        std_fs::write(work.path().join("README.md"), "base").unwrap();
1937        git(work.path(), &["add", "."]);
1938        git(work.path(), &["commit", "-m", "init"]);
1939        git(work.path(), &["push", "origin", "HEAD:main"]);
1940        git(work.path(), &["checkout", "-b", "feat"]);
1941        std_fs::write(work.path().join("fix.txt"), "the fix").unwrap();
1942        git(work.path(), &["add", "."]);
1943        git(work.path(), &["commit", "-m", "apply the fix"]);
1944        git(work.path(), &["push", "-u", "origin", "feat"]);
1945
1946        // Another clone rewrites the same change and force-pushes it
1947        let other = tempfile::tempdir().unwrap();
1948        init_clone(remote.path(), other.path());
1949        git(other.path(), &["checkout", "feat"]);
1950        git(
1951            other.path(),
1952            &["commit", "--amend", "-m", "apply the fix (rebased)"],
1953        );
1954        git(other.path(), &["push", "--force", "origin", "feat"]);
1955
1956        // orch now has an unpushed commit of its own on top of the stale branch
1957        std_fs::write(work.path().join("more.txt"), "follow-up").unwrap();
1958        git(work.path(), &["add", "."]);
1959        git(work.path(), &["commit", "-m", "follow-up"]);
1960
1961        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1962        let store_id = store
1963            .create_internal("owner/repo", "Push recovery", "", "task", "3783", None)
1964            .await
1965            .unwrap();
1966        let task_id = format!("internal:{store_id}");
1967        let store_opt = Some(Arc::clone(&store));
1968        let ctx = StoreCtx {
1969            store: &store_opt,
1970            store_id_opt: Some(store_id),
1971            repo: "owner/repo",
1972            task_id: &task_id,
1973        };
1974
1975        let result =
1976            push_branch_with_log(&ctx, work.path(), "feat", "main", "claude", Some("opus")).await;
1977
1978        assert!(
1979            matches!(result, PushResult::Success),
1980            "orch must land the push itself after adopting the moved remote branch"
1981        );
1982
1983        let task = store.get(store_id).await.unwrap();
1984        assert!(
1985            task.last_error.is_empty(),
1986            "a recovered push must leave no error behind, got: {}",
1987            task.last_error
1988        );
1989        assert_eq!(task.push_failures, 0, "recovery is not a push failure");
1990
1991        // push_branch recovers the stale lease itself, so the log below is the proof: the
1992        // follow-up commit is on the remote, on top of the rebased history
1993        let log = Command::new("git")
1994            .current_dir(work.path())
1995            .args(["log", "--oneline", "origin/feat"])
1996            .output()
1997            .unwrap();
1998        let log = String::from_utf8_lossy(&log.stdout);
1999        assert!(
2000            log.contains("follow-up"),
2001            "remote must carry the task's commit: {log}"
2002        );
2003        assert!(
2004            log.contains("apply the fix (rebased)"),
2005            "orch must adopt the rebased remote history, not re-push its own: {log}"
2006        );
2007        assert!(
2008            !log.contains("apply the fix\n"),
2009            "the superseded commit must not come back: {log}"
2010        );
2011    }
2012
2013    #[test]
2014    fn missing_path_error_detects_io_not_found() {
2015        let err = anyhow::Error::from(io::Error::new(
2016            ErrorKind::NotFound,
2017            "simulated missing path",
2018        ));
2019        assert!(is_missing_path_error(&err));
2020    }
2021
2022    #[test]
2023    fn missing_path_error_detects_message_fallback() {
2024        let err = anyhow::anyhow!("push failed: No such file or directory (os error 2)");
2025        assert!(is_missing_path_error(&err));
2026    }
2027
2028    #[test]
2029    fn superseded_conflict_pr_requires_conflict_reroute_and_no_commits() {
2030        // Conflict reroute, nothing ahead of the default branch → close the PR.
2031        assert_eq!(superseded_conflict_pr(1, Some(42), false), Some(42));
2032        // Commits exist → the agent did work, keep the PR.
2033        assert_eq!(superseded_conflict_pr(1, Some(42), true), None);
2034        // No conflict reroute → an ordinary no-code run.
2035        assert_eq!(superseded_conflict_pr(0, Some(42), false), None);
2036        // No PR to close.
2037        assert_eq!(superseded_conflict_pr(1, None, false), None);
2038    }
2039
2040    /// End-to-end: a conflict reroute that comes back with zero commits ahead of
2041    /// the default branch closes the superseded PR and marks the task done,
2042    /// instead of blocking it as a same-agent no-code loop (#3780).
2043    #[tokio::test]
2044    async fn conflict_reroute_with_no_commits_closes_pr_and_marks_done() {
2045        fn git(dir: &Path, args: &[&str]) {
2046            let ok = Command::new("git")
2047                .args(args)
2048                .current_dir(dir)
2049                .env("GIT_AUTHOR_NAME", "t")
2050                .env("GIT_AUTHOR_EMAIL", "t@example.com")
2051                .env("GIT_COMMITTER_NAME", "t")
2052                .env("GIT_COMMITTER_EMAIL", "t@example.com")
2053                .output()
2054                .expect("git runs")
2055                .status
2056                .success();
2057            assert!(ok, "git {args:?} failed");
2058        }
2059
2060        // A worktree whose branch has nothing ahead of origin/main — the state
2061        // the agent leaves behind when the fix already landed on the base.
2062        let dir = tempfile::tempdir().unwrap();
2063        let origin = dir.path().join("origin.git");
2064        std_fs::create_dir(&origin).unwrap();
2065        git(&origin, &["init", "--bare", "-b", "main"]);
2066        let work_dir = dir.path().join("work");
2067        std_fs::create_dir(&work_dir).unwrap();
2068        git(&work_dir, &["init", "-b", "main"]);
2069        git(
2070            &work_dir,
2071            &["remote", "add", "origin", &origin.display().to_string()],
2072        );
2073        std_fs::write(work_dir.join("a.txt"), "a").unwrap();
2074        git(&work_dir, &["add", "-A"]);
2075        git(&work_dir, &["commit", "-m", "init"]);
2076        git(&work_dir, &["push", "-u", "origin", "main"]);
2077        git(&work_dir, &["checkout", "-b", "fix-branch"]);
2078
2079        let wt = worktree::WorktreeSetup {
2080            work_dir: work_dir.clone(),
2081            branch: "fix-branch".to_string(),
2082            default_branch: "main".to_string(),
2083            main_project_dir: work_dir.clone(),
2084        };
2085
2086        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2087        let store_id = store
2088            .create(&NewTask {
2089                external_id: Some("3772".to_string()),
2090                repo: "owner/repo".to_string(),
2091                origin: "github".to_string(),
2092                title: "Fix the thing".to_string(),
2093                body: String::new(),
2094                source: "manual".to_string(),
2095                source_id: String::new(),
2096                author: "bot".to_string(),
2097                url: String::new(),
2098                labels: vec![],
2099                parent_id: None,
2100            })
2101            .await
2102            .unwrap();
2103        store
2104            .set_fields(store_id, &[("pr_number", serde_json::json!(42))])
2105            .await
2106            .unwrap();
2107        // review_poll rerouted this task to resolve a merge conflict.
2108        store
2109            .increment(store_id, "merge_conflict_retries")
2110            .await
2111            .unwrap();
2112        // A previous no-code run by the same agent — without the superseded
2113        // check this run would block the task as a same-agent loop.
2114        store
2115            .set_fields(
2116                store_id,
2117                &[("no_code_last_agent", serde_json::json!("claude"))],
2118            )
2119            .await
2120            .unwrap();
2121
2122        let parsed = agents::ParsedResponse {
2123            response: AgentResponse {
2124                status: "done".to_string(),
2125                summary: "the fix is already on main".to_string(),
2126                ..Default::default()
2127            },
2128            input_tokens: None,
2129            output_tokens: None,
2130            cost_usd: None,
2131            duration_ms: None,
2132        };
2133
2134        let (final_status, push_failed) = handle_success(
2135            "3772",
2136            parsed,
2137            &wt,
2138            "Fix the thing",
2139            "claude",
2140            Some("sonnet"),
2141            1,
2142            "owner/repo",
2143            &Some(Arc::clone(&store)),
2144            "",
2145        )
2146        .await
2147        .unwrap();
2148
2149        assert_eq!(
2150            final_status, "done",
2151            "a superseded conflict reroute must end done, not blocked"
2152        );
2153        assert!(!push_failed);
2154
2155        let task = store.get(store_id).await.unwrap();
2156        assert!(
2157            task.last_error.contains("superseded"),
2158            "the close attempt must be recorded on the task: {}",
2159            task.last_error
2160        );
2161        assert_eq!(
2162            task.pr_number, None,
2163            "a superseded PR must not stay on the task, the blocker refresh would read it as closed unmerged"
2164        );
2165    }
2166
2167    /// A conflict reroute with zero commits ahead marks the task done instead of
2168    /// blocking it as a same-agent no-code loop (#3780).
2169    #[test]
2170    fn classify_superseded_conflict_marks_done() {
2171        let status = classify_final_status(&DecisionInput {
2172            agent_status: "done",
2173            requires_pr: true,
2174            is_same_agent: true,
2175            is_superseded_conflict: true,
2176            ..Default::default()
2177        });
2178        assert_eq!(status, "done");
2179    }
2180
2181    // ── classify_final_status — one test per decision branch ─────────────────
2182
2183    /// Branch 1: workflow-scope push failure → block immediately (non-retryable).
2184    #[test]
2185    fn classify_workflow_scope_failure_blocks() {
2186        let status = classify_final_status(&DecisionInput {
2187            is_workflow_scope_failure: true,
2188            push_failed: true,
2189            push_failures: 1,
2190            ..Default::default()
2191        });
2192        assert_eq!(status, "blocked");
2193    }
2194
2195    /// Branch 1b: automatic rebase recovery failed (conflicts) → block immediately.
2196    #[test]
2197    fn classify_rebase_conflict_failure_blocks() {
2198        let status = classify_final_status(&DecisionInput {
2199            is_rebase_conflict_failure: true,
2200            push_failed: true,
2201            ..Default::default()
2202        });
2203        assert_eq!(status, "blocked");
2204    }
2205
2206    /// Branch 2a: push failed, < 3 times → reroute with "new".
2207    #[test]
2208    fn classify_push_failed_under_threshold_reroutes() {
2209        let status = classify_final_status(&DecisionInput {
2210            push_failed: true,
2211            push_failures: 2, // < 3
2212            ..Default::default()
2213        });
2214        assert_eq!(status, "new");
2215    }
2216
2217    #[test]
2218    fn denied_push_block_detected() {
2219        let resp = |s: &str| AgentResponse {
2220            status: "blocked".to_string(),
2221            summary: s.to_string(),
2222            ..Default::default()
2223        };
2224        assert!(is_denied_push_block(&resp(
2225            "Work committed, but `git push -u origin HEAD` was denied"
2226        )));
2227        assert!(is_denied_push_block(&resp(
2228            "It is not pushed: `git push --force-with-lease` needs approval that this session could not get."
2229        )));
2230        assert!(is_denied_push_block(&resp(
2231            "`git push --force-with-lease` was denied because this session cannot get approval"
2232        )));
2233        assert!(is_denied_push_block(&resp("The push requires approval")));
2234        assert!(!is_denied_push_block(&resp("Missing API key")));
2235    }
2236
2237    /// Branch 2b: push failed >= 3 times → block for human intervention.
2238    #[test]
2239    fn classify_push_failed_at_threshold_blocks() {
2240        let status = classify_final_status(&DecisionInput {
2241            push_failed: true,
2242            push_failures: 3, // >= 3
2243            ..Default::default()
2244        });
2245        assert_eq!(status, "blocked");
2246    }
2247
2248    /// A GitHub-side push failure never reaches the router, the engine retries the push (#4025).
2249    #[test]
2250    fn classify_transient_push_failure_waits_for_the_engine_retry() {
2251        for push_failures in 1..push_retry::MAX_PUSH_FAILURES {
2252            let status = classify_final_status(&DecisionInput {
2253                push_failed: true,
2254                is_transient_push_failure: true,
2255                push_failures,
2256                ..Default::default()
2257            });
2258            assert_eq!(status, "needs_review", "push_failures={push_failures}");
2259        }
2260    }
2261
2262    #[test]
2263    fn classify_transient_push_failure_blocks_after_the_last_retry() {
2264        let status = classify_final_status(&DecisionInput {
2265            push_failed: true,
2266            is_transient_push_failure: true,
2267            push_failures: push_retry::MAX_PUSH_FAILURES,
2268            ..Default::default()
2269        });
2270        assert_eq!(status, "blocked");
2271    }
2272
2273    /// Branch 3: done + PR exists → send to review.
2274    #[test]
2275    fn classify_done_with_pr_goes_to_needs_review() {
2276        let status = classify_final_status(&DecisionInput {
2277            agent_status: "done",
2278            has_pr: true,
2279            ..Default::default()
2280        });
2281        assert_eq!(status, "needs_review");
2282    }
2283
2284    /// Branch 4: done + delegations, no PR → block (waiting on child tasks).
2285    #[test]
2286    fn classify_done_with_delegations_no_pr_blocks() {
2287        let status = classify_final_status(&DecisionInput {
2288            agent_status: "done",
2289            has_delegations: true,
2290            ..Default::default()
2291        });
2292        assert_eq!(status, "blocked");
2293    }
2294
2295    /// Branch 5: done + commits pushed but PR creation failed → re-dispatch.
2296    #[test]
2297    fn classify_done_pushed_no_pr_reroutes_for_pr_creation() {
2298        let status = classify_final_status(&DecisionInput {
2299            agent_status: "done",
2300            has_pushed: true,
2301            ..Default::default()
2302        });
2303        assert_eq!(status, "routed");
2304    }
2305
2306    /// Branch 5b: done + pushed + PR base invalid → block (terminal error).
2307    #[test]
2308    fn classify_done_pushed_pr_base_invalid_blocks() {
2309        let status = classify_final_status(&DecisionInput {
2310            agent_status: "done",
2311            has_pushed: true,
2312            is_pr_base_invalid: true,
2313            ..Default::default()
2314        });
2315        assert_eq!(status, "blocked");
2316    }
2317
2318    /// Branch 5c: completed + pushed + PR base invalid → block (terminal error).
2319    #[test]
2320    fn classify_completed_pushed_pr_base_invalid_blocks() {
2321        let status = classify_final_status(&DecisionInput {
2322            agent_status: "completed",
2323            is_completed_status: true,
2324            has_pushed: true,
2325            is_pr_base_invalid: true,
2326            ..Default::default()
2327        });
2328        assert_eq!(status, "blocked");
2329    }
2330
2331    /// Branch 6a: done + requires_pr, under max reroutes → reroute.
2332    #[test]
2333    fn classify_done_requires_pr_under_max_reroutes() {
2334        let status = classify_final_status(&DecisionInput {
2335            agent_status: "done",
2336            requires_pr: true,
2337            no_code_reroutes: 1,
2338            max_reroutes: 3,
2339            is_same_agent: false,
2340            ..Default::default()
2341        });
2342        assert_eq!(status, "new");
2343    }
2344
2345    /// Branch 6a edge: same agent on no-code reroute → block immediately.
2346    #[test]
2347    fn classify_done_requires_pr_same_agent_blocks_immediately() {
2348        let status = classify_final_status(&DecisionInput {
2349            agent_status: "done",
2350            requires_pr: true,
2351            no_code_reroutes: 1,
2352            max_reroutes: 3,
2353            is_same_agent: true, // Same agent would be selected again
2354            ..Default::default()
2355        });
2356        assert_eq!(status, "blocked");
2357    }
2358
2359    /// Branch 6b: done + requires_pr, at max reroutes → block.
2360    #[test]
2361    fn classify_done_requires_pr_at_max_reroutes_blocks() {
2362        let status = classify_final_status(&DecisionInput {
2363            agent_status: "done",
2364            requires_pr: true,
2365            no_code_reroutes: 3,
2366            max_reroutes: 3,
2367            is_same_agent: false,
2368            ..Default::default()
2369        });
2370        assert_eq!(status, "blocked");
2371    }
2372
2373    /// Branch 6b edge: exceeding max also blocks.
2374    #[test]
2375    fn classify_done_requires_pr_exceeds_max_reroutes_blocks() {
2376        let status = classify_final_status(&DecisionInput {
2377            agent_status: "done",
2378            requires_pr: true,
2379            no_code_reroutes: 5,
2380            max_reroutes: 3,
2381            is_same_agent: false,
2382            ..Default::default()
2383        });
2384        assert_eq!(status, "blocked");
2385    }
2386
2387    /// Same agent on external task requiring PR → block immediately (not wait for max).
2388    #[test]
2389    fn classify_done_external_no_pushed_same_agent_blocks_immediately() {
2390        let status = classify_final_status(&DecisionInput {
2391            agent_status: "done",
2392            requires_pr: true, // always true for external tasks with !has_pr + done
2393            no_code_reroutes: 0,
2394            max_reroutes: 3,
2395            is_same_agent: true,
2396            ..Default::default()
2397        });
2398        assert_eq!(status, "blocked");
2399    }
2400
2401    /// External task with no pushed commits: reroute (agent must produce commits
2402    /// before the issue can be closed). This was the source of issue #1898 — an
2403    /// agent claiming "already implemented" without any code changes would
2404    /// previously match non-code keywords and close the issue falsely.
2405    ///
2406    /// External tasks with done+!has_pr+!has_pushed always have requires_pr=true
2407    /// (see handle_success), so they are caught by branch 6, not branch 7.
2408    #[test]
2409    fn classify_done_external_no_pushed_commits_reroutes() {
2410        let status = classify_final_status(&DecisionInput {
2411            agent_status: "done",
2412            has_pushed: false,
2413            requires_pr: true, // always true for external tasks with !has_pr + done
2414            no_code_reroutes: 0,
2415            max_reroutes: 3,
2416            is_same_agent: false,
2417            ..Default::default()
2418        });
2419        assert_eq!(status, "new");
2420    }
2421
2422    /// Internal task with no pushed commits may still be marked done — internal
2423    /// tasks may produce no git-visible changes.
2424    #[test]
2425    fn classify_done_internal_task_no_pr_is_done() {
2426        let status = classify_final_status(&DecisionInput {
2427            agent_status: "done",
2428            has_pushed: false,
2429            requires_pr: false,
2430            ..Default::default()
2431        });
2432        assert_eq!(status, "done");
2433    }
2434
2435    /// Pass-through: non-"done" status is returned unchanged.
2436    #[test]
2437    fn classify_non_done_status_passes_through() {
2438        for status_str in &["in_progress", "needs_review", "blocked"] {
2439            let result = classify_final_status(&DecisionInput {
2440                agent_status: status_str,
2441                ..Default::default()
2442            });
2443            assert_eq!(
2444                result, *status_str,
2445                "status '{status_str}' should pass through unchanged"
2446            );
2447        }
2448    }
2449
2450    /// Descriptive completion text should normalize to done.
2451    #[test]
2452    fn classify_descriptive_completion_status_normalizes_to_done() {
2453        let status = classify_final_status(&DecisionInput {
2454            agent_status: "Trading scan complete. Nothing to trade.",
2455            ..Default::default()
2456        });
2457        assert_eq!(status, "done");
2458    }
2459
2460    /// Do not normalize to done when completion-like text includes failure cues.
2461    #[test]
2462    fn classify_descriptive_completion_with_failure_cues_does_not_normalize() {
2463        let status = classify_final_status(&DecisionInput {
2464            agent_status: "completed but failed to push branch due to error",
2465            ..Default::default()
2466        });
2467        assert_eq!(status, "completed but failed to push branch due to error");
2468    }
2469
2470    /// push_failed takes precedence over done+has_pr (push failure detected first).
2471    #[test]
2472    fn classify_push_failed_takes_precedence_over_has_pr() {
2473        let status = classify_final_status(&DecisionInput {
2474            agent_status: "done",
2475            has_pr: true,
2476            push_failed: true,
2477            push_failures: 1,
2478            ..Default::default()
2479        });
2480        // push_failed branch runs before done+has_pr check
2481        assert_eq!(status, "new");
2482    }
2483
2484    /// workflow_scope_failure takes precedence over push_failed < 3.
2485    #[test]
2486    fn classify_workflow_scope_failure_takes_precedence_over_push_reroute() {
2487        let status = classify_final_status(&DecisionInput {
2488            is_workflow_scope_failure: true,
2489            push_failed: true,
2490            push_failures: 1, // would normally reroute
2491            ..Default::default()
2492        });
2493        assert_eq!(status, "blocked");
2494    }
2495
2496    // ── "completed" status tests ────────────────────────────────────────────────
2497
2498    /// "completed" + has_pr → needs_review.
2499    #[test]
2500    fn classify_completed_with_pr_goes_to_needs_review() {
2501        let status = classify_final_status(&DecisionInput {
2502            agent_status: "completed",
2503            has_pr: true,
2504            is_completed_status: true,
2505            ..Default::default()
2506        });
2507        assert_eq!(status, "needs_review");
2508    }
2509
2510    /// "completed" + delegations, no PR → blocked.
2511    #[test]
2512    fn classify_completed_with_delegations_no_pr_blocks() {
2513        let status = classify_final_status(&DecisionInput {
2514            agent_status: "completed",
2515            has_delegations: true,
2516            is_completed_status: true,
2517            ..Default::default()
2518        });
2519        assert_eq!(status, "blocked");
2520    }
2521
2522    /// "completed" + pushed, no PR → routed for PR creation.
2523    #[test]
2524    fn classify_completed_pushed_no_pr_reroutes_for_pr_creation() {
2525        let status = classify_final_status(&DecisionInput {
2526            agent_status: "completed",
2527            has_pushed: true,
2528            is_completed_status: true,
2529            ..Default::default()
2530        });
2531        assert_eq!(status, "routed");
2532    }
2533
2534    /// "completed" + external task requiring PR, under max reroutes → reroute.
2535    #[test]
2536    fn classify_completed_requires_pr_under_max_reroutes() {
2537        let status = classify_final_status(&DecisionInput {
2538            agent_status: "completed",
2539            requires_pr: true,
2540            no_code_reroutes: 1,
2541            max_reroutes: 3,
2542            is_completed_status: true,
2543            is_same_agent: false,
2544            ..Default::default()
2545        });
2546        assert_eq!(status, "new");
2547    }
2548
2549    /// "completed" + external task, at max reroutes → block.
2550    #[test]
2551    fn classify_completed_requires_pr_at_max_reroutes_blocks() {
2552        let status = classify_final_status(&DecisionInput {
2553            agent_status: "completed",
2554            requires_pr: true,
2555            no_code_reroutes: 3,
2556            max_reroutes: 3,
2557            is_completed_status: true,
2558            is_same_agent: false,
2559            ..Default::default()
2560        });
2561        assert_eq!(status, "blocked");
2562    }
2563
2564    /// "completed" + external task, same agent on no-code reroute → block immediately.
2565    #[test]
2566    fn classify_completed_same_agent_blocks_immediately() {
2567        let status = classify_final_status(&DecisionInput {
2568            agent_status: "completed",
2569            requires_pr: true,
2570            no_code_reroutes: 1,
2571            max_reroutes: 3,
2572            is_completed_status: true,
2573            is_same_agent: true,
2574            ..Default::default()
2575        });
2576        assert_eq!(status, "blocked");
2577    }
2578
2579    /// "completed" on internal task (no requires_pr) → mark done.
2580    #[test]
2581    fn classify_completed_internal_task_is_done() {
2582        let status = classify_final_status(&DecisionInput {
2583            agent_status: "completed",
2584            requires_pr: false,
2585            is_completed_status: true,
2586            ..Default::default()
2587        });
2588        assert_eq!(status, "done");
2589    }
2590
2591    // ── agent_blocked_reason — regression tests for issue #3012 ──────────────
2592
2593    /// Agent explicitly returned blocked with an error field — use error as reason.
2594    #[test]
2595    fn agent_blocked_reason_prefers_error_field() {
2596        let resp = AgentResponse {
2597            status: "blocked".to_string(),
2598            error: Some("CDP endpoint not reachable".to_string()),
2599            summary: "Could not complete research".to_string(),
2600            remaining: vec!["Run x-twitter-brave with reachable endpoint".to_string()],
2601            ..Default::default()
2602        };
2603        let reason = agent_blocked_reason(&resp);
2604        assert!(
2605            reason.contains("CDP endpoint not reachable"),
2606            "reason: {reason}"
2607        );
2608        assert!(reason.contains("Remaining:"), "reason: {reason}");
2609        assert!(reason.contains("x-twitter-brave"), "reason: {reason}");
2610    }
2611
2612    /// No error field — falls back to summary.
2613    #[test]
2614    fn agent_blocked_reason_falls_back_to_summary() {
2615        let resp = AgentResponse {
2616            status: "blocked".to_string(),
2617            error: None,
2618            summary: "Could not access required data sources in sandboxed environment".to_string(),
2619            remaining: vec![],
2620            ..Default::default()
2621        };
2622        let reason = agent_blocked_reason(&resp);
2623        assert_eq!(
2624            reason,
2625            "Could not access required data sources in sandboxed environment"
2626        );
2627    }
2628
2629    /// No error or summary — returns generic fallback.
2630    #[test]
2631    fn agent_blocked_reason_generic_fallback() {
2632        let resp = AgentResponse {
2633            status: "blocked".to_string(),
2634            ..Default::default()
2635        };
2636        let reason = agent_blocked_reason(&resp);
2637        assert_eq!(reason, "agent returned blocked status without a reason");
2638    }
2639
2640    /// Agent-returned "blocked" status passes through classify_final_status unchanged.
2641    #[test]
2642    fn classify_agent_blocked_passes_through() {
2643        let status = classify_final_status(&DecisionInput {
2644            agent_status: "blocked",
2645            ..Default::default()
2646        });
2647        assert_eq!(status, "blocked");
2648    }
2649
2650    #[test]
2651    fn classify_retryable_agent_blocked_reroutes() {
2652        let status = classify_final_status(&DecisionInput {
2653            agent_status: "blocked",
2654            is_retryable_blocked: true,
2655            ..Default::default()
2656        });
2657        assert_eq!(status, "new");
2658    }
2659
2660    #[test]
2661    fn retryable_blocked_reason_detects_transient_patterns() {
2662        assert!(is_retryable_blocked_reason(
2663            "Twitter access unavailable: service timed out"
2664        ));
2665        assert!(is_retryable_blocked_reason(
2666            "final commit blocked by git worktree lock permission error"
2667        ));
2668        assert!(is_retryable_blocked_reason(
2669            "could not commit due a worktree git lock permission error"
2670        ));
2671        assert!(is_retryable_blocked_reason(
2672            "git lockfile permission restrictions in this environment"
2673        ));
2674        assert!(is_retryable_blocked_reason(
2675            "API rate limit hit, try again later"
2676        ));
2677        assert!(is_retryable_blocked_reason(
2678            "Credential bean/hyperliquid-address exists in the pass store but GPG decryption fails in this agent session — no passphrase available."
2679        ));
2680        assert!(is_retryable_blocked_reason(
2681            "credential resolution failed via PasswordStoreProvider; AgentVaultProvider unavailable"
2682        ));
2683    }
2684
2685    #[test]
2686    fn retryable_blocked_reason_rejects_permanent_patterns() {
2687        assert!(!is_retryable_blocked_reason(
2688            "invalid request payload: malformed JSON"
2689        ));
2690        assert!(!is_retryable_blocked_reason(
2691            "resource not found in repository"
2692        ));
2693    }
2694}