1pub mod agent;
19pub mod agents;
20pub mod commit;
21pub mod context;
22pub mod cow;
23pub mod diff;
24pub mod direct;
25pub mod fallback;
26pub mod git_ops;
27pub mod ndjson;
28#[cfg(test)]
29mod recorded_fixtures;
30pub mod response;
31pub mod response_handler;
32pub mod sandbox;
33pub mod screenshots;
34pub mod session;
35pub mod task_init;
36pub mod worktree;
37
38use crate::backends::{ExternalBackend, ExternalTask, Status};
39use crate::config;
40use crate::cooldown;
41use crate::engine;
42use crate::engine::cleanup;
43use crate::engine::router::RouteResult;
44use crate::engine::tasks;
45use crate::engine::tasks::is_internal_id;
46#[cfg(not(test))]
47use crate::github::http;
48use crate::github::http::GhHttp;
49use crate::home;
50use crate::parser;
51use crate::parser::AgentResponse;
52use crate::parser::Delegation;
53use crate::status_heuristics;
54use crate::store;
55use crate::store::InsertTaskMetric;
56use crate::store::RunTokenUsage;
57use crate::store::TaskStatus;
58use crate::store::TaskStore;
59use crate::tmux::TmuxManager;
60use anyhow::Context;
61use chrono::Utc;
62pub use response::WeightSignal;
63use serde_json::Value;
64use std::collections::HashSet;
65use std::env;
66use std::error;
67use std::fmt;
68use std::fmt::Debug;
69use std::fmt::Formatter;
70use std::path::PathBuf;
71use std::slice;
72use std::sync::Arc;
73use std::time::Duration;
74use tokio::fs;
75use tokio::task;
76
77#[derive(Debug, Clone)]
79pub struct RunAudit {
80 pub stdout: String,
81 pub stderr: String,
82 pub parsed_response: String,
83 pub outcome: String,
84 pub error: String,
85 pub input_tokens: u64,
86 pub output_tokens: u64,
87 pub total_cost_usd: f64,
88 pub duration_secs: f64,
89}
90
91#[derive(Debug, Clone)]
93pub struct RunExecution {
94 pub status: String,
95 pub exit_code: Option<i32>,
96 pub audit: RunAudit,
97}
98
99fn serialize_parsed_response(
100 parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
101 raw_stdout: &str,
102) -> String {
103 match parse_result {
104 Ok(parsed) => serde_json::json!({
105 "response": parsed.response,
106 "input_tokens": parsed.input_tokens,
107 "output_tokens": parsed.output_tokens,
108 "cost_usd": parsed.cost_usd,
109 "duration_ms": parsed.duration_ms,
110 })
111 .to_string(),
112 Err(agents::AgentError::InvalidResponse { raw }) => {
113 serde_json::json!({"raw": raw}).to_string()
114 }
115 Err(_) => serde_json::json!({"raw": raw_stdout}).to_string(),
116 }
117}
118
119fn classify_run_outcome(
120 status: &str,
121 parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
122 push_failed: bool,
123) -> &'static str {
124 if push_failed {
125 return "push_failed";
126 }
127 match parse_result {
128 Err(agents::AgentError::Timeout { .. }) => "timeout",
129 Err(agents::AgentError::Interrupted { .. }) => "interrupted",
130 Err(agents::AgentError::RateLimit { message }) => {
135 cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("rate_limit")
136 }
137 Err(agents::AgentError::Auth { message }) => {
138 cooldown::detect_credit_exhaustion_outcome(message).unwrap_or("failed")
139 }
140 Err(agents::AgentError::InvalidResponse { .. }) => "parse_error",
141 Ok(_)
142 if matches!(
143 status,
144 "done" | "completed" | "in_progress" | "in_review" | "needs_review" | "routed"
145 ) =>
146 {
147 "success"
148 }
149 Ok(_) if status == "blocked" => "blocked",
150 Ok(_) if status_heuristics::status_looks_like_descriptive_completion(status) => "success",
153 Err(_) | Ok(_) => "failed",
154 }
155}
156
157fn classify_run_error_type(last_error: &str) -> &'static str {
158 if last_error.is_empty() {
159 "success"
161 } else if last_error.contains("timeout") {
162 "timeout"
163 } else if last_error.contains("interrupted") {
164 "interrupted"
165 } else if last_error.contains("billing cycle") || last_error.contains("monthly quota") {
166 "billing_cycle_exhausted"
167 } else if last_error.contains("rate limit") || last_error.contains("usage limit") {
168 "rate_limit"
169 } else if last_error.contains("auth") {
170 "auth_error"
171 } else if last_error.contains("push failed") {
172 "push_failed"
173 } else if last_error.contains("No commits between") || last_error.contains("no commits") {
174 "no_commits"
175 } else if last_error.contains("create PR failed")
176 || last_error.contains("failed to create pull request")
177 || last_error.contains("pull request creation failed")
178 {
179 "pr_failed"
180 } else if last_error.contains("invalid response") || last_error.contains("parse error") {
181 "parse_error"
182 } else if last_error.contains("exceeded max attempts") {
183 "max_attempts"
184 } else {
185 let lower = last_error.to_ascii_lowercase();
186 if lower.contains("build failed")
187 || lower.contains("tests failed")
188 || lower.contains("test failed")
189 || lower.contains("test suite failed")
190 || lower.contains("lint failed")
191 {
192 "ci_failure"
193 } else {
194 "failed"
195 }
196 }
197}
198
199fn extract_run_tokens(
200 parse_result: &Result<agents::ParsedResponse, agents::AgentError>,
201) -> (u64, u64) {
202 match parse_result {
203 Ok(parsed) => (
204 parsed
205 .input_tokens
206 .or(parsed.response.input_tokens)
207 .unwrap_or(0),
208 parsed
209 .output_tokens
210 .or(parsed.response.output_tokens)
211 .unwrap_or(0),
212 ),
213 Err(_) => (0, 0),
214 }
215}
216
217#[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
218fn run_duration_secs(started_at: &chrono::DateTime<Utc>) -> f64 {
219 (Utc::now() - *started_at).num_milliseconds() as f64 / 1000.0
220}
221
222struct RunAuditInput<'a> {
223 task_id: &'a str,
224 status: &'a str,
225 parse_result: &'a Result<agents::ParsedResponse, agents::AgentError>,
226 raw_stdout: &'a str,
227 raw_stderr: &'a str,
228 started_at: &'a chrono::DateTime<Utc>,
229 error_override: Option<String>,
230 elapsed_secs: Option<u64>,
231 push_failed: bool,
232}
233
234fn parse_success_output(
235 task_id: &str,
236 agent_name: &str,
237 agent_runner: &dyn agents::AgentRunner,
238 raw_stdout: &str,
239) -> Result<agents::ParsedResponse, agents::AgentError> {
240 let agent_result = agents::find_agent_result(agent_name, raw_stdout);
243 if let Some(result) = &agent_result
244 && !result.is_error
245 && let Ok(response) = parser::parse(&result.result_text)
246 {
247 return Ok(agents::ParsedResponse {
248 response,
249 input_tokens: result.input_tokens,
250 output_tokens: result.output_tokens,
251 cost_usd: result.cost_usd,
252 duration_ms: result.duration_ms,
253 });
254 }
255
256 if raw_stdout.contains("\"terminal_reason\":\"completed\"")
263 && !raw_stdout.contains("\"is_error\":true")
264 {
265 let assistant_text = agents::collect_assistant_messages_text(agent_name, raw_stdout);
267 if !assistant_text.is_empty() {
268 if let Ok(response) = parser::parse(&assistant_text) {
269 tracing::debug!(
270 task_id,
271 agent = agent_name,
272 "found AgentResponse JSON in earlier assistant message (terminal_reason:completed)"
273 );
274 return Ok(agents::ParsedResponse {
275 response,
276 input_tokens: None,
277 output_tokens: None,
278 cost_usd: None,
279 duration_ms: None,
280 });
281 }
282 if let Some(response) = agents::synthesize_response_from_text(&assistant_text) {
283 tracing::warn!(
284 task_id,
285 agent = agent_name,
286 "synthesizing response from assistant message due to terminal_reason:completed"
287 );
288 return Ok(agents::ParsedResponse {
289 response,
290 input_tokens: None,
291 output_tokens: None,
292 cost_usd: None,
293 duration_ms: None,
294 });
295 }
296 }
297 }
304
305 if let Some(agent_result) = agent_result {
307 if agent_result.is_error {
309 if let Some(e) = agents::patterns::detect_rate_limit(&agent_result.result_text) {
316 return Err(e);
317 }
318 if let Some(e) = agents::patterns::detect_auth_error(&agent_result.result_text) {
319 return Err(e);
320 }
321 if let Some(e) = agents::patterns::detect_model_unavailable(&agent_result.result_text) {
322 return Err(e);
323 }
324 let classified = agent_runner.classify_error(1, raw_stdout, "");
327 if matches!(classified, agents::AgentError::Timeout { .. }) {
328 return Err(classified);
329 }
330 return Err(agents::AgentError::AgentFailed {
331 message: agent_result.result_text,
332 });
333 }
334
335 let assistant_text = agents::collect_assistant_messages_text(agent_name, raw_stdout);
341 if !assistant_text.is_empty()
342 && let Ok(response) = parser::parse(&assistant_text)
343 {
344 tracing::debug!(
345 task_id,
346 agent = agent_name,
347 "found AgentResponse JSON in earlier assistant message"
348 );
349 return Ok(agents::ParsedResponse {
350 response,
351 input_tokens: agent_result.input_tokens,
352 output_tokens: agent_result.output_tokens,
353 cost_usd: agent_result.cost_usd,
354 duration_ms: agent_result.duration_ms,
355 });
356 }
357
358 if let Some(response) = agents::synthesize_response_from_text(&agent_result.result_text) {
360 tracing::warn!(
361 task_id,
362 agent = agent_name,
363 "parse failed on agent result, synthesizing response from plain text"
364 );
365 return Ok(agents::ParsedResponse {
366 response,
367 input_tokens: agent_result.input_tokens,
368 output_tokens: agent_result.output_tokens,
369 cost_usd: agent_result.cost_usd,
370 duration_ms: agent_result.duration_ms,
371 });
372 }
373
374 if !agent_result.is_error
387 && result_envelope_completed(raw_stdout)
388 && !agent_result.result_text.is_empty()
389 {
390 let summary_end = agents::truncate_at_char_boundary(&agent_result.result_text, 500);
391 let summary = agent_result.result_text[..summary_end].to_string();
392 tracing::warn!(
393 task_id,
394 agent = agent_name,
395 "NDJSON envelope indicates success but result lacks AgentResponse \
396 schema — synthesizing done response"
397 );
398 return Ok(agents::ParsedResponse {
399 response: AgentResponse {
400 status: "done".to_string(),
401 summary,
402 ..Default::default()
403 },
404 input_tokens: agent_result.input_tokens,
405 output_tokens: agent_result.output_tokens,
406 cost_usd: agent_result.cost_usd,
407 duration_ms: agent_result.duration_ms,
408 });
409 }
410 }
411
412 match agent_runner.parse_response(raw_stdout) {
414 Ok(parsed) => Ok(parsed),
415 Err(agents::AgentError::InvalidResponse { raw }) => {
416 if let Some(response) = agents::synthesize_response_from_text(&raw) {
417 tracing::warn!(
418 task_id,
419 agent = agent_name,
420 "parse failed, synthesizing response from plain text"
421 );
422 let agent_result = agents::find_agent_result(agent_name, raw_stdout);
426 let input_tokens = agent_result.as_ref().and_then(|r| r.input_tokens);
427 let output_tokens = agent_result.as_ref().and_then(|r| r.output_tokens);
428 let cost_usd = agent_result.as_ref().and_then(|r| r.cost_usd);
429 let duration_ms = agent_result.as_ref().and_then(|r| r.duration_ms);
430 Ok(agents::ParsedResponse {
431 response,
432 input_tokens,
433 output_tokens,
434 cost_usd,
435 duration_ms,
436 })
437 } else {
438 Err(agents::AgentError::InvalidResponse { raw })
439 }
440 }
441 Err(err) => Err(err),
442 }
443}
444
445fn result_envelope_line(raw_stdout: &str) -> Option<serde_json::Value> {
448 raw_stdout
449 .lines()
450 .rev()
451 .filter_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
452 .find(|v| v.get("type").and_then(|t| t.as_str()) == Some("result"))
453}
454
455fn has_result_envelope(raw_stdout: &str) -> bool {
456 result_envelope_line(raw_stdout).is_some()
457}
458
459fn result_envelope_completed(raw_stdout: &str) -> bool {
460 result_envelope_line(raw_stdout).is_some_and(|v| {
461 v.get("subtype").and_then(|t| t.as_str()) == Some("success")
462 || v.get("terminal_reason").and_then(|t| t.as_str()) == Some("completed")
463 })
464}
465
466fn salvage_wrapup(raw: &str) -> Option<String> {
469 let mut calls: Vec<(String, String, Option<bool>)> = Vec::new();
471 let mut last_text = String::new();
472 for v in raw
473 .lines()
474 .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
475 {
476 let blocks = v.pointer("/message/content").and_then(|c| c.as_array());
477 for b in blocks.into_iter().flatten() {
478 match b.get("type").and_then(|t| t.as_str()) {
479 Some("tool_use") => calls.push((
480 b["name"].as_str().unwrap_or("").to_string(),
481 b.pointer("/input/command")
482 .and_then(|c| c.as_str())
483 .unwrap_or("")
484 .to_string(),
485 None,
486 )),
487 Some("text") if v["type"] == "assistant" => {
488 last_text = b["text"].as_str().unwrap_or("").to_string();
489 }
490 Some("tool_result") => {
491 let ok = b.get("is_error").and_then(serde_json::Value::as_bool) != Some(true);
492 if let Some(c) = calls.iter_mut().find(|c| c.2.is_none()) {
494 c.2 = Some(ok);
495 }
496 }
497 _ => {}
498 }
499 }
500 }
501 let commit = calls
502 .iter()
503 .rposition(|(_, cmd, ok)| cmd.contains("git commit") && *ok == Some(true))?;
504 let tail_ok = calls[commit..].iter().all(|(name, _, ok)| {
505 matches!(name.as_str(), "Bash" | "run_terminal_cmd") && *ok == Some(true)
506 });
507 let lower = last_text.to_lowercase();
508 if !tail_ok || lower.contains("still running") || lower.contains("in progress") {
509 return None;
510 }
511 Some(last_text.chars().take(500).collect())
512}
513
514pub fn parse_session_output(
523 task_id: &str,
524 agent_name: &str,
525 agent_runner: &dyn agents::AgentRunner,
526 session_output: &session::SessionOutput,
527) -> Result<agents::ParsedResponse, agents::AgentError> {
528 let combined_output = format!("{}{}", session_output.raw_stdout, session_output.raw_stderr);
533 if !(session_output.raw_stdout.is_empty() && session_output.raw_stderr.is_empty()) {
534 match parse_success_output(task_id, agent_name, agent_runner, &combined_output) {
535 Ok(parsed) => return Ok(parsed),
536 Err(err) => {
537 if session_output.exit_code == 124 {
538 if let Some(summary) = salvage_wrapup(&combined_output) {
539 tracing::warn!(
540 task_id,
541 agent = agent_name,
542 "timed out after commit during wrap-up, salvaging as done"
543 );
544 return Ok(agents::ParsedResponse {
545 response: AgentResponse {
546 status: "done".to_string(),
547 summary,
548 ..Default::default()
549 },
550 input_tokens: None,
551 output_tokens: None,
552 cost_usd: None,
553 duration_ms: None,
554 });
555 }
556 return Err(agent_runner.classify_error_with_elapsed(
559 session_output.exit_code,
560 &session_output.raw_stdout,
561 &session_output.raw_stderr,
562 session_output.elapsed_secs,
563 ));
564 }
565 if !matches!(err, agents::AgentError::InvalidResponse { .. }) {
573 let mut err = err;
574 if let agents::AgentError::Timeout { elapsed } = &mut err
575 && let Some(secs) = session_output.elapsed_secs
576 {
577 *elapsed = Duration::from_secs(secs);
578 }
579 return Err(err);
580 }
581 if session_output.exit_code != 0 {
582 let combined = &combined_output;
593 let is_completed_signal =
594 combined.contains("\"terminal_reason\":\"completed\"");
595 let is_cost_telemetry_only = combined.contains("\"costUSD\":")
601 && !combined.contains("\"is_error\":true");
602 if is_completed_signal || is_cost_telemetry_only {
603 let raw_tail = agents::patterns::safe_tail(combined, 300);
604 return Err(agents::AgentError::InvalidResponse {
605 raw: raw_tail.to_string(),
606 });
607 }
608 return Err(agent_runner.classify_error_with_elapsed(
609 session_output.exit_code,
610 &session_output.raw_stdout,
611 &session_output.raw_stderr,
612 session_output.elapsed_secs,
613 ));
614 }
615 if !has_result_envelope(&combined_output) {
616 return Err(agents::AgentError::Interrupted {
617 message: "exited without a result envelope".to_string(),
618 });
619 }
620 return Err(err);
621 }
622 }
623 }
624
625 if session_output.exit_code != 0 {
626 return Err(agent_runner.classify_error_with_elapsed(
627 session_output.exit_code,
628 &session_output.raw_stdout,
629 &session_output.raw_stderr,
630 session_output.elapsed_secs,
631 ));
632 }
633
634 Err(agents::AgentError::Unknown {
635 exit_code: session_output.exit_code,
636 message: "empty-output-exit0: opencode returned exit 0 with empty stdout".to_string(),
637 })
638}
639
640#[derive(Debug)]
643pub(crate) struct NoProjectDir {
644 pub(crate) repo: String,
645 pub(crate) bare_clone: PathBuf,
646}
647
648impl NoProjectDir {
649 pub(crate) const BLOCK_REASON: &str = "project is not configured and has no bare clone";
651}
652
653impl fmt::Display for NoProjectDir {
654 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
655 write!(
656 f,
657 "no resolvable project directory for repo {} — not in active config, no bare clone at {}, no legacy project_dir set",
658 self.repo,
659 self.bare_clone.display()
660 )
661 }
662}
663
664impl error::Error for NoProjectDir {}
665
666pub struct TaskRunner {
668 repo: String,
670 orch_home: PathBuf,
672 store: Option<Arc<TaskStore>>,
674}
675
676impl Debug for TaskRunner {
677 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
678 f.debug_struct("TaskRunner")
679 .field("repo", &self.repo)
680 .field("orch_home", &self.orch_home)
681 .finish_non_exhaustive()
682 }
683}
684
685impl TaskRunner {
686 pub fn new(repo: String) -> Self {
687 let orch_home = home::orch_home().unwrap_or_else(|e| {
688 tracing::warn!(error = %e, "orch_home() failed — falling back to /tmp/.orch");
689 PathBuf::from("/tmp").join(".orch")
690 });
691
692 Self {
693 repo,
694 orch_home,
695 store: None,
696 }
697 }
698
699 #[must_use]
701 pub fn with_store(mut self, store: Arc<TaskStore>) -> Self {
702 self.store = Some(store);
703 self
704 }
705
706 async fn get_field(&self, task_id: &str, field: &str) -> Option<String> {
708 let task = store::opt_store_get_task(&self.store, &self.repo, task_id).await?;
709 match field {
710 "route_reason" => Some(task.route_reason),
711 "worktree" => Some(task.worktree),
712 "attempts" => Some(task.attempts.to_string()),
713 "delegations" => serde_json::to_string(&task.delegations).ok(),
714 "summary" => Some(task.summary),
715 "last_error" => Some(task.last_error),
716 "agent" => task.agent,
717 _ => None,
718 }
719 }
720
721 pub(crate) async fn clear_agent_on_reroute_unless_fallback(
723 &self,
724 task_id: &str,
725 ran_agent: &str,
726 ) {
727 let stored = store::opt_store_get_task(&self.store, &self.repo, task_id).await;
728 if Self::reroute_keeps_stored_agent(stored.as_ref(), ran_agent) {
729 tracing::debug!(
730 task_id,
731 "stored fallback agent present, skipping agent/model clear"
732 );
733 return;
734 }
735 if let Err(e) = store::store_set_result(
736 &self.store,
737 &self.repo,
738 task_id,
739 &[
740 ("agent", serde_json::json!("")),
741 ("model", serde_json::json!("")),
742 ],
743 )
744 .await
745 {
746 tracing::warn!(task_id, err = %e, "failed to clear agent/model for reroute in store");
747 }
748 }
749
750 fn reroute_keeps_stored_agent(stored: Option<&store::Task>, ran_agent: &str) -> bool {
752 let Some(task) = stored else {
753 return false;
754 };
755 if !matches!(task.status, TaskStatus::InProgress) {
756 return true;
757 }
758 let stored_agent = task.agent.as_deref().unwrap_or("");
759 !stored_agent.is_empty() && stored_agent != ran_agent
760 }
761
762 async fn build_run_audit(&self, input: RunAuditInput<'_>) -> RunAudit {
763 let last_error = self
769 .get_field(input.task_id, "last_error")
770 .await
771 .filter(|s| !s.is_empty());
772 let outcome =
773 classify_run_outcome(input.status, input.parse_result, input.push_failed).to_string();
774
775 let error = if outcome == "success" {
776 String::new()
777 } else {
778 let error = input
781 .error_override
782 .as_deref()
783 .filter(|s| !s.is_empty())
784 .map(str::to_string)
785 .or_else(|| match input.parse_result {
786 Ok(parsed) => parsed
787 .response
788 .error
789 .as_deref()
790 .filter(|s| !s.is_empty())
791 .map(str::to_string),
792 Err(_) => None,
793 })
794 .or(last_error)
795 .unwrap_or_else(|| match input.parse_result {
796 Ok(_) => String::new(),
797 Err(err) => err.to_string(),
798 });
799
800 if error.is_empty() {
801 if input.status == "blocked" {
802 match input.parse_result {
803 Ok(parsed) if !parsed.response.summary.is_empty() => {
804 parsed.response.summary.clone()
805 }
806 _ => "task blocked without explicit error".to_string(),
807 }
808 } else if matches!(
809 input.status,
810 "done"
811 | "completed"
812 | "in_progress"
813 | "in_review"
814 | "needs_review"
815 | "routed"
816 | "new"
817 ) {
818 String::new()
820 } else {
821 format!("unrecognized status: {}", input.status)
825 }
826 } else {
827 error
828 }
829 };
830
831 let total_cost_usd = input
832 .parse_result
833 .as_ref()
834 .ok()
835 .and_then(|p| p.cost_usd)
836 .unwrap_or(0.0);
837
838 let (input_tokens, output_tokens) = extract_run_tokens(input.parse_result);
839
840 #[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
841 let duration_secs = input
842 .elapsed_secs
843 .map_or_else(|| run_duration_secs(input.started_at), |s| s as f64);
844
845 RunAudit {
846 stdout: input.raw_stdout.to_string(),
847 stderr: input.raw_stderr.to_string(),
848 parsed_response: serialize_parsed_response(input.parse_result, input.raw_stdout),
849 outcome,
850 error,
851 input_tokens,
852 output_tokens,
853 total_cost_usd,
854 duration_secs,
855 }
856 }
857
858 async fn sandbox_blocked(&self, task_id: &str, reason: String) -> RunExecution {
860 tracing::error!(task_id, error = %reason, "blocking task");
861 if let Err(e) = store::store_set_result(
862 &self.store,
863 &self.repo,
864 task_id,
865 &[
866 ("last_error", serde_json::json!(reason)),
867 ("block_reason", serde_json::json!(reason)),
868 ],
869 )
870 .await
871 {
872 tracing::warn!(task_id, err = %e, "failed to write the sandbox block_reason");
873 }
874 RunExecution {
875 status: "blocked".to_string(),
876 exit_code: None,
877 audit: RunAudit {
878 stdout: String::new(),
879 stderr: String::new(),
880 parsed_response: String::new(),
881 outcome: "failed".to_string(),
882 error: reason,
883 input_tokens: 0,
884 output_tokens: 0,
885 total_cost_usd: 0.0,
886 duration_secs: 0.0,
887 },
888 }
889 }
890
891 pub async fn run(
896 &self,
897 task_id: &str,
898 agent: Option<&str>,
899 model: Option<&str>,
900 backend: Option<&dyn ExternalBackend>,
901 started_at: &chrono::DateTime<Utc>,
902 ) -> anyhow::Result<Option<RunExecution>> {
903 tracing::info!(
904 task_id,
905 agent = agent.unwrap_or("default"),
906 model = model.unwrap_or("default"),
907 "starting task execution"
908 );
909
910 let attempts = match task_init::check_guards(task_id, &self.repo, &self.store).await {
912 Ok(task_init::GuardOutcome::Proceed(a)) => a,
913 Ok(task_init::GuardOutcome::Skip) => {
914 return Ok(None);
915 }
916 Ok(task_init::GuardOutcome::MaxAttempts) => {
917 if backend.is_some() {
920 let route_reason = self
923 .get_field(task_id, "route_reason")
924 .await
925 .unwrap_or_default();
926 if route_reason.starts_with("label agent:") {
927 let agent_label = route_reason.trim_start_matches("label ");
928 let gh = GhHttp::new()?;
929 match gh.remove_label(&self.repo, task_id, agent_label).await {
930 Err(e) => {
931 tracing::warn!(task_id, label = agent_label, err = %e, "failed to remove agent label after max attempts");
932 }
933 _ => {
934 tracing::info!(
935 task_id,
936 label = agent_label,
937 "removed forced agent label after max attempts — /retry will use free routing"
938 );
939 }
940 }
941 }
942 }
943 return Ok(Some(RunExecution {
944 status: "blocked".to_string(),
945 exit_code: None,
946 audit: RunAudit {
947 stdout: String::new(),
948 stderr: String::new(),
949 parsed_response: String::new(),
950 outcome: "failed".to_string(),
951 error: "max attempts reached".to_string(),
952 input_tokens: 0,
953 output_tokens: 0,
954 total_cost_usd: 0.0,
955 duration_secs: 0.0,
956 },
957 }));
958 }
959 Err(e) => return Err(e),
960 };
961
962 let project_dir = self.resolve_project_dir().await?;
964
965 let init = task_init::prepare_task(
967 task_id,
968 agent,
969 model,
970 backend,
971 &self.repo,
972 &project_dir,
973 attempts,
974 &self.store,
975 )
976 .await?;
977
978 if init.invocation.sandbox
981 && let Err(e) = sandbox::argv(
982 &init.invocation.sandbox_scope(),
983 &env::temp_dir().join("orch-sandbox-preflight"),
984 )
985 .await
986 {
987 return Ok(Some(self.sandbox_blocked(task_id, e.to_string()).await));
988 }
989
990 let (tmux, tmux_session, session_output) = session::run_agent_session(
992 task_id,
993 &init.invocation,
994 &init.attempt_dir,
995 &self.orch_home,
996 )
997 .await;
998
999 if let Some(reason) = session_output.sandbox_error.clone() {
1001 return Ok(Some(self.sandbox_blocked(task_id, reason).await));
1002 }
1003
1004 store::store_touch_updated_at(&self.store, &self.repo, task_id).await;
1010
1011 if let Some(stored) = store::opt_store_get_task(&self.store, &self.repo, task_id).await {
1019 let silence_reset = matches!(
1020 stored.status,
1021 TaskStatus::New | TaskStatus::Routed | TaskStatus::NeedsReview
1022 );
1023 if silence_reset {
1024 let status_str = stored.status.as_str();
1025 tracing::info!(
1026 task_id,
1027 status = status_str,
1028 "task already reset by the engine — skipping fallback processing"
1029 );
1030 session::cleanup_session(task_id, &tmux, &tmux_session).await;
1031 let silence_err = agents::patterns::classify_from_text(0, "silence detected");
1032 let silence_parse: Result<agents::ParsedResponse, agents::AgentError> =
1033 Err(silence_err);
1034 let audit = self
1035 .build_run_audit(RunAuditInput {
1036 task_id,
1037 status: status_str,
1038 parse_result: &silence_parse,
1039 raw_stdout: &session_output.raw_stdout,
1040 raw_stderr: &session_output.raw_stderr,
1041 started_at,
1042 error_override: Some(format!("task was reset by the engine while the session ran (status {status_str})")),
1043 elapsed_secs: session_output.elapsed_secs,
1044 push_failed: false,
1045 })
1046 .await;
1047 return Ok(Some(RunExecution {
1048 status: status_str.to_string(),
1049 exit_code: Some(session_output.exit_code),
1050 audit,
1051 }));
1052 }
1053 }
1054
1055 let stdout_len = session_output.raw_stdout.len();
1057 let stderr_len = session_output.raw_stderr.len();
1058 let stdout_tail: String = session_output
1059 .raw_stdout
1060 .chars()
1061 .rev()
1062 .take(500)
1063 .collect::<String>()
1064 .chars()
1065 .rev()
1066 .collect();
1067 let stderr_tail: String = session_output
1068 .raw_stderr
1069 .chars()
1070 .rev()
1071 .take(500)
1072 .collect::<String>()
1073 .chars()
1074 .rev()
1075 .collect();
1076 tracing::info!(
1077 task_id,
1078 exit_code = session_output.exit_code,
1079 stdout_len,
1080 stderr_len,
1081 stdout_tail = %stdout_tail,
1082 stderr_tail = %stderr_tail,
1083 "agent raw output"
1084 );
1085
1086 for window in agents::claude::rate_limit_windows(&session_output.raw_stdout) {
1094 cooldown::record_rate_limit_window(&init.agent_name, &window).await;
1095 }
1096 let agent_runner = agents::get_runner(&init.agent_name);
1097 let parse_result =
1098 parse_session_output(task_id, &init.agent_name, &*agent_runner, &session_output);
1099
1100 response_handler::write_result_json(
1102 &init.attempt_dir,
1103 task_id,
1104 &init.agent_name,
1105 init.model_name.as_deref(),
1106 session_output.exit_code,
1107 init.new_attempts,
1108 &parse_result,
1109 &session_output.raw_stdout,
1110 &session_output.raw_stderr,
1111 )
1112 .await;
1113
1114 let (final_status, push_failed, fallback_error) = match parse_result {
1121 Ok(ref parsed) => {
1122 let (status, push_failed) = response_handler::handle_success(
1123 task_id,
1124 parsed.clone(),
1125 &init.wt,
1126 &init.task_title,
1127 &init.agent_name,
1128 init.model_name.as_deref(),
1129 init.new_attempts,
1130 &self.repo,
1131 &self.store,
1132 &session_output.raw_stdout,
1133 )
1134 .await?;
1135 (status, push_failed, None)
1136 }
1137 Err(ref agent_err) => {
1138 match fallback::handle_error(
1139 task_id,
1140 agent_err,
1141 &init.agent_name,
1142 &*agent_runner,
1143 init.model_name.as_deref(),
1144 init.complexity.as_deref(),
1145 init.new_attempts,
1146 &self.store,
1147 &self.repo,
1148 )
1149 .await?
1150 {
1151 fallback::ErrorHandleResult::EarlyReturn { status } => {
1152 session::cleanup_session(task_id, &tmux, &tmux_session).await;
1154 let audit = self
1162 .build_run_audit(RunAuditInput {
1163 task_id,
1164 status: &status,
1165 parse_result: &parse_result,
1166 raw_stdout: &session_output.raw_stdout,
1167 raw_stderr: &session_output.raw_stderr,
1168 started_at,
1169 error_override: None,
1170 elapsed_secs: session_output.elapsed_secs,
1171 push_failed: false,
1172 })
1173 .await;
1174 return Ok(Some(RunExecution {
1175 status,
1176 exit_code: Some(session_output.exit_code),
1177 audit,
1178 }));
1179 }
1180 fallback::ErrorHandleResult::Continue { status, error } => {
1181 (status, false, Some(error))
1182 }
1183 }
1184 }
1185 };
1186
1187 session::cleanup_session(task_id, &tmux, &tmux_session).await;
1189
1190 if final_status.as_str() == "done"
1194 && let Some(ref st) = self.store
1195 && let Err(e) = cleanup::cleanup_task_worktree(task_id, &self.repo, st).await
1196 {
1197 tracing::warn!(task_id, error = ?e, "worktree cleanup failed after no-op done");
1198 }
1199
1200 let audit = self
1205 .build_run_audit(RunAuditInput {
1206 task_id,
1207 status: &final_status,
1208 parse_result: &parse_result,
1209 raw_stdout: &session_output.raw_stdout,
1210 raw_stderr: &session_output.raw_stderr,
1211 started_at,
1212 error_override: fallback_error,
1213 elapsed_secs: session_output.elapsed_secs,
1214 push_failed,
1215 })
1216 .await;
1217
1218 Ok(Some(RunExecution {
1219 status: final_status.clone(),
1220 exit_code: Some(session_output.exit_code),
1221 audit,
1222 }))
1223 }
1224
1225 #[expect(
1227 clippy::too_many_arguments,
1228 reason = "a metric row needs the agent, model, route, timing and outcome together"
1229 )]
1230 async fn record_metrics(
1231 &self,
1232 task_id: &str,
1233 agent_name: &str,
1234 model_name: Option<&str>,
1235 route_result: Option<&RouteResult>,
1236 started_at: &chrono::DateTime<Utc>,
1237 attempts: u32,
1238 final_status: &str,
1239 error_type: Option<&str>,
1240 ) {
1241 let completed_at = Utc::now();
1242 #[expect(clippy::cast_precision_loss, reason = "a run duration in seconds")]
1243 let duration_seconds = (completed_at - *started_at).num_milliseconds() as f64 / 1000.0;
1244
1245 let outcome = match final_status {
1247 "done" | "in_progress" | "in_review" => "success",
1248 "new" => "rerouted",
1249 "needs_review" => classify_run_error_type(error_type.unwrap_or("")),
1250 _ => "unknown",
1251 };
1252
1253 let complexity = route_result.map(|r| r.complexity.clone());
1254 let files_changed = git_ops::count_changed_files(&PathBuf::from(
1255 self.get_field(task_id, "worktree")
1256 .await
1257 .unwrap_or_default(),
1258 ))
1259 .await
1260 .unwrap_or(0);
1261
1262 if let Some(ref store) = self.store {
1263 let db_error_type: Option<String> = if outcome == "success" {
1265 None
1266 } else {
1267 Some(outcome.to_string())
1268 };
1269
1270 let usage = store::get_token_usage(&self.store, &self.repo, task_id).await;
1271 let total_cost = store::get_reported_cost(&self.store, &self.repo, task_id).await;
1272 let input_tokens = if usage.input_tokens > 0 {
1273 Some(i64::try_from(usage.input_tokens).unwrap_or(i64::MAX))
1274 } else {
1275 None
1276 };
1277 let output_tokens = if usage.output_tokens > 0 {
1278 Some(i64::try_from(usage.output_tokens).unwrap_or(i64::MAX))
1279 } else {
1280 None
1281 };
1282
1283 let metric = InsertTaskMetric {
1284 repo: &self.repo,
1285 task_id,
1286 agent: agent_name,
1287 model: model_name,
1288 complexity: complexity.as_deref(),
1289 outcome,
1290 duration_seconds,
1291 started_at,
1292 completed_at: &completed_at,
1293 attempts: i32::try_from(attempts.saturating_add(1)).unwrap_or(i32::MAX),
1294 files_changed: i32::try_from(files_changed).unwrap_or(i32::MAX),
1295 error_type: db_error_type.as_deref(),
1296 input_tokens,
1297 output_tokens,
1298 total_cost_usd: total_cost,
1299 };
1300
1301 if let Err(e) = store.insert_task_metric(&metric).await {
1302 tracing::error!(task_id, ?e, "failed to record task metrics");
1303 }
1304 }
1305 }
1306
1307 pub async fn run_with_context(
1312 &self,
1313 task: &ExternalTask,
1314 backend: &Arc<dyn ExternalBackend>,
1315 _tmux: &Arc<TmuxManager>,
1316 route_result: Option<&RouteResult>,
1317 ) -> anyhow::Result<WeightSignal> {
1318 let task_id = &task.id.0;
1319 let agent = route_result.map(|r| r.agent.as_str());
1320 let agent_name = agent.unwrap_or("claude").to_string();
1321 let model = route_result.and_then(|r| r.model.as_deref());
1322
1323 let started_at = Utc::now();
1325
1326 let run_audit_id = if let Some(ref store) = self.store {
1330 let attempt: i32 = self
1331 .get_field(task_id, "attempts")
1332 .await
1333 .and_then(|s| s.parse().ok())
1334 .unwrap_or(0)
1335 + 1;
1336 match store.resolve_task_id(&self.repo, task_id).await {
1337 Ok(Some(store_id)) => {
1338 match store
1339 .start_run(&crate::store::StartRun {
1340 task_id: store_id,
1341 attempt,
1342 run_type: "agent",
1343 agent: &agent_name,
1344 model: model.unwrap_or(""),
1345 command: &format!(
1346 "{} --model {}",
1347 agent_name,
1348 model.unwrap_or("default")
1349 ),
1350 prompt: &task.body,
1351 })
1352 .await
1353 {
1354 Ok(run_id) => Some(run_id),
1355 Err(e) => {
1356 tracing::warn!(
1357 task_id,
1358 error = %e,
1359 "failed to record run start in audit trail"
1360 );
1361 None
1362 }
1363 }
1364 }
1365 _ => None,
1366 }
1367 } else {
1368 None
1369 };
1370
1371 let run_result = match self
1374 .run(task_id, agent, model, Some(&**backend), &started_at)
1375 .await
1376 {
1377 Ok(run_result) => run_result,
1378 Err(e) => {
1379 if let Some(run_id) = run_audit_id
1380 && let Some(ref store) = self.store
1381 && let Err(complete_err) = store
1382 .complete_run(&crate::store::CompleteRun {
1383 run_id,
1384 exit_code: Some(-1),
1385 stdout: "",
1386 stderr: "",
1387 parsed: "",
1388 outcome: "failed",
1389 error: &e.to_string(),
1390 tokens: RunTokenUsage::default(),
1391 })
1392 .await
1393 {
1394 tracing::warn!(
1395 task_id,
1396 run_id,
1397 error = %complete_err,
1398 "failed to record run completion in audit trail after runner error"
1399 );
1400 }
1401 return Err(e);
1402 }
1403 };
1404
1405 let (status, exit_code_opt, run_audit) = if let Some(result) = run_result {
1407 (result.status, result.exit_code, result.audit)
1408 } else {
1409 if let Some(run_id) = run_audit_id
1410 && let Some(ref store) = self.store
1411 && let Err(e) = store
1412 .complete_run(&crate::store::CompleteRun {
1413 run_id,
1414 exit_code: Some(-1),
1415 stdout: "",
1416 stderr: "",
1417 parsed: "",
1418 outcome: "aborted",
1419 error: "run skipped by guard",
1420 tokens: RunTokenUsage::default(),
1421 })
1422 .await
1423 {
1424 tracing::warn!(
1425 task_id,
1426 run_id,
1427 error = %e,
1428 "failed to record skipped run completion in audit trail"
1429 );
1430 }
1431 tracing::info!(task_id, "guard skipped task — not posting stale result");
1432 return Ok(WeightSignal::None);
1433 };
1434
1435 let delegations_raw = self
1437 .get_field(task_id, "delegations")
1438 .await
1439 .unwrap_or_default();
1440 if !delegations_raw.is_empty() {
1441 match serde_json::from_str::<Vec<Delegation>>(&delegations_raw) {
1442 Ok(delegations) if !delegations.is_empty() => {
1443 self.process_delegations(task, &delegations, backend)
1444 .await?;
1445 if let Err(e) = store::store_set_result(
1446 &self.store,
1447 &self.repo,
1448 task_id,
1449 &[("delegations", serde_json::json!([]))],
1450 )
1451 .await
1452 {
1453 tracing::warn!(task_id, err = %e, "failed to clear delegations in store");
1454 }
1455 }
1456 Ok(_) => {} Err(e) => {
1458 tracing::error!(task_id, error = %e, "corrupt delegations JSON — clearing");
1459 if let Err(e2) = store::store_set_result(
1460 &self.store,
1461 &self.repo,
1462 task_id,
1463 &[("delegations", serde_json::json!([]))],
1464 )
1465 .await
1466 {
1467 tracing::warn!(task_id, err = %e2, "failed to clear corrupt delegations in store");
1468 }
1469 if let Err(e2) = store::store_set_result(
1470 &self.store,
1471 &self.repo,
1472 task_id,
1473 &[(
1474 "last_error",
1475 serde_json::json!(format!("delegation parse failed: {e}")),
1476 )],
1477 )
1478 .await
1479 {
1480 tracing::warn!(task_id, err = %e2, "failed to write delegation_parse_failed last_error to store");
1481 }
1482 }
1483 }
1484 }
1485
1486 let summary = self.get_field(task_id, "summary").await.unwrap_or_default();
1488 let last_error = self
1489 .get_field(task_id, "last_error")
1490 .await
1491 .unwrap_or_default();
1492
1493 let is_rerouted = status == "new" || status == "routed";
1497 if is_rerouted {
1498 self.clear_agent_on_reroute_unless_fallback(task_id, &agent_name)
1499 .await;
1500 }
1501 let is_rate_limit_error = classify_run_error_type(&last_error) == "rate_limit";
1506 let weight_signal = if is_rerouted {
1507 if is_rate_limit_error {
1508 WeightSignal::RateLimited {
1509 agent: agent_name.clone(),
1510 }
1511 } else {
1512 WeightSignal::Rerouted
1517 }
1518 } else if status == "needs_review" {
1519 let signal = needs_review_signal(&last_error, &agent_name);
1531 match &signal {
1532 WeightSignal::RateLimited { .. } => {
1533 if let Some(ref store) = self.store
1535 && let Err(e) = store
1536 .record_rate_limit(&agent_name, "rate", Some(task_id))
1537 .await
1538 {
1539 tracing::warn!(task_id, agent = %agent_name, err = %e, "failed to persist rate_limit event — router health check may miss this signal");
1540 }
1541 cooldown::record_rate_limit(&agent_name, model, &last_error).await;
1544 }
1545 WeightSignal::Success { .. } => {
1546 cooldown::record_agent_success(&agent_name, model.unwrap_or("")).await;
1548 }
1549 _ => {}
1550 }
1551 signal
1552 } else if status == "done" || status == "in_progress" || status == "in_review" {
1553 cooldown::record_agent_success(&agent_name, model.unwrap_or("")).await;
1555 WeightSignal::Success {
1556 agent: agent_name.clone(),
1557 }
1558 } else if status == "blocked" {
1559 WeightSignal::Blocked
1560 } else {
1561 WeightSignal::None
1562 };
1563
1564 {
1566 let attempts: u32 = self
1567 .get_field(task_id, "attempts")
1568 .await
1569 .and_then(|s| s.parse().ok())
1570 .unwrap_or(0);
1571 self.record_metrics(
1572 task_id,
1573 &agent_name,
1574 model,
1575 route_result,
1576 &started_at,
1577 attempts,
1578 &status,
1579 if last_error.is_empty() {
1580 None
1581 } else {
1582 Some(&last_error)
1583 },
1584 )
1585 .await;
1586 }
1587
1588 if let Some(run_id) = run_audit_id
1590 && let Some(ref store) = self.store
1591 && let Err(e) = store
1592 .complete_run(&crate::store::CompleteRun {
1593 run_id,
1594 exit_code: exit_code_opt,
1595 stdout: &run_audit.stdout,
1596 stderr: &run_audit.stderr,
1597 parsed: &run_audit.parsed_response,
1598 outcome: &run_audit.outcome,
1599 error: &run_audit.error,
1600 tokens: RunTokenUsage {
1601 input_tokens: run_audit.input_tokens,
1602 output_tokens: run_audit.output_tokens,
1603 total_cost_usd: run_audit.total_cost_usd,
1604 duration_secs: run_audit.duration_secs,
1605 },
1606 })
1607 .await
1608 {
1609 tracing::warn!(
1610 task_id,
1611 run_id,
1612 error = %e,
1613 "failed to record run completion in audit trail"
1614 );
1615 }
1616
1617 if is_rerouted && !is_internal_id(task_id) {
1620 let new_agent = self.get_field(task_id, "agent").await.unwrap_or_default();
1621 if !new_agent.is_empty() && new_agent != agent_name {
1622 update_agent_label_after_reroute(
1623 &self.repo,
1624 task,
1625 backend,
1626 &agent_name,
1627 &new_agent,
1628 )
1629 .await;
1630 }
1631 }
1632
1633 if is_internal_id(task_id) {
1635 return Ok(weight_signal);
1636 }
1637
1638 let new_status = match status.as_str() {
1640 "done" => Status::Done,
1641 "in_progress" => Status::InProgress,
1642 "in_review" => Status::InReview,
1643 "blocked" => Status::Blocked,
1644 "routed" => Status::Routed, "new" => Status::New, _ => Status::NeedsReview,
1647 };
1648 if let Some(ref store) = self.store
1650 && let Ok(Some(store_id)) = store.resolve_task_id(&self.repo, &task.id.0).await
1651 {
1652 store
1653 .update_status(store_id, tasks::status_to_task_status(new_status))
1654 .await
1655 .context("store-first status update failed in runner")?;
1656 }
1657 if let Err(e) = backend.update_status(&task.id, new_status).await {
1658 tracing::warn!(
1659 task_id,
1660 ?new_status,
1661 err = %e,
1662 "failed to mirror runner status to backend — store is authoritative"
1663 );
1664 }
1665
1666 let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
1667 let mut comment = if !summary.is_empty() {
1668 format!("[{now}] {status}: {summary}")
1669 } else if !last_error.is_empty() {
1670 format!("[{now}] {status}: {last_error}")
1671 } else {
1672 format!("[{now}] {status}")
1673 };
1674
1675 let footer = engine::attribution_footer("Created", &agent_name, model);
1677 comment.push_str(&footer);
1678
1679 backend.post_comment(&task.id, &comment).await?;
1680
1681 Ok(weight_signal)
1682 }
1683
1684 async fn process_delegations(
1690 &self,
1691 parent_task: &ExternalTask,
1692 delegations: &[Delegation],
1693 backend: &Arc<dyn ExternalBackend>,
1694 ) -> anyhow::Result<()> {
1695 let parent_id = &parent_task.id;
1696
1697 let existing_titles: HashSet<String> = match backend.list_all_tasks().await {
1700 Ok(tasks) => tasks.into_iter().map(|t| t.title).collect(),
1701 Err(e) => {
1702 tracing::warn!(err = %e, "failed to fetch tasks for dedup — will create all");
1703 HashSet::new()
1704 }
1705 };
1706
1707 for delegation in delegations {
1708 if existing_titles.contains(&delegation.title) {
1710 tracing::info!(
1711 parent = parent_id.0,
1712 title = delegation.title,
1713 "skipping delegation — issue with same title already exists"
1714 );
1715 continue;
1716 }
1717
1718 let mut labels = delegation.labels.clone();
1720 labels.push("status:new".to_string());
1721
1722 let child_body = format!(
1724 "{}\n\n---\n_Delegated from #{}_{}",
1725 delegation.body,
1726 parent_id.0,
1727 engine::orch_footer()
1728 );
1729
1730 match backend
1731 .create_sub_task(parent_id, &delegation.title, &child_body, &labels)
1732 .await
1733 {
1734 Ok(child_id) => {
1735 tracing::info!(
1736 parent = parent_id.0,
1737 child = child_id.0,
1738 title = delegation.title,
1739 "created delegated subtask"
1740 );
1741 }
1742 Err(e) => {
1743 tracing::error!(
1744 parent = parent_id.0,
1745 title = delegation.title,
1746 err = %e,
1747 "failed to create delegated subtask"
1748 );
1749 }
1750 }
1751 }
1752
1753 if let Some(ref store) = self.store
1755 && let Ok(Some(store_id)) = store.resolve_task_id(&self.repo, &parent_id.0).await
1756 {
1757 store
1758 .update_status(store_id, TaskStatus::Blocked)
1759 .await
1760 .context("store-first: failed to block parent in store")?;
1761 }
1762 if let Err(e) = backend.update_status(parent_id, Status::Blocked).await {
1763 tracing::warn!(
1764 parent = parent_id.0,
1765 err = %e,
1766 "failed to mirror blocked status to backend — store is authoritative"
1767 );
1768 }
1769
1770 let summary = delegations
1772 .iter()
1773 .enumerate()
1774 .map(|(i, d)| format!("{}. {}", i + 1, d.title))
1775 .collect::<Vec<_>>()
1776 .join("\n");
1777
1778 backend
1779 .post_comment(
1780 parent_id,
1781 &format!(
1782 "Delegated {} subtask(s):\n\n{}\n\nParent task is blocked until all subtasks complete.{}",
1783 delegations.len(),
1784 summary,
1785 engine::orch_footer()
1786 ),
1787 )
1788 .await?;
1789
1790 Ok(())
1791 }
1792
1793 pub(crate) async fn resolve_project_dir(&self) -> anyhow::Result<PathBuf> {
1795 if let Ok(dir) = env::var("PROJECT_DIR")
1797 && !dir.is_empty()
1798 {
1799 return Ok(PathBuf::from(dir));
1800 }
1801
1802 if let Ok(paths) = config::get_project_paths() {
1804 for path_str in &paths {
1805 let path = PathBuf::from(path_str);
1806 if let Ok(repo) = config::get_repo_for_project(&path) {
1808 let path_for_check = path.clone();
1810 if repo == self.repo && fs::metadata(&path_for_check).await.is_ok() {
1811 return Ok(path);
1812 }
1813 }
1814 }
1815 }
1816
1817 if let Ok(dir) = config::get("project_dir")
1819 && !dir.is_empty()
1820 {
1821 let path = PathBuf::from(&dir);
1822 let path_for_check = path.clone();
1823 if fs::metadata(&path_for_check).await.is_ok() {
1824 return Ok(path);
1825 }
1826 }
1827
1828 let parts: Vec<&str> = self.repo.split('/').collect();
1830 if parts.len() == 2 {
1831 let bare = self
1832 .orch_home
1833 .join("projects")
1834 .join(parts[0])
1835 .join(format!("{}.git", parts[1]));
1836 let bare_for_check = bare.clone();
1837 if task::spawn_blocking(move || bare_for_check.exists())
1838 .await
1839 .unwrap_or(false)
1840 {
1841 return Ok(bare);
1842 }
1843 }
1844
1845 Err(NoProjectDir {
1850 repo: self.repo.clone(),
1851 bare_clone: self
1852 .orch_home
1853 .join("projects")
1854 .join(self.repo.split('/').next().unwrap_or_default())
1855 .join(format!(
1856 "{}.git",
1857 self.repo.split('/').nth(1).unwrap_or_default()
1858 )),
1859 }
1860 .into())
1861 }
1862}
1863
1864async fn update_agent_label_after_reroute(
1870 #[cfg_attr(
1871 test,
1872 expect(unused_variables, reason = "only the label call outside tests uses it")
1873 )]
1874 repo: &str,
1875 task: &ExternalTask,
1876 backend: &Arc<dyn ExternalBackend>,
1877 old_agent: &str,
1878 new_agent: &str,
1879) -> bool {
1880 let old_label = format!("agent:{old_agent}");
1881 if let Err(e) = backend.remove_label(&task.id, &old_label).await {
1882 tracing::warn!(
1883 task_id = ?task.id,
1884 label = old_label,
1885 error = %e,
1886 "failed to remove old agent label during re-route"
1887 );
1888 }
1889 let new_label = format!("agent:{new_agent}");
1890
1891 #[cfg(not(test))]
1894 {
1895 match GhHttp::new() {
1896 Ok(gh) => {
1897 if gh
1898 .ensure_label(
1899 repo,
1900 &new_label,
1901 http::status_label_color(&new_label),
1902 &format!("Agent: {new_agent}"),
1903 )
1904 .await
1905 .is_err()
1906 {
1907 tracing::warn!(
1908 task_id = ?task.id,
1909 label = %new_label,
1910 "ensure_label failed during agent label update after failover"
1911 );
1912 }
1913 }
1914 Err(e) => {
1915 tracing::warn!(
1916 task_id = ?task.id,
1917 err = %e,
1918 "GhHttp::new() failed — skipping ensure_label"
1919 );
1920 }
1921 }
1922 }
1923
1924 if let Err(e) = backend
1925 .set_labels(&task.id, slice::from_ref(&new_label))
1926 .await
1927 {
1928 tracing::warn!(
1929 task_id = ?task.id,
1930 label = %new_label,
1931 error = %e,
1932 "set_labels failed during agent label update after failover"
1933 );
1934 return false;
1935 }
1936 true
1937}
1938
1939fn needs_review_signal(last_error: &str, agent: &str) -> WeightSignal {
1942 let agent = agent.to_string();
1943 if classify_run_error_type(last_error) == "rate_limit" {
1944 WeightSignal::RateLimited { agent }
1945 } else if !last_error.is_empty() {
1946 WeightSignal::Failed { agent }
1947 } else {
1948 WeightSignal::Success { agent }
1949 }
1950}
1951
1952#[cfg(test)]
1953mod tests;