Skip to main content

orch/engine/review/
mod.rs

1//! PR review pipeline β€” review agent orchestration.
2//!
3//! This module handles running the review agent on completed tasks, parsing its
4//! decision, and posting automated review comments.
5//!
6//! Related modules:
7//! - [`crate::engine::review::poll`] β€” polling open PRs for human review feedback
8//! - [`crate::engine::review::auto_merge`] β€” merging approved PRs and handling change requests
9
10pub mod approval;
11pub mod auto_merge;
12pub mod mode;
13mod parse;
14pub mod poll;
15mod pr;
16mod publish;
17pub mod shipcheck;
18
19use crate::engine::git;
20pub(crate) use crate::engine::review::approval::{ReviewDecision, worktree_head_sha};
21pub(crate) use crate::github::types::parse_pr_number_from_url;
22
23use crate::engine::agents;
24
25use super::router::Router;
26/// Maximum consecutive review agent failures before the task is blocked
27/// for human intervention. Exported so `tick` and `sync` use the same threshold.
28use crate::backends::{ExternalBackend, ExternalTask, Status};
29use crate::config;
30use crate::cooldown;
31use crate::cooldown::CreditExhaustionReason;
32use crate::engine::attribution_footer;
33use crate::engine::git::git_ops;
34pub(crate) use crate::engine::review::approval::has_recorded_approval;
35use crate::engine::review::approval::review_app;
36use crate::engine::review::approval::{
37    clear_approved_sha, pr_head_already_approved, record_approved_sha, record_carried_approval,
38};
39use crate::engine::review::auto_merge::{auto_merge_pr, handle_review_changes};
40use crate::engine::router::RouterConfig;
41use crate::engine::runner;
42use crate::engine::tasks;
43use crate::engine::tasks::TaskManager;
44use crate::github::http::GhHttp;
45use crate::store::TaskStore;
46use crate::store::store_increment;
47use crate::store::store_log_activity;
48use crate::store::{CompleteRun, RunTokenUsage, StartRun};
49use crate::store::{store_set, store_set_result};
50use crate::sys::home;
51use crate::sys::tmux::TmuxManager;
52use anyhow::Context;
53use parse::{ParsedReview, parse_review_output};
54use pr::{EnsurePrResult, ensure_pr_exists, recover_missing_review_worktree};
55use publish::{post_review_comment, post_review_started};
56use std::collections::HashSet;
57use std::fs;
58use std::path::Path;
59use std::path::PathBuf;
60use std::sync::Arc;
61use std::time::Duration;
62use tokio::fs as tokio_fs;
63use tokio::process::Command;
64use tokio::sync::RwLock;
65use tokio::task;
66use tokio::time;
67
68pub(crate) const MAX_REVIEW_AGENT_FAILURES: u64 = 3;
69
70/// Maximum consecutive PR-creation failures before blocking the task.
71const MAX_PR_CREATE_FAILURES: u64 = 3;
72
73/// Map an [`AgentError`] to the structured outcome string stored in `task_runs.outcome`.
74///
75/// Mirrors the logic in `runner::classify_run_outcome` so review runs carry the
76/// same outcome fidelity as agent runs.
77fn outcome_for_agent_error(err: &agents::AgentError) -> &'static str {
78    match err {
79        agents::AgentError::Timeout { .. } => "timeout",
80        agents::AgentError::Interrupted { .. } => "interrupted",
81        // Consult credit-exhaustion detection first β€” generic rate-limit patterns
82        // (e.g. "usage limit") also match billing-cycle exhaustion messages, so
83        // reviews on a billing-cycle-exhausted model must not be stored as a
84        // plain "rate_limit"/"auth_error" outcome (issue #3529).
85        agents::AgentError::RateLimit { message } => {
86            cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("rate_limit")
87        }
88        agents::AgentError::Auth { message } => {
89            cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("auth_error")
90        }
91        agents::AgentError::InvalidResponse { .. } => "parse_error",
92        _ => "failed",
93    }
94}
95
96/// Format an [`AgentError`] as the compact string persisted to `task_runs.error`
97/// and surfaced via [`ReviewDecision::Failed`].
98///
99/// Mirrors the per-variant formatting in `runner::fallback::handle_error` so review
100/// runs never leak raw provider payloads (e.g. truncated `api_retry` NDJSON
101/// fragments) into the audit trail. Without this, `err.to_string()` would expand
102/// `AgentError::RateLimit { message }` via its `Display` impl and persist hundreds
103/// of bytes of raw JSON into `task_runs.error` (issue #3149, regression of #2881).
104fn format_review_error(agent: &str, err: &agents::AgentError) -> String {
105    match err {
106        agents::AgentError::RateLimit { message } => format!(
107            "{agent} rate limit: {}",
108            runner::fallback::summarize_rate_limit_error(message)
109        ),
110        agents::AgentError::Auth { message } => format!("{agent} auth error: {message}"),
111        agents::AgentError::Timeout { elapsed } => {
112            format!("{agent} timed out after {}s", elapsed.as_secs())
113        }
114        other => format!("{agent} agent error: {other}"),
115    }
116}
117
118fn review_started_comment(review_agent: &str, review_model: &str) -> String {
119    let footer = attribution_footer("Review started", review_agent, Some(review_model));
120    format!("πŸ” Automated review started{footer}")
121}
122
123fn should_skip_no_code_reroute_increment(last_error: &str) -> bool {
124    git_ops::is_transient_github_api_error(last_error)
125}
126
127enum ReviewPhase<T> {
128    Ready(T),
129    EarlyReturn(ReviewDecision),
130}
131
132struct ReviewContext {
133    store_id: Option<i64>,
134    had_prev_push_failure: bool,
135    review_attempt: u32,
136    worktree_path: PathBuf,
137    branch_name: String,
138    pr_number: u64,
139    /// PR head SHA when the review started, the commit the decision applies to
140    head_sha: Option<String>,
141    default_branch: String,
142    review_agent: String,
143    review_model: Option<String>,
144    review_task_id: String,
145    review_attempt_dir: PathBuf,
146    output_file: PathBuf,
147    invocation: runner::agent::AgentInvocation,
148    same_agent_fallback: bool,
149}
150
151impl ReviewContext {
152    fn review_model_str(&self) -> &str {
153        self.review_model.as_deref().unwrap_or("")
154    }
155}
156
157struct ReviewRun {
158    run_id: Option<i64>,
159}
160
161const REVIEW_TIMEOUT_DEFAULT_SECS: u64 = 900;
162const REVIEW_TIMEOUT_MIN_SECS: u64 = 300;
163
164// A review reads a diff and runs the tests, so it gets its own limit, shorter than a task's
165fn review_timeout_secs(configured: Option<u64>) -> u64 {
166    configured
167        .unwrap_or(REVIEW_TIMEOUT_DEFAULT_SECS)
168        .max(REVIEW_TIMEOUT_MIN_SECS)
169}
170
171fn build_review_disallowed_tools(worktree_path: &Path) -> Vec<String> {
172    let mut tools = vec![
173        "Bash(rm *)".to_string(),
174        "Bash(rm -*)".to_string(),
175        "Bash(git push*)".to_string(),
176        // Pushing and opening the PR are orch's steps, never the agent's (#3783)
177        "Bash(gh pr create*)".to_string(),
178    ];
179    tools.extend(agents::remote_change_tools());
180    let orch_yml = worktree_path.join(".orch.yml");
181    let orch_yml_str = orch_yml.to_string_lossy();
182    tools.extend([
183        format!("Write({orch_yml_str})"),
184        format!("Edit({orch_yml_str})"),
185    ]);
186    if let Ok(orch_home) = home::orch_home() {
187        for path in [
188            orch_home.join("config.yml"),
189            orch_home.join("config.example.yml"),
190        ] {
191            let path_str = path.to_string_lossy();
192            tools.extend([
193                format!("Read({path_str})"),
194                format!("Write({path_str})"),
195                format!("Edit({path_str})"),
196            ]);
197        }
198    }
199    tools
200}
201
202async fn select_review_agent(
203    task_id: &str,
204    task_agent: &str,
205    store_id: Option<i64>,
206    router: &Arc<RwLock<Router>>,
207    store: &Arc<TaskStore>,
208) -> anyhow::Result<(String, Option<String>, bool)> {
209    let mut exclude_set: HashSet<String> = HashSet::new();
210    if !task_agent.is_empty() {
211        exclude_set.insert(task_agent.to_string());
212    }
213    if let Some(store_id) = store_id
214        && let Ok(failed) = store.previous_review_agents(store_id).await
215    {
216        for agent in failed {
217            exclude_set.insert(agent);
218        }
219    }
220
221    let mut r = router.write().await;
222    let mut tried_agents: HashSet<String> = HashSet::new();
223    let mut chosen_agent: Option<String> = None;
224    let mut chosen_model: Option<String> = None;
225    let available_count = r.available_agent_count().max(1);
226
227    loop {
228        let tmp_exclude_refs: Vec<&str> = exclude_set.iter().map(String::as_str).collect();
229        let Some(agent) = r.next_round_robin_agent(&tmp_exclude_refs, "review") else {
230            break;
231        };
232
233        if tried_agents.contains(&agent) {
234            break;
235        }
236        tried_agents.insert(agent.clone());
237
238        let model = r.model_for_complexity(&agent, "review", task_id);
239        if model.is_some() {
240            chosen_agent = Some(agent);
241            chosen_model = model;
242            break;
243        }
244
245        exclude_set.insert(agent);
246        if exclude_set.len() >= available_count {
247            break;
248        }
249    }
250
251    if let Some(agent) = chosen_agent {
252        let same = !task_agent.is_empty() && agent == task_agent;
253        Ok((agent, chosen_model, same))
254    } else {
255        let final_exclude_refs: Vec<&str> = exclude_set.iter().map(String::as_str).collect();
256        let fallback_agent = r
257            .next_round_robin_agent(&final_exclude_refs, "review")
258            .unwrap_or_else(|| "claude".to_string());
259        let fallback_model = r.model_for_complexity(&fallback_agent, "review", task_id);
260        if fallback_model.is_none() {
261            anyhow::bail!(
262                "no review agent with a configured review model is available for task {task_id}"
263            );
264        }
265        let same = !task_agent.is_empty() && fallback_agent == task_agent;
266        Ok((fallback_agent, fallback_model, same))
267    }
268}
269
270async fn build_review_context(
271    task: &ExternalTask,
272    repo: &str,
273    router: &Arc<RwLock<Router>>,
274    task_manager: &Arc<TaskManager>,
275    store: &Arc<TaskStore>,
276) -> anyhow::Result<ReviewPhase<ReviewContext>> {
277    let stored_task = store
278        .get_by_external_id(repo, &task.id.0)
279        .await
280        .with_context(|| format!("store lookup failed for task {}", task.id.0))?;
281
282    let store_id: Option<i64> = stored_task.as_ref().map(|t| t.id);
283
284    // A commit that already has an approval must not be reviewed again. Checked before
285    // the review_invocations increment so a stuck merge cannot exhaust the review quota
286    if let Some(pr_number) = stored_task
287        .as_ref()
288        .and_then(|t| t.pr_number)
289        .and_then(|n| u64::try_from(n).ok())
290        && pr_head_already_approved(store, repo, &task.id.0, pr_number).await
291    {
292        tracing::info!(
293            task_id = task.id.0,
294            pr_number,
295            "PR head already approved β€” skipping review, merge retry continues"
296        );
297        record_carried_approval(store, repo, &task.id.0, pr_number).await;
298        return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Approve {
299            issues: Vec::new(),
300        }));
301    }
302
303    let had_prev_push_failure = stored_task
304        .as_ref()
305        .is_some_and(|t| t.last_error.contains("push failed"));
306    let review_attempt: u32 = match store_increment(
307        &Some(Arc::clone(store)),
308        repo,
309        &task.id.0,
310        "review_invocations",
311    )
312    .await
313    {
314        Ok(v) => u32::try_from(v).unwrap_or(u32::MAX),
315        Err(e) => {
316            tracing::warn!(task_id = task.id.0, err = %e, "failed to increment review_invocations β€” using fallback attempt=1");
317            1
318        }
319    };
320
321    let no_code_review = stored_task.as_ref().is_some_and(|t| {
322        t.worktree.trim().is_empty() && t.branch.trim().is_empty() && t.pr_number.is_none()
323    });
324    if no_code_review {
325        if tasks::is_internal_id(&task.id.0) {
326            // Internal tasks legitimately reach needs_review with nothing to review.
327            tracing::info!(
328                task_id = task.id.0,
329                "no worktree/branch/pr for internal needs_review task β€” skipping review and marking done"
330            );
331            if let Err(e) = task_manager
332                .update_task_status(&task.id, Status::Done)
333                .await
334            {
335                tracing::error!(
336                    task_id = task.id.0,
337                    err = %e,
338                    "update_task_status(Done) failed for no-code review skip"
339                );
340            }
341            return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Skipped));
342        }
343
344        // External task with no code produced: re-route instead of marking done.
345        // Shares the no_code_reroutes circuit breaker with the no-PR/no-commits path below.
346        let max_reroutes: u32 = config::get("workflow.max_reroute_attempts")
347            .ok()
348            .and_then(|s| s.parse().ok())
349            .or_else(|| {
350                config::get("workflow.max_attempts")
351                    .ok()
352                    .and_then(|s| s.parse().ok())
353            })
354            .unwrap_or(3);
355
356        let reroutes = match store_increment(
357            &Some(Arc::clone(store)),
358            repo,
359            &task.id.0,
360            "no_code_reroutes",
361        )
362        .await
363        {
364            Ok(v) => v,
365            Err(e) => {
366                tracing::warn!(task_id = task.id.0, err = %e, "failed to increment no_code_reroutes β€” skipping reroute/block decision this tick");
367                return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Failed(format!(
368                    "transient store error: {e}"
369                ))));
370            }
371        };
372
373        if reroutes >= u64::from(max_reroutes) {
374            tracing::error!(
375                task_id = task.id.0,
376                reroutes,
377                max_reroutes,
378                "reached max reroute attempts for no-worktree/branch/pr result β€” blocking for human review"
379            );
380            let msg =
381                format!("no worktree/branch/pr after {reroutes}/{max_reroutes} reroute attempts");
382            let fields = [
383                (
384                    "block_reason",
385                    serde_json::json!(format!(
386                        "max reroute attempts ({}) reached β€” no worktree/branch/pr produced",
387                        max_reroutes
388                    )),
389                ),
390                ("last_error", serde_json::json!(msg)),
391                ("agent", serde_json::json!(null)),
392                ("model", serde_json::json!(null)),
393            ];
394            if let Err(e) = task_manager
395                .update_task_status_and_result(&task.id, Status::Blocked, &fields)
396                .await
397            {
398                tracing::error!(task_id = task.id.0, err = %e, "update_task_status_and_result(Blocked) failed β€” skipping block to avoid silent auto-unblock loop");
399            }
400            return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Blocked(msg)));
401        }
402
403        tracing::warn!(
404            task_id = task.id.0,
405            reroutes,
406            max_reroutes,
407            "no worktree/branch/pr for external needs_review task β€” re-routing to a different agent"
408        );
409        match store_set_result(
410            &Some(Arc::clone(store)),
411            repo,
412            &task.id.0,
413            &[
414                ("agent", serde_json::json!(null)),
415                ("model", serde_json::json!(null)),
416                (
417                    "last_error",
418                    serde_json::json!("no worktree/branch/pr produced"),
419                ),
420            ],
421        )
422        .await
423        {
424            Err(e) => {
425                tracing::error!(task_id = task.id.0, err = %e, "failed to clear agent/model for reroute β€” skipping status transition");
426            }
427            _ => {
428                if let Err(e) = task_manager.update_task_status(&task.id, Status::New).await {
429                    tracing::error!(task_id = task.id.0, err = %e, "update_task_status(New) failed β€” task may be stuck in InReview");
430                }
431            }
432        }
433        return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Rerouted));
434    }
435
436    let mut worktree_path = match stored_task.as_ref().map(|t| t.worktree.as_str()) {
437        Some(w) if !w.is_empty() => PathBuf::from(w),
438        _ => {
439            tracing::warn!(task_id = task.id.0, "no worktree found for review");
440            return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Failed(
441                "no worktree found".to_string(),
442            )));
443        }
444    };
445
446    let mut branch_name = match stored_task.as_ref().map(|t| t.branch.as_str()) {
447        Some(b) if !b.is_empty() => b.to_string(),
448        _ => {
449            tracing::warn!(task_id = task.id.0, "no branch found for review");
450            return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Failed(
451                "no branch found".to_string(),
452            )));
453        }
454    };
455
456    let mut missing_worktree_recovered = false;
457    if !worktree_path.exists() {
458        match recover_missing_review_worktree(task, repo, store).await {
459            Ok(recovered) => {
460                branch_name = recovered.branch;
461                worktree_path = recovered.work_dir;
462                missing_worktree_recovered = true;
463            }
464            Err(e) => {
465                let reason = format!("missing review worktree recovery failed: {e}");
466                tracing::error!(task_id = task.id.0, error = %reason, "cannot recover review worktree");
467                store_set(
468                    &Some(Arc::clone(store)),
469                    repo,
470                    &task.id.0,
471                    &[("last_error", serde_json::json!(reason.clone()))],
472                )
473                .await;
474                return Ok(ReviewPhase::EarlyReturn(ReviewDecision::Blocked(reason)));
475            }
476        }
477    }
478
479    if missing_worktree_recovered {
480        store_set(
481            &Some(Arc::clone(store)),
482            repo,
483            &task.id.0,
484            &[("last_error", serde_json::json!(""))],
485        )
486        .await;
487    }
488
489    let agent_summary = stored_task
490        .as_ref()
491        .map(|t| t.summary.clone())
492        .unwrap_or_default();
493    let stored_pr_number = stored_task
494        .as_ref()
495        .and_then(|t| t.pr_number)
496        .and_then(|n| u64::try_from(n).ok())
497        .filter(|&n| n > 0);
498
499    let pr_number = match ensure_pr_exists(
500        task,
501        &branch_name,
502        &worktree_path,
503        repo,
504        &agent_summary,
505        store,
506        task_manager,
507        stored_pr_number,
508    )
509    .await?
510    {
511        EnsurePrResult::Ready(n) => n,
512        EnsurePrResult::EarlyReturn(decision) => return Ok(ReviewPhase::EarlyReturn(decision)),
513    };
514
515    // Run `git fetch` with a timeout so a hung network call cannot stall the
516    // review pipeline indefinitely. Treat a timeout or non-zero exit as a
517    // non-fatal warning (stale remote refs are acceptable for the review).
518    {
519        let fetch_timeout = Duration::from_secs(60);
520        let fetch_future = async {
521            let mut cmd = git::git_ops::git().await;
522            cmd.args(["fetch", "origin", "--prune"])
523                .current_dir(&worktree_path);
524            // Ensure the child is killed if the timeout elapses
525            cmd.kill_on_drop(true);
526            cmd.output_with_context().await
527        };
528
529        match time::timeout(fetch_timeout, fetch_future).await {
530            Ok(Ok(o)) if o.status.success() => {
531                // ok
532            }
533            Ok(Ok(o)) => {
534                tracing::warn!(
535                    task_id = task.id.0,
536                    exit_code = ?o.status.code(),
537                    stdout = %git_ops::sanitize_push_error(&String::from_utf8_lossy(&o.stdout)),
538                    stderr = %git_ops::sanitize_push_error(&String::from_utf8_lossy(&o.stderr)),
539                    "review: git fetch failed (non-zero exit) β€” diff/log may use stale remote refs"
540                );
541            }
542            Ok(Err(e)) => {
543                tracing::warn!(
544                    task_id = task.id.0,
545                    error = %e,
546                    "review: git fetch failed β€” diff/log may use stale remote refs"
547                );
548            }
549            Err(_) => {
550                tracing::warn!(
551                    task_id = task.id.0,
552                    "review: git fetch timed out after 60s β€” diff/log may use stale remote refs"
553                );
554            }
555        }
556    }
557
558    let default_branch = git::worktree::detect_default_branch(&worktree_path).await;
559    let git_diff = runner::context::build_git_diff(&worktree_path, &default_branch).await;
560    let git_log = runner::context::build_git_log(&worktree_path, &default_branch).await;
561    // An unknown project falls back to the global config, never to the worktree's .orch.yml,
562    // which the task agent may have written
563    let project_dir = review_project_dir(repo);
564    let sandboxed = sandboxed_in(project_dir.as_deref());
565    let main_project_dir = project_dir.unwrap_or_else(|| worktree_path.clone());
566    let review_prompt = runner::agent::build_review_prompt(
567        task,
568        &agent_summary,
569        &git_diff,
570        &git_log,
571        &default_branch,
572        pr_number,
573        runner::agent::Shipcheck::detect(&worktree_path)
574            .await
575            .in_sandbox(sandboxed, &worktree_path)
576            .await,
577    );
578
579    let task_agent = stored_task
580        .as_ref()
581        .and_then(|t| t.agent.clone())
582        .unwrap_or_default();
583    let (review_agent, review_model, same_agent_fallback) =
584        select_review_agent(&task.id.0, &task_agent, store_id, router, store).await?;
585
586    anyhow::ensure!(
587        review_model.is_some(),
588        "review model missing for task {} after agent selection β€” refusing to dispatch",
589        task.id.0
590    );
591
592    if same_agent_fallback {
593        tracing::warn!(
594            task_id = task.id.0,
595            agent = %review_agent,
596            "no other agent available for review β€” falling back to the agent that wrote the code"
597        );
598        store_log_activity(
599            &Some(Arc::clone(store)),
600            repo,
601            &task.id.0,
602            "review_agent_fallback",
603            None,
604            None,
605            Some(&review_agent),
606            review_model.as_deref(),
607            Some(&serde_json::json!({
608                "reason": "all available agents excluded (author + previous reviewers)",
609            })),
610        )
611        .await;
612    }
613
614    tracing::info!(
615        task_id = task.id.0,
616        agent = %review_agent,
617        model = ?review_model,
618        "spawning review agent"
619    );
620
621    let review_task_id = format!("{}-review", task.id.0);
622    let review_attempt_dir =
623        home::task_attempt_dir_async(repo, &review_task_id, review_attempt).await?;
624    let output_file = review_attempt_dir.join("output.json");
625
626    let git_name = config::get("git.name").unwrap_or_else(|_| format!("{review_agent}[bot]"));
627    let git_email = config::get("git.email")
628        .unwrap_or_else(|_| format!("{review_agent}[bot]@users.noreply.github.com"));
629    let review_timeout_secs = review_timeout_seconds();
630
631    let invocation = runner::agent::AgentInvocation {
632        agent: review_agent.clone(),
633        model: review_model.clone(),
634        reasoning_effort: None,
635        work_dir: worktree_path.clone(),
636        system_prompt: runner::agent::review_system_prompt(),
637        agent_message: review_prompt,
638        task_id: review_task_id.clone(),
639        disallowed_tools: build_review_disallowed_tools(&worktree_path),
640        git_author_name: git_name,
641        git_author_email: git_email,
642        output_file: output_file.clone(),
643        timeout_seconds: review_timeout_secs,
644        repo: repo.to_string(),
645        attempt: review_attempt,
646        sandbox: sandboxed,
647        main_project_dir,
648        branch: branch_name.clone(),
649    };
650
651    let head_sha = match GhHttp::new() {
652        Ok(gh) => gh.get_pr(repo, pr_number).await.ok().map(|pr| pr.head.sha),
653        Err(_) => None,
654    };
655
656    Ok(ReviewPhase::Ready(ReviewContext {
657        store_id,
658        had_prev_push_failure,
659        review_attempt,
660        worktree_path,
661        branch_name,
662        pr_number,
663        head_sha,
664        default_branch,
665        review_agent,
666        review_model,
667        review_task_id,
668        review_attempt_dir,
669        output_file,
670        invocation,
671        same_agent_fallback,
672    }))
673}
674
675#[expect(
676    clippy::too_many_arguments,
677    reason = "the run record needs the outcome, the agent and the timing together"
678)]
679async fn complete_review_run(
680    store: &Arc<TaskStore>,
681    run_id: Option<i64>,
682    exit_code: Option<i32>,
683    stdout: &str,
684    stderr: &str,
685    parsed: &str,
686    outcome: &str,
687    error: &str,
688    tokens: RunTokenUsage,
689) {
690    if let Some(run_id) = run_id
691        && let Err(e) = store
692            .complete_run(&CompleteRun {
693                run_id,
694                exit_code,
695                stdout,
696                stderr,
697                parsed,
698                outcome,
699                error,
700                tokens,
701            })
702            .await
703    {
704        tracing::warn!(
705            run_id,
706            error = %e,
707            "failed to record review run completion in audit trail"
708        );
709    }
710}
711
712async fn invoke_review_agent(
713    task: &ExternalTask,
714    tmux: &Arc<TmuxManager>,
715    ctx: &ReviewContext,
716    repo: &str,
717    store: &Arc<TaskStore>,
718) -> ReviewPhase<ReviewRun> {
719    let run_id = if let Some(sid) = ctx.store_id {
720        match store
721            .start_run(&StartRun {
722                task_id: sid,
723                attempt: i32::try_from(ctx.review_attempt).unwrap_or(i32::MAX),
724                run_type: "review",
725                agent: &ctx.review_agent,
726                model: ctx.review_model.as_deref().unwrap_or(""),
727                command: "",
728                prompt: "",
729            })
730            .await
731        {
732            Ok(run_id) => Some(run_id),
733            Err(e) => {
734                tracing::warn!(
735                    task_id = task.id.0,
736                    error = %e,
737                    "failed to record review run start in audit trail"
738                );
739                None
740            }
741        }
742    } else {
743        None
744    };
745
746    let session = match runner::agent::spawn_in_tmux(tmux, &ctx.invocation).await {
747        Ok(session) => session,
748        Err(e) => {
749            tracing::error!(task_id = task.id.0, error = %e, "failed to spawn review agent");
750            complete_review_run(
751                store,
752                run_id,
753                None,
754                "",
755                &e.to_string(),
756                "",
757                "failed",
758                &format!("spawn failed: {e}"),
759                RunTokenUsage::default(),
760            )
761            .await;
762            return ReviewPhase::EarlyReturn(ReviewDecision::Failed(format!("spawn failed: {e}")));
763        }
764    };
765
766    let start_comment = review_started_comment(&ctx.review_agent, ctx.review_model_str());
767    match GhHttp::new() {
768        Ok(gh) => {
769            let app = review_app(repo).await;
770            post_review_started(app.as_deref(), &gh, repo, ctx.head_sha.as_deref()).await;
771            // The comment is comment mode's only start signal, the App's check run shows it already
772            if app.is_none()
773                && let Err(e) = gh
774                    .add_comment(repo, &ctx.pr_number.to_string(), &start_comment)
775                    .await
776            {
777                tracing::debug!(
778                    task_id = task.id.0,
779                    pr_number = ctx.pr_number,
780                    error = %e,
781                    "failed to post review-started comment"
782                );
783            }
784        }
785        Err(e) => {
786            tracing::debug!(
787                task_id = task.id.0,
788                pr_number = ctx.pr_number,
789                error = %e,
790                "failed to create GitHub client for review-started comment"
791            );
792        }
793    }
794
795    let poll_interval = Duration::from_secs(5);
796    let timeout_duration = Duration::from_secs(ctx.invocation.timeout_seconds);
797    let wait_result = time::timeout(timeout_duration, async {
798        tokio::select! {
799            result = tmux.wait_for_completion(&session, poll_interval) => result,
800            // An agent can write its decision and still hold the session open
801            () = wait_for_review_decision(ctx, poll_interval) => {
802                tracing::info!(task_id = task.id.0, "review decision is in while the session is still open, ending it");
803                Ok(String::new())
804            }
805        }
806    })
807    .await;
808
809    match wait_result {
810        Ok(Ok(_)) => {
811            tracing::info!(task_id = task.id.0, "review agent completed");
812            let _ = tmux.kill_session(&session).await;
813            ReviewPhase::Ready(ReviewRun { run_id })
814        }
815        Ok(Err(e)) => {
816            tracing::warn!(task_id = task.id.0, error = %e, "review agent process exited with error");
817            let _ = tmux.kill_session(&session).await;
818
819            // Before recording failure, check if this is a "successful exit with non-zero
820            // code" agent like kimi/minimax. Read the output file and check for a valid
821            // result with is_error=false β€” if found, treat as success and proceed to
822            // parse_review_output where the real result will be extracted.
823            let exit_code: i32 = task::spawn_blocking({
824                let review_attempt_dir = ctx.review_attempt_dir.clone();
825                move || {
826                    fs::read_to_string(review_attempt_dir.join("exit.txt"))
827                        .ok()
828                        .and_then(|s| s.trim().parse().ok())
829                        .unwrap_or(-1)
830                }
831            })
832            .await
833            .unwrap_or(-1);
834
835            if exit_code != 0 {
836                // Try reading output via read_output_file which checks both the primary path
837                // and all prior attempt dirs as a fallback. This handles agents like kimi/minimax
838                // that exit non-zero even on success, as well as cases where the current attempt's
839                // output.json was not written but a prior attempt's output contains a valid result.
840                let raw_output =
841                    runner::response::read_output_file(&ctx.review_task_id, &ctx.output_file, repo)
842                        .await;
843                let agent_result = agents::find_agent_result(&ctx.review_agent, &raw_output);
844                // Treat as success if we found a valid result without is_error set
845                if agent_result.as_ref().is_some_and(|r| !r.is_error) {
846                    tracing::info!(
847                        task_id = task.id.0,
848                        agent = %ctx.review_agent,
849                        exit_code,
850                        output_found = !raw_output.is_empty(),
851                        "review agent succeeded despite non-zero exit β€” proceeding to parse output"
852                    );
853                    return ReviewPhase::Ready(ReviewRun { run_id });
854                }
855            }
856
857            tracing::error!(task_id = task.id.0, error = %e, "review agent failed");
858            complete_review_run(
859                store,
860                run_id,
861                Some(exit_code),
862                "",
863                &e.to_string(),
864                "",
865                "failed",
866                &format!("agent error: {e}"),
867                RunTokenUsage::default(),
868            )
869            .await;
870            ReviewPhase::EarlyReturn(ReviewDecision::Failed(format!("agent error: {e}")))
871        }
872        Err(_) => {
873            let _ = tmux.kill_session(&session).await;
874            if review_output_has_decision(ctx).await {
875                tracing::warn!(
876                    task_id = task.id.0,
877                    "review agent timed out after writing its decision, using it"
878                );
879                return ReviewPhase::Ready(ReviewRun { run_id });
880            }
881
882            tracing::error!(task_id = task.id.0, "review agent timed out");
883            store_review_timeout(store, run_id, -1, "", "timeout").await
884        }
885    }
886}
887
888/// Exit code of the `timeout` command that wraps the review agent
889const REVIEW_TIMEOUT_EXIT_CODE: i32 = 124;
890
891/// A slow review says nothing about the model, so no cooldown: the task goes back
892/// to needs_review and the next review picks an agent as usual
893async fn store_review_timeout<T>(
894    store: &Arc<TaskStore>,
895    run_id: Option<i64>,
896    exit_code: i32,
897    raw_output: &str,
898    stderr: &str,
899) -> ReviewPhase<T> {
900    complete_review_run(
901        store,
902        run_id,
903        Some(exit_code),
904        raw_output,
905        stderr,
906        "",
907        "timeout",
908        "timeout",
909        RunTokenUsage::default(),
910    )
911    .await;
912    ReviewPhase::EarlyReturn(ReviewDecision::Failed("timeout".to_string()))
913}
914
915/// The decision is in when this attempt's final result parses as a review, whatever the session
916/// does. Only this attempt's file counts, an older attempt may have reviewed another commit
917async fn review_output_has_decision(ctx: &ReviewContext) -> bool {
918    let raw = tokio_fs::read_to_string(&ctx.output_file)
919        .await
920        .unwrap_or_default();
921    output_has_review_decision(&ctx.review_agent, &raw)
922}
923
924fn output_has_review_decision(agent: &str, raw: &str) -> bool {
925    let raw = agents::claude::strip_tty_control_lines(raw);
926    agents::find_agent_result(agent, &raw)
927        .filter(|result| !result.is_error)
928        .is_some_and(|result| runner::response::parse_review_response(&result.result_text).is_ok())
929}
930
931async fn wait_for_review_decision(ctx: &ReviewContext, poll_interval: Duration) {
932    loop {
933        time::sleep(poll_interval).await;
934        if review_output_has_decision(ctx).await {
935            return;
936        }
937    }
938}
939
940async fn record_review_agent_failure(
941    task_id: &str,
942    review_agent: &str,
943    review_model: Option<&str>,
944    err: &agents::AgentError,
945) {
946    match err {
947        agents::AgentError::RateLimit { message } | agents::AgentError::Auth { message } => {
948            tracing::warn!(
949                task_id,
950                agent = %review_agent,
951                "review agent hit error β€” adding to cooldown"
952            );
953            if let Some(reason) = cooldown::detect_credit_exhaustion(message) {
954                if reason == CreditExhaustionReason::BillingCycleExhausted {
955                    if let Some(model) = review_model {
956                        // Quota is model-scoped: don't penalize the whole agent.
957                        cooldown::record_persistent_model_failure(review_agent, model).await;
958                    } else {
959                        cooldown::record_credit_exhaustion(review_agent, reason).await;
960                    }
961                } else {
962                    cooldown::record_credit_exhaustion(review_agent, reason).await;
963                }
964            } else {
965                runner::response::record_agent_failure_with_message(review_agent, &err.to_string())
966                    .await;
967            }
968        }
969        // Killed or truncated review run, not a model fault
970        agents::AgentError::Interrupted { .. } => {}
971        agents::AgentError::InvalidResponse { .. } => {
972            // No usable review output, a short backoff since the model itself still works
973            if let Some(model) = review_model {
974                cooldown::record_transient_model_failure(review_agent, model).await;
975            }
976        }
977        agents::AgentError::ModelUnavailable { message, .. } => {
978            // The agent is not penalized, its other models still route normally
979            if let Some(model) = review_model {
980                cooldown::record_model_unavailable(review_agent, model, message).await;
981            }
982        }
983        _ => {
984            // Generic failure (AgentFailed, NetworkError, etc.)
985            // Apply standard model backoff (5min→4h max) to prevent immediate re-selection.
986            if let Some(model) = review_model {
987                cooldown::record_model_failure(review_agent, model).await;
988            }
989        }
990    }
991}
992
993async fn finalize_review_run(
994    task: &ExternalTask,
995    ctx: &ReviewContext,
996    parsed: &ParsedReview,
997    store: &Arc<TaskStore>,
998) {
999    let outcome = match &parsed.decision {
1000        ReviewDecision::Approve { .. }
1001        | ReviewDecision::RequestChanges { .. }
1002        | ReviewDecision::Skipped
1003        | ReviewDecision::Rerouted => "success",
1004        ReviewDecision::Failed(_) | ReviewDecision::Blocked(_) => "failed",
1005    };
1006    let error = match &parsed.decision {
1007        ReviewDecision::Failed(error) | ReviewDecision::Blocked(error) => error.as_str(),
1008        _ => "",
1009    };
1010
1011    if outcome == "success" {
1012        // Mirror the runner's success path so review-only models don't ratchet
1013        // into multi-day cooldowns from isolated failures never offset by resets.
1014        cooldown::record_agent_success(&ctx.review_agent, ctx.review_model_str()).await;
1015    }
1016
1017    complete_review_run(
1018        store,
1019        parsed.run_id,
1020        Some(parsed.exit_code),
1021        &parsed.raw_output,
1022        &parsed.stderr,
1023        &parsed.text_for_review,
1024        outcome,
1025        error,
1026        parsed.token_usage,
1027    )
1028    .await;
1029
1030    if let Some(store_id) = ctx.store_id
1031        && (parsed.token_usage.input_tokens > 0 || parsed.token_usage.output_tokens > 0)
1032    {
1033        let cost_usd = Some(parsed.token_usage.total_cost_usd).filter(|c| *c > 0.0);
1034        if let Err(e) = store
1035            .store_tokens(
1036                store_id,
1037                parsed.token_usage.input_tokens,
1038                parsed.token_usage.output_tokens,
1039                cost_usd,
1040            )
1041            .await
1042        {
1043            tracing::warn!(
1044                task_id = task.id.0,
1045                ?e,
1046                "failed to store review agent token usage"
1047            );
1048        }
1049    }
1050}
1051
1052async fn restore_review_config_if_needed(
1053    task_id: &str,
1054    worktree_path: &Path,
1055    default_branch: &str,
1056) {
1057    let _ = Command::new("git")
1058        .args(["checkout", "HEAD", "--", ".orch.yml"])
1059        .current_dir(worktree_path)
1060        .status()
1061        .await;
1062
1063    let merge_base = Command::new("git")
1064        .args(["merge-base", "HEAD", default_branch])
1065        .current_dir(worktree_path)
1066        .output()
1067        .await
1068        .ok()
1069        .filter(|output| output.status.success())
1070        .and_then(|output| String::from_utf8(output.stdout).ok())
1071        .map(|s| s.trim().to_string())
1072        .unwrap_or_default();
1073
1074    if merge_base.is_empty() {
1075        return;
1076    }
1077
1078    let orch_yml_changed = Command::new("git")
1079        .args([
1080            "diff",
1081            "--name-only",
1082            &merge_base,
1083            "HEAD",
1084            "--",
1085            ".orch.yml",
1086        ])
1087        .current_dir(worktree_path)
1088        .output()
1089        .await
1090        .ok()
1091        .filter(|output| output.status.success())
1092        .is_some_and(|output| !output.stdout.is_empty());
1093
1094    if !orch_yml_changed {
1095        return;
1096    }
1097
1098    tracing::warn!(
1099        task_id,
1100        "review agent modified .orch.yml (forbidden); restoring to merge-base version"
1101    );
1102    let restore_ok = Command::new("git")
1103        .args(["checkout", &merge_base, "--", ".orch.yml"])
1104        .current_dir(worktree_path)
1105        .status()
1106        .await
1107        .is_ok_and(|status| status.success());
1108
1109    if !restore_ok {
1110        return;
1111    }
1112
1113    let staged = Command::new("git")
1114        .args(["diff", "--cached", "--name-only", "--", ".orch.yml"])
1115        .current_dir(worktree_path)
1116        .output()
1117        .await
1118        .ok()
1119        .filter(|output| output.status.success())
1120        .is_some_and(|output| !output.stdout.is_empty());
1121
1122    if staged {
1123        let _ = Command::new("git")
1124            .args([
1125                "-c",
1126                "commit.gpgsign=false",
1127                "commit",
1128                "-m",
1129                "revert: restore .orch.yml (review agent must not modify project config)",
1130            ])
1131            .current_dir(worktree_path)
1132            .status()
1133            .await;
1134    }
1135}
1136
1137fn is_missing_path_error_message(err: &str) -> bool {
1138    err.to_ascii_lowercase()
1139        .contains("no such file or directory")
1140}
1141
1142async fn push_review_branch(
1143    task: &ExternalTask,
1144    repo: &str,
1145    ctx: &ReviewContext,
1146    store: &Arc<TaskStore>,
1147) -> Result<(), String> {
1148    let mut worktree_path = ctx.worktree_path.clone();
1149    let mut branch_name = ctx.branch_name.clone();
1150    let mut retried_missing_worktree = false;
1151
1152    let push_result = loop {
1153        match git::git_ops::push_branch(&worktree_path, &branch_name, &ctx.default_branch).await {
1154            Ok(ok) => break Ok(ok),
1155            Err(e)
1156                if !retried_missing_worktree
1157                    && !worktree_path.exists()
1158                    && is_missing_path_error_message(&e.to_string()) =>
1159            {
1160                retried_missing_worktree = true;
1161                tracing::warn!(
1162                    task_id = task.id.0,
1163                    worktree = %worktree_path.display(),
1164                    branch = %branch_name,
1165                    "review push failed because worktree disappeared; attempting one-time recovery"
1166                );
1167                match recover_missing_review_worktree(task, repo, store).await {
1168                    Ok(recovered) => {
1169                        worktree_path = recovered.work_dir;
1170                        branch_name = recovered.branch;
1171                    }
1172                    Err(recover_err) => {
1173                        break Err(anyhow::anyhow!(
1174                            "missing review worktree recovery failed after push error: {recover_err}"
1175                        ));
1176                    }
1177                }
1178            }
1179            Err(e) => break Err(e),
1180        }
1181    };
1182
1183    match push_result {
1184        Ok(true) => {
1185            store_log_activity(
1186                &Some(Arc::clone(store)),
1187                repo,
1188                &task.id.0,
1189                "push",
1190                None,
1191                None,
1192                Some(&ctx.review_agent),
1193                ctx.review_model.as_deref(),
1194                Some(&serde_json::json!({
1195                    "status": "ok",
1196                    "branch": branch_name.clone(),
1197                    "default_branch": ctx.default_branch.clone(),
1198                    "phase": "review",
1199                })),
1200            )
1201            .await;
1202            if ctx.had_prev_push_failure
1203                && let Err(e) = store_set_result(
1204                    &Some(Arc::clone(store)),
1205                    repo,
1206                    &task.id.0,
1207                    &[
1208                        ("last_error", serde_json::json!("")),
1209                        ("push_failures", serde_json::json!(0)),
1210                    ],
1211                )
1212                .await
1213            {
1214                tracing::warn!(task_id = task.id.0, err = %e, "failed to reset push_failures β€” counter may drift");
1215            }
1216            Ok(())
1217        }
1218        Ok(false) => {
1219            store_log_activity(
1220                &Some(Arc::clone(store)),
1221                repo,
1222                &task.id.0,
1223                "push",
1224                None,
1225                None,
1226                Some(&ctx.review_agent),
1227                ctx.review_model.as_deref(),
1228                Some(&serde_json::json!({
1229                    "status": "skipped",
1230                    "branch": branch_name.clone(),
1231                    "default_branch": ctx.default_branch.clone(),
1232                    "phase": "review",
1233                })),
1234            )
1235            .await;
1236            Err("push skipped".to_string())
1237        }
1238        Err(e) => {
1239            store_log_activity(
1240                &Some(Arc::clone(store)),
1241                repo,
1242                &task.id.0,
1243                "push",
1244                None,
1245                None,
1246                Some(&ctx.review_agent),
1247                ctx.review_model.as_deref(),
1248                Some(&serde_json::json!({
1249                    "status": "error",
1250                    "branch": branch_name.clone(),
1251                    "default_branch": ctx.default_branch.clone(),
1252                    "phase": "review",
1253                    "error": e.to_string(),
1254                })),
1255            )
1256            .await;
1257            tracing::error!(
1258                task_id = task.id.0,
1259                branch = %ctx.branch_name,
1260                error = %e,
1261                "review push failed"
1262            );
1263            store_set(
1264                &Some(Arc::clone(store)),
1265                repo,
1266                &task.id.0,
1267                &[("last_error", serde_json::json!(format!("push failed: {e}")))],
1268            )
1269            .await;
1270            Err(e.to_string())
1271        }
1272    }
1273}
1274
1275#[expect(
1276    clippy::too_many_arguments,
1277    reason = "applying a decision touches the backend, the store, tmux and the router"
1278)]
1279async fn apply_review_decision(
1280    task: &ExternalTask,
1281    backend: &Arc<dyn ExternalBackend>,
1282    repo: &str,
1283    task_manager: &Arc<TaskManager>,
1284    store: &Arc<TaskStore>,
1285    ctx: &ReviewContext,
1286    parsed: &ParsedReview,
1287    router_config: &RouterConfig,
1288) -> anyhow::Result<ReviewDecision> {
1289    restore_review_config_if_needed(&task.id.0, &ctx.worktree_path, &ctx.default_branch).await;
1290
1291    if let Err(e) = push_review_branch(task, repo, ctx, store).await {
1292        return Ok(ReviewDecision::Failed(format!("push failed: {e}")));
1293    }
1294
1295    post_review_comment(
1296        task,
1297        repo,
1298        ctx,
1299        &parsed.decision,
1300        &parsed.review_notes_for_comment,
1301    )
1302    .await?;
1303
1304    match &parsed.decision {
1305        ReviewDecision::Approve { .. } => {
1306            record_approved_sha(
1307                store,
1308                repo,
1309                &task.id.0,
1310                ctx.pr_number,
1311                &ctx.worktree_path,
1312                &ctx.branch_name,
1313                &ctx.default_branch,
1314            )
1315            .await;
1316            // auto_merge_pr refuses unless the stored status is already Approved
1317            if let Err(e) = task_manager
1318                .update_task_status_if(&task.id, Status::Approved, Status::InReview)
1319                .await
1320            {
1321                tracing::warn!(
1322                    task_id = task.id.0,
1323                    err = %e,
1324                    "failed to set Approved before auto-merge"
1325                );
1326            }
1327            // Always attempt auto-merge on approval. Tasks are only marked
1328            // Done when the PR is actually merged (detected by review_poll).
1329            // Never mark Done on approval alone β€” that closes the issue
1330            // before the code lands.
1331            if let Err(e) = auto_merge_pr(
1332                task,
1333                &ctx.branch_name,
1334                backend,
1335                repo,
1336                &ctx.review_agent,
1337                ctx.review_model_str(),
1338                task_manager,
1339                store,
1340            )
1341            .await
1342            {
1343                let error_msg = e.to_string();
1344                if error_msg.contains("not yet computed") {
1345                    tracing::warn!(
1346                        task_id = task.id.0,
1347                        pr_number = ctx.pr_number,
1348                        branch = %ctx.branch_name,
1349                        error = %e,
1350                        "auto-merge deferred β€” PR mergeability not yet computed"
1351                    );
1352                } else {
1353                    tracing::error!(
1354                        task_id = task.id.0,
1355                        pr_number = ctx.pr_number,
1356                        branch = %ctx.branch_name,
1357                        error = %e,
1358                        "auto-merge failed"
1359                    );
1360                }
1361                return Ok(ReviewDecision::Failed(format!("merge failed: {e}")));
1362            }
1363            Ok(parsed.decision.clone())
1364        }
1365        ReviewDecision::RequestChanges { notes, issues } => {
1366            clear_approved_sha(store, repo, &task.id.0, ctx.pr_number).await;
1367            handle_review_changes(
1368                task,
1369                notes,
1370                issues,
1371                backend,
1372                repo,
1373                ctx.pr_number,
1374                &ctx.review_agent,
1375                ctx.review_model_str(),
1376                task_manager,
1377                store,
1378                router_config,
1379            )
1380            .await?;
1381            Ok(parsed.decision.clone())
1382        }
1383        _ => Ok(parsed.decision.clone()),
1384    }
1385}
1386
1387fn review_project_dir(repo: &str) -> Option<PathBuf> {
1388    config::get_projects_with_paths()
1389        .unwrap_or_default()
1390        .into_iter()
1391        .find(|(candidate, _)| candidate == repo)
1392        .map(|(_, dir)| dir)
1393}
1394
1395fn sandboxed_in(project_dir: Option<&Path>) -> bool {
1396    match project_dir {
1397        Some(dir) => runner::sandbox::enabled(dir),
1398        None => runner::sandbox::enabled_globally(),
1399    }
1400}
1401
1402/// Whether the review agent for `repo` runs in the OS sandbox
1403pub(crate) fn review_sandboxed(repo: &str) -> bool {
1404    sandboxed_in(review_project_dir(repo).as_deref())
1405}
1406
1407/// The review agent's own time limit, as configured.
1408pub(crate) fn review_timeout_seconds() -> u64 {
1409    review_timeout_secs(
1410        config::get("workflow.review_timeout_seconds")
1411            .ok()
1412            .and_then(|s| s.parse().ok()),
1413    )
1414}
1415
1416/// Seconds a finished review needs to get its result from the agent's output file into the engine.
1417/// The agent ends its tmux session first, so the no-session recovery sees a dead session while the
1418/// result is still in flight
1419pub(crate) const REVIEW_RESULT_DELIVERY_SECS: u64 = 120;
1420
1421/// Smallest no-session recovery limit that cannot cut a review short. Below the review agent's own
1422/// timeout plus delivery time, recovery resets a task whose finished review is still arriving and
1423/// the result is dropped as stale
1424pub(crate) fn no_session_review_floor(configured: u64, review_timeout: u64) -> u64 {
1425    configured.max(review_timeout + REVIEW_RESULT_DELIVERY_SECS)
1426}
1427
1428/// Run the review agent on a completed task and handle the outcome.
1429///
1430/// Called after a task completes with status:done and a PR is created.
1431/// The review agent checks the changes and either approves (triggers auto-merge)
1432/// or requests changes (re-dispatches the original agent).
1433pub(crate) async fn review_and_merge(
1434    task: &ExternalTask,
1435    backend: &Arc<dyn ExternalBackend>,
1436    tmux: &Arc<TmuxManager>,
1437    repo: &str,
1438    router: &Arc<RwLock<Router>>,
1439    task_manager: &Arc<TaskManager>,
1440    store: &Arc<TaskStore>,
1441) -> anyhow::Result<ReviewDecision> {
1442    let ctx = match build_review_context(task, repo, router, task_manager, store).await? {
1443        ReviewPhase::Ready(ctx) => ctx,
1444        ReviewPhase::EarlyReturn(decision) => return Ok(decision),
1445    };
1446
1447    let run = match invoke_review_agent(task, tmux, &ctx, repo, store).await {
1448        ReviewPhase::Ready(run) => run,
1449        ReviewPhase::EarlyReturn(decision) => return Ok(decision),
1450    };
1451
1452    let parsed = match parse_review_output(task, repo, &ctx, run, store).await {
1453        ReviewPhase::Ready(parsed) => parsed,
1454        ReviewPhase::EarlyReturn(decision) => return Ok(decision),
1455    };
1456
1457    finalize_review_run(task, &ctx, &parsed, store).await;
1458
1459    let router_config = router.read().await.config.clone();
1460    apply_review_decision(
1461        task,
1462        backend,
1463        repo,
1464        task_manager,
1465        store,
1466        &ctx,
1467        &parsed,
1468        &router_config,
1469    )
1470    .await
1471}
1472
1473#[cfg(test)]
1474mod tests;
1475
1476#[cfg(test)]
1477mod approval_tests;