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