1use super::{PrCreateError, PrCreateResult, format_task_ref};
4use crate::github::http::GhHttp;
5use crate::plan;
6use regex::Regex;
7use std::fmt::Write as _;
8use std::path::Path;
9use std::sync::LazyLock;
10use std::time::Duration;
11use tokio::process::Command;
12use tokio::time;
13
14fn strip_push_and_pr_creation(text: &str) -> String {
17 let mut kept_lines: Vec<String> = Vec::new();
18 for line in text.lines() {
19 if line.trim().is_empty() {
20 if kept_lines.last().is_some_and(|l| !l.is_empty()) {
21 kept_lines.push(String::new());
22 }
23 continue;
24 }
25
26 let indent_len = line.len() - line.trim_start().len();
27 let indent = &line[..indent_len];
28 let trimmed = line.trim();
29 let (marker, rest) = match list_marker(trimmed) {
30 Some((m, r)) => (m, r),
31 None => ("", trimmed),
32 };
33
34 let kept: Vec<&str> = split_statements(rest)
35 .into_iter()
36 .filter(|s| !is_push_or_pr_creation_statement(s))
37 .collect();
38 if kept.is_empty() {
39 continue;
40 }
41 kept_lines.push(format!("{indent}{marker}{}", kept.join(" ")));
42 }
43 while kept_lines.last().is_some_and(String::is_empty) {
44 kept_lines.pop();
45 }
46 kept_lines.join("\n")
47}
48
49fn split_statements(text: &str) -> Vec<&str> {
50 static SEP: LazyLock<Regex> =
51 LazyLock::new(|| Regex::new(r"(\.{2,}|(?:[.!?]))\s+").expect("valid statement separator"));
52 let mut statements = Vec::new();
53 let mut last = 0;
54 for cap in SEP.captures_iter(text) {
55 let full = cap.get(0).expect("full separator match");
56 let punct = cap.get(1).expect("punctuation capture");
57 let ellipsis = punct.as_str().len() >= 2 && punct.as_str().bytes().all(|b| b == b'.');
58 let end = if ellipsis { punct.start() } else { punct.end() };
59 let stmt = text[last..end].trim();
60 if !stmt.is_empty() {
61 statements.push(stmt);
62 }
63 last = full.end();
64 }
65 let rest = text[last..].trim();
66 if !rest.is_empty() {
67 statements.push(rest);
68 }
69 statements
70}
71
72fn list_marker(line: &str) -> Option<(&str, &str)> {
73 for prefix in ["- ", "* ", "+ "] {
74 if let Some(rest) = line.strip_prefix(prefix) {
75 return Some((prefix, rest));
76 }
77 }
78 let dot = line.find(". ")?;
79 if !line[..dot].is_empty() && line[..dot].bytes().all(|b| b.is_ascii_digit()) {
80 Some((&line[..dot + 2], &line[dot + 2..]))
81 } else {
82 None
83 }
84}
85
86fn is_push_or_pr_creation_statement(text: &str) -> bool {
87 static PAT: LazyLock<Regex> = LazyLock::new(|| {
88 Regex::new(concat!(
89 r"(?i)",
90 r"\bgit\s+push\b",
91 r"|\bgh\s+pr\s+create\b",
92 r"|\bgh\s+pr\s+open\b",
93 r"|\bpush\s+(was\s+)?(denied|blocked|rejected)\b",
94 r"|\bpush\s+permission\b",
95 r"|\bcouldn['’]?t\s+push\b",
96 r"|\bcould\s+not\s+push\b",
97 r"|\bcan['’]?t\s+push\b",
98 r"|\bcannot\s+push\b",
99 r"|\bdidn['’]?t\s+push\b",
100 r"|\bdid\s+not\s+push\b",
101 r"|\bnothing\s+is\s+on\s+the\s+remote\b",
102 r"|\bnot\s+on\s+the\s+remote\b",
103 r"|\bopen(?:ing)?\s+(?:the|a)\s+pr\b",
104 r"|\bcreat(?:e|ing)\s+(?:the|a)\s+pr\b",
105 r"|\bopen(?:ing)?\s+(?:the|a)\s+pull\s+request\b",
106 r"|\bcreat(?:e|ing)\s+(?:the|a)\s+pull\s+request\b",
107 ))
108 .expect("valid push/pr-creation regex")
109 });
110 PAT.is_match(text)
111}
112
113fn cleaned_pr_items(items: &[String]) -> Vec<String> {
114 items
115 .iter()
116 .filter_map(|item| {
117 let cleaned = strip_push_and_pr_creation(item);
118 (!cleaned.is_empty()).then_some(cleaned)
119 })
120 .collect()
121}
122
123#[expect(
125 clippy::too_many_arguments,
126 reason = "each argument is one section of the PR body"
127)]
128pub(super) fn build_pr_body(
129 title: &str,
130 summary: &str,
131 accomplished: &[String],
132 remaining: &[String],
133 files: &[String],
134 task_id: &str,
135 agent: &str,
136 model: Option<&str>,
137) -> String {
138 let cleaned_summary = strip_push_and_pr_creation(summary);
139 let summary_text = if cleaned_summary.is_empty() {
140 title
141 } else {
142 cleaned_summary.as_str()
143 };
144 let accomplished = cleaned_pr_items(accomplished);
145 let remaining = cleaned_pr_items(remaining);
146
147 let mut body = format!("## Summary\n\n{summary_text}");
148
149 if !accomplished.is_empty() {
150 body.push_str("\n\n### What was done\n\n");
151 for item in &accomplished {
152 let _ = writeln!(body, "- {item}");
153 }
154 }
155
156 if !remaining.is_empty() {
157 body.push_str("\n\n### Remaining\n\n");
158 for item in &remaining {
159 let _ = writeln!(body, "- {item}");
160 }
161 }
162
163 if !files.is_empty() {
164 body.push_str("\n\n### Files changed\n\n");
165 for file in files {
166 let _ = writeln!(body, "- `{file}`");
167 }
168 }
169
170 let bootstrap = plan::is_ci_bootstrap_id(title.split_whitespace().next().unwrap_or(title));
172 if !bootstrap
173 && !task_id.starts_with("internal:")
174 && let Ok(issue_num) = task_id.parse::<u64>()
175 {
176 let _ = write!(body, "\n\nCloses #{issue_num}");
177 }
178
179 let model_str = model.map(|m| format!(" using `{m}`")).unwrap_or_default();
180 let task_ref = format_task_ref(task_id);
181 let _ = write!(
182 body,
183 "\n\n---\n*Task {task_ref} · Created by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch){model_str}*"
184 );
185 body
186}
187
188#[expect(
197 clippy::too_many_arguments,
198 reason = "the PR needs its branch, body sections, attribution and target together"
199)]
200pub async fn create_pr_if_needed(
201 dir: &Path,
202 branch: &str,
203 title: &str,
204 summary: &str,
205 accomplished: &[String],
206 remaining: &[String],
207 files: &[String],
208 task_id: &str,
209 agent: &str,
210 model: Option<&str>,
211 repo: &str,
212 base_branch: &str,
213) -> PrCreateResult<String> {
214 const MAX_RETRIES: u32 = 3;
216 let gh = GhHttp::new()?;
217
218 match gh.get_pr_number(repo, branch).await {
220 Ok(Some(pr_number)) => {
221 tracing::info!(task_id, pr = pr_number, "PR already exists");
222 append_pr_footer_if_missing(&gh, repo, pr_number, task_id, agent, model).await;
224 let pr = match gh.get_pr(repo, pr_number).await {
226 Ok(pr) => pr,
227 Err(e) => {
228 tracing::warn!(task_id, error = %e, "get_pr API call failed after detecting existing PR");
229 return Err(PrCreateError::ApiError(e));
230 }
231 };
232 return Ok(pr.html_url);
233 }
234 Ok(None) => {
235 }
237 Err(e) => {
238 tracing::warn!(task_id, error = %e, "get_pr_number API call failed");
239 return Err(PrCreateError::ApiError(e));
240 }
241 }
242
243 let git_files: Vec<String>;
245 let effective_files: &[String] = if files.is_empty() {
246 match Command::new("git")
247 .args([
248 "diff",
249 &format!("origin/{base_branch}...HEAD"),
250 "--name-only",
251 ])
252 .current_dir(dir)
253 .output()
254 .await
255 {
256 Ok(output) if output.status.success() => {
257 git_files = String::from_utf8_lossy(&output.stdout)
258 .lines()
259 .filter(|l| !l.is_empty())
260 .map(ToString::to_string)
261 .collect();
262 &git_files
263 }
264 _ => files,
265 }
266 } else {
267 files
268 };
269
270 let body = build_pr_body(
271 title,
272 summary,
273 accomplished,
274 remaining,
275 effective_files,
276 task_id,
277 agent,
278 model,
279 );
280
281 let pr_title = title;
283
284 let mut last_error: Option<anyhow::Error> = None;
286 let mut created_url: Option<String> = None;
287 let mut had_transient_error = false;
288 let mut effective_base = base_branch.to_string();
289 let mut tried_api_fallback = false;
290
291 for attempt in 1..=MAX_RETRIES {
292 match gh
293 .create_pr(repo, pr_title, &body, branch, &effective_base)
294 .await
295 {
296 Ok(u) => {
297 created_url = Some(u);
298 break;
299 }
300 Err(e) => {
301 let err_str = format!("{e}");
302 if is_transient_github_error(&err_str) {
303 had_transient_error = true;
304 if attempt < MAX_RETRIES {
305 let delay = Duration::from_secs(2u64.pow(attempt));
306 tracing::warn!(
307 task_id,
308 attempt,
309 delay_secs = delay.as_secs(),
310 error = %e,
311 "transient GitHub API error during PR creation — retrying"
312 );
313 time::sleep(delay).await;
314 }
315 } else if is_invalid_base_error(&err_str) && !tried_api_fallback {
316 tried_api_fallback = true;
319 tracing::warn!(
320 task_id,
321 base_branch = %effective_base,
322 error = %e,
323 "PR creation failed with invalid base — fetching default branch from GitHub API"
324 );
325 match gh.get_default_branch(repo).await {
326 Ok(api_default) if api_default != effective_base => {
327 tracing::info!(
328 task_id,
329 old_base = %effective_base,
330 new_base = %api_default,
331 "retrying PR creation with GitHub API default branch"
332 );
333 effective_base = api_default;
334 continue;
335 }
336 Ok(api_default) => {
337 tracing::warn!(
338 task_id,
339 base_branch = %api_default,
340 "GitHub API default branch matches local — no fallback possible"
341 );
342 }
343 Err(api_err) => {
344 tracing::warn!(
345 task_id,
346 error = %api_err,
347 "failed to fetch default branch from GitHub API"
348 );
349 }
350 }
351 }
352 last_error = Some(e);
353 }
354 }
355 }
356
357 let url = if let Some(u) = created_url {
358 u
359 } else {
360 let e = last_error.unwrap_or_else(|| {
361 anyhow::anyhow!("PR creation failed after retries (no error captured)")
362 });
363 let err_str = format!("{e}");
364 if is_transient_github_error(&err_str) || had_transient_error {
371 tracing::warn!(
372 task_id,
373 error = %e,
374 "transient GitHub API error after all retries — checking if PR was actually created"
375 );
376 match gh.get_pr_number(repo, branch).await {
377 Ok(Some(pr_number)) => {
378 tracing::info!(
379 task_id,
380 pr = pr_number,
381 "PR was created despite transient errors — recovering"
382 );
383 append_pr_footer_if_missing(&gh, repo, pr_number, task_id, agent, model).await;
384 match gh.get_pr(repo, pr_number).await {
385 Ok(pr) => pr.html_url,
386 Err(get_err) => {
387 tracing::warn!(
388 task_id,
389 error = %get_err,
390 "failed to fetch PR URL after transient-error recovery"
391 );
392 return Err(PrCreateError::ApiError(e));
393 }
394 }
395 }
396 Ok(None) => {
397 tracing::warn!(
398 task_id,
399 "PR was not created after all retries — propagating original error"
400 );
401 return Err(PrCreateError::ApiError(e));
402 }
403 Err(check_err) => {
404 tracing::warn!(
405 task_id,
406 error = %check_err,
407 "failed to verify PR existence after transient error retries — propagating original error"
408 );
409 return Err(PrCreateError::ApiError(e));
410 }
411 }
412 } else {
413 return Err(PrCreateError::ApiError(e));
414 }
415 };
416
417 tracing::info!(task_id, pr_url = %url, "created PR via GhHttp API");
418
419 Ok(url)
420}
421
422pub(crate) fn is_transient_github_error(err_str: &str) -> bool {
426 if err_str.contains("HTTP send failed") {
430 return true;
431 }
432 if err_str.contains("GitHub API server error") {
433 return true;
434 }
435
436 if extract_github_http_status(err_str).is_some_and(|s| (500..600).contains(&s)) {
438 return true;
439 }
440
441 let lower = err_str.to_lowercase();
443
444 if lower.contains("connection reset")
446 || lower.contains("broken pipe")
447 || lower.contains("connection refused")
448 || lower.contains("connection closed")
449 || lower.contains("transport error")
450 || lower.contains("failed to connect")
451 || lower.contains("failed to connect to github.com port")
452 || lower.contains("curl: (7) failed to connect")
453 || lower.contains("couldn't connect to server")
454 || lower.contains("could not connect to server")
455 {
456 return true;
457 }
458
459 if lower.contains("timeout") {
461 return true;
462 }
463
464 if lower.contains("dns error")
466 || lower.contains("resolve")
467 || lower.contains("name resolution")
468 || lower.contains("no such host")
469 {
470 return true;
471 }
472
473 if lower.contains("tls handshake")
475 || lower.contains("certificate")
476 || lower.contains("ssl error")
477 {
478 return true;
479 }
480
481 if lower.contains("network is unreachable")
483 || lower.contains("host unreachable")
484 || lower.contains("temporary failure")
485 {
486 return true;
487 }
488
489 if lower.contains("unexpected eof") || lower.contains("unexpected end of file") {
491 return true;
492 }
493
494 if lower.contains("circuit-breaker") || lower.contains("circuit breaker") {
496 return true;
497 }
498
499 if lower.contains("rate limit") || lower.contains("too many requests") {
501 return true;
502 }
503
504 false
505}
506
507pub(crate) fn is_invalid_base_error(err_str: &str) -> bool {
513 let lower = err_str.to_lowercase();
514 lower.contains("422") && lower.contains("base") && lower.contains("invalid")
515}
516
517pub(crate) fn is_transient_github_api_error(err_str: &str) -> bool {
525 if !is_transient_github_error(err_str) {
526 return false;
527 }
528
529 if extract_github_http_status(err_str).is_some() {
530 return true;
531 }
532
533 let lower = err_str.to_lowercase();
534 lower.contains("github")
535 || lower.contains("api.github.com")
536 || lower.contains("gh api")
537 || lower.contains("gh pr")
538 || lower.contains("gh error")
539 || lower.contains("circuit-breaker")
544 || lower.contains("circuit breaker")
545}
546
547pub(super) fn extract_github_http_status(err_str: &str) -> Option<u16> {
552 let marker = "failed (";
553 let start = err_str.find(marker)? + marker.len();
554 let rest = &err_str[start..];
555 let end = rest.find(')')?;
556 rest[..end].parse().ok()
557}
558
559async fn append_pr_footer_if_missing(
564 gh: &GhHttp,
565 repo: &str,
566 pr_number: u64,
567 task_id: &str,
568 agent: &str,
569 model: Option<&str>,
570) {
571 let pr = match gh.get_pr(repo, pr_number).await {
572 Ok(pr) => pr,
573 Err(e) => {
574 tracing::debug!(task_id, error = %e, "failed to fetch PR for footer check");
575 return;
576 }
577 };
578
579 let body = pr.body.unwrap_or_default();
580 if body.contains("via [Orch]") {
581 return; }
583
584 let model_str = model.map(|m| format!(" using `{m}`")).unwrap_or_default();
585 let task_ref = format_task_ref(task_id);
586 let footer = format!(
587 "\n\n---\n*Task {task_ref} · Created by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch){model_str}*"
588 );
589 let new_body = format!("{body}{footer}");
590
591 match gh.update_pr_body(repo, pr_number, &new_body).await {
592 Err(e) => {
593 tracing::warn!(task_id, error = %e, "failed to append footer to PR (non-fatal)");
594 }
595 _ => {
596 tracing::info!(
597 task_id,
598 pr = pr_number,
599 "appended attribution footer to agent-created PR"
600 );
601 }
602 }
603}