1use 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
24pub 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#[derive(Debug)]
52pub enum GuardOutcome {
53 Proceed(u32),
55 Skip,
57 MaxAttempts,
59}
60
61pub 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 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 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
114pub 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
139fn 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#[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 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 let wt = worktree::setup_worktree(task_id, &title_for_branch, project_dir, store, repo).await?;
185
186 git_ops::rebase_on_default(&wt.work_dir, &wt.default_branch).await;
189
190 let route_result = if let Some(s) = store {
192 match get_route_result(s, repo, task_id).await {
193 Ok(r) => Some(r),
194 Err(RouteResultError::NoAgent { .. }) => {
197 tracing::warn!(task_id, "routed task has no agent — using fallback");
198 None
199 }
200 Err(e) => {
203 tracing::error!(task_id, error = %e, "failed to get route result from store — blocking task");
204 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 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 let pseudo_task = build_pseudo_task(task_id, store, repo).await;
243 let task_title = pseudo_task.title.clone();
244
245 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 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 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 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 let mut disallowed_tools = vec![
291 "Bash(rm *)".to_string(),
292 "Bash(rm -*)".to_string(),
293 "Bash(git push*)".to_string(),
294 "Bash(gh pr create*)".to_string(),
297 ];
298 disallowed_tools.extend(git_ops::remote_change_tools());
299
300 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 {
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 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 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 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 async fn prepare_run(seed_error: &str) -> (Arc<TaskStore>, i64) {
411 let orch_home = tempfile::tempdir().unwrap();
412 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 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 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}