1use 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::engine::tasks::jobs;
27use crate::sys::home;
28
29pub struct TaskInitResult {
31 pub agent_name: String,
32 pub model_name: Option<String>,
33 pub complexity: Option<String>,
34 pub task_title: String,
35 pub wt: worktree::WorktreeSetup,
36 pub invocation: agent::AgentInvocation,
37 pub attempt_dir: PathBuf,
38 pub new_attempts: u32,
39}
40
41impl Debug for TaskInitResult {
42 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
43 f.debug_struct("TaskInitResult")
44 .field("agent_name", &self.agent_name)
45 .field("model_name", &self.model_name)
46 .field("complexity", &self.complexity)
47 .field("task_title", &self.task_title)
48 .field("wt", &self.wt)
49 .field("attempt_dir", &self.attempt_dir)
50 .field("new_attempts", &self.new_attempts)
51 .finish_non_exhaustive()
52 }
53}
54
55#[derive(Debug)]
57pub enum GuardOutcome {
58 Proceed(u32),
60 Skip,
62 MaxAttempts,
64}
65
66pub async fn check_guards(
70 task_id: &str,
71 repo: &str,
72 store: &Option<Arc<TaskStore>>,
73) -> anyhow::Result<GuardOutcome> {
74 let attempts: u32 = store::opt_store_get_task(store, repo, task_id)
75 .await
76 .map_or(0, |t| u32::try_from(t.attempts).unwrap_or(0));
77
78 let tmux = TmuxManager::new();
80 let session_name = tmux.session_name(repo, task_id);
81 if tmux.session_blocks_dispatch(&session_name, None).await {
82 tracing::info!(
83 task_id,
84 session = %session_name,
85 "skipping task: tmux session already exists"
86 );
87 return Ok(GuardOutcome::Skip);
88 }
89
90 let max_attempts: u32 = config::get("workflow.max_attempts")
92 .ok()
93 .and_then(|s| s.parse().ok())
94 .unwrap_or(5);
95
96 if attempts >= max_attempts {
97 tracing::warn!(task_id, attempts, max_attempts, "exceeded max attempts");
98 let msg =
99 format!("exceeded max attempts ({attempts}/{max_attempts}). Use `/retry` to reset.");
100 if let Err(e) = store::store_set_result(
101 store,
102 repo,
103 task_id,
104 &[
105 ("last_error", serde_json::json!(msg)),
106 ("block_reason", serde_json::json!(msg)),
107 ],
108 )
109 .await
110 {
111 tracing::warn!(task_id, err = %e, "failed to write max_attempts last_error to store");
112 }
113 return Ok(GuardOutcome::MaxAttempts);
114 }
115
116 Ok(GuardOutcome::Proceed(attempts))
117}
118
119pub async fn build_pseudo_task(
121 task_id: &str,
122 store: &Option<Arc<TaskStore>>,
123 repo: &str,
124) -> ExternalTask {
125 let (task_title, task_body) = store::opt_store_get_task(store, repo, task_id)
126 .await
127 .map_or_else(
128 || (format!("Task #{task_id}"), String::new()),
129 |t| (t.title, t.body),
130 );
131 ExternalTask {
132 id: ExternalId(task_id.to_string()),
133 title: task_title,
134 body: task_body,
135 state: "open".to_string(),
136 labels: vec![],
137 author: String::new(),
138 created_at: String::new(),
139 updated_at: String::new(),
140 url: String::new(),
141 }
142}
143
144fn resolve_model_name(
147 param: Option<&str>,
148 routed: Option<&str>,
149 stored: Option<&str>,
150) -> Option<String> {
151 [param, routed, stored]
152 .into_iter()
153 .flatten()
154 .map(str::trim)
155 .find(|m| !m.is_empty())
156 .map(String::from)
157}
158
159#[expect(
161 clippy::too_many_arguments,
162 reason = "task setup needs the routing result, backend, project paths and store together"
163)]
164pub async fn prepare_task(
165 task_id: &str,
166 agent: Option<&str>,
167 model: Option<&str>,
168 backend: Option<&dyn ExternalBackend>,
169 repo: &str,
170 project_dir: &Path,
171 attempts: u32,
172 store: &Option<Arc<TaskStore>>,
173) -> anyhow::Result<TaskInitResult> {
174 let initial_task = store::opt_store_get_task(store, repo, task_id).await;
182 let title_for_branch = initial_task
183 .as_ref()
184 .map(|t| t.title.clone())
185 .unwrap_or_default();
186 let stored_model = initial_task.and_then(|t| t.model);
187
188 let wt = worktree::setup_worktree(task_id, &title_for_branch, project_dir, store, repo).await?;
190
191 git_ops::rebase_on_default(&wt.work_dir, &wt.default_branch).await;
194
195 let route_result = if let Some(s) = store {
197 match get_route_result(s, repo, task_id).await {
198 Ok(r) => Some(r),
199 Err(RouteResultError::NoAgent { .. }) => {
202 tracing::warn!(task_id, "routed task has no agent — using fallback");
203 None
204 }
205 Err(e) => {
208 tracing::error!(task_id, error = %e, "failed to get route result from store — blocking task");
209 let err_msg = format!("failed to read routing result: {e}");
211 if let Err(set_err) = store::store_set_result(
212 store,
213 repo,
214 task_id,
215 &[("last_error", serde_json::json!(err_msg.clone()))],
216 )
217 .await
218 {
219 tracing::warn!(task_id, err = %set_err, "failed to write route read error to store");
220 }
221 if let Some(s) = store {
224 let _ = cleanup::cleanup_task_worktree(task_id, repo, s).await;
225 }
226 return Err(anyhow::anyhow!(err_msg));
227 }
228 }
229 } else {
230 None
231 };
232
233 let agent_name = agent
234 .map(String::from)
235 .or_else(|| route_result.as_ref().map(|r| r.agent.clone()))
236 .unwrap_or_else(|| "claude".to_string());
237
238 let model_name = resolve_model_name(
239 model,
240 route_result.as_ref().and_then(|r| r.model.as_deref()),
241 stored_model.as_deref(),
242 );
243
244 let complexity = route_result.as_ref().map(|r| r.complexity.clone());
245
246 let pseudo_task = build_pseudo_task(task_id, store, repo).await;
248 let task_title = pseudo_task.title.clone();
249
250 let ctx = context::build_full_context(
252 &pseudo_task,
253 backend,
254 &wt.work_dir,
255 &wt.default_branch,
256 attempts,
257 store,
258 repo,
259 )
260 .await;
261
262 let sandboxed = super::sandbox::enabled(&wt.main_project_dir)
263 && !match store {
264 Some(s) => jobs::sandbox_off_for(s, repo, &wt.main_project_dir, task_id).await,
265 None => false,
266 };
267 let shipcheck = agent::Shipcheck::detect(&wt.work_dir).await;
268 agent::install_shipcheck_hooks(&wt.work_dir, shipcheck, Path::new("shipcheck")).await;
269
270 let system_prompt = agent::build_system_prompt(
272 &pseudo_task,
273 &ctx,
274 route_result.as_ref(),
275 &wt.default_branch,
276 shipcheck.in_sandbox(sandboxed, &wt.work_dir).await,
277 sandboxed,
278 );
279 let agent_message = agent::build_agent_message(&pseudo_task, &ctx, attempts);
280
281 let git_name = config::get("git.name").unwrap_or_else(|_| format!("{agent_name}[bot]"));
283 let git_email = config::get("git.email")
284 .unwrap_or_else(|_| format!("{agent_name}[bot]@users.noreply.github.com"));
285
286 let next_attempt = attempts + 1;
288 let attempt_dir = match home::task_attempt_dir_async(repo, task_id, next_attempt).await {
289 Ok(dir) => dir,
290 Err(e) => {
291 if let Some(s) = store {
292 let _ = cleanup::cleanup_task_worktree(task_id, repo, s).await;
293 }
294 return Err(e);
295 }
296 };
297 let output_file = attempt_dir.join("output.json");
298
299 let mut disallowed_tools = vec![
301 "Bash(rm *)".to_string(),
302 "Bash(rm -*)".to_string(),
303 "Bash(git push*)".to_string(),
304 "Bash(gh pr create*)".to_string(),
307 ];
308 disallowed_tools.extend(agents::remote_change_tools());
309
310 if wt.work_dir != wt.main_project_dir {
312 let main_str = wt.main_project_dir.to_string_lossy();
313 disallowed_tools.extend([
314 format!("Bash(cd {main_str}*)"),
315 format!("Read({main_str}/*)"),
316 format!("Write({main_str}/*)"),
317 format!("Edit({main_str}/*)"),
318 ]);
319 }
320
321 if let Ok(orch_home) = home::orch_home() {
322 for path in [
323 orch_home.join("config.yml"),
324 orch_home.join("config.example.yml"),
325 ] {
326 let path_str = path.to_string_lossy();
327 disallowed_tools.extend([
328 format!("Read({path_str})"),
329 format!("Write({path_str})"),
330 format!("Edit({path_str})"),
331 ]);
332 }
333 }
334
335 {
337 let orch_yml = wt.work_dir.join(".orch.yml");
338 let orch_yml_str = orch_yml.to_string_lossy();
339 disallowed_tools.extend([
340 format!("Write({orch_yml_str})"),
341 format!("Edit({orch_yml_str})"),
342 ]);
343 }
344
345 let timeout_tier = match (complexity.as_deref(), model_name.as_deref()) {
348 (Some(c), Some(m)) if !m.is_empty() => {
349 Some(RouterConfig::from_config().tier_of_model(&agent_name, m, c))
350 }
351 (c, _) => c.map(String::from),
352 };
353 let timeout_seconds = RunTimeouts::from_config().for_complexity(timeout_tier.as_deref());
354
355 let invocation = agent::AgentInvocation {
357 agent: agent_name.clone(),
358 model: model_name.clone(),
359 reasoning_effort: route_result
360 .as_ref()
361 .and_then(|r| r.profile.execution.as_ref())
362 .filter(|p| p.matches_route(&agent_name, model_name.as_deref()))
363 .and_then(|p| p.effort.clone()),
364 work_dir: wt.work_dir.clone(),
365 system_prompt,
366 agent_message,
367 task_id: task_id.to_string(),
368 disallowed_tools,
369 git_author_name: git_name,
370 git_author_email: git_email,
371 output_file,
372 timeout_seconds,
373 repo: repo.to_string(),
374 attempt: next_attempt,
375 sandbox: sandboxed,
376 main_project_dir: wt.main_project_dir.clone(),
377 branch: wt.branch.clone(),
378 };
379
380 if let Err(e) = store::store_set_result(
383 store,
384 repo,
385 task_id,
386 &[
387 ("attempts", serde_json::json!(next_attempt)),
388 ("last_error", serde_json::json!("")),
389 ],
390 )
391 .await
392 {
393 if let Some(s) = store {
394 let _ = cleanup::cleanup_task_worktree(task_id, repo, s).await;
395 }
396 return Err(anyhow::anyhow!("failed to persist attempts counter: {e}"));
397 }
398
399 Ok(TaskInitResult {
400 agent_name,
401 model_name,
402 complexity,
403 task_title,
404 wt,
405 invocation,
406 attempt_dir,
407 new_attempts: next_attempt,
408 })
409}
410
411#[cfg(test)]
412mod tests {
413 use std::env;
414 use std::mem;
415 use std::process::Command;
416
417 use super::*;
418 use crate::engine::runner::{WeightSignal, needs_review_signal};
419 use crate::engine::tick::display_status_for;
420 use crate::store::NewTask;
421
422 const FAILOVER_ERROR: &str = "claude timed out after 1804s, switching to codex for re-route";
423
424 async fn prepare_run(seed_error: &str) -> (Arc<TaskStore>, i64) {
426 let orch_home = tempfile::tempdir().unwrap();
427 unsafe { env::set_var("ORCH_HOME", orch_home.path()) };
429 mem::forget(orch_home);
430
431 let project = tempfile::tempdir().unwrap();
432 for args in [
433 &["init", "-b", "main"][..],
434 &["config", "user.email", "t@t.com"],
435 &["config", "user.name", "T"],
436 &["commit", "--allow-empty", "-m", "base"],
437 ] {
438 let out = Command::new("git")
439 .args(["-c", "commit.gpgsign=false"])
440 .args(args)
441 .current_dir(project.path())
442 .output()
443 .unwrap();
444 assert!(out.status.success(), "git {args:?} failed");
445 }
446
447 let task_store = Arc::new(TaskStore::open_memory().await.unwrap());
448 let store_id = task_store
449 .create(&NewTask {
450 repo: "owner/repo".to_string(),
451 origin: "internal".to_string(),
452 title: "Check the report".to_string(),
453 ..Default::default()
454 })
455 .await
456 .unwrap();
457 task_store
458 .set_fields(store_id, &[("last_error", serde_json::json!(seed_error))])
459 .await
460 .unwrap();
461 let task_id = format!("internal:{store_id}");
462 let store = Some(Arc::clone(&task_store));
463
464 prepare_task(
465 &task_id,
466 Some("claude"),
467 Some("sonnet"),
468 None,
469 "owner/repo",
470 project.path(),
471 0,
472 &store,
473 )
474 .await
475 .expect("prepare_task should succeed");
476 (task_store, store_id)
477 }
478
479 async fn stored_last_error(store: &TaskStore, store_id: i64) -> String {
480 store.get(store_id).await.unwrap().last_error
481 }
482
483 #[tokio::test]
484 async fn no_code_task_is_done_after_a_failover_when_the_fallback_run_succeeds() {
485 let (store, id) = prepare_run(FAILOVER_ERROR).await;
486
487 let last_error = stored_last_error(&store, id).await;
488 assert_eq!(last_error, "", "starting a run clears the failover error");
489 let signal = needs_review_signal(&last_error, "codex");
491 assert!(matches!(signal, WeightSignal::Success { .. }));
492 assert_eq!(display_status_for(&signal, true, false), "done");
493 }
494
495 #[tokio::test]
496 async fn no_code_task_is_done_after_a_first_run_with_no_commits() {
497 let (store, id) = prepare_run("").await;
498
499 let signal = needs_review_signal(&stored_last_error(&store, id).await, "claude");
500 assert!(matches!(signal, WeightSignal::Success { .. }));
501 assert_eq!(display_status_for(&signal, true, false), "done");
502 }
503
504 #[tokio::test]
505 async fn timed_out_run_with_no_fallback_stays_in_needs_review() {
506 let (store, id) = prepare_run(FAILOVER_ERROR).await;
507
508 store
510 .set_fields(
511 id,
512 &[(
513 "last_error",
514 serde_json::json!("claude timed out after 1804s, no fallback agents"),
515 )],
516 )
517 .await
518 .unwrap();
519
520 let signal = needs_review_signal(&stored_last_error(&store, id).await, "claude");
521 assert!(matches!(signal, WeightSignal::Failed { .. }));
522 assert_eq!(display_status_for(&signal, true, false), "needs_review");
523 }
524
525 #[test]
526 fn resolve_model_name_skips_a_model_cleared_to_empty() {
527 assert_eq!(resolve_model_name(None, None, Some("")), None);
528 assert_eq!(resolve_model_name(None, Some(""), Some("")), None);
529 assert_eq!(
530 resolve_model_name(None, None, Some("sonnet")).as_deref(),
531 Some("sonnet")
532 );
533 assert_eq!(
534 resolve_model_name(Some("opus"), Some("sonnet"), Some("haiku")).as_deref(),
535 Some("opus")
536 );
537 }
538
539 #[tokio::test]
540 async fn max_attempts_writes_block_reason() {
541 let task_store = Arc::new(TaskStore::open_memory().await.unwrap());
542 let store_id = task_store
543 .create(&NewTask {
544 repo: "owner/repo".to_string(),
545 origin: "internal".to_string(),
546 title: "Test".to_string(),
547 ..Default::default()
548 })
549 .await
550 .unwrap();
551 task_store
552 .set_fields(store_id, &[("attempts", serde_json::json!(1000))])
553 .await
554 .unwrap();
555 let store = Some(Arc::clone(&task_store));
556
557 let outcome = check_guards(&format!("internal:{store_id}"), "owner/repo", &store)
558 .await
559 .unwrap();
560
561 assert!(matches!(outcome, GuardOutcome::MaxAttempts));
562 let task = task_store.get(store_id).await.unwrap();
563 assert!(
564 task.block_reason
565 .is_some_and(|r| r.contains("exceeded max attempts"))
566 );
567 }
568}