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