Skip to main content

orch/engine/runner/
task_init.rs

1//! Task initialization — guard checks, worktree setup, and invocation building.
2//!
3//! Extracted from `runner/mod.rs`. Contains the first phase of `run()`:
4//! guard checks, worktree creation, context building, and prompt assembly.
5
6use crate::backends::{ExternalBackend, ExternalId, ExternalTask};
7use crate::config;
8use crate::engine::router::{RouteResultError, get_route_result};
9use crate::store;
10use crate::store::TaskStore;
11use crate::sys::tmux::TmuxManager;
12use std::fmt;
13use std::fmt::Debug;
14use std::fmt::Formatter;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use super::{agent, context};
19use crate::engine::RouterConfig;
20use crate::engine::RunTimeouts;
21use crate::engine::git::cleanup;
22use crate::engine::git::git_ops;
23use crate::engine::git::worktree;
24use crate::sys::home;
25
26/// Result of task preparation: everything needed to run an agent session.
27pub struct TaskInitResult {
28    pub agent_name: String,
29    pub model_name: Option<String>,
30    pub complexity: Option<String>,
31    pub task_title: String,
32    pub wt: worktree::WorktreeSetup,
33    pub invocation: agent::AgentInvocation,
34    pub attempt_dir: PathBuf,
35    pub new_attempts: u32,
36}
37
38impl Debug for TaskInitResult {
39    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
40        f.debug_struct("TaskInitResult")
41            .field("agent_name", &self.agent_name)
42            .field("model_name", &self.model_name)
43            .field("complexity", &self.complexity)
44            .field("task_title", &self.task_title)
45            .field("wt", &self.wt)
46            .field("attempt_dir", &self.attempt_dir)
47            .field("new_attempts", &self.new_attempts)
48            .finish_non_exhaustive()
49    }
50}
51
52/// Outcome of the guard check.
53#[derive(Debug)]
54pub enum GuardOutcome {
55    /// Task should proceed; returns current attempt count.
56    Proceed(u32),
57    /// Task should be skipped (already running, status=needs_review, etc.).
58    Skip,
59    /// Task has exceeded max attempts, caller marks it blocked.
60    MaxAttempts,
61}
62
63/// Check task guards and return the outcome.
64///
65/// Also checks for existing tmux sessions to prevent duplicate dispatch.
66pub async fn check_guards(
67    task_id: &str,
68    repo: &str,
69    store: &Option<Arc<TaskStore>>,
70) -> anyhow::Result<GuardOutcome> {
71    let attempts: u32 = store::opt_store_get_task(store, repo, task_id)
72        .await
73        .map_or(0, |t| u32::try_from(t.attempts).unwrap_or(0));
74
75    // Guard: check if tmux session already exists (prevents duplicate dispatch)
76    let tmux = TmuxManager::new();
77    let session_name = tmux.session_name(repo, task_id);
78    if tmux.session_blocks_dispatch(&session_name).await {
79        tracing::info!(
80            task_id,
81            session = %session_name,
82            "skipping task: tmux session already exists"
83        );
84        return Ok(GuardOutcome::Skip);
85    }
86
87    // Check max attempts
88    let max_attempts: u32 = config::get("workflow.max_attempts")
89        .ok()
90        .and_then(|s| s.parse().ok())
91        .unwrap_or(5);
92
93    if attempts >= max_attempts {
94        tracing::warn!(task_id, attempts, max_attempts, "exceeded max attempts");
95        let msg =
96            format!("exceeded max attempts ({attempts}/{max_attempts}). Use `/retry` to reset.");
97        if let Err(e) = store::store_set_result(
98            store,
99            repo,
100            task_id,
101            &[
102                ("last_error", serde_json::json!(msg)),
103                ("block_reason", serde_json::json!(msg)),
104            ],
105        )
106        .await
107        {
108            tracing::warn!(task_id, err = %e, "failed to write max_attempts last_error to store");
109        }
110        return Ok(GuardOutcome::MaxAttempts);
111    }
112
113    Ok(GuardOutcome::Proceed(attempts))
114}
115
116/// Build a minimal `ExternalTask` from store state for prompt building.
117pub async fn build_pseudo_task(
118    task_id: &str,
119    store: &Option<Arc<TaskStore>>,
120    repo: &str,
121) -> ExternalTask {
122    let (task_title, task_body) = store::opt_store_get_task(store, repo, task_id)
123        .await
124        .map_or_else(
125            || (format!("Task #{task_id}"), String::new()),
126            |t| (t.title, t.body),
127        );
128    ExternalTask {
129        id: ExternalId(task_id.to_string()),
130        title: task_title,
131        body: task_body,
132        state: "open".to_string(),
133        labels: vec![],
134        author: String::new(),
135        created_at: String::new(),
136        updated_at: String::new(),
137        url: String::new(),
138    }
139}
140
141/// The router clears a stale model by writing an empty string, and `--model ""` makes the claude
142/// API answer 400, so an empty name at any level means no model
143fn resolve_model_name(
144    param: Option<&str>,
145    routed: Option<&str>,
146    stored: Option<&str>,
147) -> Option<String> {
148    [param, routed, stored]
149        .into_iter()
150        .flatten()
151        .map(str::trim)
152        .find(|m| !m.is_empty())
153        .map(String::from)
154}
155
156/// Prepare the full task: set up worktree, build context and prompts, create invocation.
157#[expect(
158    clippy::too_many_arguments,
159    reason = "task setup needs the routing result, backend, project paths and store together"
160)]
161pub async fn prepare_task(
162    task_id: &str,
163    agent: Option<&str>,
164    model: Option<&str>,
165    backend: Option<&dyn ExternalBackend>,
166    repo: &str,
167    project_dir: &Path,
168    attempts: u32,
169    store: &Option<Arc<TaskStore>>,
170) -> anyhow::Result<TaskInitResult> {
171    // Load title (and model fallback) from store.
172    // `model` param and `route_result.model` can both be None when a prior
173    // ModelUnavailable failover wrote the new model to tasks.model but did not
174    // update task_routes.model.  Reading tasks.model here ensures model_name is
175    // never None when the task already has a model assigned — which matters for
176    // BillingCycleExhausted handling in fallback.rs (model-known → model-level
177    // cooldown only; model-unknown → agent-wide 24 h cooldown).
178    let initial_task = store::opt_store_get_task(store, repo, task_id).await;
179    let title_for_branch = initial_task
180        .as_ref()
181        .map(|t| t.title.clone())
182        .unwrap_or_default();
183    let stored_model = initial_task.and_then(|t| t.model);
184
185    // Set up worktree
186    let wt = worktree::setup_worktree(task_id, &title_for_branch, project_dir, store, repo).await?;
187
188    // Rebase worktree on default branch to pick up latest changes.
189    // This prevents non-fast-forward push failures when the task is re-dispatched.
190    git_ops::rebase_on_default(&wt.work_dir, &wt.default_branch).await;
191
192    // Get routing result — distinguish between "no route" and store errors
193    let route_result = if let Some(s) = store {
194        match get_route_result(s, repo, task_id).await {
195            Ok(r) => Some(r),
196            // NoAgent means the router hasn't set a route for this task yet;
197            // fall back to the default agent (caller may re-route later).
198            Err(RouteResultError::NoAgent { .. }) => {
199                tracing::warn!(task_id, "routed task has no agent — using fallback");
200                None
201            }
202            // Any other error indicates a store/IO problem — surface it so the
203            // caller doesn't silently proceed with an incorrect fallback.
204            Err(e) => {
205                tracing::error!(task_id, error = %e, "failed to get route result from store — blocking task");
206                // Persist the error to the task result so operators can see it.
207                let err_msg = format!("failed to read routing result: {e}");
208                if let Err(set_err) = store::store_set_result(
209                    store,
210                    repo,
211                    task_id,
212                    &[("last_error", serde_json::json!(err_msg.clone()))],
213                )
214                .await
215                {
216                    tracing::warn!(task_id, err = %set_err, "failed to write route read error to store");
217                }
218                // Attempt to clean up the worktree we created to avoid leaving
219                // partial artifacts behind.
220                if let Some(s) = store {
221                    let _ = cleanup::cleanup_task_worktree(task_id, repo, s).await;
222                }
223                return Err(anyhow::anyhow!(err_msg));
224            }
225        }
226    } else {
227        None
228    };
229
230    let agent_name = agent
231        .map(String::from)
232        .or_else(|| route_result.as_ref().map(|r| r.agent.clone()))
233        .unwrap_or_else(|| "claude".to_string());
234
235    let model_name = resolve_model_name(
236        model,
237        route_result.as_ref().and_then(|r| r.model.as_deref()),
238        stored_model.as_deref(),
239    );
240
241    let complexity = route_result.as_ref().map(|r| r.complexity.clone());
242
243    // Build a minimal ExternalTask for prompt building
244    let pseudo_task = build_pseudo_task(task_id, store, repo).await;
245    let task_title = pseudo_task.title.clone();
246
247    // Build full context: memory, issue comments, and parent context are all loaded here
248    let ctx = context::build_full_context(
249        &pseudo_task,
250        backend,
251        &wt.work_dir,
252        &wt.default_branch,
253        attempts,
254        store,
255        repo,
256    )
257    .await;
258
259    let sandboxed = super::sandbox::enabled(&wt.main_project_dir);
260    let shipcheck = agent::Shipcheck::detect(&wt.work_dir).await;
261    agent::install_shipcheck_hooks(&wt.work_dir, shipcheck, Path::new("shipcheck")).await;
262
263    // Build prompts
264    let system_prompt = agent::build_system_prompt(
265        &pseudo_task,
266        &ctx,
267        route_result.as_ref(),
268        &wt.default_branch,
269        shipcheck.in_sandbox(sandboxed, &wt.work_dir).await,
270        sandboxed,
271    );
272    let agent_message = agent::build_agent_message(&pseudo_task, &ctx, attempts);
273
274    // Git identity
275    let git_name = config::get("git.name").unwrap_or_else(|_| format!("{agent_name}[bot]"));
276    let git_email = config::get("git.email")
277        .unwrap_or_else(|_| format!("{agent_name}[bot]@users.noreply.github.com"));
278
279    // Output file in per-task attempt directory (attempt = attempts + 1, set below)
280    let next_attempt = attempts + 1;
281    let attempt_dir = match home::task_attempt_dir_async(repo, task_id, next_attempt).await {
282        Ok(dir) => dir,
283        Err(e) => {
284            if let Some(s) = store {
285                let _ = cleanup::cleanup_task_worktree(task_id, repo, s).await;
286            }
287            return Err(e);
288        }
289    };
290    let output_file = attempt_dir.join("output.json");
291
292    // Build sandbox disallowed tools
293    let mut disallowed_tools = vec![
294        "Bash(rm *)".to_string(),
295        "Bash(rm -*)".to_string(),
296        "Bash(git push*)".to_string(),
297        // Pushing and opening the PR are orch's steps. An agent that tries either hits a
298        // permission prompt or a rejection and reports it as its own failure (#3783)
299        "Bash(gh pr create*)".to_string(),
300    ];
301    disallowed_tools.extend(git_ops::remote_change_tools());
302
303    // Sandbox: block access to main project dir
304    if wt.work_dir != wt.main_project_dir {
305        let main_str = wt.main_project_dir.to_string_lossy();
306        disallowed_tools.extend([
307            format!("Bash(cd {main_str}*)"),
308            format!("Read({main_str}/*)"),
309            format!("Write({main_str}/*)"),
310            format!("Edit({main_str}/*)"),
311        ]);
312    }
313
314    if let Ok(orch_home) = home::orch_home() {
315        for path in [
316            orch_home.join("config.yml"),
317            orch_home.join("config.example.yml"),
318        ] {
319            let path_str = path.to_string_lossy();
320            disallowed_tools.extend([
321                format!("Read({path_str})"),
322                format!("Write({path_str})"),
323                format!("Edit({path_str})"),
324            ]);
325        }
326    }
327
328    // Sandbox: block .orch.yml project config (settled architecture: agents must not modify it)
329    {
330        let orch_yml = wt.work_dir.join(".orch.yml");
331        let orch_yml_str = orch_yml.to_string_lossy();
332        disallowed_tools.extend([
333            format!("Write({orch_yml_str})"),
334            format!("Edit({orch_yml_str})"),
335        ]);
336    }
337
338    // Stuck recovery reads the same limits, so a live session is never taken before this runs out
339    // A model taken from another tier runs with that tier's timeout
340    let timeout_tier = match (complexity.as_deref(), model_name.as_deref()) {
341        (Some(c), Some(m)) if !m.is_empty() => {
342            Some(RouterConfig::from_config().tier_of_model(&agent_name, m, c))
343        }
344        (c, _) => c.map(String::from),
345    };
346    let timeout_seconds = RunTimeouts::from_config().for_complexity(timeout_tier.as_deref());
347
348    // Build agent invocation
349    let invocation = agent::AgentInvocation {
350        agent: agent_name.clone(),
351        model: model_name.clone(),
352        reasoning_effort: route_result
353            .as_ref()
354            .and_then(|r| r.profile.execution.as_ref())
355            .filter(|p| p.matches_route(&agent_name, model_name.as_deref()))
356            .and_then(|p| p.effort.clone()),
357        work_dir: wt.work_dir.clone(),
358        system_prompt,
359        agent_message,
360        task_id: task_id.to_string(),
361        disallowed_tools,
362        git_author_name: git_name,
363        git_author_email: git_email,
364        output_file,
365        timeout_seconds,
366        repo: repo.to_string(),
367        attempt: next_attempt,
368        sandbox: sandboxed,
369        main_project_dir: wt.main_project_dir.clone(),
370        branch: wt.branch.clone(),
371    };
372
373    // Increment attempts counter — must succeed so max_attempts guard cannot be bypassed.
374    // Also clears last_error, so a failover's error never reads as this run's outcome
375    if let Err(e) = store::store_set_result(
376        store,
377        repo,
378        task_id,
379        &[
380            ("attempts", serde_json::json!(next_attempt)),
381            ("last_error", serde_json::json!("")),
382        ],
383    )
384    .await
385    {
386        if let Some(s) = store {
387            let _ = cleanup::cleanup_task_worktree(task_id, repo, s).await;
388        }
389        return Err(anyhow::anyhow!("failed to persist attempts counter: {e}"));
390    }
391
392    Ok(TaskInitResult {
393        agent_name,
394        model_name,
395        complexity,
396        task_title,
397        wt,
398        invocation,
399        attempt_dir,
400        new_attempts: next_attempt,
401    })
402}
403
404#[cfg(test)]
405mod tests {
406    use std::env;
407    use std::mem;
408    use std::process::Command;
409
410    use super::*;
411    use crate::engine::runner::{WeightSignal, needs_review_signal};
412    use crate::engine::tick::display_status_for;
413    use crate::store::NewTask;
414
415    const FAILOVER_ERROR: &str = "claude timed out after 1804s, switching to codex for re-route";
416
417    /// Seeds a no-code task with `seed_error`, then runs `prepare_task` for its next run
418    async fn prepare_run(seed_error: &str) -> (Arc<TaskStore>, i64) {
419        let orch_home = tempfile::tempdir().unwrap();
420        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
421        unsafe { env::set_var("ORCH_HOME", orch_home.path()) };
422        mem::forget(orch_home);
423
424        let project = tempfile::tempdir().unwrap();
425        for args in [
426            &["init", "-b", "main"][..],
427            &["config", "user.email", "t@t.com"],
428            &["config", "user.name", "T"],
429            &["commit", "--allow-empty", "-m", "base"],
430        ] {
431            let out = Command::new("git")
432                .args(args)
433                .current_dir(project.path())
434                .output()
435                .unwrap();
436            assert!(out.status.success(), "git {args:?} failed");
437        }
438
439        let task_store = Arc::new(TaskStore::open_memory().await.unwrap());
440        let store_id = task_store
441            .create(&NewTask {
442                repo: "owner/repo".to_string(),
443                origin: "internal".to_string(),
444                title: "Check the report".to_string(),
445                ..Default::default()
446            })
447            .await
448            .unwrap();
449        task_store
450            .set_fields(store_id, &[("last_error", serde_json::json!(seed_error))])
451            .await
452            .unwrap();
453        let task_id = format!("internal:{store_id}");
454        let store = Some(Arc::clone(&task_store));
455
456        prepare_task(
457            &task_id,
458            Some("claude"),
459            Some("sonnet"),
460            None,
461            "owner/repo",
462            project.path(),
463            0,
464            &store,
465        )
466        .await
467        .expect("prepare_task should succeed");
468        (task_store, store_id)
469    }
470
471    async fn stored_last_error(store: &TaskStore, store_id: i64) -> String {
472        store.get(store_id).await.unwrap().last_error
473    }
474
475    #[tokio::test]
476    async fn no_code_task_is_done_after_a_failover_when_the_fallback_run_succeeds() {
477        let (store, id) = prepare_run(FAILOVER_ERROR).await;
478
479        let last_error = stored_last_error(&store, id).await;
480        assert_eq!(last_error, "", "starting a run clears the failover error");
481        // The fallback agent finishes with no commits and no PR, so nothing writes last_error
482        let signal = needs_review_signal(&last_error, "codex");
483        assert!(matches!(signal, WeightSignal::Success { .. }));
484        assert_eq!(display_status_for(&signal, true, false), "done");
485    }
486
487    #[tokio::test]
488    async fn no_code_task_is_done_after_a_first_run_with_no_commits() {
489        let (store, id) = prepare_run("").await;
490
491        let signal = needs_review_signal(&stored_last_error(&store, id).await, "claude");
492        assert!(matches!(signal, WeightSignal::Success { .. }));
493        assert_eq!(display_status_for(&signal, true, false), "done");
494    }
495
496    #[tokio::test]
497    async fn timed_out_run_with_no_fallback_stays_in_needs_review() {
498        let (store, id) = prepare_run(FAILOVER_ERROR).await;
499
500        // handle_error stores this when the run times out and no fallback agent is left
501        store
502            .set_fields(
503                id,
504                &[(
505                    "last_error",
506                    serde_json::json!("claude timed out after 1804s, no fallback agents"),
507                )],
508            )
509            .await
510            .unwrap();
511
512        let signal = needs_review_signal(&stored_last_error(&store, id).await, "claude");
513        assert!(matches!(signal, WeightSignal::Failed { .. }));
514        assert_eq!(display_status_for(&signal, true, false), "needs_review");
515    }
516
517    #[test]
518    fn resolve_model_name_skips_a_model_cleared_to_empty() {
519        assert_eq!(resolve_model_name(None, None, Some("")), None);
520        assert_eq!(resolve_model_name(None, Some(""), Some("")), None);
521        assert_eq!(
522            resolve_model_name(None, None, Some("sonnet")).as_deref(),
523            Some("sonnet")
524        );
525        assert_eq!(
526            resolve_model_name(Some("opus"), Some("sonnet"), Some("haiku")).as_deref(),
527            Some("opus")
528        );
529    }
530
531    #[tokio::test]
532    async fn max_attempts_writes_block_reason() {
533        let task_store = Arc::new(TaskStore::open_memory().await.unwrap());
534        let store_id = task_store
535            .create(&NewTask {
536                repo: "owner/repo".to_string(),
537                origin: "internal".to_string(),
538                title: "Test".to_string(),
539                ..Default::default()
540            })
541            .await
542            .unwrap();
543        task_store
544            .set_fields(store_id, &[("attempts", serde_json::json!(1000))])
545            .await
546            .unwrap();
547        let store = Some(Arc::clone(&task_store));
548
549        let outcome = check_guards(&format!("internal:{store_id}"), "owner/repo", &store)
550            .await
551            .unwrap();
552
553        assert!(matches!(outcome, GuardOutcome::MaxAttempts));
554        let task = task_store.get(store_id).await.unwrap();
555        assert!(
556            task.block_reason
557                .is_some_and(|r| r.contains("exceeded max attempts"))
558        );
559    }
560}