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