1use crate::engine::git::commit;
8use crate::github::types::parse_pr_number_from_url;
9
10use crate::config;
11use crate::parser::AgentResponse;
12use crate::store;
13use crate::store::TaskStore;
14use std::io;
15use std::io::ErrorKind;
16use std::path::Path;
17use std::sync::Arc;
18
19use tokio::fs;
20
21use super::response;
22use crate::cooldown;
23use crate::engine::agents;
24use crate::engine::git::git_ops;
25use crate::engine::git::screenshots;
26use crate::engine::git::worktree;
27use crate::engine::push_retry;
28use crate::github::http::GhHttp;
29use crate::status_heuristics;
30use crate::store::Task;
31
32#[expect(
34 clippy::too_many_arguments,
35 reason = "each field of result.json is a separate argument"
36)]
37pub async fn write_result_json(
38 attempt_dir: &Path,
39 task_id: &str,
40 agent_name: &str,
41 model_name: Option<&str>,
42 exit_code: i32,
43 new_attempts: u32,
44 parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
45 raw_stdout: &str,
46 raw_stderr: &str,
47) {
48 let result_json = match parse_result {
49 Ok(parsed) => {
50 serde_json::json!({
51 "outcome": "success",
52 "agent": agent_name,
53 "model": model_name.unwrap_or("default"),
54 "exit_code": exit_code,
55 "attempt": new_attempts,
56 "status": parsed.response.status,
57 "summary": parsed.response.summary,
58 "input_tokens": parsed.input_tokens,
59 "output_tokens": parsed.output_tokens,
60 "duration_ms": parsed.duration_ms,
61 "files": parsed.response.files,
62 "accomplished": parsed.response.accomplished,
63 "remaining": parsed.response.remaining,
64 "error": parsed.response.error,
65 "learnings": parsed.response.learnings,
66 "delegations": parsed.response.delegations.iter()
67 .map(|d| serde_json::json!({"title": d.title, "body": d.body}))
68 .collect::<Vec<_>>(),
69 })
70 }
71 Err(agent_err) => {
72 serde_json::json!({
73 "outcome": "error",
74 "agent": agent_name,
75 "model": model_name.unwrap_or("default"),
76 "exit_code": exit_code,
77 "attempt": new_attempts,
78 "error_class": agents::error_class_name(agent_err),
79 "error_message": agent_err.to_string(),
80 "stderr_tail": agents::patterns::safe_tail(raw_stderr, 2000),
81 "stdout_tail": agents::patterns::safe_tail(raw_stdout, 2000),
82 })
83 }
84 };
85
86 if let Err(e) = fs::write(
87 attempt_dir.join("result.json"),
88 serde_json::to_string_pretty(&result_json).unwrap_or_default(),
89 )
90 .await
91 {
92 tracing::debug!(task_id, ?e, "failed to write result.json");
93 }
94}
95
96#[derive(Default)]
102#[expect(
103 clippy::struct_excessive_bools,
104 reason = "each flag is an independent input to the status decision"
105)]
106struct DecisionInput<'a> {
107 agent_status: &'a str,
109 is_workflow_scope_failure: bool,
112 is_rebase_conflict_failure: bool,
115 push_failed: bool,
117 push_failures: u64,
120 is_transient_push_failure: bool,
123 has_pr: bool,
125 has_delegations: bool,
127 has_pushed: bool,
129 is_pr_base_invalid: bool,
133 requires_pr: bool,
136 no_code_reroutes: u64,
138 max_reroutes: u32,
140 is_same_agent: bool,
143 is_completed_status: bool,
148 is_retryable_blocked: bool,
150 is_superseded_conflict: bool,
154}
155
156fn classify_final_status(input: &DecisionInput<'_>) -> String {
163 if input.is_workflow_scope_failure || input.is_rebase_conflict_failure {
164 "blocked".to_string()
165 } else if input.push_failed {
166 if input.is_transient_push_failure && input.push_failures < push_retry::MAX_PUSH_FAILURES {
167 "needs_review".to_string()
168 } else if input.push_failures >= 3 {
169 "blocked".to_string()
170 } else {
171 "new".to_string()
172 }
173 } else if input.agent_status == "done" && input.has_pr {
174 "needs_review".to_string()
175 } else if input.agent_status == "done" && !input.has_pr && input.has_delegations {
176 "blocked".to_string()
177 } else if input.agent_status == "done"
178 && !input.has_pr
179 && input.has_pushed
180 && input.is_pr_base_invalid
181 {
182 "blocked".to_string()
186 } else if input.agent_status == "done" && !input.has_pr && input.has_pushed {
187 "routed".to_string()
188 } else if input.is_superseded_conflict {
189 "done".to_string()
190 } else if input.agent_status == "done" && input.requires_pr {
191 if input.is_same_agent || input.no_code_reroutes >= u64::from(input.max_reroutes) {
195 "blocked".to_string()
196 } else {
197 "new".to_string()
198 }
199 } else if input.agent_status == "done" && !input.has_pushed {
200 "done".to_string()
205 } else if input.is_completed_status && input.has_pr {
206 "needs_review".to_string()
208 } else if input.is_completed_status && !input.has_pr && input.has_delegations {
209 "blocked".to_string()
211 } else if input.is_completed_status
212 && !input.has_pr
213 && input.has_pushed
214 && input.is_pr_base_invalid
215 {
216 "blocked".to_string()
217 } else if input.is_completed_status && !input.has_pr && input.has_pushed {
218 "routed".to_string()
220 } else if input.is_completed_status && input.requires_pr {
221 if input.is_same_agent || input.no_code_reroutes >= u64::from(input.max_reroutes) {
224 "blocked".to_string()
225 } else {
226 "new".to_string()
227 }
228 } else if input.is_completed_status {
229 "done".to_string()
233 } else if input.agent_status == "blocked" && input.is_retryable_blocked {
234 "new".to_string()
235 } else if status_heuristics::status_looks_like_descriptive_completion(input.agent_status) {
236 "done".to_string()
237 } else {
238 input.agent_status.to_string()
239 }
240}
241
242struct StoreCtx<'a> {
246 store: &'a Option<Arc<TaskStore>>,
247 store_id_opt: Option<i64>,
248 repo: &'a str,
249 task_id: &'a str,
250}
251
252impl StoreCtx<'_> {
253 async fn set(&self, fields: &[(&str, serde_json::Value)]) {
255 if let Some(store_id) = self.store_id_opt {
256 let _ = store::store_set_by_id(self.store.as_ref(), store_id, fields).await;
257 } else {
258 store::store_set(self.store, self.repo, self.task_id, fields).await;
259 }
260 }
261
262 async fn reset_retry_streaks(&self) {
264 self.set(&[
265 ("network_retries", serde_json::json!(0)),
266 ("timeout_retries", serde_json::json!(0)),
267 ])
268 .await;
269 }
270
271 async fn get_task(&self) -> Option<Task> {
273 if let Some(store_id) = self.store_id_opt {
274 store::opt_store_get_task_by_id(self.store, store_id).await
275 } else {
276 store::opt_store_get_task(self.store, self.repo, self.task_id).await
277 }
278 }
279
280 async fn increment(&self, field: &str) -> anyhow::Result<u64> {
282 if let Some(store_id) = self.store_id_opt {
283 store::store_increment_by_id(self.store, store_id, field).await
284 } else {
285 store::store_increment(self.store, self.repo, self.task_id, field).await
286 }
287 }
288
289 async fn append_activity(
291 &self,
292 event_type: &str,
293 agent: Option<&str>,
294 model: Option<&str>,
295 details: Option<&serde_json::Value>,
296 ) {
297 if let Some(store_id) = self.store_id_opt {
298 if let Some(s) = self.store
299 && let Err(e) = s
300 .append_activity(store_id, event_type, None, None, agent, model, details)
301 .await
302 {
303 tracing::warn!(
304 task_id = self.task_id,
305 event_type,
306 error = %e,
307 "store append_activity failed"
308 );
309 }
310 } else {
311 store::store_log_activity(
312 self.store,
313 self.repo,
314 self.task_id,
315 event_type,
316 None,
317 None,
318 agent,
319 model,
320 details,
321 )
322 .await;
323 }
324 }
325}
326
327#[derive(Default)]
331#[expect(
332 clippy::struct_excessive_bools,
333 reason = "each flag is an independent outcome of the git pipeline"
334)]
335struct GitOpsResult {
336 has_pr: bool,
337 has_pushed: bool,
338 has_commits: bool,
339 pr_base_invalid: bool,
343}
344
345#[expect(
347 clippy::struct_excessive_bools,
348 reason = "each flag is an independent kind of push failure"
349)]
350struct PushFailureState {
351 push_failed: bool,
352 is_workflow_scope_failure: bool,
353 is_rebase_conflict_failure: bool,
354 is_transient_failure: bool,
356 push_failures: u64,
358 stored_last_error: String,
360}
361
362async fn auto_commit_changes(
366 ctx: &StoreCtx<'_>,
367 work_dir: &Path,
368 task_title: &str,
369 agent_name: &str,
370 new_attempts: u32,
371) {
372 if let Err(e) = git_ops::auto_commit(
373 work_dir,
374 ctx.task_id,
375 task_title,
376 agent_name,
377 new_attempts,
378 commit::When::Always,
379 )
380 .await
381 {
382 tracing::error!(task_id = ctx.task_id, error = ?e, "auto commit failed");
383 ctx.set(&[(
384 "last_error",
385 serde_json::json!(format!("auto commit failed: {e}")),
386 )])
387 .await;
388 }
389}
390
391async fn check_commits_and_clear_stale_errors(
396 ctx: &StoreCtx<'_>,
397 work_dir: &Path,
398 default_branch: &str,
399) -> bool {
400 let has_commits = git_ops::has_commits_ahead(work_dir, default_branch).await;
401 if !has_commits {
402 tracing::info!(
403 task_id = ctx.task_id,
404 "no commits ahead of default branch, skipping push + PR"
405 );
406 let last_err = ctx
408 .get_task()
409 .await
410 .map(|t| t.last_error)
411 .unwrap_or_default();
412 if last_err.contains("push failed") {
413 ctx.set(&[("last_error", serde_json::json!(""))]).await;
414 }
415 }
416 has_commits
417}
418
419enum PushResult {
429 Success,
430 Failed,
431 Skipped, NoCommits, WorktreeMissing, }
435
436fn is_missing_path_error(err: &anyhow::Error) -> bool {
437 err.chain().any(|cause| {
438 cause
439 .downcast_ref::<io::Error>()
440 .is_some_and(|ioe| ioe.kind() == ErrorKind::NotFound)
441 }) || err
442 .to_string()
443 .to_ascii_lowercase()
444 .contains("no such file or directory")
445}
446
447async fn recover_missing_worktree_for_push(
448 ctx: &StoreCtx<'_>,
449 wt: &worktree::WorktreeSetup,
450 task_title: &str,
451 agent_name: &str,
452 model_name: Option<&str>,
453) -> anyhow::Result<worktree::WorktreeSetup> {
454 tracing::warn!(
455 task_id = ctx.task_id,
456 worktree = %wt.work_dir.display(),
457 branch = wt.branch,
458 "worktree missing during push; attempting one-time recovery"
459 );
460 ctx.append_activity(
461 "push_recover_worktree",
462 Some(agent_name),
463 model_name,
464 Some(&serde_json::json!({
465 "status": "start",
466 "worktree": wt.work_dir.display().to_string(),
467 "branch": wt.branch,
468 })),
469 )
470 .await;
471
472 let recovered = worktree::setup_worktree(
473 ctx.task_id,
474 task_title,
475 &wt.main_project_dir,
476 ctx.store,
477 ctx.repo,
478 )
479 .await?;
480
481 if !recovered.work_dir.exists() {
482 anyhow::bail!(
483 "recovered worktree path is still missing: {}",
484 recovered.work_dir.display()
485 );
486 }
487
488 ctx.append_activity(
489 "push_recover_worktree",
490 Some(agent_name),
491 model_name,
492 Some(&serde_json::json!({
493 "status": "ok",
494 "worktree": recovered.work_dir.display().to_string(),
495 "branch": recovered.branch,
496 })),
497 )
498 .await;
499
500 Ok(recovered)
501}
502
503async fn push_after_rebase(
508 ctx: &StoreCtx<'_>,
509 work_dir: &Path,
510 branch: &str,
511 default_branch: &str,
512 agent_name: &str,
513 model_name: Option<&str>,
514) -> PushResult {
515 match git_ops::push_branch(work_dir, branch, default_branch).await {
516 Ok(true) => {
517 ctx.append_activity(
518 "push",
519 Some(agent_name),
520 model_name,
521 Some(&serde_json::json!({
522 "status": "ok",
523 "branch": branch,
524 "default_branch": default_branch,
525 "reason": "pushed_after_rebase",
526 })),
527 )
528 .await;
529 ctx.set(&[
530 ("last_error", serde_json::json!("")),
531 ("push_failures", serde_json::json!(0)),
532 ])
533 .await;
534 PushResult::Success
535 }
536 Ok(false) => {
537 tracing::info!(
538 task_id = ctx.task_id,
539 branch,
540 default_branch,
541 "push skipped after rebase"
542 );
543 ctx.append_activity(
544 "push",
545 Some(agent_name),
546 model_name,
547 Some(&serde_json::json!({
548 "status": "skipped",
549 "branch": branch,
550 "default_branch": default_branch,
551 "reason": "pushed_after_rebase",
552 })),
553 )
554 .await;
555 PushResult::Skipped
556 }
557 Err(e) => {
558 tracing::error!(
559 task_id = ctx.task_id,
560 branch = branch,
561 error = ?e,
562 "push failed again after rebasing on the remote branch"
563 );
564 ctx.append_activity(
565 "push",
566 Some(agent_name),
567 model_name,
568 Some(&serde_json::json!({
569 "status": "error",
570 "branch": branch,
571 "default_branch": default_branch,
572 "reason": "pushed_after_rebase",
573 "error": e.to_string(),
574 })),
575 )
576 .await;
577 ctx.set(&[(
578 "last_error",
579 serde_json::json!(format!("push failed after rebase on remote branch: {e}")),
580 )])
581 .await;
582 PushResult::Failed
583 }
584 }
585}
586
587async fn push_branch_with_log(
588 ctx: &StoreCtx<'_>,
589 work_dir: &Path,
590 branch: &str,
591 default_branch: &str,
592 agent_name: &str,
593 model_name: Option<&str>,
594) -> PushResult {
595 match git_ops::push_branch(work_dir, branch, default_branch).await {
596 Ok(true) => {
597 ctx.append_activity(
598 "push",
599 Some(agent_name),
600 model_name,
601 Some(&serde_json::json!({
602 "status": "ok",
603 "branch": branch,
604 "default_branch": default_branch,
605 })),
606 )
607 .await;
608 ctx.set(&[
611 ("last_error", serde_json::json!("")),
612 ("push_failures", serde_json::json!(0)),
613 ])
614 .await;
615 PushResult::Success
616 }
617 Ok(false) => {
618 tracing::info!(
619 task_id = ctx.task_id,
620 branch,
621 default_branch,
622 "push skipped"
623 );
624 ctx.append_activity(
625 "push",
626 Some(agent_name),
627 model_name,
628 Some(&serde_json::json!({
629 "status": "skipped",
630 "branch": branch,
631 "default_branch": default_branch,
632 })),
633 )
634 .await;
635 PushResult::Skipped
636 }
637 Err(e) => {
638 let err_str = e.to_string();
639 tracing::error!(task_id = ctx.task_id, error = ?e, "push failed");
640
641 if is_missing_path_error(&e) && !work_dir.exists() {
642 tracing::warn!(
643 task_id = ctx.task_id,
644 worktree = %work_dir.display(),
645 "push failed because worktree path disappeared; will attempt recovery"
646 );
647 ctx.append_activity(
648 "push",
649 Some(agent_name),
650 model_name,
651 Some(&serde_json::json!({
652 "status": "retry",
653 "branch": branch,
654 "default_branch": default_branch,
655 "reason": "worktree_missing",
656 "error": err_str,
657 })),
658 )
659 .await;
660 return PushResult::WorktreeMissing;
661 }
662
663 if push_error_is_diverged(&err_str) {
665 tracing::info!(
666 task_id = ctx.task_id,
667 branch = branch,
668 "attempting fetch and rebase to recover from diverged branch"
669 );
670
671 match git_ops::rebase_on_branch(work_dir, branch).await {
673 Ok(true) => {
674 tracing::info!(
678 task_id = ctx.task_id,
679 branch = branch,
680 "rebase succeeded — retrying the push"
681 );
682 ctx.append_activity(
683 "push_rebased",
684 Some(agent_name),
685 model_name,
686 Some(&serde_json::json!({
687 "status": "rebased",
688 "branch": branch,
689 "reason": "diverged_from_remote",
690 })),
691 )
692 .await;
693 return push_after_rebase(
694 ctx,
695 work_dir,
696 branch,
697 default_branch,
698 agent_name,
699 model_name,
700 )
701 .await;
702 }
703 Ok(false) => {
704 tracing::info!(
706 task_id = ctx.task_id,
707 branch = branch,
708 "no local commits after fetch — marking as success"
709 );
710 ctx.append_activity(
711 "push",
712 Some(agent_name),
713 model_name,
714 Some(&serde_json::json!({
715 "status": "ok",
716 "branch": branch,
717 "reason": "no_commits_after_fetch",
718 })),
719 )
720 .await;
721 ctx.set(&[
722 ("last_error", serde_json::json!("")),
723 ("push_failures", serde_json::json!(0)),
724 ])
725 .await;
726 return PushResult::Success;
727 }
728 Err(rebase_err) if git_ops::is_missing_remote_ref_error(&rebase_err) => {
729 tracing::warn!(
732 task_id = ctx.task_id,
733 branch = branch,
734 "remote branch does not exist, skipping rebase recovery"
735 );
736 ctx.append_activity(
737 "push",
738 Some(agent_name),
739 model_name,
740 Some(&serde_json::json!({
741 "status": "error",
742 "branch": branch,
743 "default_branch": default_branch,
744 "error": err_str,
745 })),
746 )
747 .await;
748 ctx.set(&[("last_error", serde_json::json!(format!("push failed: {e}")))])
749 .await;
750 return PushResult::Failed;
751 }
752 Err(rebase_err) => {
753 tracing::error!(
755 task_id = ctx.task_id,
756 branch = branch,
757 error = ?rebase_err,
758 "rebase failed — blocking task for human intervention"
759 );
760 ctx.append_activity(
761 "push_rebased",
762 Some(agent_name),
763 model_name,
764 Some(&serde_json::json!({
765 "status": "error",
766 "branch": branch,
767 "error": rebase_err.to_string(),
768 })),
769 )
770 .await;
771 ctx.set(&[(
772 "last_error",
773 serde_json::json!(format!(
774 "push failed and rebase failed: {rebase_err} — manual resolution required"
775 )),
776 )])
777 .await;
778 return PushResult::Failed;
779 }
780 }
781 }
782
783 ctx.append_activity(
785 "push",
786 Some(agent_name),
787 model_name,
788 Some(&serde_json::json!({
789 "status": "error",
790 "branch": branch,
791 "default_branch": default_branch,
792 "error": err_str,
793 })),
794 )
795 .await;
796 ctx.set(&[("last_error", serde_json::json!(format!("push failed: {e}")))])
797 .await;
798 PushResult::Failed
799 }
800 }
801}
802
803fn push_error_is_diverged(err_str: &str) -> bool {
806 err_str.contains("non-fast-forward")
807 || err_str.contains("! [rejected]")
808 || err_str.contains("fetch first")
809 || err_str.contains("behind")
810}
811
812fn is_local_rate_limit_skip(err_str: &str) -> bool {
814 err_str.contains("rate-limited, skipping call")
815}
816
817async fn create_pr_with_log(
824 ctx: &StoreCtx<'_>,
825 wt: &worktree::WorktreeSetup,
826 task_title: &str,
827 resp: &AgentResponse,
828 agent_name: &str,
829 model_name: Option<&str>,
830 mut has_pushed: bool,
831) -> (bool, bool, bool) {
832 match git_ops::create_pr_if_needed(
833 &wt.work_dir,
834 &wt.branch,
835 task_title,
836 &resp.summary,
837 &resp.accomplished,
838 &resp.remaining,
839 &resp.files,
840 ctx.task_id,
841 agent_name,
842 model_name,
843 ctx.repo,
844 &wt.default_branch,
845 )
846 .await
847 {
848 Ok(ref url) => {
849 match parse_pr_number_from_url(url) {
853 Ok(pr_num) => {
854 if let Err(e) = store::store_set_result(
855 ctx.store,
856 ctx.repo,
857 ctx.task_id,
858 &[("pr_number", serde_json::json!(pr_num))],
859 )
860 .await
861 {
862 tracing::error!(
863 task_id = ctx.task_id,
864 pr_url = %url,
865 err = %e,
866 "CRITICAL: failed to save pr_number to store — downstream review gate may trigger duplicate gh pr create"
867 );
868 }
869 }
870 Err(e) => {
871 tracing::warn!(
872 task_id = ctx.task_id,
873 pr_url = %url,
874 error = %e,
875 "PR created but failed to parse PR number from URL"
876 );
877 }
878 }
879 ctx.append_activity(
880 "pr_create",
881 Some(agent_name),
882 model_name,
883 Some(&serde_json::json!({"status": "created", "url": url})),
884 )
885 .await;
886 (true, has_pushed, false)
887 }
888 Err(e) => {
889 let err_str = format!("{e}");
890 tracing::error!(task_id = ctx.task_id, error = ?e, "create PR failed");
891 ctx.append_activity(
892 "pr_create",
893 Some(agent_name),
894 model_name,
895 Some(&serde_json::json!({
896 "status": "error",
897 "branch": wt.branch,
898 "error": err_str.clone(),
899 })),
900 )
901 .await;
902 ctx.set(&[(
903 "last_error",
904 serde_json::json!(format!("create PR failed: {e}")),
905 )])
906 .await;
907 let mut pr_base_invalid = false;
917 if is_local_rate_limit_skip(&err_str) {
918 tracing::warn!(
921 task_id = ctx.task_id,
922 "PR creation skipped by local GitHub rate limit — review gate will create the PR"
923 );
924 return (true, has_pushed, false);
925 }
926 if agents::patterns::detect_auth_error(&err_str).is_some() {
927 tracing::error!(
928 task_id = ctx.task_id,
929 "PR creation failed with GitHub auth error — blocking task"
930 );
931 pr_base_invalid = true;
932 } else if err_str.contains("422") {
933 if err_str.contains("No commits between") || err_str.contains("head") {
934 tracing::info!(
935 task_id = ctx.task_id,
936 "PR creation returned 422/no-commits/head-invalid — agent made no code changes or branch merged, marking done"
937 );
938 has_pushed = false;
939 } else if git_ops::is_invalid_base_error(&err_str) {
940 tracing::error!(
941 task_id = ctx.task_id,
942 "PR creation failed with invalid base branch — blocking task"
943 );
944 pr_base_invalid = true;
945 }
946 }
947 (false, has_pushed, pr_base_invalid)
948 }
949 }
950}
951
952async fn run_git_ops(
954 ctx: &StoreCtx<'_>,
955 wt: &worktree::WorktreeSetup,
956 task_title: &str,
957 resp: &AgentResponse,
958 agent_name: &str,
959 model_name: Option<&str>,
960 new_attempts: u32,
961) -> GitOpsResult {
962 auto_commit_changes(ctx, &wt.work_dir, task_title, agent_name, new_attempts).await;
963
964 let mut has_commits =
965 check_commits_and_clear_stale_errors(ctx, &wt.work_dir, &wt.default_branch).await;
966
967 let push_result = if has_commits {
971 push_branch_with_log(
972 ctx,
973 &wt.work_dir,
974 &wt.branch,
975 &wt.default_branch,
976 agent_name,
977 model_name,
978 )
979 .await
980 } else {
981 store::store_log_activity(
982 ctx.store,
983 ctx.repo,
984 ctx.task_id,
985 "push",
986 None,
987 None,
988 Some(agent_name),
989 model_name,
990 Some(&serde_json::json!({
991 "status": "skipped",
992 "reason": "no_commits_ahead",
993 "branch": wt.branch,
994 "default_branch": wt.default_branch,
995 })),
996 )
997 .await;
998 PushResult::NoCommits
999 };
1000 let push_result = if matches!(push_result, PushResult::WorktreeMissing) {
1001 match recover_missing_worktree_for_push(ctx, wt, task_title, agent_name, model_name).await {
1002 Ok(recovered) => {
1003 let wt_for_ops = &recovered;
1004 has_commits = check_commits_and_clear_stale_errors(
1005 ctx,
1006 &wt_for_ops.work_dir,
1007 &wt_for_ops.default_branch,
1008 )
1009 .await;
1010 if has_commits {
1011 push_branch_with_log(
1012 ctx,
1013 &wt_for_ops.work_dir,
1014 &wt_for_ops.branch,
1015 &wt_for_ops.default_branch,
1016 agent_name,
1017 model_name,
1018 )
1019 .await
1020 } else {
1021 PushResult::NoCommits
1022 }
1023 }
1024 Err(e) => {
1025 tracing::error!(
1026 task_id = ctx.task_id,
1027 err = %e,
1028 "worktree recovery before push failed"
1029 );
1030 ctx.append_activity(
1031 "push_recover_worktree",
1032 Some(agent_name),
1033 model_name,
1034 Some(&serde_json::json!({
1035 "status": "error",
1036 "worktree": wt.work_dir.display().to_string(),
1037 "branch": wt.branch,
1038 "error": e.to_string(),
1039 })),
1040 )
1041 .await;
1042 ctx.set(&[(
1043 "last_error",
1044 serde_json::json!(format!(
1045 "push failed: worktree disappeared and recovery failed: {e}"
1046 )),
1047 )])
1048 .await;
1049 PushResult::Failed
1050 }
1051 }
1052 } else {
1053 push_result
1054 };
1055
1056 let mut has_pushed = matches!(push_result, PushResult::Success);
1057 let mut has_pr = false;
1058
1059 if has_commits && matches!(push_result, PushResult::Failed) {
1061 tracing::warn!(
1062 task_id = ctx.task_id,
1063 "skipping PR creation due to push failure"
1064 );
1065 } else if matches!(push_result, PushResult::Skipped) {
1066 tracing::info!(task_id = ctx.task_id, "push skipped, skipping PR creation");
1067 } else if matches!(push_result, PushResult::NoCommits) {
1068 tracing::info!(
1069 task_id = ctx.task_id,
1070 "no commits ahead of default branch, skipping push + PR"
1071 );
1072 } else if !has_pushed {
1073 } else if ctx.repo.is_empty() {
1075 tracing::warn!(
1076 task_id = ctx.task_id,
1077 "skipping PR creation — repo is empty (internal task?)"
1078 );
1079 } else {
1080 let (pr, updated_pushed, pr_base_invalid) = create_pr_with_log(
1081 ctx, wt, task_title, resp, agent_name, model_name, has_pushed,
1082 )
1083 .await;
1084 has_pr = pr;
1085 has_pushed = updated_pushed;
1086 return GitOpsResult {
1087 has_pr,
1088 has_pushed,
1089 has_commits,
1090 pr_base_invalid,
1091 };
1092 }
1093
1094 GitOpsResult {
1095 has_pr,
1096 has_pushed,
1097 has_commits,
1098 pr_base_invalid: false,
1099 }
1100}
1101
1102async fn post_screenshots(
1106 ctx: &StoreCtx<'_>,
1107 work_dir: &Path,
1108 resp: &AgentResponse,
1109) -> Option<String> {
1110 let note = resp.screenshot_note.as_deref().map(str::trim);
1111 let note = note.filter(|n| !n.is_empty());
1112 if resp.screenshots.is_empty() && note.is_none() {
1113 return None;
1114 }
1115 let pr_number = ctx.get_task().await.and_then(|t| t.pr_number);
1116 let (Some(pr_number), false) = (pr_number, ctx.repo.is_empty()) else {
1117 return note.map(String::from);
1118 };
1119 let Ok(pr) = u64::try_from(pr_number) else {
1120 return note.map(String::from);
1121 };
1122
1123 let roots = screenshots::allowed_roots(work_dir).await;
1124 let (images, skipped) = screenshots::prepare(&resp.screenshots, work_dir, &roots, pr);
1125 let commit = if images.is_empty() {
1126 String::new()
1127 } else {
1128 match screenshots::publish(work_dir, &images, pr).await {
1129 Ok(commit) => commit,
1130 Err(e) => {
1131 tracing::warn!(task_id = ctx.task_id, err = %e, "failed to push screenshots");
1132 let body = screenshots::build_unpublished_comment(note, &skipped);
1133 comment_screenshots(ctx, pr, &body).await;
1134 return note.map(String::from);
1135 }
1136 }
1137 };
1138 let body = screenshots::build_comment(ctx.repo, &commit, &images, note, &skipped);
1139 comment_screenshots(ctx, pr, &body).await;
1140 note.map(String::from)
1141}
1142
1143async fn comment_screenshots(ctx: &StoreCtx<'_>, pr: u64, body: &str) {
1144 match GhHttp::new() {
1145 Ok(gh) => {
1146 if let Err(e) = gh.add_comment(ctx.repo, &pr.to_string(), body).await {
1147 tracing::warn!(task_id = ctx.task_id, pr, err = %e, "failed to comment screenshots");
1148 }
1149 }
1150 Err(e) => tracing::warn!(task_id = ctx.task_id, err = %e, "cannot comment screenshots"),
1151 }
1152}
1153
1154async fn close_superseded_pr(ctx: &StoreCtx<'_>, pr_number: u64) {
1156 if ctx.repo.is_empty() {
1157 return;
1158 }
1159 match GhHttp::new() {
1160 Ok(gh) => {
1161 let note = "Closing as superseded: the change is already on the default branch, so this branch has no commits ahead of it.";
1162 if let Err(e) = gh.add_comment(ctx.repo, &pr_number.to_string(), note).await {
1163 tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to comment on superseded PR");
1164 }
1165 if let Err(e) = gh.close_pr(ctx.repo, pr_number).await {
1166 tracing::warn!(task_id = ctx.task_id, pr_number, err = %e, "failed to close superseded PR");
1167 }
1168 }
1169 Err(e) => {
1170 tracing::warn!(task_id = ctx.task_id, err = %e, "cannot close superseded PR");
1171 }
1172 }
1173 ctx.set(&[
1175 (
1176 "last_error",
1177 serde_json::json!(
1178 "PR closed as superseded: the fix already landed on the default branch"
1179 ),
1180 ),
1181 ("pr_number", serde_json::json!(null)),
1182 ])
1183 .await;
1184}
1185
1186fn superseded_conflict_pr(
1192 merge_conflict_retries: i32,
1193 pr_number: Option<i32>,
1194 has_commits: bool,
1195) -> Option<u64> {
1196 if has_commits || merge_conflict_retries <= 0 {
1197 return None;
1198 }
1199 pr_number
1200 .filter(|n| *n > 0)
1201 .and_then(|n| u64::try_from(n).ok())
1202}
1203
1204async fn detect_push_failure_state(
1206 ctx: &StoreCtx<'_>,
1207 has_commits: bool,
1208 has_pushed: bool,
1209) -> PushFailureState {
1210 let stored_last_error = ctx
1212 .get_task()
1213 .await
1214 .map(|t| t.last_error)
1215 .unwrap_or_default();
1216
1217 let push_failed = !has_pushed && has_commits && stored_last_error.contains("push failed");
1218
1219 let is_workflow_scope_failure = push_failed
1222 && (stored_last_error.contains("workflow` scope")
1223 || stored_last_error.contains("workflow' scope")
1224 || (stored_last_error.contains("refusing to allow")
1225 && stored_last_error.contains("workflow")));
1226
1227 let is_rebase_conflict_failure =
1228 push_failed && stored_last_error.contains("push failed and rebase failed:");
1229
1230 let is_transient_failure = push_failed
1231 && !is_workflow_scope_failure
1232 && !is_rebase_conflict_failure
1233 && git_ops::is_transient_network_error(&stored_last_error);
1234
1235 let push_failures = if push_failed && !is_workflow_scope_failure && !is_rebase_conflict_failure
1240 {
1241 match ctx.increment("push_failures").await {
1242 Ok(v) => v,
1243 Err(e) => {
1244 tracing::warn!(
1245 task_id = ctx.task_id,
1246 err = %e,
1247 "failed to increment push_failures — reading current value from store"
1248 );
1249 ctx.get_task()
1251 .await
1252 .map_or(1, |t| u64::try_from(t.push_failures).unwrap_or(0) + 1)
1253 }
1255 }
1256 } else {
1257 0
1258 };
1259
1260 PushFailureState {
1261 push_failed,
1262 is_workflow_scope_failure,
1263 is_rebase_conflict_failure,
1264 is_transient_failure,
1265 push_failures,
1266 stored_last_error,
1267 }
1268}
1269
1270async fn detect_no_code_reroutes(
1273 ctx: &StoreCtx<'_>,
1274 is_no_code_reroute: bool,
1275 new_attempts: u32,
1276 max_reroutes: u32,
1277) -> u64 {
1278 if !is_no_code_reroute {
1279 return 0;
1280 }
1281 tracing::warn!(
1282 task_id = ctx.task_id,
1283 attempts = new_attempts,
1284 max_reroutes,
1285 "agent reported done but produced no code changes on external task requiring PR"
1286 );
1287 match ctx.increment("no_code_reroutes").await {
1288 Ok(v) => v,
1289 Err(e) => {
1290 tracing::warn!(
1291 task_id = ctx.task_id,
1292 err = %e,
1293 "failed to increment no_code_reroutes — reading current value from store"
1294 );
1295 ctx.get_task()
1297 .await
1298 .map_or(1, |t| u64::try_from(t.no_code_reroutes).unwrap_or(0) + 1)
1299 }
1301 }
1302}
1303
1304fn agent_blocked_reason(resp: &AgentResponse) -> String {
1311 let summary_opt = if resp.summary.is_empty() {
1312 None
1313 } else {
1314 Some(resp.summary.as_str())
1315 };
1316 let base = resp
1317 .error
1318 .as_deref()
1319 .filter(|s| !s.is_empty())
1320 .or(summary_opt)
1321 .unwrap_or("agent returned blocked status without a reason");
1322 if resp.remaining.is_empty() {
1323 base.to_string()
1324 } else {
1325 format!("{base}. Remaining: {}", resp.remaining.join("; "))
1326 }
1327}
1328
1329fn is_denied_push_block(resp: &AgentResponse) -> bool {
1331 let r = agent_blocked_reason(resp).to_lowercase();
1332 r.contains("push")
1333 && [
1334 "denied",
1335 "not allowed",
1336 "permission",
1337 "disallowed",
1338 "approval",
1339 ]
1340 .iter()
1341 .any(|p| r.contains(p))
1342}
1343
1344fn is_retryable_blocked_reason(reason: &str) -> bool {
1350 let r = reason.to_lowercase();
1351
1352 let permanent_patterns = [
1353 "not found",
1354 "does not exist",
1355 "invalid",
1356 "malformed",
1357 "syntax error",
1358 "unsupported",
1359 "unimplemented",
1360 "manual intervention required",
1361 "human intervention required",
1362 ];
1363 if permanent_patterns.iter().any(|p| r.contains(p)) {
1364 return false;
1365 }
1366
1367 let transient_patterns = [
1368 "unavailable",
1369 "temporarily unavailable",
1370 "timeout",
1371 "timed out",
1372 "connection reset",
1373 "connection refused",
1374 "network error",
1375 "rate limit",
1376 "try again",
1377 "service down",
1378 "permission denied",
1379 "worktree lock",
1380 "git lock",
1381 "lockfile permission",
1382 "lock permission",
1383 "resource busy",
1384 "could not resolve host",
1385 "gpg decryption fails",
1388 "gpg decryption failed",
1389 "gpg agent",
1390 "no passphrase available",
1391 "passphrase unavailable",
1392 "pass store",
1393 "passwordstoreprovider",
1394 "agentvaultprovider",
1395 "onepasswordprovider",
1396 "decryption failed in this agent session",
1397 ];
1398 transient_patterns.iter().any(|p| r.contains(p))
1399}
1400
1401#[expect(
1403 clippy::too_many_arguments,
1404 reason = "the decision and its context arrive as separate values"
1405)]
1406async fn apply_post_decision_effects(
1407 ctx: &StoreCtx<'_>,
1408 final_status: &str,
1409 resp_status: &str,
1410 push_state: &PushFailureState,
1411 is_no_code_reroute: bool,
1412 has_pr: bool,
1413 has_pushed: bool,
1414 is_pr_base_invalid: bool,
1415 has_delegations: bool,
1416 is_external: bool,
1417 no_code_reroutes: u64,
1418 max_reroutes: u32,
1419 agent_name: &str,
1420) {
1421 if push_state.is_workflow_scope_failure {
1422 tracing::error!(
1424 task_id = ctx.task_id,
1425 "push failed: token lacks `workflow` OAuth scope — blocking immediately \
1426 (rerouting would not help)"
1427 );
1428 ctx.set(&[(
1429 "last_error",
1430 serde_json::json!(format!(
1431 "push failed: GitHub token lacks `workflow` OAuth scope. \
1432 The agent modified .github/workflows/ files but the token cannot push them. \
1433 Fix: add `workflow` scope to your GitHub token, or use a GitHub App for auth. \
1434 Original error: {}",
1435 push_state.stored_last_error
1436 )),
1437 )])
1438 .await;
1439 } else if push_state.is_rebase_conflict_failure {
1440 tracing::error!(
1441 task_id = ctx.task_id,
1442 "push failed and automatic rebase recovery failed — blocking for human intervention"
1443 );
1444 ctx.set(&[
1445 ("agent", serde_json::json!(null)),
1446 ("model", serde_json::json!(null)),
1447 ])
1448 .await;
1449 } else if push_state.push_failed && final_status == "needs_review" {
1450 tracing::warn!(
1453 task_id = ctx.task_id,
1454 push_failures = push_state.push_failures,
1455 "agent done but push failed on a GitHub or network error — engine retries the push"
1456 );
1457 } else if push_state.push_failed {
1458 ctx.set(&[
1460 ("agent", serde_json::json!(null)),
1461 ("model", serde_json::json!(null)),
1462 ])
1463 .await;
1464 let push_failures = push_state.push_failures;
1465 if push_failures >= 3 {
1466 tracing::error!(
1467 task_id = ctx.task_id,
1468 push_failures,
1469 "push failed {push_failures} times — blocking for human intervention"
1470 );
1471 } else {
1472 tracing::warn!(
1473 task_id = ctx.task_id,
1474 push_failures,
1475 "agent done but push failed ({push_failures}/3) — rerouting to different agent"
1476 );
1477 }
1478 } else if resp_status == "done" && !has_pr && has_delegations {
1479 tracing::info!(
1480 task_id = ctx.task_id,
1481 "agent reported done with delegations but no PR — setting blocked"
1482 );
1483 } else if (resp_status == "done" || resp_status == "completed")
1484 && !has_pr
1485 && has_pushed
1486 && is_pr_base_invalid
1487 {
1488 tracing::error!(
1489 task_id = ctx.task_id,
1490 "PR creation failed with invalid base branch — blocking for human intervention"
1491 );
1492 ctx.set(&[(
1493 "last_error",
1494 serde_json::json!(
1495 "PR creation failed terminally (invalid base branch or GitHub auth error). The agent's commits were pushed successfully. \
1496 Check the repository default branch and the GitHub token, then create the PR manually or unblock the task."
1497 ),
1498 )])
1499 .await;
1500 } else if resp_status == "done" && !has_pr && has_pushed {
1501 tracing::warn!(
1503 task_id = ctx.task_id,
1504 "agent done, commits pushed, but PR creation failed — re-dispatching as routed"
1505 );
1506 } else if is_no_code_reroute {
1507 if final_status == "blocked" {
1512 let prev_no_code_agent = ctx
1516 .get_task()
1517 .await
1518 .map(|t| t.no_code_last_agent)
1519 .unwrap_or_default();
1520 let is_same_agent = !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name;
1521
1522 let msg = if is_same_agent {
1523 tracing::error!(
1524 task_id = ctx.task_id,
1525 agent = %agent_name,
1526 "blocking same-agent no-code loop: agent {} would be selected again",
1527 agent_name
1528 );
1529 format!(
1530 "agent {agent_name} completed without code changes twice — same-agent loop detected, blocking for human review"
1531 )
1532 } else {
1533 tracing::error!(
1534 task_id = ctx.task_id,
1535 no_code_reroutes,
1536 max_reroutes,
1537 "blocking no-code reroute: reached max reroute attempts ({}/{}) for no-code-result",
1538 no_code_reroutes,
1539 max_reroutes
1540 );
1541 format!(
1542 "agent completed without code changes after {no_code_reroutes}/{max_reroutes} reroute attempts on external task requiring PR"
1543 )
1544 };
1545 ctx.set(&[("last_error", serde_json::json!(msg))]).await;
1546 } else {
1547 ctx.set(&[(
1549 "last_error",
1550 serde_json::json!(
1551 "agent completed without code changes on external task requiring PR"
1552 ),
1553 )])
1554 .await;
1555 }
1556
1557 ctx.set(&[
1562 ("no_code_last_agent", serde_json::json!(agent_name)),
1563 ("agent", serde_json::json!(null)),
1564 ("model", serde_json::json!(null)),
1565 ])
1566 .await;
1567 } else if resp_status == "done" && !has_pr && is_external {
1568 tracing::info!(
1571 task_id = ctx.task_id,
1572 "external task with non-code labels reported done — marking done without PR"
1573 );
1574 } else if resp_status == "done" && !has_pr {
1575 tracing::info!(
1576 task_id = ctx.task_id,
1577 "internal task reported done with no PR — marking done"
1578 );
1579 }
1580}
1581
1582async fn store_token_usage(
1585 ctx: &StoreCtx<'_>,
1586 input_tokens: Option<u64>,
1587 output_tokens: Option<u64>,
1588 cost_usd: Option<f64>,
1589) {
1590 let (Some(input), Some(output)) = (input_tokens, output_tokens) else {
1591 return;
1592 };
1593 if let Some(st) = ctx.store {
1594 if let Some(store_id) = ctx.store_id_opt {
1595 if let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await {
1596 tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1597 }
1598 } else if let Ok(Some(store_id)) = st.resolve_task_id(ctx.repo, ctx.task_id).await
1599 && let Err(e) = st.store_tokens(store_id, input, output, cost_usd).await
1600 {
1601 tracing::warn!(task_id = ctx.task_id, ?e, "failed to store token usage");
1602 }
1603 }
1604}
1605
1606#[expect(
1612 clippy::too_many_arguments,
1613 reason = "the runner passes each part of the run result"
1614)]
1615pub async fn handle_success(
1616 task_id: &str,
1617 parsed: agents::ParsedResponse,
1618 wt: &worktree::WorktreeSetup,
1619 task_title: &str,
1620 agent_name: &str,
1621 model_name: Option<&str>,
1622 new_attempts: u32,
1623 repo: &str,
1624 store: &Option<Arc<TaskStore>>,
1625 raw_stdout: &str,
1626) -> anyhow::Result<(String, bool)> {
1627 let input_tokens = parsed.input_tokens;
1629 let output_tokens = parsed.output_tokens;
1630 let cost_usd = parsed.cost_usd;
1631 let mut resp = parsed.response;
1632
1633 tracing::info!(
1634 task_id,
1635 status = resp.status,
1636 summary = resp.summary,
1637 "agent completed successfully"
1638 );
1639
1640 let push_denied = resp.status == "blocked" && is_denied_push_block(&resp);
1641
1642 let store_id_opt = store::resolve_store_id(store, repo, task_id).await;
1645 let ctx = StoreCtx {
1646 store,
1647 store_id_opt,
1648 repo,
1649 task_id,
1650 };
1651
1652 ctx.reset_retry_streaks().await;
1653
1654 let git = if resp.status == "done"
1656 || resp.status == "completed"
1657 || resp.status == "in_progress"
1658 || resp.status == "needs_review"
1659 || push_denied
1660 {
1661 run_git_ops(
1662 &ctx,
1663 wt,
1664 task_title,
1665 &resp,
1666 agent_name,
1667 model_name,
1668 new_attempts,
1669 )
1670 .await
1671 } else {
1672 GitOpsResult::default()
1673 };
1674
1675 if push_denied && (git.has_pr || git.has_pushed) {
1678 tracing::info!(
1679 task_id,
1680 "agent blocked on denied push, orch pushed the branch"
1681 );
1682 resp.status = "done".to_string();
1683 }
1684
1685 let screenshot_note = if git.has_pr {
1686 post_screenshots(&ctx, &wt.work_dir, &resp).await
1687 } else {
1688 None
1689 };
1690
1691 if !resp.delegations.is_empty() {
1693 ctx.set(&[("delegations", serde_json::json!(resp.delegations))])
1694 .await;
1695 }
1696
1697 let has_delegations = !resp.delegations.is_empty();
1704
1705 let push_state = detect_push_failure_state(&ctx, git.has_commits, git.has_pushed).await;
1707
1708 let is_external = !task_id.starts_with("internal:");
1716 let requires_pr = is_external && !git.has_pr && !resp.status.starts_with("needs_review");
1717
1718 let max_reroutes: u32 = config::get("workflow.max_reroute_attempts")
1721 .ok()
1722 .and_then(|s| s.parse().ok())
1723 .or_else(|| {
1724 config::get("workflow.max_attempts")
1725 .ok()
1726 .and_then(|s| s.parse().ok())
1727 })
1728 .unwrap_or(3);
1729
1730 let is_no_code_reroute = !push_state.is_workflow_scope_failure
1733 && !push_state.push_failed
1734 && (resp.status == "done" || resp.status == "completed")
1735 && !has_delegations
1736 && !git.has_pushed
1737 && requires_pr;
1738
1739 let superseded_pr = match (is_no_code_reroute, ctx.get_task().await) {
1742 (true, Some(task)) => {
1743 superseded_conflict_pr(task.merge_conflict_retries, task.pr_number, git.has_commits)
1744 }
1745 _ => None,
1746 };
1747 let is_no_code_reroute = is_no_code_reroute && superseded_pr.is_none();
1748
1749 let no_code_reroutes =
1750 detect_no_code_reroutes(&ctx, is_no_code_reroute, new_attempts, max_reroutes).await;
1751
1752 let blocked_reason = if resp.status == "blocked" {
1753 Some(agent_blocked_reason(&resp))
1754 } else {
1755 None
1756 };
1757 let is_retryable_blocked = blocked_reason
1758 .as_deref()
1759 .is_some_and(is_retryable_blocked_reason);
1760
1761 let is_same_agent = if is_no_code_reroute {
1766 let prev_no_code_agent = ctx
1767 .get_task()
1768 .await
1769 .map(|t| t.no_code_last_agent)
1770 .unwrap_or_default();
1771 !prev_no_code_agent.is_empty() && prev_no_code_agent == agent_name
1772 } else {
1773 false
1774 };
1775
1776 let final_status_owned = classify_final_status(&DecisionInput {
1779 agent_status: &resp.status,
1780 is_workflow_scope_failure: push_state.is_workflow_scope_failure,
1781 is_rebase_conflict_failure: push_state.is_rebase_conflict_failure,
1782 push_failed: push_state.push_failed,
1783 push_failures: push_state.push_failures,
1784 is_transient_push_failure: push_state.is_transient_failure,
1785 has_pr: git.has_pr,
1786 has_delegations,
1787 has_pushed: git.has_pushed,
1788 is_pr_base_invalid: git.pr_base_invalid,
1789 requires_pr,
1790 no_code_reroutes,
1791 max_reroutes,
1792 is_same_agent,
1793 is_completed_status: resp.status == "completed",
1794 is_retryable_blocked,
1795 is_superseded_conflict: superseded_pr.is_some(),
1796 });
1797 let final_status = final_status_owned.as_str();
1798
1799 apply_post_decision_effects(
1802 &ctx,
1803 final_status,
1804 &resp.status,
1805 &push_state,
1806 is_no_code_reroute,
1807 git.has_pr,
1808 git.has_pushed,
1809 git.pr_base_invalid,
1810 has_delegations,
1811 is_external,
1812 no_code_reroutes,
1813 max_reroutes,
1814 agent_name,
1815 )
1816 .await;
1817
1818 if resp.status == "blocked" {
1824 let reason = blocked_reason.unwrap_or_else(|| agent_blocked_reason(&resp));
1825 if final_status == "new" {
1826 cooldown::record_agent_failure_with_message(agent_name, &reason).await;
1829 if let Some(m) = model_name {
1830 cooldown::record_model_failure(agent_name, m).await;
1831 }
1832 ctx.set(&[
1833 (
1834 "last_error",
1835 serde_json::json!(format!(
1836 "transient blocker (auto-retry scheduled): {reason}"
1837 )),
1838 ),
1839 ("agent", serde_json::json!(null)),
1840 ("model", serde_json::json!(null)),
1841 ])
1842 .await;
1843 tracing::warn!(
1844 task_id = ctx.task_id,
1845 reason = %reason,
1846 "agent returned retryable blocked status — rerouting as new with cooldown"
1847 );
1848 } else if final_status == "blocked" {
1849 ctx.set(&[("last_error", serde_json::json!(reason))]).await;
1850 }
1851 }
1852
1853 if let Some(pr_number) = superseded_pr {
1854 tracing::info!(
1855 task_id = ctx.task_id,
1856 pr_number,
1857 "conflict reroute found the fix already on the default branch — closing superseded PR"
1858 );
1859 close_superseded_pr(&ctx, pr_number).await;
1860 }
1861
1862 let summary = match &screenshot_note {
1864 Some(note) => format!("{}\n\nScreenshots: {note}", resp.summary),
1865 None => resp.summary.clone(),
1866 };
1867 ctx.set(&[("summary", serde_json::json!(summary))]).await;
1868
1869 store_token_usage(
1871 &ctx,
1872 input_tokens.or(resp.input_tokens),
1873 output_tokens.or(resp.output_tokens),
1874 cost_usd,
1875 )
1876 .await;
1877
1878 response::store_learnings_from_response(
1880 task_id,
1881 new_attempts,
1882 agent_name,
1883 model_name,
1884 &resp,
1885 resp.error.as_deref(),
1886 store,
1887 repo,
1888 raw_stdout,
1889 )
1890 .await;
1891
1892 Ok((final_status.to_string(), push_state.push_failed))
1895}
1896
1897#[cfg(test)]
1899mod tests;