1use crate::github::http::GhHttp;
4use crate::github::types::is_own_check;
5use crate::github::types::{GitHubCheckRun, RequiredStatusCheck};
6use crate::security;
7use crate::store::TaskStore;
8use crate::store::store_increment;
9use std::collections::HashSet;
10use std::fmt::Write as _;
11use std::sync::Arc;
12
13pub(crate) const MAX_CI_MERGE_FAILURES: u64 = 3;
17
18pub(crate) const CI_FAILURE_AUTO_MERGE_STAGE: &str = "during auto-merge";
20
21pub(crate) const CI_FAILURE_BEFORE_REVIEW_STAGE: &str = "before review";
23
24pub(crate) fn ci_failure_limit_reason(stage: &str) -> String {
26 format!("CI failure limit ({MAX_CI_MERGE_FAILURES}) reached {stage}")
27}
28
29pub(super) async fn record_ci_check(
30 store: &Arc<TaskStore>,
31 repo: &str,
32 task_id: &str,
33) -> anyhow::Result<()> {
34 let key = ci_check_ts_key(repo, task_id);
35 let now = chrono::Utc::now().to_rfc3339();
36 store.kv_set(&key, &now).await
37}
38
39pub(super) fn ci_check_ts_key(repo: &str, task_id: &str) -> String {
40 format!("ci_check_ts:{repo}#{task_id}")
41}
42
43pub(super) fn ci_pending_since_prefix(repo: &str, task_id: &str) -> String {
45 format!("ci_pending_since:{repo}#{task_id}#")
46}
47
48pub(super) fn ci_pending_since_key(repo: &str, task_id: &str, head_sha: &str) -> String {
50 format!("{}{head_sha}", ci_pending_since_prefix(repo, task_id))
51}
52
53fn ci_failure_sha_prefix(repo: &str, task_id: &str) -> String {
55 format!("ci_failure_sha:{repo}#{task_id}#")
56}
57
58pub(super) fn ci_failure_sha_key(repo: &str, task_id: &str, head_sha: &str) -> String {
59 format!("{}{head_sha}", ci_failure_sha_prefix(repo, task_id))
60}
61
62pub(crate) async fn count_ci_failure_for_head(
64 store: &Arc<TaskStore>,
65 repo: &str,
66 task_id: &str,
67 head_sha: &str,
68) -> anyhow::Result<Option<u64>> {
69 let key = (!head_sha.is_empty()).then(|| ci_failure_sha_key(repo, task_id, head_sha));
70 if let Some(ref key) = key
71 && store.kv_increment(key).await? > 1
72 {
73 return Ok(None);
74 }
75 match store_increment(&Some(Arc::clone(store)), repo, task_id, "ci_merge_failures").await {
76 Ok(n) => Ok(Some(n)),
77 Err(e) => {
78 if let Some(ref key) = key
79 && let Err(del) = store.kv_delete(key).await
80 {
81 tracing::warn!(
82 task_id,
83 err = %del,
84 "failed to roll back ci_failure_sha after increment error"
85 );
86 }
87 Err(e)
88 }
89 }
90}
91
92pub(super) async fn ci_pending_elapsed(
104 store: &Arc<TaskStore>,
105 repo: &str,
106 task_id: &str,
107 head_sha: &str,
108) -> anyhow::Result<chrono::Duration> {
109 let key = ci_pending_since_key(repo, task_id, head_sha);
110 let now = chrono::Utc::now();
111 let stored = store.kv_insert_if_absent(&key, &now.to_rfc3339()).await?;
120 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&stored) {
121 Ok(now.signed_duration_since(dt.with_timezone(&chrono::Utc)))
122 } else {
123 tracing::warn!(
124 task_id,
125 stored,
126 "ci_pending_since value unparseable — resetting"
127 );
128 store.kv_set(&key, &now.to_rfc3339()).await?;
129 Ok(chrono::Duration::zero())
130 }
131}
132
133pub(super) async fn clear_ci_pending_since(
143 store: &Arc<TaskStore>,
144 repo: &str,
145 task_id: &str,
146 reason: &str,
147) -> anyhow::Result<()> {
148 for (key, prior) in store
149 .kv_list_prefix(&ci_pending_since_prefix(repo, task_id))
150 .await?
151 {
152 tracing::debug!(task_id, reason, prior_since = %prior, "clearing ci_pending_since");
153 store.kv_delete(&key).await?;
154 }
155 Ok(())
156}
157
158pub(crate) async fn sweep_ci_timer_keys(
160 store: &Arc<TaskStore>,
161 repo: &str,
162 finished_task_ids: &[String],
163) -> anyhow::Result<()> {
164 let finished: HashSet<&str> = finished_task_ids.iter().map(String::as_str).collect();
165 let repo_marker = format!("{repo}#");
166 for prefix in [
167 "ci_check_ts:",
168 "ci_pending_since:",
169 "review_ci_wait_since:",
170 "ci_failure_sha:",
171 "ci_bootstrap_wait_since:",
172 "ci_bootstrap_no_checks_comment:",
173 "ci_bootstrap_never_run_comment:",
174 ] {
175 for (key, _) in store.kv_list_prefix(prefix).await? {
176 let rest = &key[prefix.len()..];
177 let stale = match rest.strip_prefix(repo_marker.as_str()) {
178 Some(tail) => finished.contains(tail.split('#').next().unwrap_or(tail)),
180 None => !rest.contains('#'),
181 };
182 if stale {
183 store.kv_delete(&key).await?;
184 }
185 }
186 }
187 Ok(())
188}
189
190pub(crate) fn required_checks_state(
191 required_contexts: &[RequiredStatusCheck],
192 check_runs: &[GitHubCheckRun],
193 statuses: &[(String, String)],
194) -> (String, u64, u64, u64, u64) {
195 if required_contexts.is_empty() {
196 return ("success".to_string(), 0, 0, 0, 0);
197 }
198
199 let mut passing = 0u64;
200 let mut failing = 0u64;
201 let mut pending = 0u64;
202
203 for required in required_contexts {
204 let mut matched = false;
205
206 if let Some(run) = check_runs
207 .iter()
208 .find(|run| required_check_run_matches(required, run))
209 {
210 matched = true;
211 if !run.is_finished() {
212 pending += 1;
213 } else if run.is_passed() {
214 passing += 1;
215 } else {
216 failing += 1;
217 }
218 } else {
219 for (name, state) in statuses {
220 if !required_commit_status_matches(required, name) {
221 continue;
222 }
223 matched = true;
224 match state.as_str() {
225 "success" | "neutral" | "skipped" => passing += 1,
226 "failure" | "error" => failing += 1,
227 _ => pending += 1,
228 }
229 break;
230 }
231 }
232
233 if !matched {
234 pending += 1;
235 }
236 }
237
238 let total = required_contexts.len() as u64;
239 let state = if failing > 0 {
240 "failure".to_string()
241 } else if pending > 0 {
242 "pending".to_string()
243 } else {
244 "success".to_string()
245 };
246
247 (state, total, passing, failing, pending)
248}
249
250pub(crate) fn required_check_run_matches(
251 required: &RequiredStatusCheck,
252 run: &GitHubCheckRun,
253) -> bool {
254 if run.name != required.context {
255 return false;
256 }
257 match required.integration_id {
258 None => true,
259 Some(id) => run.app.as_ref().is_some_and(|app| app.id == id),
260 }
261}
262
263pub(crate) fn required_commit_status_matches(
264 required: &RequiredStatusCheck,
265 context: &str,
266) -> bool {
267 required.integration_id.is_none() && required.context == context
268}
269
270const CI_LOG_TAIL_LINES: usize = 80;
271
272const CI_CONTEXT_MAX_CHARS: usize = 8000;
273
274pub(crate) async fn red_ci_context(
276 gh: &GhHttp,
277 repo: &str,
278 pr_number: u64,
279 sha: &str,
280 failed: &[String],
281) -> String {
282 let mut sections: Vec<(String, String)> = Vec::new();
283 match gh.get_check_runs(repo, sha).await {
284 Ok(runs) => {
285 let failed_runs = runs.iter().filter(|r| {
286 matches!(r.conclusion.as_deref(), Some("failure" | "timed_out"))
287 && (failed.is_empty() || failed.contains(&r.name))
288 });
289 for run in failed_runs {
290 sections.push((run.name.clone(), failure_text(gh, repo, run).await));
291 }
292 }
293 Err(e) => {
294 tracing::debug!(err = %e, "failed to fetch check runs for the CI failure context");
295 }
296 }
297 for name in failed {
298 if !sections.iter().any(|(n, _)| n == name) {
299 sections.push((name.clone(), String::new()));
300 }
301 }
302 format_red_ci_context(pr_number, sha, §ions)
303}
304
305async fn failure_text(gh: &GhHttp, repo: &str, run: &GitHubCheckRun) -> String {
307 match gh.get_check_run_annotations(repo, run.id).await {
308 Ok(annotations) => {
309 let lines: Vec<String> = annotations
310 .iter()
311 .filter(|a| a.annotation_level.as_deref() != Some("notice"))
312 .map(|a| {
313 let place = match (&a.path, a.start_line) {
314 (Some(path), Some(line)) => format!("{path}:{line}: "),
315 (Some(path), None) => format!("{path}: "),
316 _ => String::new(),
317 };
318 let title = a.title.as_deref().unwrap_or("");
319 let message = a.message.as_deref().unwrap_or("");
320 format!("{place}{title} {message}").trim().to_string()
321 })
322 .filter(|l| !l.is_empty())
323 .collect();
324 if !lines.is_empty() {
325 return lines.join("\n");
326 }
327 }
328 Err(e) => {
329 tracing::debug!(check_run_id = run.id, err = %e, "failed to fetch check run annotations");
330 }
331 }
332 gh.get_job_log_tail(repo, run.id, CI_LOG_TAIL_LINES)
333 .await
334 .unwrap_or_default()
335}
336
337pub(crate) fn format_red_ci_context(
338 pr_number: u64,
339 sha: &str,
340 sections: &[(String, String)],
341) -> String {
342 let names = sections
343 .iter()
344 .map(|(n, _)| n.as_str())
345 .collect::<Vec<_>>()
346 .join(", ");
347 let mut out = format!(
348 "CI failed on PR #{pr_number} at head {sha}. Failed checks: {names}.\n\
349 Run each failing check locally and fix it. Do not report done until it passes.\n"
350 );
351 for (name, text) in sections {
352 let text = text.trim();
353 let text = if text.is_empty() {
354 "No failure text was available. Read the log of this check on the PR."
355 } else {
356 text
357 };
358 let _ = write!(out, "\n### {name}\n```\n{text}\n```\n");
359 }
360 let mut out = security::redact(&out);
361 if out.chars().count() > CI_CONTEXT_MAX_CHARS {
362 out = out.chars().take(CI_CONTEXT_MAX_CHARS).collect();
363 out.push_str("\n[truncated]");
364 }
365 out
366}
367
368pub(crate) async fn billing_failed_runs(
379 gh: &GhHttp,
380 repo: &str,
381 sha: &str,
382 prefetched: Option<Vec<GitHubCheckRun>>,
383) -> u64 {
384 let check_runs = match prefetched {
385 Some(runs) => runs,
386 None => match gh.get_check_runs(repo, sha).await {
387 Ok(runs) => runs,
388 Err(e) => {
389 tracing::debug!(err = %e, "failed to fetch check runs for billing failure check");
390 return 0;
391 }
392 },
393 };
394
395 let mut count = 0;
396 for run in check_runs
397 .iter()
398 .filter(|r| r.conclusion.as_deref() == Some("failure"))
399 {
400 match gh.get_check_run_annotations(repo, run.id).await {
401 Ok(annotations) => {
402 for annotation in &annotations {
403 let msg = annotation.message.as_deref().unwrap_or("");
404 let title = annotation.title.as_deref().unwrap_or("");
405 if msg.contains("account payments have failed")
406 || msg.contains("spending limit")
407 || title.contains("account payments have failed")
408 || title.contains("spending limit")
409 {
410 count += 1;
411 break;
412 }
413 }
414 }
415 Err(e) => {
416 tracing::debug!(
417 check_run_id = run.id,
418 err = %e,
419 "failed to fetch check run annotations"
420 );
421 }
422 }
423 }
424
425 count
426}
427
428pub(super) fn may_merge_onto_base(behind_by: Option<u64>) -> bool {
434 behind_by == Some(0)
435}
436
437pub(super) fn any_check_pending(
439 check_runs: &[GitHubCheckRun],
440 statuses: &[(String, String)],
441) -> bool {
442 check_runs
443 .iter()
444 .any(|run| !is_own_check(&run.name) && !run.is_finished())
445 || statuses.iter().any(|(name, state)| {
446 !is_own_check(name)
447 && !matches!(
448 state.as_str(),
449 "success" | "failure" | "error" | "neutral" | "skipped"
450 )
451 })
452}
453
454pub(super) fn failing_optional_check_names(
456 required: &[RequiredStatusCheck],
457 check_runs: &[GitHubCheckRun],
458 statuses: &[(String, String)],
459) -> Vec<String> {
460 let mut names = Vec::new();
461 for run in check_runs {
462 if required.iter().any(|r| required_check_run_matches(r, run)) {
463 continue;
464 }
465 if run.is_finished() && !run.is_passed() {
466 names.push(run.name.clone());
467 }
468 }
469 for (name, state) in statuses {
470 if !matches!(state.as_str(), "failure" | "error") {
471 continue;
472 }
473 if required
474 .iter()
475 .any(|r| required_commit_status_matches(r, name))
476 {
477 continue;
478 }
479 if !names.contains(name) {
480 names.push(name.clone());
481 }
482 }
483 names
484}
485
486pub(super) fn mergeable_state_ready(
489 state: &str,
490 required: &[RequiredStatusCheck],
491 check_runs: &[GitHubCheckRun],
492 statuses: &[(String, String)],
493) -> bool {
494 match state {
495 "clean" | "has_hooks" => true,
496 "unstable" => {
497 if required.is_empty() {
498 !any_check_pending(check_runs, statuses)
499 } else {
500 required_checks_state(required, check_runs, statuses).0 == "success"
501 }
502 }
503 _ => false,
504 }
505}
506
507pub(super) async fn required_ci_checks_pass(
513 gh: &GhHttp,
514 repo: &str,
515 pr_number: u64,
516) -> Option<bool> {
517 let pr = match gh.get_pr(repo, pr_number).await {
518 Ok(pr) => pr,
519 Err(e) => {
520 tracing::warn!(pr_number, err = %e, "required_ci_checks_pass: failed to fetch PR");
521 return None;
522 }
523 };
524
525 let head_sha = pr.head.sha.clone();
526 let base_branch = pr.base.ref_.clone();
527
528 let required_contexts = match gh
529 .get_required_status_check_contexts(repo, &base_branch)
530 .await
531 {
532 Ok(ctx) => ctx,
533 Err(e) => {
534 tracing::warn!(
535 pr_number,
536 err = %e,
537 "required_ci_checks_pass: failed to fetch required contexts"
538 );
539 return None;
540 }
541 };
542
543 if required_contexts.is_empty() {
545 return Some(true);
546 }
547
548 let check_runs = match gh.get_check_runs(repo, &head_sha).await {
549 Ok(runs) => runs,
550 Err(e) => {
551 tracing::warn!(
552 pr_number,
553 err = %e,
554 "required_ci_checks_pass: failed to fetch check runs"
555 );
556 return None;
557 }
558 };
559
560 let statuses = match gh.get_commit_status_contexts(repo, &head_sha).await {
561 Ok(s) => s,
562 Err(e) => {
563 tracing::warn!(
564 pr_number,
565 err = %e,
566 "required_ci_checks_pass: failed to fetch commit statuses"
567 );
568 return None;
569 }
570 };
571
572 let (state, ..) = required_checks_state(&required_contexts, &check_runs, &statuses);
573 Some(state == "success")
574}