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