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