Skip to main content

orch/github/
http.rs

1//! Native `reqwest` HTTP client for the GitHub API — replaces `gh` CLI subprocesses.
2//!
3//! Uses a shared `reqwest::Client` with connection pooling, reads rate-limit
4//! headers proactively, and supports concurrent requests via `tokio::join!`.
5//!
6//! Auth: uses the centralized [`TokenResolver`] which supports:
7//! - `GH_TOKEN` / `GITHUB_TOKEN` environment variables
8//! - `gh.auth.token` config value
9//! - `gh auth token` CLI fallback (default — just run `gh auth login`)
10
11use super::token;
12use super::types::GitHubUser;
13use super::types::{
14    GitHubAnnotation, GitHubCheckRun, GitHubComment, GitHubIssue, GitHubPullRequest, GitHubReview,
15    GitHubReviewComment, RequiredStatusCheck,
16};
17use crate::backends::BlockedByFetch;
18use crate::backends::BlockedByIssue;
19use crate::config;
20use crate::engine::cooldown as engine_cooldown;
21use crate::engine::cooldown;
22use crate::engine::review_gate;
23use crate::github::types;
24use crate::security;
25use anyhow::Context;
26use base64::Engine;
27use base64::engine::general_purpose::STANDARD as BASE64;
28use reqwest::{Client, Response, StatusCode, header};
29use serde::Serialize;
30use serde::de::DeserializeOwned;
31use std::any;
32use std::cmp::Reverse;
33use std::collections::HashMap;
34use std::collections::HashSet;
35use std::error::Error as _;
36use std::fmt;
37use std::fmt::Debug;
38use std::fmt::Formatter;
39use std::fmt::Write as _;
40use std::path::Path;
41use std::sync::LazyLock;
42use std::sync::{
43    Arc, Mutex, OnceLock,
44    atomic::{AtomicU64, Ordering},
45};
46use std::time as std_time;
47use std::time::SystemTime;
48use std::time::{Duration, Instant};
49use tokio::runtime::Handle;
50use tokio::time;
51use urlencoding;
52
53#[cfg(not(test))]
54const GITHUB_API: &str = "https://api.github.com";
55// Tests that reach a real GhHttp must fail fast here, never send the operator's token to GitHub
56#[cfg(test)]
57const GITHUB_API: &str = "http://127.0.0.1:9";
58
59#[derive(Debug, serde::Deserialize)]
60struct BlockedByPayload {
61    #[serde(default)]
62    id: i64,
63    number: i64,
64    #[serde(default)]
65    state: String,
66    #[serde(default)]
67    state_reason: Option<String>,
68    #[serde(default)]
69    repository: Option<BlockedByRepoPayload>,
70}
71
72#[derive(Debug, serde::Deserialize)]
73struct BlockedByRepoPayload {
74    full_name: String,
75}
76
77pub(crate) fn is_full_commit_sha(sha: &str) -> bool {
78    let len = sha.len();
79    (len == 40 || len == 64) && sha.bytes().all(|b| b.is_ascii_hexdigit())
80}
81
82// Shared gate for every GitHub-posted body so a new call site cannot skip the scan
83/// `owner/repo` from a REST URL such as `https://api.github.com/repos/owner/repo/pulls`
84fn repo_from_url(url: &str) -> Option<String> {
85    let rest = url.split_once("/repos/")?.1;
86    let mut parts = rest.split(['/', '?']);
87    let owner = parts.next().filter(|s| !s.is_empty())?;
88    let name = parts.next().filter(|s| !s.is_empty())?;
89    Some(format!("{owner}/{name}"))
90}
91
92pub(crate) fn redact_posted_body(body: &str) -> String {
93    if !security::has_leaks(body) {
94        return body.to_string();
95    }
96    let leaks = security::scan(body);
97    let rules: Vec<&str> = leaks.iter().map(|leak| leak.rule).collect();
98    let warning = format!(
99        "\n\n> ⚠️ **Security Notice**: {} potential secret(s) detected and redacted: {}",
100        leaks.len(),
101        rules.join(", ")
102    );
103    format!("{}{warning}", security::redact(body))
104}
105
106fn merge_pr_body(head_sha: &str) -> serde_json::Value {
107    serde_json::json!({
108        "merge_method": "squash",
109        "sha": head_sha,
110    })
111}
112
113fn parse_positive_issue_number(number: &str) -> anyhow::Result<i64> {
114    let parsed = number
115        .parse::<i64>()
116        .with_context(|| format!("invalid issue number: {number}"))?;
117    if parsed <= 0 {
118        anyhow::bail!("invalid issue number: {number}");
119    }
120    Ok(parsed)
121}
122
123// ── Rate-limit state ─────────────────────────────────────────────────
124
125/// Proactive rate-limit state derived from `X-RateLimit-*` response headers.
126struct RateLimit {
127    /// Remaining requests in the current window.
128    remaining: Option<u32>,
129    /// UTC epoch second when the window resets.
130    reset_at: Option<u64>,
131    /// Hard backoff after a 403/429 (fallback when reset time is absent).
132    backoff_until: Option<Instant>,
133    backoff_delay: Duration,
134    backoff_base: Duration,
135    backoff_max: Duration,
136    /// Stop making calls when remaining drops below this threshold (default 200). The
137    /// reserve is for the dispatched agents, which run `gh` against the same token.
138    throttle_threshold: u32,
139}
140
141impl RateLimit {
142    fn new() -> Self {
143        let base = config::get("gh.backoff.base_seconds")
144            .ok()
145            .and_then(|v| v.parse::<u64>().ok())
146            .unwrap_or(30);
147        let max = config::get("gh.backoff.max_seconds")
148            .ok()
149            .and_then(|v| v.parse::<u64>().ok())
150            .unwrap_or(900);
151        let threshold = config::get("gh.rate_limit.throttle_threshold")
152            .ok()
153            .and_then(|v| v.parse::<u32>().ok())
154            .unwrap_or(200);
155
156        Self {
157            remaining: None,
158            reset_at: None,
159            backoff_until: None,
160            backoff_delay: Duration::ZERO,
161            backoff_base: Duration::from_secs(base),
162            backoff_max: Duration::from_secs(max),
163            throttle_threshold: threshold,
164        }
165    }
166
167    /// Update state from response headers.
168    fn update_from_headers(&mut self, headers: &header::HeaderMap) {
169        if let Some(v) = headers.get("x-ratelimit-remaining") {
170            self.remaining = v.to_str().ok().and_then(|s| s.parse().ok());
171        }
172        if let Some(v) = headers.get("x-ratelimit-reset") {
173            self.reset_at = v.to_str().ok().and_then(|s| s.parse().ok());
174        }
175    }
176
177    /// Record a successful call — reset hard backoff.
178    fn record_success(&mut self) {
179        if self.backoff_delay > Duration::ZERO {
180            tracing::info!("GitHub backoff cleared after successful API call");
181        }
182        self.backoff_delay = Duration::ZERO;
183        self.backoff_until = None;
184    }
185
186    /// Record a 403/429 — use reset_at timestamp if available, else exponential backoff.
187    fn record_rate_limit(&mut self) {
188        METRIC_RATE_LIMIT_HITS.fetch_add(1, Ordering::Relaxed);
189
190        // Prefer reset_at when available — avoids over-waiting with exponential backoff
191        if let Some(reset_epoch) = self.reset_at {
192            match SystemTime::now().duration_since(std_time::UNIX_EPOCH) {
193                Ok(since_epoch) => {
194                    let now_epoch = since_epoch.as_secs();
195                    if reset_epoch > now_epoch {
196                        let wait_secs = reset_epoch - now_epoch + 1;
197                        self.backoff_delay = Duration::from_secs(wait_secs);
198                        self.backoff_until = Some(Instant::now() + self.backoff_delay);
199                        tracing::warn!(
200                            wait_secs,
201                            "GitHub rate limit hit, waiting until reset time"
202                        );
203                        return;
204                    }
205                }
206                Err(e) => {
207                    tracing::error!(
208                        error = %e,
209                        "System clock is before UNIX epoch; ignoring reset_at and falling back to exponential backoff"
210                    );
211                }
212            }
213        }
214
215        // Fall back to exponential backoff when reset time is unknown
216        self.backoff_delay = if self.backoff_delay.is_zero() {
217            self.backoff_base
218        } else {
219            (self.backoff_delay * 2).min(self.backoff_max)
220        };
221        self.backoff_until = Some(Instant::now() + self.backoff_delay);
222        tracing::warn!(
223            delay_secs = self.backoff_delay.as_secs(),
224            "GitHub rate limit hit, backing off (no reset header)"
225        );
226    }
227
228    /// Returns remaining hard-backoff duration (post-403/429), or None.
229    fn backoff_remaining(&self) -> Option<Duration> {
230        if let Some(until) = self.backoff_until {
231            let now = Instant::now();
232            if now < until {
233                return Some(until - now);
234            }
235        }
236        None
237    }
238
239    /// Returns how long until the window resets when the quota is under the reserve.
240    ///
241    /// Returns Some only when:
242    /// - not already in hard backoff,
243    /// - `remaining` is known and below `throttle_threshold`, and
244    /// - `reset_at` is known and in the future.
245    fn proactive_wait_duration(&self) -> Option<Duration> {
246        // Don't double-throttle when already in hard backoff
247        if self.backoff_remaining().is_some() {
248            return None;
249        }
250        if let Some(remaining) = self.remaining
251            && remaining < self.throttle_threshold
252            && let Some(reset_epoch) = self.reset_at
253        {
254            let now_epoch = SystemTime::now()
255                .duration_since(std_time::UNIX_EPOCH)
256                .unwrap_or_default()
257                .as_secs();
258            if now_epoch < reset_epoch {
259                return Some(Duration::from_secs(reset_epoch - now_epoch + 1));
260            }
261        }
262        None
263    }
264
265    /// Combined check: backoff or proactive throttle. Used by engine's is_rate_limited().
266    fn is_active(&self) -> Option<Duration> {
267        self.backoff_remaining()
268            .or_else(|| self.proactive_wait_duration())
269    }
270}
271
272// ── Global state ─────────────────────────────────────────────────────
273
274static REST_RATE_LIMIT: LazyLock<Mutex<RateLimit>> = LazyLock::new(|| Mutex::new(RateLimit::new()));
275
276/// Separate rate-limit tracker for the GraphQL endpoint (distinct quota from REST).
277static GRAPHQL_RATE_LIMIT: LazyLock<Mutex<RateLimit>> =
278    LazyLock::new(|| Mutex::new(RateLimit::new()));
279
280// ── Rate-limit metrics ────────────────────────────────────────────────
281
282/// Total 403/429 rate-limit responses received (REST + GraphQL).
283static METRIC_RATE_LIMIT_HITS: AtomicU64 = AtomicU64::new(0);
284/// Calls skipped because the quota was under the reserve threshold or a backoff was active.
285static METRIC_PROACTIVE_THROTTLES: AtomicU64 = AtomicU64::new(0);
286/// Total 5xx server error responses received (REST + GraphQL).
287static METRIC_5XX_HITS: AtomicU64 = AtomicU64::new(0);
288
289// ── Rate-limit generic helpers ────────────────────────────────────────
290
291/**
292 * Fail fast when the limiter is in hard backoff (post-403/429) or the remaining quota is
293 * under the reserve threshold. This must never sleep: the engine runs every tick phase
294 * through these calls, so waiting out a reset here froze the whole tick loop for up to an
295 * hour and tripped the watchdog. Returning an error lets the phase give up and the tick
296 * finish, and the next tick retries once the window resets
297 **/
298fn check_rate_limit_backoff(cell: &Mutex<RateLimit>, api: &str) -> anyhow::Result<()> {
299    let Some(remaining) = cell.lock().ok().and_then(|rl| rl.is_active()) else {
300        return Ok(());
301    };
302    METRIC_PROACTIVE_THROTTLES.fetch_add(1, Ordering::Relaxed);
303    anyhow::bail!(
304        "GitHub {} API rate-limited, skipping call for {}s",
305        api,
306        remaining.as_secs()
307    );
308}
309
310/// API calls since the last drain, keyed by (project, call type), for the per-tick debug report.
311static CALL_COUNTS: LazyLock<Mutex<HashMap<(String, String), u64>>> =
312    LazyLock::new(|| Mutex::new(HashMap::new()));
313
314/// Project is `owner/repo` from a `/repos/` URL and call type is the path segment after it
315/// (`pulls`, `issues`, `check-runs`), so non-repo endpoints land under `-`.
316fn count_api_call(url: &str) {
317    let path = url.split('?').next().unwrap_or(url);
318    let key = match path.split_once("/repos/") {
319        Some((_, rest)) => {
320            let mut parts = rest.split('/');
321            let project = format!(
322                "{}/{}",
323                parts.next().unwrap_or(""),
324                parts.next().unwrap_or("")
325            );
326            (project, parts.next().unwrap_or("repo").to_string())
327        }
328        None if path.ends_with("/graphql") => ("-".to_string(), "graphql".to_string()),
329        None => ("-".to_string(), "other".to_string()),
330    };
331    if let Ok(mut counts) = CALL_COUNTS.lock() {
332        *counts.entry(key).or_insert(0) += 1;
333    }
334}
335
336/// Take the call counts accumulated since the last drain, largest first.
337pub fn drain_call_counts() -> Vec<(String, String, u64)> {
338    let mut rows: Vec<_> = CALL_COUNTS
339        .lock()
340        .map(|mut c| c.drain().map(|((p, k), n)| (p, k, n)).collect())
341        .unwrap_or_default();
342    rows.sort_by_key(|r| Reverse(r.2));
343    rows
344}
345
346// ── Conditional-request cache ─────────────────────────────────────────
347
348/// A stored 200 response, replayed when GitHub answers the next conditional GET with 304.
349struct CachedPage {
350    etag: String,
351    body: String,
352    /// `Link: rel="next"` from the cached response; a 304 does not repeat it.
353    next: Option<String>,
354}
355
356/**
357 * Keyed by the full request URL plus the decoded type, since the body is replayed through
358 * `serde_json` and two call sites can share a URL while wanting different shapes. GitHub
359 * answers a conditional GET with 304 and no body when nothing changed, and that response
360 * does not count against the core quota, so the listing endpoints orch polls every tick
361 * cost one request per hour of quiet instead of one per tick
362 **/
363static PAGE_CACHE: LazyLock<Mutex<HashMap<String, CachedPage>>> =
364    LazyLock::new(|| Mutex::new(HashMap::new()));
365
366/// Distinct cacheable list URLs are few (per repo, per query), so the cap only guards a
367/// leak. Each entry holds a full page body, so keep it small.
368const PAGE_CACHE_MAX: usize = 64;
369
370/// `None` when the request cannot produce a hit, so it is neither sent conditionally nor
371/// stored. A `since` filter is computed from the clock on every call, so its key never
372/// recurs and caching it would only grow the map with page-sized bodies.
373fn page_cache_key<T>(url: &str, query: Option<&[(&str, &str)]>) -> Option<String> {
374    let mut key = String::from(any::type_name::<T>());
375    key.push(' ');
376    key.push_str(url);
377    if let Some(q) = query {
378        for (i, (k, v)) in q.iter().enumerate() {
379            key.push(if i == 0 { '?' } else { '&' });
380            key.push_str(k);
381            key.push('=');
382            key.push_str(v);
383        }
384    }
385    if key.contains("since=") {
386        return None;
387    }
388    Some(key)
389}
390
391fn page_cache_etag(key: &str) -> Option<String> {
392    PAGE_CACHE.lock().ok()?.get(key).map(|c| c.etag.clone())
393}
394
395/// Returns the stored body and `next` link for a 304 reply.
396fn page_cache_hit(key: &str) -> Option<(String, Option<String>)> {
397    let cache = PAGE_CACHE.lock().ok()?;
398    let entry = cache.get(key)?;
399    Some((entry.body.clone(), entry.next.clone()))
400}
401
402fn page_cache_store(key: String, etag: String, body: String, next: Option<String>) {
403    let Ok(mut cache) = PAGE_CACHE.lock() else {
404        return;
405    };
406    // ponytail: clears everything at the cap instead of evicting one entry, switch to an
407    // LRU if the hit rate ever matters more than the bookkeeping
408    if cache.len() >= PAGE_CACHE_MAX && !cache.contains_key(&key) {
409        cache.clear();
410    }
411    cache.insert(key, CachedPage { etag, body, next });
412}
413
414/// Check response body for rate-limit signals on 403 responses.
415/// Not all 403s are rate limits — some are permission errors.
416fn maybe_record_body_rate_limit(cell: &Mutex<RateLimit>, status: StatusCode, body: &str) {
417    if status == StatusCode::FORBIDDEN {
418        let lower = body.to_lowercase();
419        if (lower.contains("rate limit")
420            || lower.contains("abuse detection")
421            || lower.contains("secondary rate"))
422            && let Ok(mut rl) = cell.lock()
423        {
424            rl.record_rate_limit();
425        }
426    }
427}
428
429/// Update rate-limit state from response headers/status and detect 5xx errors.
430fn record_response_for_limiter(cell: &Mutex<RateLimit>, resp: &Response) {
431    if let Ok(mut rl) = cell.lock() {
432        rl.update_from_headers(resp.headers());
433        // Only backoff on 429 (always rate limit) — 403 requires body inspection
434        // which is handled in maybe_record_body_rate_limit().
435        if resp.status() == StatusCode::TOO_MANY_REQUESTS {
436            rl.record_rate_limit();
437        } else if resp.status().is_success() || resp.status() == StatusCode::NOT_MODIFIED {
438            rl.record_success();
439        }
440    }
441    // Detect 5xx server errors for the global circuit breaker.
442    let status = resp.status();
443    if status.is_server_error() {
444        METRIC_5XX_HITS.fetch_add(1, Ordering::Relaxed);
445        if Handle::try_current().is_ok() {
446            tokio::spawn(async move {
447                cooldown::record_github_5xx().await;
448            });
449        }
450    }
451}
452
453// ── Shared token resolver ────────────────────────────────────────────
454
455// ── GhHttp client ────────────────────────────────────────────────────
456
457/// Native HTTP client for the GitHub API with connection pooling and
458/// proactive rate-limit avoidance.
459#[derive(Clone)]
460pub struct GhHttp {
461    client: Client,
462    token_resolver: Arc<token::TokenResolver>,
463    // An App only tests set, production calls always use the gh token
464    app: Option<Arc<super::app::AppAuth>>,
465    // Calls the App cannot make, such as `GET /user` and Projects V2 on a personal account
466    owner_only: bool,
467    cached_username: OnceLock<String>,
468    #[cfg(test)]
469    api_base: Option<String>,
470}
471
472impl Debug for GhHttp {
473    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
474        f.debug_struct("GhHttp")
475            .field("owner_only", &self.owner_only)
476            .finish_non_exhaustive()
477    }
478}
479
480/// The error with its full source chain plus the timeout and connect flags, because the
481/// top-level reqwest message alone hides why the request failed
482fn transport_error_detail(e: &reqwest::Error) -> String {
483    let mut out = e.to_string();
484    let mut source = e.source();
485    while let Some(s) = source {
486        let _ = write!(out, ": {s}");
487        source = s.source();
488    }
489    let _ = write!(
490        out,
491        " (is_timeout={}, is_connect={})",
492        e.is_timeout(),
493        e.is_connect()
494    );
495    out
496}
497
498impl GhHttp {
499    /// Create a new client backed by the process-wide shared [`TokenResolver`].
500    ///
501    /// Token is resolved lazily on first request:
502    ///   GH_TOKEN → GITHUB_TOKEN → gh.auth.token config → gh auth token CLI
503    /// The result is cached in the shared resolver for the life of the process,
504    /// so `gh auth token` is only called once regardless of how many instances
505    /// are created.
506    pub fn new() -> anyhow::Result<Self> {
507        let client = Client::builder()
508            .user_agent("orch/0.1 (reqwest)")
509            .pool_max_idle_per_host(4)
510            .timeout(Duration::from_secs(30))
511            .connect_timeout(Duration::from_secs(10))
512            .tcp_keepalive(Duration::from_secs(30))
513            .pool_idle_timeout(Duration::from_secs(60))
514            .build()
515            .map_err(|e| anyhow::anyhow!("failed to build HTTP client (TLS init): {e}"))?;
516
517        Ok(Self {
518            client,
519            token_resolver: token::shared(),
520            app: None,
521            owner_only: false,
522            cached_username: OnceLock::new(),
523            #[cfg(test)]
524            api_base: None,
525        })
526    }
527
528    /// A client that always uses the owner token, for calls the App cannot make, such as
529    /// `GET /user` and Projects V2 on a personal account
530    pub fn owner() -> anyhow::Result<Self> {
531        let mut gh = Self::new()?;
532        gh.owner_only = true;
533        Ok(gh)
534    }
535
536    #[cfg(test)]
537    pub(crate) fn for_test(api_base: String, app: Option<Arc<super::app::AppAuth>>) -> Self {
538        Self {
539            client: Client::new(),
540            token_resolver: Arc::new(token::TokenResolver::default_env()),
541            app,
542            owner_only: false,
543            cached_username: OnceLock::new(),
544            api_base: Some(api_base),
545        }
546    }
547
548    #[cfg_attr(
549        not(test),
550        expect(
551            clippy::unused_self,
552            reason = "only the test build reads the api base override"
553        )
554    )]
555    fn api_root(&self) -> &str {
556        #[cfg(test)]
557        if let Some(base) = &self.api_base {
558            return base;
559        }
560        GITHUB_API
561    }
562
563    // ── Rate-limit helpers ────────────────────────────────────────
564
565    /// Check if the REST GitHub API is currently rate-limited (backoff or approaching limit).
566    /// Used by the engine to decide whether to skip a tick.
567    pub fn is_rate_limited() -> Option<Duration> {
568        REST_RATE_LIMIT.lock().ok().and_then(|rl| rl.is_active())
569    }
570
571    /// Fail fast if the REST API is in hard backoff (post-403/429).
572    fn check_backoff(url: &str) -> anyhow::Result<()> {
573        count_api_call(url);
574        check_rate_limit_backoff(&REST_RATE_LIMIT, "REST")
575    }
576
577    /// Fail fast if the GraphQL API is in hard backoff (post-403/429).
578    fn check_graphql_backoff(url: &str) -> anyhow::Result<()> {
579        count_api_call(url);
580        check_rate_limit_backoff(&GRAPHQL_RATE_LIMIT, "GraphQL")
581    }
582
583    fn record_response(resp: &Response) {
584        record_response_for_limiter(&REST_RATE_LIMIT, resp);
585    }
586
587    fn record_graphql_response(resp: &Response) {
588        record_response_for_limiter(&GRAPHQL_RATE_LIMIT, resp);
589    }
590
591    /// Check response body for rate-limit signals on 403 responses (REST).
592    fn maybe_record_rate_limit_from_body(status: StatusCode, body: &str) {
593        maybe_record_body_rate_limit(&REST_RATE_LIMIT, status, body);
594    }
595
596    /// Check response body for rate-limit signals on 403 responses (GraphQL).
597    fn maybe_record_graphql_rate_limit_from_body(status: StatusCode, body: &str) {
598        maybe_record_body_rate_limit(&GRAPHQL_RATE_LIMIT, status, body);
599    }
600
601    fn record_success() {
602        if let Ok(mut rl) = REST_RATE_LIMIT.lock() {
603            rl.record_success();
604        }
605    }
606
607    // ── Low-level HTTP helpers ────────────────────────────────────
608
609    fn app(&self) -> Option<Arc<super::app::AppAuth>> {
610        if self.owner_only {
611            return None;
612        }
613
614        // orch's own calls use the gh token, the App only reviews (src/engine/review.rs). The App
615        // must not open PRs, GitHub refuses a review from a PR's author
616        self.app.clone()
617    }
618
619    /// The App's token for a repository it is installed on, the owner token for anything else,
620    /// including GraphQL, whose URL names no repository
621    async fn auth_header(&self, url: &str) -> anyhow::Result<String> {
622        if let (Some(app), Some(repo)) = (self.app(), repo_from_url(url)) {
623            match app.token_for_repo(&repo).await {
624                Ok(Some(token)) => return Ok(format!("Bearer {token}")),
625                Ok(None) => {}
626                Err(e) => {
627                    tracing::warn!(error = %e, repo, "GitHub App token unavailable, using the owner token");
628                }
629            }
630        }
631        match self.token_resolver.get_token().await? {
632            Some(token) if !token.is_empty() => Ok(format!("Bearer {token}")),
633            _ => anyhow::bail!("No GitHub token available — run `gh auth login` or set GH_TOKEN"),
634        }
635    }
636
637    /// Generic send wrapper that retries on 5xx server errors with exponential
638    /// backoff and sets a short-lived circuit-breaker in KV when retries fail.
639    async fn send_with_retries<F>(
640        &self,
641        mut make_req: F,
642        is_graphql: bool,
643    ) -> anyhow::Result<Response>
644    where
645        F: FnMut() -> anyhow::Result<reqwest::RequestBuilder>,
646    {
647        // Circuit-breaker: if set, fail fast to avoid wasting work.
648        if engine_cooldown::is_agent_in_cooldown("github:5xx") {
649            if let Some(until) = engine_cooldown::cooldown_until("github:5xx") {
650                let now = chrono::Utc::now().timestamp();
651                let remaining = if until > now { until - now } else { 0 };
652                anyhow::bail!("GitHub API transient 5xx circuit-breaker active for {remaining}s");
653            }
654            anyhow::bail!("GitHub API transient 5xx circuit-breaker active");
655        }
656
657        // Configurable retry params (defaults chosen conservatively)
658        let attempts = config::get("gh.5xx.retry_attempts")
659            .ok()
660            .and_then(|v| v.parse::<u32>().ok())
661            .unwrap_or(3);
662        let base_secs = config::get("gh.5xx.base_backoff_seconds")
663            .ok()
664            .and_then(|v| v.parse::<u64>().ok())
665            .unwrap_or(1);
666        let max_secs = config::get("gh.5xx.max_backoff_seconds")
667            .ok()
668            .and_then(|v| v.parse::<u64>().ok())
669            .unwrap_or(30);
670        let circuit_cooldown_secs = config::get("gh.5xx.circuit_breaker_cooldown_seconds")
671            .ok()
672            .and_then(|v| v.parse::<u64>().ok())
673            .unwrap_or(300);
674
675        let mut last_err: Option<anyhow::Error> = None;
676        // A cached token can go bad mid-process (revoked, rotated, stale keychain read).
677        // On the first 401 Bad credentials: evict the cache, re-resolve once, resend
678        let mut auth_override: Option<String> = None;
679        let mut auth_retried = false;
680        for attempt in 0..attempts {
681            let mut req = make_req()?;
682            if let Some(auth) = &auth_override {
683                req = req.header(header::AUTHORIZATION, auth.clone());
684            }
685            let resp_result = req.send().await;
686
687            match resp_result {
688                Ok(resp) => {
689                    // Record rate-limit state depending on REST vs GraphQL
690                    if is_graphql {
691                        Self::record_graphql_response(&resp);
692                    } else {
693                        Self::record_response(&resp);
694                    }
695
696                    if resp.status() == StatusCode::UNAUTHORIZED {
697                        let resp_url = resp.url().to_string();
698                        let status = resp.status();
699                        let body = resp.text().await.unwrap_or_default();
700                        if body.contains("Bad credentials") && !auth_retried {
701                            tracing::warn!(
702                                "GitHub API 401 Bad credentials — clearing cached token and re-resolving"
703                            );
704                            self.token_resolver.clear_cache().await;
705                            if let Some(app) = self.app() {
706                                app.invalidate();
707                            }
708                            match self.auth_header(&resp_url).await {
709                                Ok(new_auth) => {
710                                    auth_retried = true;
711                                    auth_override = Some(new_auth);
712                                }
713                                Err(e) => {
714                                    last_err = Some(
715                                        e.context("GitHub token re-resolution failed after 401"),
716                                    );
717                                    break;
718                                }
719                            }
720                            // ponytail: consumes one 5xx-retry slot, attempts default is 3
721                            continue;
722                        }
723                        if auth_retried {
724                            // Fresh token also rejected; leave the cache empty so the next
725                            // call re-resolves and picks up env/config fixes immediately
726                            self.token_resolver.clear_cache().await;
727                            anyhow::bail!(
728                                "GitHub authentication failed ({status}): token re-resolved after cache clear but still rejected"
729                            );
730                        }
731                        anyhow::bail!("GitHub API request failed ({status}): {body}");
732                    }
733
734                    // If server error, treat as transient and retry
735                    if resp.status().is_server_error() {
736                        let status = resp.status();
737                        let headers = resp.headers().clone();
738                        let body = resp.text().await.unwrap_or_default();
739                        let req_id = headers
740                            .get("x-github-request-id")
741                            .and_then(|v| v.to_str().ok())
742                            .unwrap_or("<none>");
743                        let snippet: String = body.chars().take(400).collect();
744                        tracing::warn!(
745                            status = %status,
746                            request_id = %req_id,
747                            attempt,
748                            "GitHub server error (5xx) — attempt {attempt}: {snippet}"
749                        );
750
751                        last_err = Some(anyhow::anyhow!(
752                            "GitHub API server error ({status}) request_id={req_id}: {snippet}"
753                        ));
754
755                        if attempt + 1 < attempts {
756                            // Exponential backoff (2^attempt * base), capped
757                            // Cap exponent at 63 (max valid shift for u64) to prevent overflow
758                            let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
759                            let mut backoff = base_secs.saturating_mul(exp);
760                            if backoff > max_secs {
761                                backoff = max_secs;
762                            }
763                            // Add small linear jitter to avoid synchronized retries
764                            let jitter_ms = u64::from(attempt) * 100;
765                            let sleep_dur = Duration::from_secs(backoff)
766                                + Duration::from_millis(jitter_ms.min(1000));
767                            time::sleep(sleep_dur).await;
768                            continue;
769                        }
770                        // Exhausted attempts — set circuit-breaker and break so last_err is read
771                        tracing::warn!(
772                            "GitHub API 5xx persisted after {} attempts — setting circuit-breaker for {}s",
773                            attempts,
774                            circuit_cooldown_secs
775                        );
776                        engine_cooldown::set_agent_cooldown("github:5xx", circuit_cooldown_secs)
777                            .await;
778                        break;
779                    }
780
781                    // Non-5xx response — return it for caller to handle success/failure
782                    return Ok(resp);
783                }
784                Err(e) => {
785                    // Transport error — the request never reached GitHub (DNS failure,
786                    // connection refused, no route to host, TLS failure, etc). This is a
787                    // local/network condition, not evidence that GitHub itself is unhealthy,
788                    // so unlike the 5xx arm above it must NOT trip the shared "github:5xx"
789                    // circuit breaker: other subsystems (routing-phase skip, cooldown
790                    // throttling) key off that breaker as a signal about GitHub's health.
791                    let detail = transport_error_detail(&e);
792                    tracing::warn!(err = %detail, attempt, "HTTP request failed to send (transport error, GitHub not reached), will retry if attempts remain");
793                    last_err = Some(anyhow::anyhow!(
794                        "HTTP request failed to send (transport error): {detail}"
795                    ));
796                    if attempt + 1 < attempts {
797                        // Cap exponent at 63 (max valid shift for u64) to prevent overflow
798                        let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
799                        let backoff = base_secs.saturating_mul(exp);
800                        let sleep_dur = Duration::from_secs(backoff)
801                            + Duration::from_millis((u64::from(attempt) * 100).min(1000));
802                        time::sleep(sleep_dur).await;
803                        continue;
804                    }
805                    // Exhausted attempts — break so last_err is read. Deliberately does not
806                    // call set_agent_cooldown("github:5xx", ...): GitHub was never reached,
807                    // so its health is unknown and the shared breaker must stay untouched.
808                    tracing::warn!(
809                        "HTTP request failed to send after {} attempts (transport error, GitHub not reached) — not tripping the github:5xx circuit-breaker",
810                        attempts
811                    );
812                    break;
813                }
814            }
815        }
816
817        Err(last_err.unwrap_or_else(|| anyhow::anyhow!("unexpected send_with_retries failure")))
818    }
819
820    /// GET request, returns deserialized JSON.
821    async fn get_json<T: DeserializeOwned>(&self, url: &str) -> anyhow::Result<T> {
822        Self::check_backoff(url)?;
823        let auth = self.auth_header(url).await?;
824        // Use send_with_retries to handle transient 5xx/network failures
825        let make_req = || {
826            Ok(self
827                .client
828                .get(url)
829                .header(header::AUTHORIZATION, auth.clone())
830                .header(header::ACCEPT, "application/vnd.github+json")
831                .header("X-GitHub-Api-Version", "2022-11-28"))
832        };
833        let resp = self.send_with_retries(make_req, false).await?;
834        let status = resp.status();
835        if !status.is_success() {
836            let body = resp.text().await.unwrap_or_default();
837            Self::maybe_record_rate_limit_from_body(status, &body);
838            anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
839        }
840        let body = resp.text().await?;
841        serde_json::from_str(&body)
842            .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
843    }
844
845    /// GET raw bytes (for endpoints that return non-JSON or we parse manually).
846    async fn get_bytes(&self, url: &str) -> anyhow::Result<Vec<u8>> {
847        Self::check_backoff(url)?;
848        let auth = self.auth_header(url).await?;
849        let make_req = || {
850            Ok(self
851                .client
852                .get(url)
853                .header(header::AUTHORIZATION, auth.clone())
854                .header(header::ACCEPT, "application/vnd.github+json")
855                .header("X-GitHub-Api-Version", "2022-11-28"))
856        };
857        let resp = self.send_with_retries(make_req, false).await?;
858        let status = resp.status();
859        if !status.is_success() {
860            let body = resp.text().await.unwrap_or_default();
861            Self::maybe_record_rate_limit_from_body(status, &body);
862            anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
863        }
864        Ok(resp.bytes().await?.to_vec())
865    }
866
867    /// GET with query params, returns deserialized JSON.
868    async fn get_with_query<T: DeserializeOwned>(
869        &self,
870        url: &str,
871        query: &[(&str, &str)],
872    ) -> anyhow::Result<T> {
873        Self::check_backoff(url)?;
874        let auth = self.auth_header(url).await?;
875        let make_req = || {
876            Ok(self
877                .client
878                .get(url)
879                .query(query)
880                .header(header::AUTHORIZATION, auth.clone())
881                .header(header::ACCEPT, "application/vnd.github+json")
882                .header("X-GitHub-Api-Version", "2022-11-28"))
883        };
884        let resp = self.send_with_retries(make_req, false).await?;
885        let status = resp.status();
886        if !status.is_success() {
887            let body = resp.text().await.unwrap_or_default();
888            Self::maybe_record_rate_limit_from_body(status, &body);
889            anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
890        }
891        let body = resp.text().await?;
892        serde_json::from_str(&body)
893            .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
894    }
895
896    /// POST with JSON body, returns raw response text.
897    async fn post_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
898        Self::check_backoff(url)?;
899        let auth = self.auth_header(url).await?;
900        let make_req = || {
901            Ok(self
902                .client
903                .post(url)
904                .json(body)
905                .header(header::AUTHORIZATION, auth.clone())
906                .header(header::ACCEPT, "application/vnd.github+json")
907                .header("X-GitHub-Api-Version", "2022-11-28"))
908        };
909        let resp = self.send_with_retries(make_req, false).await?;
910        let status = resp.status();
911        let text_res = resp.text().await;
912        if !status.is_success() {
913            let text = text_res.unwrap_or_default();
914            Self::maybe_record_rate_limit_from_body(status, &text);
915            anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
916        }
917        let text = text_res?;
918        Ok(text)
919    }
920
921    /// POST with JSON body, returns deserialized JSON.
922    async fn post_json<T: DeserializeOwned>(
923        &self,
924        url: &str,
925        body: &serde_json::Value,
926    ) -> anyhow::Result<T> {
927        let text = self.post_json_raw(url, body).await?;
928        Ok(serde_json::from_str(&text)?)
929    }
930
931    /// PATCH with JSON body, returns raw response.
932    async fn patch_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
933        Self::check_backoff(url)?;
934        let auth = self.auth_header(url).await?;
935        let make_req = || {
936            Ok(self
937                .client
938                .patch(url)
939                .json(body)
940                .header(header::AUTHORIZATION, auth.clone())
941                .header(header::ACCEPT, "application/vnd.github+json")
942                .header("X-GitHub-Api-Version", "2022-11-28"))
943        };
944        let resp = self.send_with_retries(make_req, false).await?;
945        let status = resp.status();
946        let text_res = resp.text().await;
947        if !status.is_success() {
948            let text = text_res.unwrap_or_default();
949            Self::maybe_record_rate_limit_from_body(status, &text);
950            anyhow::bail!("GitHub API PATCH {url} failed ({status}): {text}");
951        }
952        let text = text_res?;
953        Ok(text)
954    }
955
956    /// Create or replace one file on a branch with a commit, the way the GitHub web editor does
957    pub async fn put_file(
958        &self,
959        repo: &str,
960        path: &str,
961        branch: &str,
962        message: &str,
963        content: &str,
964    ) -> anyhow::Result<()> {
965        let encoded_path = path
966            .split('/')
967            .map(|segment| urlencoding::encode(segment).into_owned())
968            .collect::<Vec<_>>()
969            .join("/");
970        let url = format!("{}/repos/{repo}/contents/{encoded_path}", self.api_root());
971        // Replacing a file needs the blob it replaces, a new file has none
972        let current = self
973            .get_json::<serde_json::Value>(&format!("{url}?ref={}", urlencoding::encode(branch)))
974            .await
975            .ok()
976            .and_then(|v| v.get("sha").and_then(|s| s.as_str()).map(str::to_string));
977        let mut body = serde_json::json!({
978            "message": message,
979            "content": BASE64.encode(content),
980            "branch": branch,
981        });
982        if let Some(sha) = current {
983            body["sha"] = serde_json::Value::String(sha);
984        }
985        self.put_json_raw(&url, &body).await.map(|_| ())
986    }
987
988    /// PUT with JSON body, returns raw response.
989    async fn put_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
990        Self::check_backoff(url)?;
991        let auth = self.auth_header(url).await?;
992        let make_req = || {
993            Ok(self
994                .client
995                .put(url)
996                .json(body)
997                .header(header::AUTHORIZATION, auth.clone())
998                .header(header::ACCEPT, "application/vnd.github+json")
999                .header("X-GitHub-Api-Version", "2022-11-28"))
1000        };
1001        let resp = self.send_with_retries(make_req, false).await?;
1002        let status = resp.status();
1003        let text_res = resp.text().await;
1004        if !status.is_success() {
1005            let text = text_res.unwrap_or_default();
1006            Self::maybe_record_rate_limit_from_body(status, &text);
1007            anyhow::bail!("GitHub API PUT {url} failed ({status}): {text}");
1008        }
1009        let text = text_res?;
1010        Ok(text)
1011    }
1012
1013    /// DELETE request.
1014    async fn delete(&self, url: &str) -> anyhow::Result<StatusCode> {
1015        Self::check_backoff(url)?;
1016        let auth = self.auth_header(url).await?;
1017        let make_req = || {
1018            Ok(self
1019                .client
1020                .delete(url)
1021                .header(header::AUTHORIZATION, auth.clone())
1022                .header(header::ACCEPT, "application/vnd.github+json")
1023                .header("X-GitHub-Api-Version", "2022-11-28"))
1024        };
1025        let resp = self.send_with_retries(make_req, false).await?;
1026        let status = resp.status();
1027        if !status.is_success() && status != StatusCode::NOT_FOUND {
1028            let body = resp.text().await.unwrap_or_default();
1029            Self::maybe_record_rate_limit_from_body(status, &body);
1030            anyhow::bail!("GitHub API DELETE {url} failed ({status}): {body}");
1031        }
1032        Ok(status)
1033    }
1034
1035    /// Paginated GET — follows Link: <next> headers, with conditional requests.
1036    ///
1037    /// Each page is sent with `If-None-Match` when a prior ETag is known; GitHub's 304
1038    /// reply is free of quota and the stored body is replayed.
1039    async fn get_all_pages<T: DeserializeOwned>(
1040        &self,
1041        url: &str,
1042        query: &[(&str, &str)],
1043    ) -> anyhow::Result<Vec<T>> {
1044        const MAX_JSON_DECODE_RETRIES: u32 = 2;
1045        const JSON_DECODE_RETRY_BACKOFF_MS: u64 = 200;
1046        Self::check_backoff(url)?;
1047        let mut all: Vec<T> = Vec::new();
1048        let mut next_url: Option<String> = None;
1049        let mut is_first = true;
1050
1051        loop {
1052            let (request_url, request_query) = if is_first {
1053                is_first = false;
1054                (url, Some(query))
1055            } else {
1056                let Some(u) = next_url.as_ref() else { break };
1057                (u.as_str(), None)
1058            };
1059
1060            let cache_key = page_cache_key::<T>(request_url, request_query);
1061            let mut cached_etag = cache_key.as_deref().and_then(page_cache_etag);
1062            let mut decode_attempt = 0;
1063            let (page, next) = loop {
1064                let auth = self.auth_header(request_url).await?;
1065                let mut req = self
1066                    .client
1067                    .get(request_url)
1068                    .header(header::AUTHORIZATION, auth)
1069                    .header(header::ACCEPT, "application/vnd.github+json")
1070                    .header("X-GitHub-Api-Version", "2022-11-28");
1071                if let Some(q) = request_query {
1072                    req = req.query(q);
1073                }
1074                if let Some(etag) = &cached_etag {
1075                    req = req.header(header::IF_NONE_MATCH, etag.clone());
1076                }
1077
1078                let make_req = || {
1079                    req.try_clone()
1080                        .ok_or_else(|| anyhow::anyhow!("request clone failed"))
1081                };
1082                let resp = self.send_with_retries(make_req, false).await?;
1083                let status = resp.status();
1084                let next_from_headers = parse_link_next(resp.headers());
1085                let etag = resp
1086                    .headers()
1087                    .get(header::ETAG)
1088                    .and_then(|v| v.to_str().ok())
1089                    .map(ToString::to_string);
1090                let content_type = resp
1091                    .headers()
1092                    .get(header::CONTENT_TYPE)
1093                    .and_then(|v| v.to_str().ok())
1094                    .map_or_else(|| "<missing>".to_string(), ToString::to_string);
1095
1096                if status == StatusCode::NOT_MODIFIED {
1097                    if let Some((body, next)) = cache_key.as_deref().and_then(page_cache_hit) {
1098                        break (serde_json::from_str::<Vec<T>>(&body)?, next);
1099                    }
1100                    // The entry is normally there, since If-None-Match is only sent
1101                    // when it is, but the size cap can clear the map in between.
1102                    // Dropping the ETag makes the retry unconditional, so the loop
1103                    // cannot see a second 304
1104                    cached_etag = None;
1105                    continue;
1106                }
1107
1108                if !status.is_success() {
1109                    let body = resp.text().await.unwrap_or_default();
1110                    Self::maybe_record_rate_limit_from_body(status, &body);
1111                    anyhow::bail!("GitHub API GET (paginated) failed ({status}): {body}");
1112                }
1113
1114                let text = resp.text().await?;
1115                match serde_json::from_str::<Vec<T>>(&text) {
1116                    Ok(page) => {
1117                        if let (Some(key), Some(etag)) = (cache_key.clone(), etag) {
1118                            page_cache_store(key, etag, text, next_from_headers.clone());
1119                        }
1120                        break (page, next_from_headers);
1121                    }
1122                    Err(err) => {
1123                        let snippet: String = text.chars().take(200).collect();
1124                        let decode_error = anyhow::anyhow!(
1125                            "GitHub API GET (paginated) JSON decode failed ({status}, content-type={content_type}): {snippet}"
1126                        )
1127                        .context(err);
1128                        if decode_attempt < MAX_JSON_DECODE_RETRIES {
1129                            decode_attempt += 1;
1130                            tracing::warn!(
1131                                attempt = decode_attempt,
1132                                max_attempts = MAX_JSON_DECODE_RETRIES,
1133                                status = %status,
1134                                content_type,
1135                                err = %decode_error,
1136                                "json decode failed; retrying paginated GET"
1137                            );
1138                            time::sleep(Duration::from_millis(
1139                                JSON_DECODE_RETRY_BACKOFF_MS * u64::from(decode_attempt),
1140                            ))
1141                            .await;
1142                            continue;
1143                        }
1144                        return Err(decode_error);
1145                    }
1146                }
1147            };
1148
1149            next_url = next;
1150            all.extend(page);
1151
1152            if next_url.is_none() {
1153                break;
1154            }
1155        }
1156
1157        Ok(all)
1158    }
1159
1160    /// Paginated GET for GitHub endpoints that return a wrapper object instead of a raw
1161    /// array.  Each page is expected to look like `{ "<array_field>": [...], ... }`.
1162    /// The function extracts `array_field` from every page and appends the elements
1163    /// to the accumulated result, following `Link: <next>` headers until exhausted.
1164    ///
1165    /// This is necessary for endpoints such as `/commits/{sha}/check-runs` which
1166    /// return `{ "total_count": N, "check_runs": [...] }` rather than a bare `[...]`
1167    /// array.  Using `get_all_pages` on those endpoints would fail at the
1168    /// `serde_json::from_str::<Vec<T>>` step because the body is an object, not an
1169    /// array.
1170    async fn get_all_pages_from_wrapper<T: DeserializeOwned>(
1171        &self,
1172        url: &str,
1173        array_field: &str,
1174    ) -> anyhow::Result<Vec<T>> {
1175        Self::check_backoff(url)?;
1176        let mut all: Vec<T> = Vec::new();
1177        let mut current_url: String = url.to_string();
1178
1179        loop {
1180            let auth = self.auth_header(&current_url).await?;
1181            let make_req = || {
1182                self.client
1183                    .get(&current_url)
1184                    .header(header::AUTHORIZATION, auth.clone())
1185                    .header(header::ACCEPT, "application/vnd.github+json")
1186                    .header("X-GitHub-Api-Version", "2022-11-28")
1187                    .try_clone()
1188                    .ok_or_else(|| anyhow::anyhow!("request clone failed"))
1189            };
1190            let resp = self.send_with_retries(make_req, false).await?;
1191            let status = resp.status();
1192            let next = parse_link_next(resp.headers());
1193
1194            if !status.is_success() {
1195                let body = resp.text().await.unwrap_or_default();
1196                Self::maybe_record_rate_limit_from_body(status, &body);
1197                anyhow::bail!(
1198                    "GitHub API GET (wrapped paginated) {current_url} failed ({status}): {body}"
1199                );
1200            }
1201
1202            let body = resp.text().await?;
1203            let wrapper: serde_json::Value = serde_json::from_str(&body).with_context(|| {
1204                format!("failed to parse wrapper response from {current_url}: {body}")
1205            })?;
1206            let items = wrapper
1207                .get(array_field)
1208                .and_then(|v| v.as_array())
1209                .cloned()
1210                .unwrap_or_default();
1211
1212            for item in items {
1213                match serde_json::from_value::<T>(item) {
1214                    Ok(v) => all.push(v),
1215                    Err(e) => {
1216                        tracing::warn!(
1217                            field = array_field,
1218                            err = %e,
1219                            "skipping item that failed to deserialize in wrapped pagination"
1220                        );
1221                    }
1222                }
1223            }
1224
1225            match next {
1226                Some(next_url) => current_url = next_url,
1227                None => break,
1228            }
1229        }
1230
1231        Ok(all)
1232    }
1233
1234    /// POST to the GraphQL endpoint. Uses separate rate-limit tracking from REST.
1235    async fn graphql_request(
1236        &self,
1237        query: &str,
1238        extra_headers: &[(&str, &str)],
1239        variables: Option<serde_json::Value>,
1240    ) -> anyhow::Result<serde_json::Value> {
1241        self.graphql_request_to_url(
1242            &format!("{GITHUB_API}/graphql"),
1243            query,
1244            extra_headers,
1245            variables,
1246        )
1247        .await
1248    }
1249
1250    async fn graphql_request_to_url(
1251        &self,
1252        url: &str,
1253        query: &str,
1254        extra_headers: &[(&str, &str)],
1255        variables: Option<serde_json::Value>,
1256    ) -> anyhow::Result<serde_json::Value> {
1257        Self::check_graphql_backoff(url)?;
1258        let body = if let Some(vars) = variables {
1259            serde_json::json!({ "query": query, "variables": vars })
1260        } else {
1261            serde_json::json!({ "query": query })
1262        };
1263        let auth = self.auth_header(url).await?;
1264        let mut req = self
1265            .client
1266            .post(url)
1267            .json(&body)
1268            .header(header::AUTHORIZATION, auth)
1269            .header(header::ACCEPT, "application/vnd.github+json")
1270            .header("X-GitHub-Api-Version", "2022-11-28");
1271
1272        for (k, v) in extra_headers {
1273            req = req.header(*k, *v);
1274        }
1275
1276        // Use send_with_retries wrapper for GraphQL (is_graphql = true)
1277        let make_req = || {
1278            req.try_clone()
1279                .ok_or_else(|| anyhow::anyhow!("graphql request clone failed"))
1280        };
1281        let resp = self.send_with_retries(make_req, true).await?;
1282        let status = resp.status();
1283        let text_res = resp.text().await;
1284        if !status.is_success() {
1285            let text = text_res.unwrap_or_default();
1286            Self::maybe_record_graphql_rate_limit_from_body(status, &text);
1287            anyhow::bail!("GitHub GraphQL failed ({status}): {text}");
1288        }
1289        let text = text_res?;
1290        let json: serde_json::Value = serde_json::from_str(&text)?;
1291        // GraphQL always returns 200 even for errors; check the errors field explicitly.
1292        if let Some(errors) = json.get("errors").and_then(|e| e.as_array())
1293            && !errors.is_empty()
1294        {
1295            let messages: Vec<&str> = errors
1296                .iter()
1297                .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
1298                .collect();
1299            if json.get("data").is_none() || json["data"].is_null() {
1300                // No data at all — surface the errors as a proper error.
1301                anyhow::bail!("GitHub GraphQL errors: {}", messages.join("; "));
1302            }
1303            // Partial data alongside errors — log and continue.
1304            tracing::warn!(errors = ?messages, "GitHub GraphQL returned partial errors");
1305        }
1306        Ok(json)
1307    }
1308
1309    // ── Public API (mirrors GhCli) ───────────────────────────────
1310
1311    pub async fn graphql_with_vars(
1312        &self,
1313        query: &str,
1314        variables: serde_json::Value,
1315    ) -> anyhow::Result<serde_json::Value> {
1316        self.graphql_request(query, &[], Some(variables)).await
1317    }
1318
1319    pub async fn graphql_with_headers(
1320        &self,
1321        query: &str,
1322        headers: &[&str],
1323    ) -> anyhow::Result<serde_json::Value> {
1324        // Convert "Key:Value" strings to (&str, &str) tuples.
1325        let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1326        self.graphql_request(query, &pairs, None).await
1327    }
1328
1329    pub async fn graphql_with_headers_and_vars(
1330        &self,
1331        query: &str,
1332        headers: &[&str],
1333        variables: serde_json::Value,
1334    ) -> anyhow::Result<serde_json::Value> {
1335        let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1336        self.graphql_request(query, &pairs, Some(variables)).await
1337    }
1338
1339    /// Verify authentication by fetching the current user.
1340    ///
1341    /// Returns detailed error messages for common auth failures to help
1342    /// users diagnose configuration issues at startup.
1343    pub async fn auth_status(&self) -> anyhow::Result<()> {
1344        match self
1345            .get_json::<serde_json::Value>(&format!("{GITHUB_API}/user"))
1346            .await
1347        {
1348            Ok(_) => Ok(()),
1349            Err(e) => {
1350                let err_str = e.to_string();
1351
1352                // Provide helpful error messages for common auth failures
1353                if err_str.contains("401") || err_str.contains("Bad credentials") {
1354                    anyhow::bail!(
1355                        "GitHub authentication failed: Invalid or expired token. \
1356                         Check your GH_TOKEN/GITHUB_TOKEN environment variables, \
1357                         or gh.auth configuration in ~/.orch/config.yml. \
1358                         Run `orch auth check` to verify your setup."
1359                    );
1360                }
1361
1362                if err_str.contains("403") && err_str.contains("rate limit") {
1363                    anyhow::bail!(
1364                        "GitHub API rate limited. Wait before retrying, \
1365                         or check your token's rate limit quota."
1366                    );
1367                }
1368
1369                Err(e)
1370            }
1371        }
1372    }
1373
1374    /// Create a GitHub issue.
1375    pub async fn create_issue(
1376        &self,
1377        repo: &str,
1378        title: &str,
1379        body: &str,
1380        labels: &[String],
1381    ) -> anyhow::Result<GitHubIssue> {
1382        let url = format!("{GITHUB_API}/repos/{repo}/issues");
1383        let payload = serde_json::json!({
1384            "title": title,
1385            "body": body,
1386            "labels": labels,
1387        });
1388        self.post_json(&url, &payload).await
1389    }
1390
1391    /// Replace an issue's title, body and labels.
1392    ///
1393    /// Labels replace the full set. Callers pass labels they want to keep
1394    pub async fn update_issue(
1395        &self,
1396        repo: &str,
1397        number: u64,
1398        title: &str,
1399        body: &str,
1400        labels: &[String],
1401    ) -> anyhow::Result<GitHubIssue> {
1402        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
1403        let payload = serde_json::json!({
1404            "title": title,
1405            "body": body,
1406            "labels": labels,
1407        });
1408        let text = self.patch_json_raw(&url, &payload).await?;
1409        serde_json::from_str(&text)
1410            .with_context(|| format!("failed to parse issue update response: {text}"))
1411    }
1412
1413    /// List issues that block `issue_number`.
1414    ///
1415    /// `GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`.
1416    /// GA since 2025-08-21, no preview media type. This call sends
1417    /// `X-GitHub-Api-Version: 2026-03-10` and `Accept: application/vnd.github+json`.
1418    /// 404 and 403 (except rate limit) are `Unavailable`. Transport errors and
1419    /// 5xx are `Failed`, so the caller does not drop stored links
1420    pub async fn list_blocked_by(
1421        &self,
1422        repo: &str,
1423        issue_number: u64,
1424    ) -> anyhow::Result<BlockedByFetch> {
1425        let mut next = Some(format!(
1426            "{GITHUB_API}/repos/{repo}/issues/{issue_number}/dependencies/blocked_by?per_page=100"
1427        ));
1428        let mut found = Vec::new();
1429        while let Some(url) = next.take() {
1430            let resp = match self
1431                .dependency_request(&url, reqwest::Method::GET, None)
1432                .await
1433            {
1434                Ok(resp) => resp,
1435                Err(err) => {
1436                    let message = err.to_string();
1437                    // `send_with_retries` words a send failure with this marker
1438                    if message.contains("(transport error)") {
1439                        return Ok(BlockedByFetch::Unreachable(message));
1440                    }
1441                    return Ok(BlockedByFetch::Failed(message));
1442                }
1443            };
1444            let status = resp.status();
1445            if status == StatusCode::NOT_FOUND || status == StatusCode::FORBIDDEN {
1446                let body = resp.text().await.unwrap_or_default();
1447                if status == StatusCode::FORBIDDEN
1448                    && body.to_ascii_lowercase().contains("rate limit")
1449                {
1450                    Self::maybe_record_rate_limit_from_body(status, &body);
1451                    return Ok(BlockedByFetch::Failed(body));
1452                }
1453                return Ok(BlockedByFetch::Unavailable);
1454            }
1455            if !status.is_success() {
1456                let body = resp.text().await.unwrap_or_default();
1457                Self::maybe_record_rate_limit_from_body(status, &body);
1458                return Ok(BlockedByFetch::Failed(format!("{status}: {body}")));
1459            }
1460            Self::record_success();
1461            let page_next = parse_link_next(resp.headers());
1462            let body = resp.text().await.unwrap_or_default();
1463            let page: Vec<BlockedByPayload> = match serde_json::from_str(&body) {
1464                Ok(page) => page,
1465                Err(err) => {
1466                    return Ok(BlockedByFetch::Failed(format!(
1467                        "blocked_by parse failed: {err}"
1468                    )));
1469                }
1470            };
1471            for item in page {
1472                if item.number <= 0 {
1473                    continue;
1474                }
1475                let item_repo = item
1476                    .repository
1477                    .as_ref()
1478                    .map(|r| r.full_name.clone())
1479                    .filter(|name| !name.is_empty())
1480                    .unwrap_or_else(|| repo.to_string());
1481                found.push(BlockedByIssue {
1482                    github_id: item.id,
1483                    repo: item_repo,
1484                    number: item.number,
1485                    state: item.state,
1486                    state_reason: item.state_reason,
1487                });
1488            }
1489            next = page_next;
1490        }
1491        Ok(BlockedByFetch::Native(found))
1492    }
1493
1494    /// `POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`
1495    /// with `{"issue_id": blocking_issue_id}`. Same API version as `list_blocked_by`.
1496    /// 201 is success. A body that says the link already exists is also success
1497    pub async fn add_blocked_by(
1498        &self,
1499        repo: &str,
1500        issue_number: u64,
1501        blocking_issue_id: i64,
1502    ) -> anyhow::Result<()> {
1503        let url =
1504            format!("{GITHUB_API}/repos/{repo}/issues/{issue_number}/dependencies/blocked_by");
1505        let resp = self
1506            .dependency_request(
1507                &url,
1508                reqwest::Method::POST,
1509                Some(serde_json::json!({ "issue_id": blocking_issue_id })),
1510            )
1511            .await?;
1512        let status = resp.status();
1513        if status.is_success() {
1514            Self::record_success();
1515            return Ok(());
1516        }
1517        let body = resp.text().await.unwrap_or_default();
1518        if body.to_ascii_lowercase().contains("already") {
1519            return Ok(());
1520        }
1521        Self::maybe_record_rate_limit_from_body(status, &body);
1522        anyhow::bail!("add blocked_by failed ({status}): {body}")
1523    }
1524
1525    /// Remove a blocked-by link. `issue_id` in the path is the blocking issue's database id
1526    pub async fn remove_blocked_by(
1527        &self,
1528        repo: &str,
1529        number: u64,
1530        blocking_issue_id: u64,
1531    ) -> anyhow::Result<()> {
1532        let url = format!(
1533            "{GITHUB_API}/repos/{repo}/issues/{number}/dependencies/blocked_by/{blocking_issue_id}"
1534        );
1535        self.delete(&url).await?;
1536        Ok(())
1537    }
1538
1539    /// GET or POST an issue-dependency URL with API version 2026-03-10
1540    async fn dependency_request(
1541        &self,
1542        url: &str,
1543        method: reqwest::Method,
1544        body: Option<serde_json::Value>,
1545    ) -> anyhow::Result<Response> {
1546        Self::check_backoff(url)?;
1547        let auth = self.auth_header(url).await?;
1548        let make_req = || {
1549            let mut req = self
1550                .client
1551                .request(method.clone(), url)
1552                .header(header::AUTHORIZATION, auth.clone())
1553                .header(header::ACCEPT, "application/vnd.github+json")
1554                .header("X-GitHub-Api-Version", "2026-03-10");
1555            if let Some(ref payload) = body {
1556                req = req.json(payload);
1557            }
1558            Ok(req)
1559        };
1560        self.send_with_retries(make_req, false).await
1561    }
1562
1563    /// Get a single issue.
1564    pub async fn get_issue(&self, repo: &str, number: &str) -> anyhow::Result<GitHubIssue> {
1565        self.get_json(&format!("{}/repos/{repo}/issues/{number}", self.api_root()))
1566            .await
1567    }
1568
1569    /// Check whether an issue number refers to a pull request.
1570    pub async fn is_pull_request(&self, repo: &str, number: &str) -> bool {
1571        self.get_issue(repo, number)
1572            .await
1573            .is_ok_and(|i| i.pull_request.is_some())
1574    }
1575
1576    /// List issues filtered by a label (paginated).
1577    pub async fn list_issues(&self, repo: &str, label: &str) -> anyhow::Result<Vec<GitHubIssue>> {
1578        self.list_issues_with_state(repo, label, "open").await
1579    }
1580
1581    /// List issues filtered by a label and issue state (paginated).
1582    ///
1583    /// `state` is passed directly to the GitHub API: `"open"`, `"closed"`, or `"all"`.
1584    pub async fn list_issues_with_state(
1585        &self,
1586        repo: &str,
1587        label: &str,
1588        state: &str,
1589    ) -> anyhow::Result<Vec<GitHubIssue>> {
1590        let url = format!("{GITHUB_API}/repos/{repo}/issues");
1591        // An empty label lists every issue
1592        let mut query = vec![("state", state), ("per_page", "100")];
1593        if !label.is_empty() {
1594            query.push(("labels", label));
1595        }
1596        let all: Vec<GitHubIssue> = self.get_all_pages(&url, &query).await?;
1597        // GitHub /issues API returns PRs too — filter them out
1598        Ok(all
1599            .into_iter()
1600            .filter(|i| i.pull_request.is_none())
1601            .collect())
1602    }
1603
1604    /// List closed issues updated since `since` (ISO 8601), filtered by label.
1605    ///
1606    /// Used for dedup checks — prevents re-creating issues that were recently closed.
1607    pub async fn list_issues_closed_since(
1608        &self,
1609        repo: &str,
1610        label: &str,
1611        since: &str,
1612    ) -> anyhow::Result<Vec<GitHubIssue>> {
1613        let url = format!("{GITHUB_API}/repos/{repo}/issues");
1614        let all: Vec<GitHubIssue> = self
1615            .get_all_pages(
1616                &url,
1617                &[
1618                    ("labels", label),
1619                    ("state", "closed"),
1620                    ("since", since),
1621                    ("per_page", "100"),
1622                ],
1623            )
1624            .await?;
1625        Ok(all
1626            .into_iter()
1627            .filter(|i| i.pull_request.is_none())
1628            .collect())
1629    }
1630
1631    /// List closed issues updated since `since` (ISO 8601), no label filter.
1632    pub async fn list_closed_issues_since(
1633        &self,
1634        repo: &str,
1635        since: &str,
1636    ) -> anyhow::Result<Vec<GitHubIssue>> {
1637        let url = format!("{GITHUB_API}/repos/{repo}/issues");
1638        let all: Vec<GitHubIssue> = self
1639            .get_all_pages(
1640                &url,
1641                &[("state", "closed"), ("since", since), ("per_page", "100")],
1642            )
1643            .await?;
1644        Ok(all
1645            .into_iter()
1646            .filter(|i| i.pull_request.is_none())
1647            .collect())
1648    }
1649
1650    /// List all open issues (no label filter, paginated).
1651    ///
1652    /// The URL carries no `since`, so it repeats across calls and `get_all_pages` can send
1653    /// it conditionally. GitHub answers 304 while nothing changed, which is free quota
1654    pub async fn list_all_open_issues(&self, repo: &str) -> anyhow::Result<Vec<GitHubIssue>> {
1655        let url = format!("{GITHUB_API}/repos/{repo}/issues");
1656        let params = [("state", "open"), ("per_page", "100")];
1657        let all: Vec<GitHubIssue> = self.get_all_pages(&url, &params).await?;
1658        // GitHub /issues API returns PRs too — filter them out
1659        Ok(all
1660            .into_iter()
1661            .filter(|i| i.pull_request.is_none())
1662            .collect())
1663    }
1664
1665    /// List open pull requests (paginated) using the REST pulls endpoint.
1666    /// Returns raw JSON values for flexibility in callers.
1667    pub async fn list_open_pulls(&self, repo: &str) -> anyhow::Result<Vec<serde_json::Value>> {
1668        let url = format!("{GITHUB_API}/repos/{repo}/pulls");
1669        let all: Vec<serde_json::Value> = self
1670            .get_all_pages(&url, &[("state", "open"), ("per_page", "100")])
1671            .await?;
1672        Ok(all)
1673    }
1674
1675    /// List all issues (open and closed, no label filter, paginated).
1676    ///
1677    /// This is more efficient than making separate calls for open and closed.
1678    pub async fn list_all_issues(&self, repo: &str) -> anyhow::Result<Vec<GitHubIssue>> {
1679        let url = format!("{GITHUB_API}/repos/{repo}/issues");
1680        let all: Vec<GitHubIssue> = self
1681            .get_all_pages(&url, &[("state", "all"), ("per_page", "100")])
1682            .await?;
1683        // GitHub /issues API returns PRs too — filter them out
1684        Ok(all
1685            .into_iter()
1686            .filter(|i| i.pull_request.is_none())
1687            .collect())
1688    }
1689
1690    /// Add labels to an issue.
1691    pub async fn add_labels(
1692        &self,
1693        repo: &str,
1694        number: &str,
1695        labels: &[String],
1696    ) -> anyhow::Result<()> {
1697        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/labels");
1698        let payload = serde_json::json!({ "labels": labels });
1699        self.post_json_raw(&url, &payload).await?;
1700        Ok(())
1701    }
1702
1703    /// Ensure a label exists on the repo, creating it if needed.
1704    pub async fn ensure_label(
1705        &self,
1706        repo: &str,
1707        name: &str,
1708        color: &str,
1709        description: &str,
1710    ) -> anyhow::Result<()> {
1711        let encoded = urlencoding::encode(name);
1712        let get_url = format!("{GITHUB_API}/repos/{repo}/labels/{encoded}");
1713
1714        // Check if label exists
1715        match self.get_bytes(&get_url).await {
1716            Ok(_) => return Ok(()),
1717            Err(e) if e.to_string().contains("404") => {
1718                tracing::debug!(repo, name, "ensure_label: label not found, creating");
1719            }
1720            Err(e) => {
1721                tracing::warn!(repo, name, err = %e, "ensure_label: GET failed, attempting create");
1722            }
1723        }
1724
1725        // Create the label
1726        let create_url = format!("{GITHUB_API}/repos/{repo}/labels");
1727        let payload = serde_json::json!({
1728            "name": name,
1729            "color": color,
1730            "description": description,
1731        });
1732
1733        match self.post_json_raw(&create_url, &payload).await {
1734            Ok(_) => {
1735                Self::record_success();
1736            }
1737            Err(e) => {
1738                let msg = e.to_string();
1739                if msg.contains("422")
1740                    || msg.contains("already_exists")
1741                    || msg.contains("Unprocessable")
1742                {
1743                    tracing::debug!(repo, name, "ensure_label: label already exists (race)");
1744                    return Ok(());
1745                }
1746                // Tolerate creation failures (matches old behavior).
1747                tracing::warn!(repo, name, err = %msg, "ensure_label: create failed, continuing");
1748            }
1749        }
1750        Ok(())
1751    }
1752
1753    /// Remove a label from an issue.
1754    pub async fn remove_label(&self, repo: &str, number: &str, label: &str) -> anyhow::Result<()> {
1755        let encoded = urlencoding::encode(label);
1756        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/labels/{encoded}");
1757        match self.delete(&url).await {
1758            Ok(_) => Ok(()),
1759            Err(e) if e.to_string().contains("404") => {
1760                tracing::debug!(repo, number, label, "label already removed (404)");
1761                Ok(())
1762            }
1763            Err(e) => Err(e),
1764        }
1765    }
1766
1767    /// Add a comment to an issue.
1768    pub async fn add_comment(&self, repo: &str, number: &str, body: &str) -> anyhow::Result<()> {
1769        let body = redact_posted_body(body);
1770        let url = format!("{}/repos/{repo}/issues/{number}/comments", self.api_root());
1771        let payload = serde_json::json!({ "body": body });
1772        self.post_json_raw(&url, &payload).await?;
1773        Ok(())
1774    }
1775
1776    /// Post a commit status. `state` is one of pending, success, failure, error.
1777    pub async fn post_commit_status(
1778        &self,
1779        repo: &str,
1780        sha: &str,
1781        state: &str,
1782        context: &str,
1783        description: &str,
1784    ) -> anyhow::Result<()> {
1785        let url = format!("{GITHUB_API}/repos/{repo}/statuses/{sha}");
1786        let payload = serde_json::json!({
1787            "state": state,
1788            "context": context,
1789            "description": description,
1790        });
1791        self.post_json_raw(&url, &payload).await?;
1792        Ok(())
1793    }
1794
1795    /// Add a reaction to an issue.
1796    ///
1797    /// Supported content values: "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes"
1798    pub async fn add_reaction(
1799        &self,
1800        repo: &str,
1801        number: &str,
1802        content: &str,
1803    ) -> anyhow::Result<()> {
1804        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/reactions");
1805        let payload = serde_json::json!({ "content": content });
1806        self.post_json_raw(&url, &payload).await?;
1807        Ok(())
1808    }
1809
1810    /// Add a reaction to an issue comment.
1811    ///
1812    /// Supported content values: "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes"
1813    pub async fn add_comment_reaction(
1814        &self,
1815        repo: &str,
1816        comment_id: &str,
1817        content: &str,
1818    ) -> anyhow::Result<()> {
1819        let url = format!("{GITHUB_API}/repos/{repo}/issues/comments/{comment_id}/reactions");
1820        let payload = serde_json::json!({ "content": content });
1821        self.post_json_raw(&url, &payload).await?;
1822        Ok(())
1823    }
1824
1825    /// List comments on an issue.
1826    pub async fn list_comments(
1827        &self,
1828        repo: &str,
1829        number: &str,
1830    ) -> anyhow::Result<Vec<GitHubComment>> {
1831        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/comments");
1832        self.get_all_pages(&url, &[("per_page", "100")]).await
1833    }
1834
1835    /// Whether a merged PR exists whose head ref is `branch`.
1836    ///
1837    /// The closed-PR list can include a PR for a different branch, so this
1838    /// uses [`Self::get_closed_pr_state`], which skips a mismatched `head.ref`
1839    pub async fn is_pr_merged(&self, repo: &str, branch: &str) -> anyhow::Result<bool> {
1840        Ok(self
1841            .get_closed_pr_state(repo, branch)
1842            .await?
1843            .is_some_and(|(_, merged, _)| merged))
1844    }
1845
1846    /// Get the state of a closed PR for the given branch.
1847    ///
1848    /// Returns `Some((merged, state))` if a closed PR exists for the branch,
1849    /// where `merged` indicates if it was merged and `state` is the PR state ("closed" or "merged").
1850    /// Returns `None` if no closed PR exists for the branch.
1851    /// Get the state of a closed PR for a given branch.
1852    ///
1853    /// Returns `Some((pr_number, merged, state))` if a closed PR is found that
1854    /// matches the expected branch. Returns `None` if no matching closed PR is found.
1855    ///
1856    /// Validates that the returned PR's head ref matches the expected branch to
1857    /// prevent incorrect merge decisions when multiple PRs exist for the same branch.
1858    pub async fn get_closed_pr_state(
1859        &self,
1860        repo: &str,
1861        branch: &str,
1862    ) -> anyhow::Result<Option<(u64, bool, String)>> {
1863        let owner = repo
1864            .split('/')
1865            .next()
1866            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
1867        let head = format!("{owner}:{branch}");
1868
1869        let url = format!("{}/repos/{repo}/pulls", self.api_root());
1870        let prs: Vec<serde_json::Value> = self
1871            .get_with_query(
1872                &url,
1873                &[("head", &head), ("state", "closed"), ("per_page", "5")],
1874            )
1875            .await?;
1876
1877        if prs.is_empty() {
1878            return Ok(None);
1879        }
1880
1881        // Find the first PR where head ref actually matches our branch
1882        // This validates that we're working with the correct PR
1883        for pr in prs {
1884            let pr_branch = pr
1885                .get("head")
1886                .and_then(|h| h.get("ref"))
1887                .and_then(|r| r.as_str())
1888                .unwrap_or("");
1889
1890            if pr_branch != branch {
1891                tracing::debug!(
1892                    repo,
1893                    branch,
1894                    pr_branch,
1895                    "skipping PR with mismatched head ref"
1896                );
1897                continue;
1898            }
1899
1900            let pr_number = pr
1901                .get("number")
1902                .and_then(serde_json::Value::as_u64)
1903                .ok_or_else(|| anyhow::anyhow!("PR missing number field"))?;
1904
1905            let merged_at = pr.get("merged_at");
1906            let merged = merged_at.is_some_and(|v| !v.is_null());
1907            let state = pr
1908                .get("state")
1909                .and_then(|v| v.as_str())
1910                .unwrap_or("closed")
1911                .to_string();
1912
1913            return Ok(Some((pr_number, merged, state)));
1914        }
1915
1916        // No PR with matching head ref found
1917        Ok(None)
1918    }
1919
1920    /// Batch-check whether the PR for each branch was merged via a single GraphQL query.
1921    ///
1922    /// Returns a map of branch → merged. Branches with no matching PR are omitted
1923    /// (callers should treat missing entries as not merged).
1924    pub async fn batch_is_pr_merged_by_branch(
1925        &self,
1926        repo: &str,
1927        branches: &[String],
1928    ) -> anyhow::Result<HashMap<String, bool>> {
1929        if branches.is_empty() {
1930            return Ok(HashMap::new());
1931        }
1932
1933        let (owner, name) = repo
1934            .split_once('/')
1935            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
1936
1937        // Build one alias per branch using positional index to avoid GraphQL
1938        // alias restrictions on branch names that contain non-identifier chars.
1939        // Branch names are passed via variables ($b0, $b1, …) to avoid injection.
1940        let mut var_defs = String::new();
1941        let mut aliases = String::new();
1942        let mut vars = serde_json::json!({ "owner": owner, "name": name });
1943        for (i, branch) in branches.iter().enumerate() {
1944            let _ = write!(var_defs, ", $b{i}: String!");
1945            let _ = write!(
1946                aliases,
1947                r"b{i}: pullRequests(headRefName: $b{i}, states: [MERGED], last: 1) {{ nodes {{ merged }} }} "
1948            );
1949            vars[format!("b{i}")] = serde_json::Value::String(branch.clone());
1950        }
1951
1952        let query = format!(
1953            r"query($owner: String!, $name: String!{var_defs}) {{
1954                repository(owner: $owner, name: $name) {{ {aliases} }}
1955            }}"
1956        );
1957
1958        let resp = self.graphql_with_vars(&query, vars).await?;
1959
1960        // Surface GraphQL partial errors before checking data structure
1961        if let Some(errors) = resp.get("errors").and_then(|e| e.as_array())
1962            && !errors.is_empty()
1963        {
1964            let messages: Vec<&str> = errors
1965                .iter()
1966                .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
1967                .collect();
1968            tracing::warn!(
1969                repo,
1970                errors = ?messages,
1971                "GraphQL returned errors in batch PR merge check"
1972            );
1973        }
1974
1975        Self::parse_batch_pr_merged_response(&resp, branches)
1976    }
1977
1978    fn parse_batch_pr_merged_response(
1979        resp: &serde_json::Value,
1980        branches: &[String],
1981    ) -> anyhow::Result<HashMap<String, bool>> {
1982        let repo_data = resp.pointer("/data/repository").ok_or_else(|| {
1983            // Check for errors array to provide a more helpful error message
1984            let error_msg = resp
1985                .get("errors")
1986                .and_then(|e| e.as_array())
1987                .and_then(|arr| arr.first())
1988                .and_then(|e| e.get("message"))
1989                .and_then(|m| m.as_str())
1990                .unwrap_or("no error details");
1991            anyhow::anyhow!("missing /data/repository in GraphQL response: {error_msg}")
1992        })?;
1993
1994        let mut result = HashMap::new();
1995        for (i, branch) in branches.iter().enumerate() {
1996            let alias = format!("b{i}");
1997            let merged = repo_data
1998                .get(&alias)
1999                .and_then(|v| v.get("nodes"))
2000                .and_then(|nodes| nodes.as_array())
2001                .and_then(|arr| arr.first())
2002                .and_then(|node| node.get("merged"))
2003                .and_then(serde_json::Value::as_bool)
2004                .unwrap_or(false);
2005            result.insert(branch.clone(), merged);
2006        }
2007
2008        Ok(result)
2009    }
2010
2011    /// Get issue/PR comments since a given timestamp (paginated).
2012    pub async fn get_mentions(
2013        &self,
2014        repo: &str,
2015        since: &str,
2016    ) -> anyhow::Result<Vec<GitHubComment>> {
2017        let url = format!("{}/repos/{repo}/issues/comments", self.api_root());
2018        self.get_all_pages(&url, &[("since", since), ("per_page", "100")])
2019            .await
2020    }
2021
2022    /// Get all comments for a specific issue number.
2023    pub async fn get_issue_comments(
2024        &self,
2025        repo: &str,
2026        issue_number: u64,
2027    ) -> anyhow::Result<Vec<GitHubComment>> {
2028        let url = format!(
2029            "{}/repos/{repo}/issues/{issue_number}/comments",
2030            self.api_root()
2031        );
2032        self.get_all_pages(&url, &[("per_page", "100")]).await
2033    }
2034
2035    /// Get the current authenticated username (cached after first call).
2036    pub async fn get_whoami(&self) -> anyhow::Result<String> {
2037        if let Some(cached) = self.cached_username.get() {
2038            return Ok(cached.clone());
2039        }
2040
2041        // An installation token cannot read `GET /user`, and the owner is the identity mentions name
2042        let mut owner = self.clone();
2043        owner.owner_only = true;
2044        let user: serde_json::Value = owner.get_json(&format!("{GITHUB_API}/user")).await?;
2045        let username = user
2046            .get("login")
2047            .and_then(|v| v.as_str())
2048            .map(String::from)
2049            .ok_or_else(|| anyhow::anyhow!("failed to get current user"))?;
2050
2051        let _ = self.cached_username.set(username.clone());
2052        Ok(username)
2053    }
2054
2055    /// Get PR number by branch name.
2056    pub async fn get_pr_number(&self, repo: &str, branch: &str) -> anyhow::Result<Option<u64>> {
2057        let owner = repo
2058            .split('/')
2059            .next()
2060            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
2061        let head = format!("{owner}:{branch}");
2062
2063        let url = format!("{GITHUB_API}/repos/{repo}/pulls");
2064        let prs: Vec<serde_json::Value> = self
2065            .get_with_query(
2066                &url,
2067                &[("head", &head), ("state", "open"), ("per_page", "1")],
2068            )
2069            .await?;
2070
2071        if prs.is_empty() {
2072            return Ok(None);
2073        }
2074        prs[0]
2075            .get("number")
2076            .and_then(serde_json::Value::as_u64)
2077            .ok_or_else(|| anyhow::anyhow!("PR missing number field"))
2078            .map(Some)
2079    }
2080
2081    /// Create a new pull request.
2082    ///
2083    /// # Arguments
2084    /// * `repo` - Repository in "owner/repo" format
2085    /// * `title` - PR title
2086    /// * `body` - PR body/description
2087    /// * `head` - Branch name to create PR from
2088    /// * `base` - Base branch to merge into (e.g., "main")
2089    ///
2090    /// Returns the created PR's URL on success.
2091    pub async fn create_pr(
2092        &self,
2093        repo: &str,
2094        title: &str,
2095        body: &str,
2096        head: &str,
2097        base: &str,
2098    ) -> anyhow::Result<String> {
2099        #[derive(Serialize)]
2100        struct CreatePullRequest<'a> {
2101            title: &'a str,
2102            body: &'a str,
2103            head: &'a str,
2104            base: &'a str,
2105        }
2106
2107        let body = redact_posted_body(body);
2108        let url = format!("{}/repos/{repo}/pulls", self.api_root());
2109        Self::check_backoff(&url)?;
2110
2111        let payload = CreatePullRequest {
2112            title,
2113            body: &body,
2114            head,
2115            base,
2116        };
2117
2118        let auth = self.auth_header(&url).await?;
2119        let make_req = || {
2120            Ok(self
2121                .client
2122                .post(&url)
2123                .header(header::AUTHORIZATION, auth.clone())
2124                .header(header::ACCEPT, "application/vnd.github+json")
2125                .header(header::USER_AGENT, "orch")
2126                .header("X-GitHub-Api-Version", "2022-11-28")
2127                .json(&payload))
2128        };
2129        let response = self.send_with_retries(make_req, false).await?;
2130        let status = response.status();
2131        let text = response.text().await.unwrap_or_default();
2132        if !status.is_success() {
2133            Self::maybe_record_rate_limit_from_body(status, &text);
2134            anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
2135        }
2136
2137        let pr: serde_json::Value = serde_json::from_str(&text)?;
2138        pr.get("html_url")
2139            .and_then(|v| v.as_str())
2140            .map(String::from)
2141            .ok_or_else(|| anyhow::anyhow!("failed to get PR URL from response: {pr:?}"))
2142    }
2143
2144    /// Get the repository's default branch from the GitHub API.
2145    ///
2146    /// Used as a fallback when local git detection yields an invalid base
2147    /// branch for PR creation.
2148    pub async fn get_default_branch(&self, repo: &str) -> anyhow::Result<String> {
2149        let url = format!("{}/repos/{repo}", self.api_root());
2150        let resp: serde_json::Value = self.get_json(&url).await?;
2151        resp.get("default_branch")
2152            .and_then(|v| v.as_str())
2153            .map(String::from)
2154            .ok_or_else(|| anyhow::anyhow!("default_branch missing from repo response"))
2155    }
2156
2157    /// Get PR details by PR number.
2158    /// Returns the full PR object including the `mergeable` field.
2159    pub async fn get_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<GitHubPullRequest> {
2160        let url = format!("{}/repos/{repo}/pulls/{pr_number}", self.api_root());
2161        self.get_json(&url).await
2162    }
2163
2164    /// Fetch the merged/state for multiple PRs in a single GraphQL query.
2165    ///
2166    /// Returns a map of pr_number → (merged, state).
2167    /// PRs that fail to fetch are silently omitted from the result.
2168    pub async fn batch_get_pr_states(
2169        &self,
2170        repo: &str,
2171        pr_numbers: &[u64],
2172    ) -> anyhow::Result<HashMap<u64, (bool, String)>> {
2173        // GitHub GraphQL complexity limit: chunk at 50 to avoid slow/rejected queries.
2174        const CHUNK_SIZE: usize = 50;
2175
2176        if pr_numbers.is_empty() {
2177            return Ok(HashMap::new());
2178        }
2179
2180        let (owner, name) = repo
2181            .split_once('/')
2182            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
2183
2184        let mut result = HashMap::new();
2185
2186        for chunk in pr_numbers.chunks(CHUNK_SIZE) {
2187            let aliases: String = chunk
2188                .iter()
2189                .map(|n| format!("pr{n}: pullRequest(number: {n}) {{ merged state }}"))
2190                .collect::<Vec<_>>()
2191                .join("\n  ");
2192
2193            let query = format!(
2194                r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
2195            );
2196
2197            let resp = self
2198                .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
2199                .await?;
2200            let repo_data = resp
2201                .pointer("/data/repository")
2202                .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
2203
2204            for n in chunk {
2205                if let Some(pr) = repo_data.get(format!("pr{n}")) {
2206                    let merged = pr
2207                        .get("merged")
2208                        .and_then(serde_json::Value::as_bool)
2209                        .unwrap_or(false);
2210                    let state = pr
2211                        .get("state")
2212                        .and_then(|v| v.as_str())
2213                        .unwrap_or("UNKNOWN")
2214                        .to_lowercase();
2215                    result.insert(*n, (merged, state));
2216                }
2217            }
2218        }
2219
2220        Ok(result)
2221    }
2222
2223    /// Batch-fetch state and labels for multiple GitHub issues in a single GraphQL request.
2224    ///
2225    /// Returns a map of issue number (as string) → `(state, labels)` where state is
2226    /// lowercase ("open" / "closed") to match the REST API convention used elsewhere.
2227    pub async fn batch_get_issue_states(
2228        &self,
2229        repo: &str,
2230        issue_numbers: &[u64],
2231        caller_context: &str,
2232    ) -> anyhow::Result<HashMap<String, (String, Vec<String>)>> {
2233        // GitHub GraphQL complexity limit: chunk at 50 to avoid slow/rejected queries.
2234        const CHUNK_SIZE: usize = 50;
2235
2236        if issue_numbers.is_empty() {
2237            return Ok(HashMap::new());
2238        }
2239
2240        let (valid_issue_numbers, invalid_issue_numbers) =
2241            sanitize_github_issue_numbers(issue_numbers);
2242        if !invalid_issue_numbers.is_empty() {
2243            tracing::warn!(
2244                repo,
2245                caller_context,
2246                invalid_issue_numbers = ?invalid_issue_numbers,
2247                total_supplied = issue_numbers.len(),
2248                "dropping invalid GitHub issue numbers before batch issue-state GraphQL query"
2249            );
2250        }
2251        if valid_issue_numbers.is_empty() {
2252            return Ok(HashMap::new());
2253        }
2254
2255        let (owner, name) = repo
2256            .split_once('/')
2257            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
2258
2259        let mut result = HashMap::new();
2260
2261        for chunk in valid_issue_numbers.chunks(CHUNK_SIZE) {
2262            let aliases: String = chunk
2263                .iter()
2264                .map(|n| {
2265                    format!("issue{n}: issue(number: {n}) {{ state labels(first: 100) {{ nodes {{ name }} }} }}")
2266                })
2267                .collect::<Vec<_>>()
2268                .join(" ");
2269
2270            let query = format!(
2271                r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
2272            );
2273
2274            let resp = self
2275                .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
2276                .await?;
2277            let repo_data = resp
2278                .pointer("/data/repository")
2279                .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
2280
2281            for n in chunk {
2282                if let Some(issue) = repo_data.get(format!("issue{n}")) {
2283                    let state = issue
2284                        .get("state")
2285                        .and_then(|v| v.as_str())
2286                        .unwrap_or("UNKNOWN")
2287                        .to_lowercase();
2288                    let labels: Vec<String> = issue
2289                        .pointer("/labels/nodes")
2290                        .and_then(|v| v.as_array())
2291                        .map(|arr| {
2292                            arr.iter()
2293                                .filter_map(|l| {
2294                                    l.get("name").and_then(|nm| nm.as_str()).map(String::from)
2295                                })
2296                                .collect()
2297                        })
2298                        .unwrap_or_default();
2299                    result.insert(n.to_string(), (state, labels));
2300                }
2301            }
2302        }
2303        Ok(result)
2304    }
2305
2306    /// Required status checks for a branch from classic protection and from rulesets
2307    pub async fn get_required_status_check_contexts(
2308        &self,
2309        repo: &str,
2310        branch: &str,
2311    ) -> anyhow::Result<Vec<RequiredStatusCheck>> {
2312        let branch = urlencoding::encode(branch);
2313        let classic_url = format!(
2314            "{}/repos/{repo}/branches/{branch}/protection",
2315            self.api_root()
2316        );
2317        let rules_url = format!("{}/repos/{repo}/rules/branches/{branch}", self.api_root());
2318
2319        let classic_fut = self.get_json::<serde_json::Value>(&classic_url);
2320        let rules_fut = self.get_all_pages::<serde_json::Value>(&rules_url, &[("per_page", "100")]);
2321        let (classic_resp, rules_resp) = tokio::join!(classic_fut, rules_fut);
2322
2323        let classic = match classic_resp {
2324            Ok(value) => parse_classic_required_status_checks(&value),
2325            Err(e) => {
2326                if is_no_branch_protection_error(&e.to_string()) {
2327                    Vec::new()
2328                } else {
2329                    return Err(e);
2330                }
2331            }
2332        };
2333
2334        let ruleset = match rules_resp {
2335            Ok(rules) => parse_ruleset_required_status_checks(&rules),
2336            Err(e) => {
2337                if e.to_string().contains("404") {
2338                    Vec::new()
2339                } else {
2340                    return Err(e);
2341                }
2342            }
2343        };
2344
2345        Ok(merge_required_status_checks(classic, ruleset))
2346    }
2347
2348    /// Get commit status contexts for a SHA.
2349    pub async fn get_commit_status_contexts(
2350        &self,
2351        repo: &str,
2352        sha: &str,
2353    ) -> anyhow::Result<Vec<(String, String)>> {
2354        let url = format!(
2355            "{}/repos/{repo}/commits/{sha}/status?per_page=100",
2356            self.api_root()
2357        );
2358        // The /commits/{sha}/status endpoint returns a wrapper object:
2359        // { "state": "pending", "total_count": N, "statuses": [...] }
2360        // Use get_all_pages_from_wrapper to follow pagination and extract the
2361        // `statuses` array across pages so we don't silently truncate at 100.
2362        let statuses: Vec<serde_json::Value> =
2363            self.get_all_pages_from_wrapper(&url, "statuses").await?;
2364
2365        Ok(statuses
2366            .into_iter()
2367            .filter_map(|status| {
2368                let context = status.get("context").and_then(|v| v.as_str())?;
2369                let state = status.get("state").and_then(|v| v.as_str())?;
2370                Some((context.to_string(), state.to_string()))
2371            })
2372            .collect())
2373    }
2374
2375    fn combined_status_state(
2376        total: u64,
2377        failing: u64,
2378        pending: u64,
2379        has_workflows: bool,
2380        mergeable_state: Option<&str>,
2381    ) -> String {
2382        if failing > 0 {
2383            "failure".to_string()
2384        } else if pending > 0 {
2385            "pending".to_string()
2386        } else if total == 0 && has_workflows {
2387            // No check runs yet. If GitHub already reports mergeable_state="clean"
2388            // the PR is ready (e.g. all workflows use paths-ignore and skipped this
2389            // commit). Treating it as pending would stall auto-merge forever.
2390            if mergeable_state == Some("clean") {
2391                "success".to_string()
2392            } else {
2393                "pending".to_string()
2394            }
2395        } else {
2396            "success".to_string()
2397        }
2398    }
2399
2400    /// Return `true` when the repository has at least one GitHub Actions workflow.
2401    ///
2402    /// This is used to distinguish repos that genuinely have no CI configured from
2403    /// repos where CI exists but GitHub has not surfaced any runs yet.
2404    pub async fn has_workflows(&self, repo: &str) -> anyhow::Result<bool> {
2405        let url = format!("{GITHUB_API}/repos/{repo}/actions/workflows?per_page=1");
2406        let resp = self.get_json::<serde_json::Value>(&url).await;
2407        match resp {
2408            Ok(value) => Ok(value
2409                .get("workflows")
2410                .and_then(|v| v.as_array())
2411                .is_some_and(|workflows| !workflows.is_empty())),
2412            Err(e) => {
2413                let err = e.to_string();
2414                if err.contains("404") {
2415                    Ok(false)
2416                } else {
2417                    Err(e)
2418                }
2419            }
2420        }
2421    }
2422
2423    /// True when `.github/workflows` on `branch` has at least one YAML file
2424    pub async fn has_workflow_on_branch(&self, repo: &str, branch: &str) -> anyhow::Result<bool> {
2425        let branch = urlencoding::encode(branch);
2426        let url = format!(
2427            "{}/repos/{repo}/contents/.github/workflows?ref={branch}",
2428            self.api_root()
2429        );
2430        match self.get_json::<serde_json::Value>(&url).await {
2431            Ok(value) => Ok(value.as_array().is_some_and(|entries| {
2432                entries.iter().any(|entry| {
2433                    entry
2434                        .get("name")
2435                        .and_then(|name| name.as_str())
2436                        .is_some_and(|name| {
2437                            Path::new(name)
2438                                .extension()
2439                                .and_then(|ext| ext.to_str())
2440                                .is_some_and(|ext| {
2441                                    ext.eq_ignore_ascii_case("yml")
2442                                        || ext.eq_ignore_ascii_case("yaml")
2443                                })
2444                        })
2445                })
2446            })),
2447            Err(e) => {
2448                let err = e.to_string();
2449                if err.contains("404") {
2450                    Ok(false)
2451                } else {
2452                    Err(e)
2453                }
2454            }
2455        }
2456    }
2457
2458    /// True when `path` exists on `branch`
2459    pub async fn has_file_on_branch(
2460        &self,
2461        repo: &str,
2462        path: &str,
2463        branch: &str,
2464    ) -> anyhow::Result<bool> {
2465        let path = path
2466            .split('/')
2467            .map(|segment| urlencoding::encode(segment).into_owned())
2468            .collect::<Vec<_>>()
2469            .join("/");
2470        let branch = urlencoding::encode(branch);
2471        let url = format!(
2472            "{}/repos/{repo}/contents/{path}?ref={branch}",
2473            self.api_root()
2474        );
2475        match self.get_json::<serde_json::Value>(&url).await {
2476            Ok(_) => Ok(true),
2477            Err(e) => {
2478                let err = e.to_string();
2479                if err.contains("404") {
2480                    Ok(false)
2481                } else {
2482                    Err(e)
2483                }
2484            }
2485        }
2486    }
2487
2488    /// SHA of the head commit on `branch`
2489    pub async fn get_branch_sha(&self, repo: &str, branch: &str) -> anyhow::Result<String> {
2490        let encoded = urlencoding::encode(branch);
2491        let url = format!("{}/repos/{repo}/branches/{encoded}", self.api_root());
2492        let resp: serde_json::Value = self.get_json(&url).await?;
2493        resp.pointer("/commit/sha")
2494            .and_then(|v| v.as_str())
2495            .map(String::from)
2496            .ok_or_else(|| anyhow::anyhow!("branch {branch} has no commit sha"))
2497    }
2498
2499    /// Create a repository ruleset that requires `checks` on the default branch
2500    pub async fn create_required_check_ruleset(
2501        &self,
2502        repo: &str,
2503        checks: &[RequiredStatusCheck],
2504    ) -> anyhow::Result<()> {
2505        let url = format!("{}/repos/{repo}/rulesets", self.api_root());
2506        let payload = required_check_ruleset_payload(checks);
2507        self.post_json_raw(&url, &payload).await?;
2508        Ok(())
2509    }
2510
2511    /// Id and required checks of the repository ruleset named `name`, if it exists
2512    pub async fn get_named_ruleset_required_checks(
2513        &self,
2514        repo: &str,
2515        name: &str,
2516    ) -> anyhow::Result<Option<(i64, Vec<RequiredStatusCheck>)>> {
2517        let url = format!("{}/repos/{repo}/rulesets", self.api_root());
2518        let rulesets: Vec<serde_json::Value> =
2519            self.get_all_pages(&url, &[("per_page", "100")]).await?;
2520        let Some(id) = rulesets.iter().find_map(|ruleset| {
2521            if ruleset.get("name").and_then(|n| n.as_str()) != Some(name) {
2522                return None;
2523            }
2524            ruleset.get("id").and_then(serde_json::Value::as_i64)
2525        }) else {
2526            return Ok(None);
2527        };
2528        let url = format!("{}/repos/{repo}/rulesets/{id}", self.api_root());
2529        let value: serde_json::Value = self.get_json(&url).await?;
2530        let rules = value
2531            .get("rules")
2532            .and_then(|r| r.as_array())
2533            .cloned()
2534            .unwrap_or_default();
2535        Ok(Some((id, parse_ruleset_required_status_checks(&rules))))
2536    }
2537
2538    /// Replace the required checks on an existing repository ruleset
2539    pub async fn update_required_check_ruleset(
2540        &self,
2541        repo: &str,
2542        ruleset_id: i64,
2543        checks: &[RequiredStatusCheck],
2544    ) -> anyhow::Result<()> {
2545        let url = format!("{}/repos/{repo}/rulesets/{ruleset_id}", self.api_root());
2546        let payload = required_check_ruleset_payload(checks);
2547        self.put_json_raw(&url, &payload).await?;
2548        Ok(())
2549    }
2550
2551    /// Get check runs for a PR head SHA.
2552    pub async fn get_check_runs(
2553        &self,
2554        repo: &str,
2555        sha: &str,
2556    ) -> anyhow::Result<Vec<GitHubCheckRun>> {
2557        // Use `filter=latest` so GitHub returns only the most recent check run
2558        // per check name. Without this, the API returns all runs (oldest
2559        // first) and callers that pick the first match may observe a stale
2560        // failed run when a newer run with the same name has succeeded.
2561        //
2562        // Use `per_page=100` and manual pagination via `get_all_pages_from_wrapper`
2563        // because this endpoint returns a *wrapper object* — `{ "total_count": N,
2564        // "check_runs": [...] }` — rather than a raw JSON array.  `get_all_pages`
2565        // cannot be used here because it calls `serde_json::from_str::<Vec<T>>`
2566        // which would fail on an object body.
2567        let url = format!(
2568            "{}/repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100",
2569            self.api_root()
2570        );
2571        self.get_all_pages_from_wrapper(&url, "check_runs").await
2572    }
2573
2574    /// Get annotations for a specific check run.
2575    ///
2576    /// Returns the list of annotations attached to the check run, including
2577    /// billing failure messages ("The job was not started because recent account
2578    /// payments have failed …") that GitHub surfaces as annotations rather than
2579    /// as a distinct CI conclusion value.
2580    pub async fn get_check_run_annotations(
2581        &self,
2582        repo: &str,
2583        check_run_id: u64,
2584    ) -> anyhow::Result<Vec<GitHubAnnotation>> {
2585        let url = format!("{GITHUB_API}/repos/{repo}/check-runs/{check_run_id}/annotations");
2586        self.get_all_pages(&url, &[("per_page", "100")]).await
2587    }
2588
2589    /// Get reviews for a PR.
2590    pub async fn get_pr_reviews(
2591        &self,
2592        repo: &str,
2593        pr_number: u64,
2594    ) -> anyhow::Result<Vec<GitHubReview>> {
2595        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/reviews");
2596        self.get_all_pages(&url, &[("per_page", "100")]).await
2597    }
2598
2599    /// Get the committer timestamp for a specific commit SHA.
2600    ///
2601    /// Returns an ISO-8601 string, e.g. `"2024-01-15T12:00:00Z"`.
2602    /// Used to determine whether the branch has been updated since a review was submitted.
2603    pub async fn get_commit_timestamp(&self, repo: &str, sha: &str) -> anyhow::Result<String> {
2604        let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}");
2605        let value: serde_json::Value = self.get_json(&url).await?;
2606        value
2607            .pointer("/commit/committer/date")
2608            .and_then(|v| v.as_str())
2609            .map(ToString::to_string)
2610            .ok_or_else(|| anyhow::anyhow!("commit {sha} has no committer date"))
2611    }
2612
2613    /// Update the body of a pull request.
2614    pub async fn update_pr_body(
2615        &self,
2616        repo: &str,
2617        pr_number: u64,
2618        body: &str,
2619    ) -> anyhow::Result<()> {
2620        let body = redact_posted_body(body);
2621        let url = format!("{}/repos/{repo}/pulls/{pr_number}", self.api_root());
2622        let payload = serde_json::json!({ "body": body });
2623        self.patch_json_raw(&url, &payload).await?;
2624        Ok(())
2625    }
2626
2627    /// Close a pull request without merging it.
2628    pub async fn close_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2629        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}");
2630        let payload = serde_json::json!({ "state": "closed" });
2631        self.patch_json_raw(&url, &payload).await?;
2632        Ok(())
2633    }
2634
2635    /// How many commits the head is missing from `base` (GitHub's `behind_by`).
2636    ///
2637    /// Zero means the head already contains the current base tip, so its checks
2638    /// ran against the code the merge would produce.
2639    pub async fn compare_behind_by(
2640        &self,
2641        repo: &str,
2642        base: &str,
2643        head_sha: &str,
2644    ) -> anyhow::Result<u64> {
2645        let url = format!("{GITHUB_API}/repos/{repo}/compare/{base}...{head_sha}");
2646        let body: serde_json::Value = self.get_json(&url).await?;
2647        parse_behind_by(&body)
2648    }
2649
2650    /// Parents, author and committer of a commit
2651    pub async fn commit_meta(&self, repo: &str, sha: &str) -> anyhow::Result<CommitMeta> {
2652        let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}");
2653        let value: serde_json::Value = self.get_json(&url).await?;
2654        Ok(parse_commit_meta(&value))
2655    }
2656
2657    /// True when `branch` already contains the commit `sha`
2658    pub async fn branch_contains(
2659        &self,
2660        repo: &str,
2661        branch: &str,
2662        sha: &str,
2663    ) -> anyhow::Result<bool> {
2664        let url = format!("{GITHUB_API}/repos/{repo}/compare/{branch}...{sha}");
2665        let body: serde_json::Value = self.get_json(&url).await?;
2666        body.get("ahead_by")
2667            .and_then(serde_json::Value::as_u64)
2668            .map(|ahead| ahead == 0)
2669            .ok_or_else(|| anyhow::anyhow!("compare response has no numeric ahead_by field"))
2670    }
2671
2672    /// Close a GitHub issue.
2673    pub async fn close_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
2674        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
2675        let payload = serde_json::json!({ "state": "closed" });
2676        self.patch_json_raw(&url, &payload).await?;
2677        Ok(())
2678    }
2679
2680    /// Reopen a closed GitHub issue.
2681    pub async fn reopen_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
2682        let url = format!("{}/repos/{repo}/issues/{number}", self.api_root());
2683        let payload = serde_json::json!({ "state": "open" });
2684        self.patch_json_raw(&url, &payload).await?;
2685        Ok(())
2686    }
2687
2688    /// Check if a user is a collaborator.
2689    pub async fn is_collaborator(&self, repo: &str, username: &str) -> anyhow::Result<bool> {
2690        let url = format!("{GITHUB_API}/repos/{repo}/collaborators/{username}");
2691        Self::check_backoff(&url)?;
2692        let auth = self.auth_header(&url).await?;
2693        let make_req = || {
2694            Ok(self
2695                .client
2696                .get(&url)
2697                .header(header::AUTHORIZATION, auth.clone())
2698                .header(header::ACCEPT, "application/vnd.github+json")
2699                .header("X-GitHub-Api-Version", "2022-11-28"))
2700        };
2701        let resp = self.send_with_retries(make_req, false).await?;
2702        let status = resp.status();
2703        if status == StatusCode::NO_CONTENT {
2704            Ok(true)
2705        } else if status == StatusCode::NOT_FOUND {
2706            Ok(false)
2707        } else {
2708            let body = resp.text().await.unwrap_or_default();
2709            anyhow::bail!("GitHub API collaborator check failed ({status}): {body}");
2710        }
2711    }
2712
2713    /// Add a sub-issue relationship via GraphQL.
2714    pub async fn add_sub_issue(
2715        &self,
2716        parent_node_id: &str,
2717        child_node_id: &str,
2718    ) -> anyhow::Result<()> {
2719        let query = format!(
2720            r#"mutation {{
2721                addSubIssue(input: {{issueId: "{parent_node_id}", subIssueId: "{child_node_id}"}}) {{
2722                    issue {{ number }}
2723                    subIssue {{ number }}
2724                }}
2725            }}"#
2726        );
2727        self.graphql_with_headers(&query, &["GraphQL-Features:sub_issues"])
2728            .await?;
2729        Ok(())
2730    }
2731
2732    /// Link an issue to a branch using GraphQL.
2733    ///
2734    /// Creates a "Development" sidebar link in GitHub that connects the issue
2735    /// to the branch, similar to `gh issue develop`.
2736    ///
2737    /// # Arguments
2738    /// * `repo` - Repository in "owner/repo" format
2739    /// * `issue_number` - The issue number to link
2740    /// * `branch` - The branch name to link the issue to
2741    ///
2742    /// Returns the linked branch ID on success.
2743    pub async fn link_issue_to_branch(
2744        &self,
2745        repo: &str,
2746        issue_number: u64,
2747        branch: &str,
2748    ) -> anyhow::Result<String> {
2749        let parts: Vec<&str> = repo.split('/').collect();
2750        if parts.len() != 2 {
2751            anyhow::bail!("invalid repo format: expected 'owner/repo', got '{repo}'");
2752        }
2753        let (owner, repo_name) = (parts[0], parts[1]);
2754
2755        // First, get the repository and issue node IDs
2756        let query = r"query($owner: String!, $name: String!, $number: Int!) {
2757                repository(owner: $owner, name: $name) {
2758                    id
2759                    issue(number: $number) {
2760                        id
2761                    }
2762                }
2763            }";
2764        let vars = serde_json::json!({
2765            "owner": owner,
2766            "name": repo_name,
2767            "number": issue_number,
2768        });
2769
2770        let result = self.graphql_with_vars(query, vars).await?;
2771
2772        let repo_id = result
2773            .pointer("/data/repository/id")
2774            .and_then(|v| v.as_str())
2775            .ok_or_else(|| anyhow::anyhow!("failed to get repository node ID"))?;
2776
2777        let issue_id = result
2778            .pointer("/data/repository/issue/id")
2779            .and_then(|v| v.as_str())
2780            .ok_or_else(|| anyhow::anyhow!("failed to get issue node ID"))?;
2781
2782        // Fetch branch ref to get the commit OID required by createLinkedBranch
2783        let branch_query = r"query($owner: String!, $name: String!, $ref: String!) {
2784                repository(owner: $owner, name: $name) {
2785                    ref(qualifiedName: $ref) {
2786                        target {
2787                            oid
2788                        }
2789                    }
2790                }
2791            }";
2792        let branch_vars = serde_json::json!({
2793            "owner": owner,
2794            "name": repo_name,
2795            "ref": format!("refs/heads/{}", branch),
2796        });
2797
2798        let branch_result = self.graphql_with_vars(branch_query, branch_vars).await?;
2799        let branch_oid = branch_result
2800            .pointer("/data/repository/ref/target/oid")
2801            .and_then(|v| v.as_str());
2802
2803        // If branch doesn't exist yet, use the default branch OID.
2804        // createLinkedBranch will create the branch at that OID AND link it.
2805        let branch_oid = if let Some(oid) = branch_oid {
2806            oid.to_string()
2807        } else {
2808            // Get default branch OID as the base for the new branch
2809            let default_query = r"query($owner: String!, $name: String!) {
2810                    repository(owner: $owner, name: $name) {
2811                        defaultBranchRef {
2812                            target {
2813                                oid
2814                            }
2815                        }
2816                    }
2817                }";
2818            let default_vars = serde_json::json!({
2819                "owner": owner,
2820                "name": repo_name,
2821            });
2822            let default_result = self.graphql_with_vars(default_query, default_vars).await?;
2823            match default_result
2824                .pointer("/data/repository/defaultBranchRef/target/oid")
2825                .and_then(|v| v.as_str())
2826            {
2827                Some(oid) => {
2828                    tracing::debug!(
2829                        repo,
2830                        issue_number,
2831                        branch,
2832                        "branch not found, using default branch OID to create and link"
2833                    );
2834                    oid.to_string()
2835                }
2836                None => {
2837                    return Ok(format!("unlinked:{branch}"));
2838                }
2839            }
2840        };
2841
2842        // Use createLinkedBranch mutation to link the issue to the existing branch.
2843        // Required fields: issueId, repositoryId, name (branch name), oid (commit SHA).
2844        let mutation = r"mutation($issueId: ID!, $repositoryId: ID!, $name: String!, $oid: GitObjectID!) {
2845                createLinkedBranch(input: {
2846                    issueId: $issueId
2847                    repositoryId: $repositoryId
2848                    name: $name
2849                    oid: $oid
2850                }) {
2851                    linkedBranch {
2852                        id
2853                        ref {
2854                            name
2855                        }
2856                    }
2857                }
2858            }";
2859        let mutation_vars = serde_json::json!({
2860            "issueId": issue_id,
2861            "repositoryId": repo_id,
2862            "name": branch,
2863            "oid": branch_oid,
2864        });
2865
2866        let link_result = self.graphql_with_vars(mutation, mutation_vars).await;
2867
2868        match link_result {
2869            Ok(result) => {
2870                let linked_branch_id = result
2871                    .pointer("/data/createLinkedBranch/linkedBranch/id")
2872                    .and_then(|v| v.as_str())
2873                    .map(String::from);
2874
2875                if let Some(id) = linked_branch_id {
2876                    tracing::info!(
2877                        repo,
2878                        issue_number,
2879                        branch,
2880                        "linked issue to branch via GraphQL API"
2881                    );
2882                    Ok(id)
2883                } else {
2884                    // Branch may already be linked - check for errors
2885                    let errors = result
2886                        .get("errors")
2887                        .and_then(|e| e.as_array())
2888                        .cloned()
2889                        .unwrap_or_default();
2890
2891                    if errors.iter().any(|e| {
2892                        e.get("message")
2893                            .and_then(|m| m.as_str())
2894                            .is_some_and(|m| m.contains("already"))
2895                    }) {
2896                        tracing::debug!(
2897                            repo,
2898                            issue_number,
2899                            branch,
2900                            "issue already linked to branch"
2901                        );
2902                        Ok(format!("already_linked:{branch}"))
2903                    } else {
2904                        anyhow::bail!("failed to link issue to branch: {result:?}")
2905                    }
2906                }
2907            }
2908            Err(e) => {
2909                // Check if it's a "already exists" type error
2910                let err_str = format!("{e}");
2911                if err_str.contains("already") || err_str.contains("existing") {
2912                    tracing::debug!(
2913                        repo,
2914                        issue_number,
2915                        branch,
2916                        "issue already linked to branch (error check)"
2917                    );
2918                    Ok(format!("already_linked:{branch}"))
2919                } else {
2920                    Err(e)
2921                }
2922            }
2923        }
2924    }
2925
2926    /// Merge a PR using the REST API (squash merge).
2927    /// GitHub rejects it when the PR head is no longer `head_sha`, the commit CI was checked against
2928    pub async fn merge_pr(
2929        &self,
2930        repo: &str,
2931        pr_number: u64,
2932        delete_branch: bool,
2933        head_sha: &str,
2934    ) -> anyhow::Result<()> {
2935        if !is_full_commit_sha(head_sha) {
2936            anyhow::bail!("merge_pr requires the full head sha, got {head_sha:?}");
2937        }
2938        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/merge");
2939        Self::check_backoff(&url)?;
2940        let payload = merge_pr_body(head_sha);
2941        let auth = self.auth_header(&url).await?;
2942        let make_req = || {
2943            Ok(self
2944                .client
2945                .put(&url)
2946                .json(&payload)
2947                .header(header::AUTHORIZATION, auth.clone())
2948                .header(header::ACCEPT, "application/vnd.github+json")
2949                .header("X-GitHub-Api-Version", "2022-11-28"))
2950        };
2951        let resp = self.send_with_retries(make_req, false).await?;
2952        let status = resp.status();
2953        if !status.is_success() {
2954            let body = resp.text().await.unwrap_or_default();
2955            anyhow::bail!("GitHub PR merge failed ({status}): {body}");
2956        }
2957        Self::record_success();
2958
2959        // Delete branch if requested
2960        if delete_branch {
2961            // Get the head ref (branch name) from the PR
2962            let pr: serde_json::Value = self
2963                .get_json(&format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}"))
2964                .await?;
2965            if let Some(ref_name) = pr.pointer("/head/ref").and_then(|v| v.as_str()) {
2966                let del_url = format!("{GITHUB_API}/repos/{repo}/git/refs/heads/{ref_name}");
2967                if let Err(e) = self.delete(&del_url).await {
2968                    let err_str = e.to_string();
2969                    if err_str.contains("Reference does not exist") {
2970                        tracing::debug!(
2971                            ref_name,
2972                            "branch already gone (GitHub auto-deleted on merge)"
2973                        );
2974                    } else {
2975                        tracing::warn!(ref_name, err = %e, "failed to delete branch after merge");
2976                    }
2977                }
2978            }
2979        }
2980        Ok(())
2981    }
2982
2983    /// Update a PR's branch by merging the latest base branch into it
2984    /// (equivalent of the "Update branch" button on GitHub, or `gh pr
2985    /// update-branch`). Produces a new merge commit on the head branch,
2986    /// which re-triggers CI — used to give a PR a chance to pick up a fix
2987    /// that landed on the base branch after the PR's last CI run failed.
2988    pub async fn update_pr_branch(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2989        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/update-branch");
2990        Self::check_backoff(&url)?;
2991        let auth = self.auth_header(&url).await?;
2992        let make_req = || {
2993            Ok(self
2994                .client
2995                .put(&url)
2996                .header(header::AUTHORIZATION, auth.clone())
2997                .header(header::ACCEPT, "application/vnd.github+json")
2998                .header("X-GitHub-Api-Version", "2022-11-28"))
2999        };
3000        let resp = self.send_with_retries(make_req, false).await?;
3001        let status = resp.status();
3002        if !status.is_success() {
3003            let body = resp.text().await.unwrap_or_default();
3004            Self::maybe_record_rate_limit_from_body(status, &body);
3005            anyhow::bail!("GitHub PR update-branch failed ({status}): {body}");
3006        }
3007        Self::record_success();
3008        Ok(())
3009    }
3010
3011    /// Enable auto-merge on a PR via GraphQL.
3012    ///
3013    /// GitHub will automatically merge the PR once all required checks pass.
3014    pub async fn enable_auto_merge(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
3015        let parts: Vec<&str> = repo.split('/').collect();
3016        if parts.len() != 2 {
3017            anyhow::bail!("invalid repo format: {repo}");
3018        }
3019        let (owner, repo_name) = (parts[0], parts[1]);
3020
3021        // First get the PR node ID
3022        let pr_query = r"query($owner: String!, $name: String!, $number: Int!) {
3023            repository(owner: $owner, name: $name) {
3024                pullRequest(number: $number) { id }
3025            }
3026        }";
3027        let body = self
3028            .graphql_with_vars(
3029                pr_query,
3030                serde_json::json!({
3031                    "owner": owner,
3032                    "name": repo_name,
3033                    "number": pr_number,
3034                }),
3035            )
3036            .await?;
3037        let pr_id = body
3038            .pointer("/data/repository/pullRequest/id")
3039            .and_then(|v| v.as_str())
3040            .ok_or_else(|| anyhow::anyhow!("could not get PR node ID"))?
3041            .to_string();
3042
3043        // Enable auto-merge with squash
3044        let mutation = r"mutation($prId: ID!) {
3045            enablePullRequestAutoMerge(input: {pullRequestId: $prId, mergeMethod: SQUASH}) {
3046                pullRequest { autoMergeRequest { enabledAt } }
3047            }
3048        }";
3049        let body = self
3050            .graphql_with_vars(mutation, serde_json::json!({ "prId": pr_id }))
3051            .await?;
3052        if let Some(errors) = body.get("errors") {
3053            anyhow::bail!("enable auto-merge GraphQL error: {errors}");
3054        }
3055
3056        tracing::info!(repo, pr_number, "auto-merge enabled on PR");
3057        Ok(())
3058    }
3059
3060    /// Get sub-issues via GraphQL (paginated).
3061    pub async fn get_sub_issues(&self, repo: &str, number: &str) -> anyhow::Result<Vec<u64>> {
3062        let parts: Vec<&str> = repo.split('/').collect();
3063        if parts.len() != 2 {
3064            anyhow::bail!("invalid repo format: expected 'owner/repo', got '{repo}'");
3065        }
3066        let (owner, repo_name) = (parts[0], parts[1]);
3067        let number = match parse_positive_issue_number(number) {
3068            Ok(number) => number,
3069            Err(e) => {
3070                tracing::debug!(repo, issue = number, ?e, "skipping sub-issues lookup");
3071                return Ok(Vec::new());
3072            }
3073        };
3074
3075        let mut all_numbers: Vec<u64> = Vec::new();
3076        let mut cursor: Option<String> = None;
3077        let page_size = 100;
3078        let max_pages = 50;
3079        let mut page_count = 0;
3080
3081        loop {
3082            page_count += 1;
3083            if page_count > max_pages {
3084                tracing::warn!(
3085                    repo,
3086                    number,
3087                    "get_sub_issues hit max page limit ({max_pages})"
3088                );
3089                break;
3090            }
3091
3092            let (query, vars) = if let Some(ref c) = cursor {
3093                (
3094                    r"query($owner: String!, $name: String!, $number: Int!, $first: Int!, $after: String!) {
3095                    repository(owner: $owner, name: $name) {
3096                        issue(number: $number) {
3097                            subIssues(first: $first, after: $after) {
3098                                nodes { number }
3099                                pageInfo { hasNextPage endCursor }
3100                            }
3101                        }
3102                    }
3103                }",
3104                    serde_json::json!({
3105                        "owner": owner,
3106                        "name": repo_name,
3107                        "number": number,
3108                        "first": page_size,
3109                        "after": c,
3110                    }),
3111                )
3112            } else {
3113                (
3114                    r"query($owner: String!, $name: String!, $number: Int!, $first: Int!) {
3115                    repository(owner: $owner, name: $name) {
3116                        issue(number: $number) {
3117                            subIssues(first: $first) {
3118                                nodes { number }
3119                                pageInfo { hasNextPage endCursor }
3120                            }
3121                        }
3122                    }
3123                }",
3124                    serde_json::json!({
3125                        "owner": owner,
3126                        "name": repo_name,
3127                        "number": number,
3128                        "first": page_size,
3129                    }),
3130                )
3131            };
3132
3133            let result = self
3134                .graphql_with_headers_and_vars(query, &["GraphQL-Features:sub_issues"], vars)
3135                .await?;
3136
3137            let sub_issues_data = result
3138                .get("data")
3139                .and_then(|d| d.get("repository"))
3140                .and_then(|r| r.get("issue"))
3141                .and_then(|i| i.get("subIssues"));
3142
3143            let nodes = sub_issues_data
3144                .and_then(|s| s.get("nodes"))
3145                .and_then(|n| n.as_array());
3146
3147            match nodes {
3148                Some(nodes) => {
3149                    let numbers: Vec<u64> = nodes
3150                        .iter()
3151                        .filter_map(|n| n.get("number").and_then(serde_json::Value::as_u64))
3152                        .collect();
3153                    all_numbers.extend(numbers);
3154                }
3155                None => break,
3156            }
3157
3158            let page_info = sub_issues_data.and_then(|s| s.get("pageInfo"));
3159            let has_next = page_info
3160                .and_then(|p| p.get("hasNextPage"))
3161                .and_then(serde_json::Value::as_bool)
3162                .unwrap_or(false);
3163
3164            if !has_next {
3165                break;
3166            }
3167
3168            cursor = page_info
3169                .and_then(|p| p.get("endCursor"))
3170                .and_then(|c| c.as_str())
3171                .map(ToString::to_string);
3172        }
3173
3174        Ok(all_numbers)
3175    }
3176
3177    /// Get combined CI check status for a git ref
3178    ///
3179    /// Counts come from [`Self::get_check_runs`], which requests `filter=latest`
3180    /// and follows pagination, so a failure or in-progress run past the first page still counts
3181    pub async fn get_combined_status(
3182        &self,
3183        repo: &str,
3184        git_ref: &str,
3185        has_workflows: bool,
3186        mergeable_state: Option<&str>,
3187    ) -> anyhow::Result<(String, u64, u64, u64, u64)> {
3188        let runs = self.get_check_runs(repo, git_ref).await?;
3189        let (total, passing, failing, pending) = Self::count_ci_runs(&runs);
3190        let state =
3191            Self::combined_status_state(total, failing, pending, has_workflows, mergeable_state);
3192
3193        Ok((state, total, passing, failing, pending))
3194    }
3195
3196    /// Count CI runs as (total, passing, failing, pending), skipping the review's own checks
3197    fn count_ci_runs(runs: &[types::GitHubCheckRun]) -> (u64, u64, u64, u64) {
3198        let mut total = 0u64;
3199        let mut passing = 0u64;
3200        let mut failing = 0u64;
3201        let mut pending = 0u64;
3202
3203        for run in runs.iter().filter(|r| !review_gate::is_own_check(&r.name)) {
3204            total += 1;
3205            if !run.is_finished() {
3206                pending += 1;
3207            } else if run.is_passed() {
3208                passing += 1;
3209            } else {
3210                failing += 1;
3211            }
3212        }
3213
3214        (total, passing, failing, pending)
3215    }
3216
3217    /// Rerun the latest failed workflow run for a given workflow name and branch.
3218    ///
3219    /// Finds the most recent failed (or cancelled) run of `workflow_name` on
3220    /// `branch` triggered by a `push` event, then calls the GitHub Actions
3221    /// rerun endpoint so the **same check run** on the commit flips green.
3222    pub async fn rerun_failed_workflow(
3223        &self,
3224        repo: &str,
3225        workflow_name: &str,
3226        branch: &str,
3227    ) -> anyhow::Result<()> {
3228        // List recent runs for this branch, filtered to push events
3229        let url = format!(
3230            "{GITHUB_API}/repos/{repo}/actions/runs?branch={branch}&event=push&per_page=10"
3231        );
3232        let resp: serde_json::Value = self.get_json(&url).await?;
3233        let runs = resp["workflow_runs"]
3234            .as_array()
3235            .ok_or_else(|| anyhow::anyhow!("no workflow_runs array in response"))?;
3236
3237        // Find the latest failed/cancelled run matching the workflow name
3238        let run_id = runs
3239            .iter()
3240            .find(|r| {
3241                r["name"].as_str() == Some(workflow_name)
3242                    && matches!(r["conclusion"].as_str(), Some("failure" | "cancelled"))
3243            })
3244            .and_then(|r| r["id"].as_u64())
3245            .ok_or_else(|| {
3246                anyhow::anyhow!(
3247                    "no failed run found for workflow '{workflow_name}' on branch '{branch}'"
3248                )
3249            })?;
3250
3251        // POST rerun — no body needed
3252        let rerun_url = format!("{GITHUB_API}/repos/{repo}/actions/runs/{run_id}/rerun");
3253        let auth = self.auth_header(&rerun_url).await?;
3254        let make_req = || {
3255            Ok(self
3256                .client
3257                .post(&rerun_url)
3258                .header(header::AUTHORIZATION, auth.clone())
3259                .header(header::ACCEPT, "application/vnd.github+json")
3260                .header("X-GitHub-Api-Version", "2022-11-28"))
3261        };
3262        let resp = self.send_with_retries(make_req, false).await?;
3263        let status = resp.status();
3264        if !status.is_success() {
3265            let body = resp.text().await.unwrap_or_default();
3266            Self::maybe_record_rate_limit_from_body(status, &body);
3267            anyhow::bail!("GitHub API POST rerun {rerun_url} failed ({status}): {body}");
3268        }
3269
3270        Ok(())
3271    }
3272
3273    /// Fetch reviews, review comments, and issue comments for multiple PRs in a
3274    /// single GraphQL query instead of 4–5 REST calls per PR.
3275    ///
3276    /// Returns a map of `pr_number → PrReviewBatchData`.
3277    /// PRs missing from the response are omitted from the result.
3278    pub async fn batch_fetch_pr_review_data(
3279        &self,
3280        repo: &str,
3281        pr_numbers: &[u64],
3282    ) -> anyhow::Result<HashMap<u64, PrReviewBatchData>> {
3283        if pr_numbers.is_empty() {
3284            return Ok(HashMap::new());
3285        }
3286
3287        let (owner, name) = repo
3288            .split_once('/')
3289            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
3290
3291        // Build one GraphQL alias per PR number.
3292        let aliases: String = pr_numbers
3293            .iter()
3294            .map(|&n| build_pr_review_alias(n))
3295            .collect::<Vec<_>>()
3296            .join("\n");
3297
3298        let query = format!(
3299            r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
3300        );
3301
3302        let resp = self
3303            .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
3304            .await?;
3305        let repo_data = resp
3306            .pointer("/data/repository")
3307            .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
3308
3309        let mut result = HashMap::new();
3310        for &n in pr_numbers {
3311            let Some(pr_data) = repo_data.get(format!("pr{n}")) else {
3312                continue;
3313            };
3314
3315            let merged = pr_data
3316                .get("merged")
3317                .and_then(serde_json::Value::as_bool)
3318                .unwrap_or(false);
3319            let mergeable = match pr_data.get("mergeable").and_then(|v| v.as_str()) {
3320                Some("MERGEABLE") => Some(true),
3321                Some("CONFLICTING") => Some(false),
3322                _ => None, // UNKNOWN or missing
3323            };
3324
3325            let mut reviews: Vec<GitHubReview> = pr_data
3326                .pointer("/reviews/nodes")
3327                .and_then(|v| v.as_array())
3328                .map(|nodes| nodes.iter().filter_map(parse_graphql_review).collect())
3329                .unwrap_or_default();
3330
3331            if connection_has_next_page(pr_data.pointer("/reviews/pageInfo")) {
3332                tracing::warn!(
3333                    pr_number = n,
3334                    fetched = reviews.len(),
3335                    "batch review fetch truncated reviews connection at first page"
3336                );
3337            }
3338
3339            // Ensure deterministic ordering by submitted timestamp (oldest -> newest).
3340            // GraphQL connections do not guarantee a stable sort unless explicitly
3341            // requested. Sort here so consumers can rely on chronological order.
3342            reviews.sort_by(|a, b| a.submitted_at.cmp(&b.submitted_at));
3343
3344            let mut review_comments: Vec<GitHubReviewComment> = pr_data
3345                .pointer("/reviewThreads/nodes")
3346                .and_then(|v| v.as_array())
3347                .map(|threads| {
3348                    threads
3349                        .iter()
3350                        .filter_map(|thread| {
3351                            thread
3352                                .pointer("/comments/nodes")
3353                                .and_then(|v| v.as_array())
3354                                .map(|nodes| {
3355                                    nodes
3356                                        .iter()
3357                                        .filter_map(parse_graphql_review_comment)
3358                                        .collect::<Vec<_>>()
3359                                })
3360                        })
3361                        .flatten()
3362                        .collect()
3363                })
3364                .unwrap_or_default();
3365
3366            if connection_has_next_page(pr_data.pointer("/reviewThreads/pageInfo")) {
3367                tracing::warn!(
3368                    pr_number = n,
3369                    fetched_threads = pr_data
3370                        .pointer("/reviewThreads/nodes")
3371                        .and_then(|v| v.as_array())
3372                        .map_or(0, Vec::len),
3373                    "batch review fetch truncated reviewThreads connection at first page"
3374                );
3375            }
3376            if pr_data
3377                .pointer("/reviewThreads/nodes")
3378                .and_then(|v| v.as_array())
3379                .is_some_and(|threads| {
3380                    threads.iter().any(|thread| {
3381                        connection_has_next_page(thread.pointer("/comments/pageInfo"))
3382                    })
3383                })
3384            {
3385                tracing::warn!(
3386                    pr_number = n,
3387                    "batch review fetch truncated one or more review thread comment connections"
3388                );
3389            }
3390
3391            // Sort inline review comments by created_at (oldest -> newest) so
3392            // callers can process them deterministically.
3393            review_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
3394
3395            let mut issue_comments: Vec<GitHubComment> = pr_data
3396                .pointer("/comments/nodes")
3397                .and_then(|v| v.as_array())
3398                .map(|nodes| {
3399                    nodes
3400                        .iter()
3401                        .filter_map(parse_graphql_issue_comment)
3402                        .collect()
3403                })
3404                .unwrap_or_default();
3405
3406            if let Some(cursor) = connection_end_cursor(pr_data.pointer("/comments/pageInfo")) {
3407                issue_comments.extend(
3408                    self.fetch_pr_issue_comments_after(owner, name, n, Some(cursor))
3409                        .await?,
3410                );
3411            }
3412
3413            // Sort issue-level comments by created_at (oldest -> newest). The
3414            // review poll logic expects chronological ordering and may iterate
3415            // in reverse to find the latest comments — so ensure a consistent
3416            // ordering here regardless of GraphQL's default.
3417            issue_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
3418
3419            result.insert(
3420                n,
3421                PrReviewBatchData {
3422                    merged,
3423                    head_sha: pr_data
3424                        .get("headRefOid")
3425                        .and_then(|v| v.as_str())
3426                        .unwrap_or_default()
3427                        .to_string(),
3428                    mergeable,
3429                    reviews,
3430                    review_comments,
3431                    issue_comments,
3432                },
3433            );
3434        }
3435
3436        Ok(result)
3437    }
3438
3439    async fn fetch_pr_issue_comments_after(
3440        &self,
3441        owner: &str,
3442        name: &str,
3443        pr_number: u64,
3444        mut cursor: Option<String>,
3445    ) -> anyhow::Result<Vec<GitHubComment>> {
3446        let mut comments = Vec::new();
3447        let mut page_count = 0;
3448        let max_pages = 50;
3449
3450        while let Some(current_cursor) = cursor.take() {
3451            page_count += 1;
3452            if page_count > max_pages {
3453                tracing::warn!(
3454                    pr_number,
3455                    fetched = comments.len(),
3456                    "stopping PR issue comment pagination after max page limit"
3457                );
3458                break;
3459            }
3460
3461            let (query, vars) =
3462                build_pr_issue_comments_page_query(owner, name, pr_number, &current_cursor);
3463            let resp = self.graphql_with_vars(&query, vars).await?;
3464            let comments_data = resp
3465                .pointer("/data/repository/pullRequest/comments")
3466                .ok_or_else(|| {
3467                    anyhow::anyhow!(
3468                        "missing /data/repository/pullRequest/comments in GraphQL response"
3469                    )
3470                })?;
3471
3472            comments.extend(
3473                comments_data
3474                    .get("nodes")
3475                    .and_then(|v| v.as_array())
3476                    .into_iter()
3477                    .flatten()
3478                    .filter_map(parse_graphql_issue_comment),
3479            );
3480
3481            cursor = connection_end_cursor(comments_data.get("pageInfo"));
3482        }
3483
3484        Ok(comments)
3485    }
3486
3487    /// Check the latest automated review comment on a PR.
3488    pub async fn get_automated_review_status(
3489        &self,
3490        repo: &str,
3491        pr_number: u64,
3492    ) -> anyhow::Result<Option<String>> {
3493        let comments = self.list_comments(repo, &pr_number.to_string()).await?;
3494
3495        // Find the most recent automated review comment authored by a collaborator or the App
3496        let app_login = super::app::bot_login().await;
3497        let mut newest: Option<&types::GitHubComment> = None;
3498        for c in &comments {
3499            if !c.body.starts_with("## Automated Review") {
3500                continue;
3501            }
3502            let trusted = match app_login.as_deref() {
3503                Some(app) if super::app::same_login(&c.user.login, app) => Ok(true),
3504                _ => self.is_collaborator(repo, &c.user.login).await,
3505            };
3506            match trusted {
3507                Ok(true) => match newest {
3508                    None => newest = Some(c),
3509                    Some(prev) => {
3510                        if c.created_at > prev.created_at {
3511                            newest = Some(c);
3512                        }
3513                    }
3514                },
3515                Ok(false) => {
3516                    tracing::warn!(
3517                        user = %c.user.login,
3518                        pr_number,
3519                        "ignoring automated review comment from non-collaborator"
3520                    );
3521                }
3522                Err(e) => {
3523                    tracing::debug!(
3524                        user = %c.user.login,
3525                        error = %e,
3526                        "failed to check collaborator status, skipping comment"
3527                    );
3528                }
3529            }
3530        }
3531
3532        match newest {
3533            Some(c) => {
3534                let first_line = c.body.lines().next().unwrap_or("");
3535                if first_line.contains("Automated Review \u{2014} Approve") {
3536                    Ok(Some("approve".to_string()))
3537                } else if first_line.contains("Automated Review \u{2014} Changes Requested") {
3538                    Ok(Some("changes_requested".to_string()))
3539                } else {
3540                    Ok(None)
3541                }
3542            }
3543            None => Ok(None),
3544        }
3545    }
3546}
3547
3548/// Read `behind_by` out of a compare response.
3549///
3550/// A missing field is an error, not zero: treating an unreadable response as
3551/// "head is up to date" would let a stale PR merge
3552/// A commit's parents, first parent first, and the GitHub accounts behind it
3553#[derive(Debug, Default, PartialEq)]
3554pub struct CommitMeta {
3555    pub parents: Vec<String>,
3556    pub author_login: Option<String>,
3557    pub committer_login: Option<String>,
3558}
3559
3560fn parse_commit_meta(commit: &serde_json::Value) -> CommitMeta {
3561    let login = |field: &str| {
3562        commit
3563            .pointer(&format!("/{field}/login"))
3564            .and_then(|v| v.as_str())
3565            .map(String::from)
3566    };
3567    CommitMeta {
3568        parents: commit
3569            .get("parents")
3570            .and_then(|p| p.as_array())
3571            .map(|parents| {
3572                parents
3573                    .iter()
3574                    .filter_map(|p| p.get("sha").and_then(|s| s.as_str()).map(String::from))
3575                    .collect()
3576            })
3577            .unwrap_or_default(),
3578        author_login: login("author"),
3579        committer_login: login("committer"),
3580    }
3581}
3582
3583fn parse_behind_by(body: &serde_json::Value) -> anyhow::Result<u64> {
3584    body.get("behind_by")
3585        .and_then(serde_json::Value::as_u64)
3586        .ok_or_else(|| anyhow::anyhow!("compare response has no numeric behind_by field"))
3587}
3588
3589/// A branch protection read that means "no protection": 404 "Branch not protected", or the 403
3590/// GitHub returns for private repos on the Free plan
3591fn is_no_branch_protection_error(err: &str) -> bool {
3592    err.contains("404")
3593        || (err.contains("403")
3594            && err.contains("Upgrade to GitHub Pro or make this repository public"))
3595}
3596
3597pub(crate) const REQUIRED_CHECK_RULESET_NAME: &str = "orch required checks";
3598
3599#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3600pub(crate) enum RulesetCreateKind {
3601    CheckNeverRun,
3602    NameTaken,
3603    Refused,
3604    Retryable,
3605    Other,
3606}
3607
3608pub(crate) fn required_check_ruleset_payload(checks: &[RequiredStatusCheck]) -> serde_json::Value {
3609    let required: Vec<serde_json::Value> = checks
3610        .iter()
3611        .map(|check| {
3612            if let Some(id) = check.integration_id {
3613                serde_json::json!({ "context": check.context, "integration_id": id })
3614            } else {
3615                serde_json::json!({ "context": check.context })
3616            }
3617        })
3618        .collect();
3619    serde_json::json!({
3620        "name": REQUIRED_CHECK_RULESET_NAME,
3621        "target": "branch",
3622        "enforcement": "active",
3623        "conditions": {
3624            "ref_name": {
3625                "include": ["~DEFAULT_BRANCH"],
3626                "exclude": []
3627            }
3628        },
3629        "rules": [{
3630            "type": "required_status_checks",
3631            "parameters": {
3632                "strict_required_status_checks_policy": true,
3633                "do_not_enforce_on_create": false,
3634                "required_status_checks": required
3635            }
3636        }]
3637    })
3638}
3639
3640pub(crate) fn classify_ruleset_create_error(err: &str) -> RulesetCreateKind {
3641    let lower = err.to_ascii_lowercase();
3642    if lower.contains("already been taken") || lower.contains("name already exists") {
3643        return RulesetCreateKind::NameTaken;
3644    }
3645    if lower.contains("not a valid check")
3646        || lower.contains("required to be present is not found")
3647        || (lower.contains("422") && lower.contains("status check") && lower.contains("not found"))
3648    {
3649        return RulesetCreateKind::CheckNeverRun;
3650    }
3651    if lower.contains("(500")
3652        || lower.contains("(502")
3653        || lower.contains("(503")
3654        || lower.contains("(504")
3655        || lower.contains("(429")
3656    {
3657        return RulesetCreateKind::Retryable;
3658    }
3659    // "(401" / "(403" is the status token, a 422 body can contain those digits
3660    if lower.contains("(403")
3661        || lower.contains("(401")
3662        || lower.contains("upgrade to github pro")
3663        || lower.contains("not accessible")
3664    {
3665        return RulesetCreateKind::Refused;
3666    }
3667    // timeout and transport errors never include an HTTP status
3668    if !has_http_status_token(&lower) {
3669        return RulesetCreateKind::Retryable;
3670    }
3671    RulesetCreateKind::Other
3672}
3673
3674fn has_http_status_token(err: &str) -> bool {
3675    err.match_indices('(').any(|(i, _)| {
3676        err.as_bytes()
3677            .get(i + 1..i + 4)
3678            .is_some_and(|digits| digits.iter().all(u8::is_ascii_digit))
3679    })
3680}
3681
3682/// Classic protection prefers `checks` (includes `app_id`) and falls back to `contexts`
3683fn parse_classic_required_status_checks(value: &serde_json::Value) -> Vec<RequiredStatusCheck> {
3684    if let Some(checks) = value
3685        .pointer("/required_status_checks/checks")
3686        .and_then(|v| v.as_array())
3687    {
3688        let parsed: Vec<RequiredStatusCheck> =
3689            checks.iter().filter_map(parse_classic_check).collect();
3690        if !parsed.is_empty() {
3691            return parsed;
3692        }
3693    }
3694
3695    value
3696        .pointer("/required_status_checks/contexts")
3697        .and_then(|v| v.as_array())
3698        .map(|contexts| {
3699            contexts
3700                .iter()
3701                .filter_map(|context| {
3702                    context.as_str().map(|s| RequiredStatusCheck {
3703                        context: s.to_string(),
3704                        integration_id: None,
3705                    })
3706                })
3707                .collect()
3708        })
3709        .unwrap_or_default()
3710}
3711
3712fn parse_classic_check(check: &serde_json::Value) -> Option<RequiredStatusCheck> {
3713    let context = check.get("context")?.as_str()?.to_string();
3714    let integration_id = check
3715        .get("app_id")
3716        .and_then(serde_json::Value::as_i64)
3717        .filter(|&id| id > 0);
3718    Some(RequiredStatusCheck {
3719        context,
3720        integration_id,
3721    })
3722}
3723
3724/// Collect `required_status_checks` entries from every active `required_status_checks` rule
3725fn parse_ruleset_required_status_checks(rules: &[serde_json::Value]) -> Vec<RequiredStatusCheck> {
3726    let mut out = Vec::new();
3727    for rule in rules {
3728        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3729            continue;
3730        }
3731        let Some(checks) = rule
3732            .pointer("/parameters/required_status_checks")
3733            .or_else(|| rule.get("required_status_checks"))
3734            .and_then(|v| v.as_array())
3735        else {
3736            continue;
3737        };
3738        for check in checks {
3739            let Some(context) = check.get("context").and_then(|v| v.as_str()) else {
3740                continue;
3741            };
3742            let integration_id = check
3743                .get("integration_id")
3744                .and_then(serde_json::Value::as_i64)
3745                .filter(|&id| id > 0);
3746            out.push(RequiredStatusCheck {
3747                context: context.to_string(),
3748                integration_id,
3749            });
3750        }
3751    }
3752    out
3753}
3754
3755fn merge_required_status_checks(
3756    mut checks: Vec<RequiredStatusCheck>,
3757    extra: Vec<RequiredStatusCheck>,
3758) -> Vec<RequiredStatusCheck> {
3759    checks.extend(extra);
3760    let mut seen = HashSet::new();
3761    checks.retain(|c| seen.insert((c.context.clone(), c.integration_id)));
3762    checks
3763}
3764
3765fn sanitize_github_issue_numbers(issue_numbers: &[u64]) -> (Vec<u64>, Vec<u64>) {
3766    let mut valid = Vec::with_capacity(issue_numbers.len());
3767    let mut invalid = Vec::new();
3768    for &issue_number in issue_numbers {
3769        if issue_number == 0 {
3770            invalid.push(issue_number);
3771        } else {
3772            valid.push(issue_number);
3773        }
3774    }
3775    (valid, invalid)
3776}
3777
3778// ── Public metrics ───────────────────────────────────────────────────
3779
3780/// Snapshot of GitHub API rate-limit metrics.
3781#[derive(Debug, Clone)]
3782pub struct RateLimitMetrics {
3783    /// Total 403/429 rate-limit responses received (REST + GraphQL combined).
3784    pub hits: u64,
3785    /// Calls skipped because the quota was low or a backoff was active.
3786    pub skipped_calls: u64,
3787    /// Current REST remaining quota (None if not yet observed).
3788    pub rest_remaining: Option<u32>,
3789    /// UTC epoch second when the REST window resets (None if not yet observed).
3790    pub rest_reset_at: Option<u64>,
3791    /// Current GraphQL remaining quota (None if not yet observed).
3792    pub graphql_remaining: Option<u32>,
3793    /// Total 5xx server error responses received (REST + GraphQL combined).
3794    pub five_xx_hits: u64,
3795}
3796
3797/// Return a snapshot of GitHub API rate-limit metrics.
3798pub fn rate_limit_metrics() -> RateLimitMetrics {
3799    let (rest_remaining, rest_reset_at) = REST_RATE_LIMIT
3800        .lock()
3801        .ok()
3802        .map_or((None, None), |rl| (rl.remaining, rl.reset_at));
3803    let graphql_remaining = GRAPHQL_RATE_LIMIT.lock().ok().and_then(|rl| rl.remaining);
3804    RateLimitMetrics {
3805        hits: METRIC_RATE_LIMIT_HITS.load(Ordering::Relaxed),
3806        skipped_calls: METRIC_PROACTIVE_THROTTLES.load(Ordering::Relaxed),
3807        rest_remaining,
3808        rest_reset_at,
3809        graphql_remaining,
3810        five_xx_hits: METRIC_5XX_HITS.load(Ordering::Relaxed),
3811    }
3812}
3813
3814// ── Link header parser ───────────────────────────────────────────────
3815
3816/// Parse the `Link` header to find the `rel="next"` URL.
3817fn parse_link_next(headers: &header::HeaderMap) -> Option<String> {
3818    let link = headers.get("link")?.to_str().ok()?;
3819    for part in link.split(',') {
3820        let part = part.trim();
3821        if part.contains("rel=\"next\"") {
3822            // Extract URL between < and >
3823            let start = part.find('<')? + 1;
3824            let end = part.find('>')?;
3825            if start >= end {
3826                return None;
3827            }
3828            return Some(part[start..end].to_string());
3829        }
3830    }
3831    None
3832}
3833
3834/// Return the hex color string for a given `status:*` label.
3835pub fn status_label_color(label: &str) -> &'static str {
3836    match label {
3837        "status:new" => "0e8a16",
3838        "status:routed" => "1d76db",
3839        "status:in_progress" => "fbca04",
3840        "status:done" => "6f42c1",
3841        "status:blocked" => "d73a4a",
3842        "status:in_review" => "0075ca",
3843        "status:approved" => "2ea44f",
3844        "status:needs_review" => "e4e669",
3845        "status:waiting" => "5319e7",
3846        _ => "c5def5",
3847    }
3848}
3849
3850// ── Batch GraphQL helpers ─────────────────────────────────────────────
3851
3852/// Data fetched for one PR by [`GhHttp::batch_fetch_pr_review_data`].
3853#[derive(Debug, Clone, Default)]
3854pub struct PrReviewBatchData {
3855    /// True when the pull request was merged.
3856    pub merged: bool,
3857    /// Head commit of the pull request, empty when GitHub did not return it.
3858    pub head_sha: String,
3859    /// `Some(true)` = MERGEABLE, `Some(false)` = CONFLICTING, `None` = UNKNOWN.
3860    pub mergeable: Option<bool>,
3861    /// All reviews submitted on the PR.
3862    pub reviews: Vec<GitHubReview>,
3863    /// All inline review comments (from all review threads).
3864    pub review_comments: Vec<GitHubReviewComment>,
3865    /// All issue-level comments on the PR.
3866    pub issue_comments: Vec<GitHubComment>,
3867}
3868
3869/// Build a GraphQL alias fragment for one pull request, fetching all data
3870/// needed by the review poll loop in a single batch request.
3871fn build_pr_review_alias(n: u64) -> String {
3872    format!(
3873        r"pr{n}: pullRequest(number: {n}) {{
3874  merged
3875  mergeable
3876  headRefOid
3877  reviews(first: 50) {{
3878    nodes {{
3879      databaseId
3880      author {{ login }}
3881      body
3882      state
3883      url
3884      submittedAt
3885      commit {{ oid }}
3886    }}
3887    pageInfo {{ hasNextPage }}
3888  }}
3889  reviewThreads(first: 50) {{
3890    nodes {{
3891      comments(first: 20) {{
3892        nodes {{
3893          databaseId
3894          author {{ login }}
3895          body
3896          path
3897          line
3898          originalLine
3899          commit {{ oid }}
3900          originalCommit {{ oid }}
3901          url
3902          createdAt
3903          updatedAt
3904          replyTo {{ databaseId }}
3905          diffHunk
3906        }}
3907        pageInfo {{ hasNextPage }}
3908      }}
3909    }}
3910    pageInfo {{ hasNextPage }}
3911  }}
3912  comments(first: 50) {{
3913    nodes {{
3914      databaseId
3915      author {{ login }}
3916      body
3917      createdAt
3918      updatedAt
3919      url
3920    }}
3921    pageInfo {{ hasNextPage endCursor }}
3922  }}
3923}}"
3924    )
3925}
3926
3927fn build_pr_issue_comments_page_query(
3928    owner: &str,
3929    name: &str,
3930    pr_number: u64,
3931    after_cursor: &str,
3932) -> (String, serde_json::Value) {
3933    let query = r"query($owner: String!, $name: String!, $number: Int!, $after: String!) {
3934  repository(owner: $owner, name: $name) {
3935    pullRequest(number: $number) {
3936      comments(first: 100, after: $after) {
3937        nodes {
3938          databaseId
3939          author { login }
3940          body
3941          createdAt
3942          updatedAt
3943          url
3944        }
3945        pageInfo { hasNextPage endCursor }
3946      }
3947    }
3948  }
3949}"
3950    .to_string();
3951    let vars = serde_json::json!({
3952        "owner": owner,
3953        "name": name,
3954        "number": pr_number,
3955        "after": after_cursor,
3956    });
3957    (query, vars)
3958}
3959
3960fn connection_has_next_page(page_info: Option<&serde_json::Value>) -> bool {
3961    page_info
3962        .and_then(|v| v.get("hasNextPage"))
3963        .and_then(serde_json::Value::as_bool)
3964        .unwrap_or(false)
3965}
3966
3967fn connection_end_cursor(page_info: Option<&serde_json::Value>) -> Option<String> {
3968    if !connection_has_next_page(page_info) {
3969        return None;
3970    }
3971
3972    page_info
3973        .and_then(|v| v.get("endCursor"))
3974        .and_then(|v| v.as_str())
3975        .map(str::to_owned)
3976}
3977
3978fn parse_graphql_review(node: &serde_json::Value) -> Option<GitHubReview> {
3979    Some(GitHubReview {
3980        id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
3981        user: GitHubUser {
3982            login: node
3983                .pointer("/author/login")
3984                .and_then(|v| v.as_str())?
3985                .to_string(),
3986        },
3987        body: node.get("body").and_then(|v| v.as_str()).map(String::from),
3988        state: node.get("state").and_then(|v| v.as_str())?.to_string(),
3989        html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
3990        submitted_at: node
3991            .get("submittedAt")
3992            .and_then(|v| v.as_str())
3993            .unwrap_or("")
3994            .to_string(),
3995        commit_id: node
3996            .pointer("/commit/oid")
3997            .and_then(|v| v.as_str())
3998            .map(String::from),
3999    })
4000}
4001
4002fn parse_graphql_review_comment(node: &serde_json::Value) -> Option<GitHubReviewComment> {
4003    Some(GitHubReviewComment {
4004        id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
4005        user: GitHubUser {
4006            login: node
4007                .pointer("/author/login")
4008                .and_then(|v| v.as_str())?
4009                .to_string(),
4010        },
4011        body: node.get("body").and_then(|v| v.as_str())?.to_string(),
4012        path: node
4013            .get("path")
4014            .and_then(|v| v.as_str())
4015            .unwrap_or("")
4016            .to_string(),
4017        line: node
4018            .get("line")
4019            .and_then(serde_json::Value::as_u64)
4020            .and_then(|v| u32::try_from(v).ok()),
4021        original_line: node
4022            .get("originalLine")
4023            .and_then(serde_json::Value::as_u64)
4024            .and_then(|v| u32::try_from(v).ok()),
4025        commit_id: node
4026            .pointer("/commit/oid")
4027            .and_then(|v| v.as_str())
4028            .unwrap_or("")
4029            .to_string(),
4030        original_commit_id: node
4031            .pointer("/originalCommit/oid")
4032            .and_then(|v| v.as_str())
4033            .unwrap_or("")
4034            .to_string(),
4035        html_url: node
4036            .get("url")
4037            .and_then(|v| v.as_str())
4038            .unwrap_or("")
4039            .to_string(),
4040        created_at: node
4041            .get("createdAt")
4042            .and_then(|v| v.as_str())
4043            .unwrap_or("")
4044            .to_string(),
4045        updated_at: node
4046            .get("updatedAt")
4047            .and_then(|v| v.as_str())
4048            .unwrap_or("")
4049            .to_string(),
4050        in_reply_to_id: node
4051            .pointer("/replyTo/databaseId")
4052            .and_then(serde_json::Value::as_u64),
4053        diff_hunk: node
4054            .get("diffHunk")
4055            .and_then(|v| v.as_str())
4056            .map(String::from),
4057    })
4058}
4059
4060fn parse_graphql_issue_comment(node: &serde_json::Value) -> Option<GitHubComment> {
4061    Some(GitHubComment {
4062        id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
4063        body: node.get("body").and_then(|v| v.as_str())?.to_string(),
4064        user: GitHubUser {
4065            login: node
4066                .pointer("/author/login")
4067                .and_then(|v| v.as_str())?
4068                .to_string(),
4069        },
4070        created_at: node
4071            .get("createdAt")
4072            .and_then(|v| v.as_str())
4073            .unwrap_or("")
4074            .to_string(),
4075        updated_at: node
4076            .get("updatedAt")
4077            .and_then(|v| v.as_str())
4078            .map(String::from),
4079        html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
4080        issue_url: None,
4081        author_association: None,
4082    })
4083}
4084
4085#[cfg(test)]
4086mod tests {
4087    // Secret redaction on posted bodies (wiremock)
4088    mod closed_pr;
4089    mod leak_redaction;
4090
4091    use std::env;
4092
4093    use super::*;
4094    use crate::github::token::TokenResolver;
4095    use tokio::io::{AsyncReadExt, AsyncWriteExt};
4096    use tokio::net::TcpListener;
4097
4098    #[test]
4099    fn repo_from_url_names_the_repository_or_nothing() {
4100        let api = "https://api.github.com";
4101        assert_eq!(
4102            repo_from_url(&format!("{api}/repos/me/a/pulls/9")).as_deref(),
4103            Some("me/a")
4104        );
4105        assert_eq!(
4106            repo_from_url(&format!("{api}/repos/org/b?per_page=1")).as_deref(),
4107            Some("org/b")
4108        );
4109        assert_eq!(
4110            repo_from_url(&format!("{api}/repos/org/b")).as_deref(),
4111            Some("org/b")
4112        );
4113        assert_eq!(repo_from_url(&format!("{api}/graphql")), None);
4114        assert_eq!(repo_from_url(&format!("{api}/user")), None);
4115        assert_eq!(repo_from_url(&format!("{api}/repos/only-owner")), None);
4116    }
4117
4118    #[test]
4119    fn no_branch_protection_errors() {
4120        let free_plan = "GitHub API GET https://api.github.com/repos/o/r/branches/main/protection failed (403 Forbidden): {\"message\":\"Upgrade to GitHub Pro or make this repository public to enable this feature.\"}";
4121        assert!(is_no_branch_protection_error(free_plan));
4122        assert!(is_no_branch_protection_error(
4123            "failed (404 Not Found): {\"message\":\"Branch not protected\"}"
4124        ));
4125        assert!(!is_no_branch_protection_error(
4126            "failed (403 Forbidden): {\"message\":\"Resource not accessible\"}"
4127        ));
4128    }
4129
4130    #[test]
4131    fn required_check_ruleset_payload_targets_the_default_branch() {
4132        let payload = required_check_ruleset_payload(&[
4133            RequiredStatusCheck {
4134                context: "test".to_string(),
4135                integration_id: Some(15368),
4136            },
4137            RequiredStatusCheck {
4138                context: "lint".to_string(),
4139                integration_id: None,
4140            },
4141        ]);
4142        assert_eq!(payload["name"], REQUIRED_CHECK_RULESET_NAME);
4143        assert_eq!(payload["target"], "branch");
4144        assert_eq!(
4145            payload["conditions"]["ref_name"]["include"],
4146            serde_json::json!(["~DEFAULT_BRANCH"])
4147        );
4148        assert_eq!(
4149            payload["rules"][0]["parameters"]["strict_required_status_checks_policy"],
4150            true
4151        );
4152        assert_eq!(
4153            payload["rules"][0]["parameters"]["required_status_checks"],
4154            serde_json::json!([
4155                { "context": "test", "integration_id": 15368 },
4156                { "context": "lint" }
4157            ])
4158        );
4159    }
4160
4161    #[test]
4162    fn classify_ruleset_create_error_splits_retry_from_refuse() {
4163        assert_eq!(
4164            classify_ruleset_create_error(
4165                "GitHub API POST https://api.github.com/repos/o/r/rulesets failed (422 Unprocessable Entity): {\"message\":\"Name has already been taken\"}"
4166            ),
4167            RulesetCreateKind::NameTaken
4168        );
4169        assert_eq!(
4170            classify_ruleset_create_error(
4171                "failed (422 Unprocessable Entity): Status check required to be present is not found"
4172            ),
4173            RulesetCreateKind::CheckNeverRun
4174        );
4175        assert_eq!(
4176            classify_ruleset_create_error("failed (422): ci/test was not a valid check"),
4177            RulesetCreateKind::CheckNeverRun
4178        );
4179        assert_eq!(
4180            classify_ruleset_create_error(
4181                "GitHub API POST /rulesets failed (403 Forbidden): {\"message\":\"Upgrade to GitHub Pro or make this repository public to enable this feature.\"}"
4182            ),
4183            RulesetCreateKind::Refused
4184        );
4185        assert_eq!(
4186            classify_ruleset_create_error("failed (500 Internal Server Error): boom"),
4187            RulesetCreateKind::Retryable
4188        );
4189        assert_eq!(
4190            classify_ruleset_create_error(
4191                "GitHub API POST /rulesets failed (429 Too Many Requests): {\"message\":\"API rate limit exceeded\"}"
4192            ),
4193            RulesetCreateKind::Retryable
4194        );
4195        assert_eq!(
4196            classify_ruleset_create_error(
4197                "HTTP request failed to send (transport error): connection reset by peer"
4198            ),
4199            RulesetCreateKind::Retryable
4200        );
4201        assert_eq!(
4202            classify_ruleset_create_error(
4203                "error sending request for url (https://api.github.com/repos/o/r/rulesets): operation timed out"
4204            ),
4205            RulesetCreateKind::Retryable
4206        );
4207        assert_eq!(
4208            classify_ruleset_create_error(
4209                "failed (422 Unprocessable Entity): {\"message\":\"Ruleset validation failed for rule 401\"}"
4210            ),
4211            RulesetCreateKind::Other
4212        );
4213        assert_eq!(
4214            classify_ruleset_create_error(
4215                "GitHub API POST /rulesets failed (401 Unauthorized): {\"message\":\"Bad credentials\"}"
4216            ),
4217            RulesetCreateKind::Refused
4218        );
4219    }
4220
4221    #[test]
4222    fn parse_classic_required_status_checks_reads_checks_app_id() {
4223        let value = serde_json::json!({
4224            "required_status_checks": {
4225                "contexts": ["ci/test"],
4226                "checks": [{ "context": "ci/test", "app_id": 42 }]
4227            }
4228        });
4229        assert_eq!(
4230            parse_classic_required_status_checks(&value),
4231            vec![RequiredStatusCheck {
4232                context: "ci/test".to_string(),
4233                integration_id: Some(42),
4234            }]
4235        );
4236    }
4237
4238    #[test]
4239    fn parse_classic_required_status_checks_falls_back_to_contexts() {
4240        let value = serde_json::json!({
4241            "required_status_checks": {
4242                "contexts": ["ci/test", "lint"]
4243            }
4244        });
4245        assert_eq!(
4246            parse_classic_required_status_checks(&value),
4247            vec![
4248                RequiredStatusCheck {
4249                    context: "ci/test".to_string(),
4250                    integration_id: None,
4251                },
4252                RequiredStatusCheck {
4253                    context: "lint".to_string(),
4254                    integration_id: None,
4255                }
4256            ]
4257        );
4258    }
4259
4260    #[test]
4261    fn parse_classic_required_status_checks_empty_when_unprotected() {
4262        let checks = parse_classic_required_status_checks(&serde_json::json!({}));
4263        assert!(checks.is_empty(), "{checks:?}");
4264    }
4265
4266    #[test]
4267    fn parse_ruleset_required_status_checks_reads_integration_id() {
4268        let rules = vec![
4269            serde_json::json!({ "type": "pull_request" }),
4270            serde_json::json!({
4271                "type": "required_status_checks",
4272                "parameters": {
4273                    "required_status_checks": [
4274                        { "context": "ci/test", "integration_id": 42 },
4275                        { "context": "lint" }
4276                    ]
4277                }
4278            }),
4279        ];
4280        assert_eq!(
4281            parse_ruleset_required_status_checks(&rules),
4282            vec![
4283                RequiredStatusCheck {
4284                    context: "ci/test".to_string(),
4285                    integration_id: Some(42),
4286                },
4287                RequiredStatusCheck {
4288                    context: "lint".to_string(),
4289                    integration_id: None,
4290                }
4291            ]
4292        );
4293    }
4294
4295    #[test]
4296    fn parse_ruleset_required_status_checks_treats_zero_integration_id_as_any_app() {
4297        let rules = vec![serde_json::json!({
4298            "type": "required_status_checks",
4299            "parameters": {
4300                "required_status_checks": [{ "context": "ci/test", "integration_id": 0 }]
4301            }
4302        })];
4303        assert_eq!(
4304            parse_ruleset_required_status_checks(&rules),
4305            vec![RequiredStatusCheck {
4306                context: "ci/test".to_string(),
4307                integration_id: None,
4308            }]
4309        );
4310    }
4311
4312    #[test]
4313    fn merge_required_status_checks_dedupes_identical_pairs() {
4314        let classic = vec![RequiredStatusCheck {
4315            context: "ci/test".to_string(),
4316            integration_id: None,
4317        }];
4318        let ruleset = vec![
4319            RequiredStatusCheck {
4320                context: "ci/test".to_string(),
4321                integration_id: None,
4322            },
4323            RequiredStatusCheck {
4324                context: "ci/test".to_string(),
4325                integration_id: Some(42),
4326            },
4327        ];
4328        assert_eq!(
4329            merge_required_status_checks(classic, ruleset),
4330            vec![
4331                RequiredStatusCheck {
4332                    context: "ci/test".to_string(),
4333                    integration_id: None,
4334                },
4335                RequiredStatusCheck {
4336                    context: "ci/test".to_string(),
4337                    integration_id: Some(42),
4338                }
4339            ]
4340        );
4341    }
4342
4343    #[test]
4344    fn parse_commit_meta_reads_parents_in_order_and_logins() {
4345        let merge = serde_json::json!({
4346            "parents": [{"sha": "approved"}, {"sha": "base"}],
4347            "author": {"login": "owner"},
4348            "committer": {"login": "web-flow"},
4349        });
4350        let meta = parse_commit_meta(&merge);
4351        assert_eq!(meta.parents, vec!["approved", "base"]);
4352        assert_eq!(meta.author_login.as_deref(), Some("owner"));
4353        assert_eq!(meta.committer_login.as_deref(), Some("web-flow"));
4354        assert_eq!(
4355            parse_commit_meta(&serde_json::json!({})),
4356            CommitMeta::default()
4357        );
4358    }
4359
4360    #[test]
4361    fn parse_behind_by_reads_compare_status() {
4362        // A head behind the base must not merge: its checks ran against old code.
4363        let behind = serde_json::json!({"status": "behind", "behind_by": 3, "ahead_by": 0});
4364        assert_eq!(parse_behind_by(&behind).unwrap(), 3);
4365        let diverged = serde_json::json!({"status": "diverged", "behind_by": 1, "ahead_by": 2});
4366        assert_eq!(parse_behind_by(&diverged).unwrap(), 1);
4367        let ahead = serde_json::json!({"status": "ahead", "behind_by": 0, "ahead_by": 2});
4368        assert_eq!(parse_behind_by(&ahead).unwrap(), 0);
4369        // An unreadable response is an error, never a permissive zero.
4370        assert!(parse_behind_by(&serde_json::json!({"status": "ahead"})).is_err());
4371    }
4372
4373    async fn spawn_truncated_body_server(body_prefix: &'static str) -> String {
4374        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
4375        let addr = listener.local_addr().unwrap();
4376
4377        tokio::spawn(async move {
4378            let (mut socket, _) = listener.accept().await.unwrap();
4379            let mut buf = [0u8; 4096];
4380            let _ = socket.read(&mut buf).await;
4381
4382            let declared_len = body_prefix.len() + 32;
4383            let response = format!(
4384                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {declared_len}\r\nconnection: close\r\n\r\n{body_prefix}"
4385            );
4386            socket.write_all(response.as_bytes()).await.unwrap();
4387            socket.shutdown().await.unwrap();
4388        });
4389
4390        format!("http://{addr}")
4391    }
4392
4393    #[test]
4394    fn merge_pr_body_pins_the_head_sha() {
4395        let sha = "0123456789abcdef0123456789abcdef01234567";
4396        let body = merge_pr_body(sha);
4397        assert_eq!(body["merge_method"], "squash");
4398        assert_eq!(body["sha"], sha);
4399        assert!(is_full_commit_sha(sha));
4400        assert!(!is_full_commit_sha("abc"));
4401        assert!(!is_full_commit_sha(""));
4402    }
4403
4404    fn test_client() -> GhHttp {
4405        GhHttp {
4406            client: reqwest::Client::new(),
4407            token_resolver: Arc::new(TokenResolver::default_env()),
4408            app: None,
4409            owner_only: false,
4410            cached_username: OnceLock::new(),
4411            api_base: None,
4412        }
4413    }
4414
4415    /// Verify `GhHttp::new()` returns `Ok` and does not panic on construction.
4416    ///
4417    /// This test guards against regressions where `GhHttp::new()` might panic
4418    /// (e.g., if TLS initialisation fails or the builder API changes).
4419    #[test]
4420    fn gh_http_new_returns_ok() {
4421        let result = GhHttp::new();
4422        assert!(
4423            result.is_ok(),
4424            "GhHttp::new() must not panic and must return Ok; got: {:?}",
4425            result.err()
4426        );
4427    }
4428
4429    #[test]
4430    fn batch_get_issue_states_query_includes_labels_pagination() {
4431        let issue_numbers = [1u64, 2, 3];
4432
4433        let aliases: String = issue_numbers
4434            .iter()
4435            .map(|n| {
4436                format!("issue{n}: issue(number: {n}) {{ state labels(first: 100) {{ nodes {{ name }} }} }}")
4437            })
4438            .collect::<Vec<_>>()
4439            .join(" ");
4440
4441        let query = format!(
4442            r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
4443        );
4444        assert!(query.contains("$owner"));
4445        assert!(query.contains("$name"));
4446        assert!(query.contains("issue1: issue(number: 1)"));
4447        assert!(query.contains("issue3: issue(number: 3)"));
4448        assert!(query.contains("labels(first: 100)"));
4449    }
4450
4451    #[test]
4452    fn parse_positive_issue_number_accepts_positive_values() {
4453        assert_eq!(parse_positive_issue_number("42").unwrap(), 42);
4454    }
4455
4456    #[test]
4457    fn parse_positive_issue_number_rejects_zero() {
4458        let err = parse_positive_issue_number("0").unwrap_err().to_string();
4459        assert!(err.contains("invalid issue number: 0"));
4460    }
4461
4462    #[test]
4463    fn parse_positive_issue_number_rejects_internal_ids() {
4464        let err = parse_positive_issue_number("internal:5")
4465            .unwrap_err()
4466            .to_string();
4467        assert!(err.contains("invalid issue number: internal:5"));
4468    }
4469
4470    #[test]
4471    fn pr_review_batch_query_includes_page_info_for_nested_connections() {
4472        let query = build_pr_review_alias(42);
4473
4474        assert!(query.contains("reviews(first: 50)"));
4475        assert!(query.contains("reviews(first: 50) {\n    nodes"));
4476        assert!(query.contains("pageInfo { hasNextPage }"));
4477        assert!(query.contains("reviewThreads(first: 50)"));
4478        assert!(query.contains("comments(first: 20)"));
4479        assert!(query.contains("pageInfo { hasNextPage endCursor }"));
4480        assert!(query.contains("updatedAt"));
4481    }
4482
4483    #[test]
4484    fn pr_issue_comments_page_query_uses_cursor_pagination() {
4485        let (query, vars) = build_pr_issue_comments_page_query("owner", "repo", 42, "cursor123");
4486
4487        assert!(query.contains("pullRequest(number: $number)"));
4488        assert!(query.contains("comments(first: 100, after: $after)"));
4489        assert!(query.contains("pageInfo { hasNextPage endCursor }"));
4490        assert!(query.contains("updatedAt"));
4491        assert_eq!(vars["owner"], "owner");
4492        assert_eq!(vars["name"], "repo");
4493        assert_eq!(vars["number"], 42);
4494        assert_eq!(vars["after"], "cursor123");
4495    }
4496
4497    #[test]
4498    fn connection_end_cursor_only_returns_cursor_when_more_pages_exist() {
4499        let page_info = serde_json::json!({
4500            "hasNextPage": true,
4501            "endCursor": "cursor123"
4502        });
4503        assert_eq!(
4504            connection_end_cursor(Some(&page_info)),
4505            Some("cursor123".to_string())
4506        );
4507
4508        let final_page = serde_json::json!({
4509            "hasNextPage": false,
4510            "endCursor": "cursor456"
4511        });
4512        assert_eq!(connection_end_cursor(Some(&final_page)), None);
4513    }
4514
4515    #[test]
4516    fn status_label_colors_match_bash_palette() {
4517        assert_eq!(status_label_color("status:new"), "0e8a16");
4518        assert_eq!(status_label_color("status:routed"), "1d76db");
4519        assert_eq!(status_label_color("status:in_progress"), "fbca04");
4520        assert_eq!(status_label_color("status:done"), "6f42c1");
4521        assert_eq!(status_label_color("status:blocked"), "d73a4a");
4522        assert_eq!(status_label_color("status:in_review"), "0075ca");
4523        assert_eq!(status_label_color("status:needs_review"), "e4e669");
4524    }
4525
4526    #[test]
4527    fn unknown_label_gets_default_color() {
4528        assert_eq!(status_label_color("agent:claude"), "c5def5");
4529        assert_eq!(status_label_color("enhancement"), "c5def5");
4530        assert_eq!(status_label_color(""), "c5def5");
4531    }
4532
4533    #[test]
4534    fn parse_link_next_finds_next_url() {
4535        let mut headers = header::HeaderMap::new();
4536        headers.insert(
4537            "link",
4538            "<https://api.github.com/repos/foo/bar/issues?page=2>; rel=\"next\", <https://api.github.com/repos/foo/bar/issues?page=5>; rel=\"last\""
4539                .parse()
4540                .unwrap(),
4541        );
4542        assert_eq!(
4543            parse_link_next(&headers),
4544            Some("https://api.github.com/repos/foo/bar/issues?page=2".to_string())
4545        );
4546    }
4547
4548    #[test]
4549    fn parse_link_next_none_when_no_next() {
4550        let mut headers = header::HeaderMap::new();
4551        headers.insert(
4552            "link",
4553            "<https://api.github.com/repos/foo/bar/issues?page=1>; rel=\"prev\""
4554                .parse()
4555                .unwrap(),
4556        );
4557        assert_eq!(parse_link_next(&headers), None);
4558    }
4559
4560    #[test]
4561    fn parse_link_next_none_when_missing() {
4562        let headers = header::HeaderMap::new();
4563        assert_eq!(parse_link_next(&headers), None);
4564    }
4565
4566    #[test]
4567    fn parse_link_next_none_when_malformed() {
4568        let mut headers = header::HeaderMap::new();
4569        // Malformed: no angle-bracket URL, just garbage
4570        headers.insert("link", "garbage; rel=\"next\"".parse().unwrap());
4571        assert_eq!(parse_link_next(&headers), None);
4572    }
4573
4574    #[test]
4575    fn parse_link_next_none_when_gt_before_lt() {
4576        let mut headers = header::HeaderMap::new();
4577        headers.insert("link", ">junk; rel=\"next\"; <url>".parse().unwrap());
4578        assert_eq!(parse_link_next(&headers), None); // should not panic
4579    }
4580
4581    #[test]
4582    fn parse_link_next_none_when_empty_url() {
4583        let mut headers = header::HeaderMap::new();
4584        headers.insert("link", "<>; rel=\"next\"".parse().unwrap());
4585        assert_eq!(parse_link_next(&headers), None);
4586    }
4587
4588    fn make_rl(base_secs: u64, max_secs: u64) -> RateLimit {
4589        RateLimit {
4590            remaining: None,
4591            reset_at: None,
4592            backoff_until: None,
4593            backoff_delay: Duration::ZERO,
4594            backoff_base: Duration::from_secs(base_secs),
4595            backoff_max: Duration::from_secs(max_secs),
4596            throttle_threshold: 10,
4597        }
4598    }
4599
4600    #[test]
4601    fn rate_limit_inactive_by_default() {
4602        let rl = make_rl(30, 900);
4603        assert!(rl.is_active().is_none());
4604    }
4605
4606    #[test]
4607    fn rate_limit_backoff_activates() {
4608        let mut rl = make_rl(5, 60);
4609        rl.record_rate_limit();
4610        assert!(rl.is_active().is_some());
4611        assert_eq!(rl.backoff_delay, Duration::from_secs(5));
4612    }
4613
4614    #[test]
4615    fn rate_limit_backoff_doubles() {
4616        let mut rl = make_rl(5, 60);
4617        rl.record_rate_limit();
4618        assert_eq!(rl.backoff_delay, Duration::from_secs(5));
4619        rl.record_rate_limit();
4620        assert_eq!(rl.backoff_delay, Duration::from_secs(10));
4621        rl.record_rate_limit();
4622        assert_eq!(rl.backoff_delay, Duration::from_secs(20));
4623    }
4624
4625    #[test]
4626    fn rate_limit_backoff_caps_at_max() {
4627        let mut rl = make_rl(30, 60);
4628        rl.record_rate_limit(); // 30
4629        rl.record_rate_limit(); // 60
4630        rl.record_rate_limit(); // capped at 60
4631        assert_eq!(rl.backoff_delay, Duration::from_secs(60));
4632    }
4633
4634    #[test]
4635    fn rate_limit_success_resets() {
4636        let mut rl = make_rl(5, 60);
4637        rl.record_rate_limit();
4638        assert!(rl.is_active().is_some());
4639        rl.record_success();
4640        assert!(rl.is_active().is_none());
4641        assert_eq!(rl.backoff_delay, Duration::ZERO);
4642    }
4643
4644    #[test]
4645    fn page_cache_key_separates_types_and_queries() {
4646        let a = page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "open")])).unwrap();
4647        let b = page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "closed")])).unwrap();
4648        let c = page_cache_key::<serde_json::Value>("/issues", Some(&[("state", "open")])).unwrap();
4649        assert_ne!(a, b);
4650        assert_ne!(a, c);
4651        assert_eq!(
4652            a,
4653            page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "open")])).unwrap()
4654        );
4655    }
4656
4657    /// `since` is derived from the clock, so the key would never recur.
4658    #[test]
4659    fn page_cache_key_skips_since_filtered_requests() {
4660        assert!(
4661            page_cache_key::<GitHubIssue>(
4662                "/issues",
4663                Some(&[("state", "closed"), ("since", "2026-10-01T00:00:00Z")])
4664            )
4665            .is_none()
4666        );
4667        // Also when it arrives embedded in a Link: next URL.
4668        assert!(
4669            page_cache_key::<GitHubIssue>("/issues?since=2026-10-01T00:00:00Z&page=2", None)
4670                .is_none()
4671        );
4672    }
4673
4674    /// A limiter with no quota left and a reset an hour out: the check must return an
4675    /// error straight away. Sleeping here is what froze the tick loop for 504s.
4676    #[test]
4677    fn low_quota_fails_fast_instead_of_waiting_for_reset() {
4678        let mut rl = make_rl(30, 900);
4679        rl.remaining = Some(0);
4680        rl.reset_at = Some(
4681            SystemTime::now()
4682                .duration_since(std_time::UNIX_EPOCH)
4683                .unwrap()
4684                .as_secs()
4685                + 3600,
4686        );
4687        let cell = Mutex::new(rl);
4688
4689        let start = Instant::now();
4690        let err = check_rate_limit_backoff(&cell, "REST").unwrap_err();
4691        assert!(
4692            start.elapsed() < Duration::from_secs(1),
4693            "check blocked for {:?}",
4694            start.elapsed()
4695        );
4696        assert!(err.to_string().contains("rate-limited"), "{err}");
4697    }
4698
4699    /// Quota above the reserve is not a reason to skip the call.
4700    #[test]
4701    fn healthy_quota_passes_the_check() {
4702        let mut rl = make_rl(30, 900);
4703        rl.remaining = Some(4000);
4704        rl.reset_at = Some(u64::MAX / 2);
4705        let cell = Mutex::new(rl);
4706        assert!(check_rate_limit_backoff(&cell, "REST").is_ok());
4707    }
4708
4709    #[test]
4710    fn rate_limit_proactive_pause() {
4711        let mut rl = make_rl(30, 900);
4712        // Simulate: 0 remaining (below default threshold of 10), reset 60s in the future
4713        rl.remaining = Some(0);
4714        let future_epoch = SystemTime::now()
4715            .duration_since(std_time::UNIX_EPOCH)
4716            .unwrap()
4717            .as_secs()
4718            + 60;
4719        rl.reset_at = Some(future_epoch);
4720        let pause = rl.is_active();
4721        assert!(pause.is_some());
4722        // Should be roughly 60 seconds (within tolerance, +1s buffer added)
4723        assert!(pause.unwrap().as_secs() <= 62);
4724    }
4725
4726    #[test]
4727    fn rate_limit_proactive_pause_threshold() {
4728        let mut rl = make_rl(30, 900);
4729        // remaining=15 is above default threshold of 10 — no proactive wait
4730        rl.remaining = Some(15);
4731        let future_epoch = SystemTime::now()
4732            .duration_since(std_time::UNIX_EPOCH)
4733            .unwrap()
4734            .as_secs()
4735            + 60;
4736        rl.reset_at = Some(future_epoch);
4737        assert!(rl.is_active().is_none());
4738
4739        // remaining=5 is below threshold — proactive wait activates
4740        rl.remaining = Some(5);
4741        assert!(rl.is_active().is_some());
4742    }
4743
4744    #[test]
4745    fn count_ci_runs_skips_the_reviews_own_checks() {
4746        let run = |name: &str, status: &str, conclusion: Option<&str>| types::GitHubCheckRun {
4747            id: 1,
4748            name: name.to_string(),
4749            status: status.to_string(),
4750            conclusion: conclusion.map(str::to_string),
4751            app: None,
4752        };
4753        let runs = vec![
4754            run("ci", "completed", Some("success")),
4755            run("review-gate", "completed", Some("failure")),
4756            run("orch/review", "in_progress", None),
4757        ];
4758        assert_eq!(GhHttp::count_ci_runs(&runs), (1, 1, 0, 0));
4759
4760        let only_own = vec![run("review-gate", "completed", Some("failure"))];
4761        assert_eq!(GhHttp::count_ci_runs(&only_own), (0, 0, 0, 0));
4762        assert_eq!(
4763            GhHttp::combined_status_state(0, 0, 0, true, Some("clean")),
4764            "success"
4765        );
4766    }
4767
4768    #[test]
4769    fn combined_status_state_treats_empty_checks_as_pending_when_workflows_exist() {
4770        // No check runs yet and GitHub hasn't said it's clean → pending (wait for CI to queue)
4771        assert_eq!(
4772            GhHttp::combined_status_state(0, 0, 0, true, None),
4773            "pending"
4774        );
4775        // No workflows configured → no need to wait
4776        assert_eq!(
4777            GhHttp::combined_status_state(0, 0, 0, false, None),
4778            "success"
4779        );
4780        // Failing check → failure regardless
4781        assert_eq!(
4782            GhHttp::combined_status_state(3, 1, 0, true, None),
4783            "failure"
4784        );
4785        // paths-ignore filtered out all workflows: no check runs but GitHub says "clean"
4786        assert_eq!(
4787            GhHttp::combined_status_state(0, 0, 0, true, Some("clean")),
4788            "success"
4789        );
4790        // mergeable_state is dirty/blocked — still pending even with has_workflows
4791        assert_eq!(
4792            GhHttp::combined_status_state(0, 0, 0, true, Some("dirty")),
4793            "pending"
4794        );
4795    }
4796
4797    #[test]
4798    fn batch_is_pr_merged_by_branch_errors_when_repository_data_missing() {
4799        let resp = serde_json::json!({
4800            "data": {},
4801            "errors": [{ "message": "Something went wrong" }],
4802        });
4803
4804        let err_text = GhHttp::parse_batch_pr_merged_response(&resp, &["branch".to_string()])
4805            .unwrap_err()
4806            .to_string();
4807        assert!(err_text.contains("missing /data/repository in GraphQL response"));
4808        assert!(err_text.contains("Something went wrong"));
4809    }
4810
4811    #[test]
4812    fn rate_limit_uses_reset_at_for_backoff() {
4813        let mut rl = make_rl(30, 900);
4814        // Set reset_at to 45s in the future
4815        let future_epoch = SystemTime::now()
4816            .duration_since(std_time::UNIX_EPOCH)
4817            .unwrap()
4818            .as_secs()
4819            + 45;
4820        rl.reset_at = Some(future_epoch);
4821        rl.record_rate_limit();
4822        // Backoff should use reset_at (~46s) not the base (30s)
4823        assert!(rl.backoff_delay.as_secs() >= 45);
4824        assert!(rl.backoff_delay.as_secs() <= 47);
4825    }
4826
4827    #[tokio::test]
4828    async fn send_with_retries_propagates_make_req_error() {
4829        let guard = env::var_os("GH_TOKEN");
4830        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4831        unsafe { env::set_var("GH_TOKEN", "test_token") };
4832        let gh = test_client();
4833        let result = gh
4834            .send_with_retries(
4835                || Err(anyhow::anyhow!("simulated request clone failure")),
4836                false,
4837            )
4838            .await;
4839        assert!(result.is_err());
4840        let err = result.unwrap_err().to_string();
4841        assert_eq!(err, "simulated request clone failure");
4842        match guard {
4843            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4844            Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4845            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4846            None => unsafe { env::remove_var("GH_TOKEN") },
4847        }
4848    }
4849
4850    /// A transport-level failure (connection refused — GitHub never reached)
4851    /// must exhaust retries without tripping the shared "github:5xx" circuit
4852    /// breaker: that breaker is read by the routing-phase skip and other
4853    /// subsystems as a signal specifically about GitHub's health, which a
4854    /// local connectivity blip says nothing about.
4855    #[tokio::test]
4856    async fn send_with_retries_transport_error_does_not_trip_5xx_breaker() {
4857        let guard = env::var_os("GH_TOKEN");
4858        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4859        unsafe { env::set_var("GH_TOKEN", "test_token") };
4860
4861        // Bind then immediately drop a listener to get a port nothing is
4862        // listening on, so connecting reliably fails with "connection refused"
4863        // rather than depending on an external unreachable host.
4864        let addr = {
4865            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
4866            listener.local_addr().unwrap()
4867        };
4868        let url = format!("http://{addr}/");
4869
4870        let gh = test_client();
4871        let make_req = || Ok(gh.client.get(&url));
4872        let result = gh.send_with_retries(make_req, false).await;
4873
4874        let err = result.unwrap_err().to_string();
4875        assert!(
4876            err.contains("is_connect=true") && err.to_lowercase().contains("refused"),
4877            "transport error should hold the source chain, got: {err}"
4878        );
4879        assert!(
4880            !cooldown::is_agent_in_cooldown("github:5xx"),
4881            "transport error must not trip the github:5xx circuit breaker"
4882        );
4883        assert!(cooldown::cooldown_until("github:5xx").is_none());
4884
4885        match guard {
4886            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4887            Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4888            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4889            None => unsafe { env::remove_var("GH_TOKEN") },
4890        }
4891    }
4892
4893    #[tokio::test]
4894    async fn post_json_raw_propagates_body_read_errors_on_success() {
4895        let guard = env::var_os("GH_TOKEN");
4896        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4897        unsafe { env::set_var("GH_TOKEN", "test_token") };
4898        let server_url = spawn_truncated_body_server("{").await;
4899        let gh = test_client();
4900
4901        let result = gh
4902            .post_json_raw(
4903                &format!("{server_url}/post"),
4904                &serde_json::json!({"ok": true}),
4905            )
4906            .await;
4907
4908        let err = result.unwrap_err().to_string();
4909        assert!(
4910            !err.contains("EOF while parsing a value"),
4911            "should surface the body read error, got: {err}"
4912        );
4913        assert!(
4914            err.contains("error decoding response body")
4915                || err.contains("request or response body error")
4916                || err.contains("end of file before message length reached"),
4917            "expected a transport/body read error, got: {err}"
4918        );
4919
4920        match guard {
4921            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4922            Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4923            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4924            None => unsafe { env::remove_var("GH_TOKEN") },
4925        }
4926    }
4927
4928    #[tokio::test]
4929    async fn patch_json_raw_propagates_body_read_errors_on_success() {
4930        let guard = env::var_os("GH_TOKEN");
4931        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4932        unsafe { env::set_var("GH_TOKEN", "test_token") };
4933        let server_url = spawn_truncated_body_server("{").await;
4934        let gh = test_client();
4935
4936        let result = gh
4937            .patch_json_raw(
4938                &format!("{server_url}/patch"),
4939                &serde_json::json!({"ok": true}),
4940            )
4941            .await;
4942
4943        let err = result.unwrap_err().to_string();
4944        assert!(
4945            !err.contains("EOF while parsing a value"),
4946            "should surface the body read error, got: {err}"
4947        );
4948        assert!(
4949            err.contains("error decoding response body")
4950                || err.contains("request or response body error")
4951                || err.contains("end of file before message length reached"),
4952            "expected a transport/body read error, got: {err}"
4953        );
4954
4955        match guard {
4956            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4957            Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4958            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4959            None => unsafe { env::remove_var("GH_TOKEN") },
4960        }
4961    }
4962
4963    #[tokio::test]
4964    async fn graphql_request_propagates_body_read_errors_on_success() {
4965        let guard = env::var_os("GH_TOKEN");
4966        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4967        unsafe { env::set_var("GH_TOKEN", "test_token") };
4968        let server_url = spawn_truncated_body_server("{").await;
4969        let gh = test_client();
4970        let query = "query { viewer { login } }";
4971
4972        let result = gh
4973            .graphql_request_to_url(
4974                &format!("{server_url}/graphql"),
4975                query,
4976                &[],
4977                Some(serde_json::json!({"k": "v"})),
4978            )
4979            .await;
4980
4981        let err = result.unwrap_err().to_string();
4982        assert!(
4983            !err.contains("EOF while parsing a value"),
4984            "should surface the body read error, got: {err}"
4985        );
4986        assert!(
4987            err.contains("error decoding response body")
4988                || err.contains("request or response body error")
4989                || err.contains("end of file before message length reached"),
4990            "expected a transport/body read error, got: {err}"
4991        );
4992
4993        match guard {
4994            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4995            Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4996            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
4997            None => unsafe { env::remove_var("GH_TOKEN") },
4998        }
4999    }
5000
5001    // ── get_all_pages integration tests (wiremock) ────────────────────────
5002
5003    #[cfg(test)]
5004    mod pagination {
5005        use super::super::*;
5006        use crate::github::token::TokenResolver;
5007        use std::env;
5008        use std::ffi::OsString;
5009        use std::sync::Arc;
5010        use std::time;
5011        use std::time::SystemTime;
5012        use wiremock::matchers::{method, path, query_param};
5013        use wiremock::{Match, Mock, MockServer, Request, ResponseTemplate, matchers};
5014
5015        /// wiremock has no negated matcher, and the first poll must be matched on the
5016        /// absence of `If-None-Match` to tell it apart from the conditional one.
5017        struct NotMatcher<M>(M);
5018
5019        impl<M: Match> Match for NotMatcher<M> {
5020            fn matches(&self, request: &Request) -> bool {
5021                !self.0.matches(request)
5022            }
5023        }
5024
5025        struct EnvVarGuard {
5026            key: &'static str,
5027            previous: Option<OsString>,
5028        }
5029
5030        impl EnvVarGuard {
5031            fn set(key: &'static str, value: &str) -> Self {
5032                let previous = env::var_os(key);
5033                // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5034                unsafe { env::set_var(key, value) };
5035                Self { key, previous }
5036            }
5037        }
5038
5039        impl Drop for EnvVarGuard {
5040            fn drop(&mut self) {
5041                match self.previous.take() {
5042                    // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5043                    Some(value) => unsafe { env::set_var(self.key, value) },
5044                    // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5045                    None => unsafe { env::remove_var(self.key) },
5046                }
5047            }
5048        }
5049
5050        /// Build a minimal GhHttp pointing at a wiremock server.
5051        /// The token resolver reads GH_TOKEN; we set it to a dummy value.
5052        fn make_client() -> (GhHttp, EnvVarGuard) {
5053            // Ensure a token is available so auth_header() doesn't bail.
5054            let guard = EnvVarGuard::set("GH_TOKEN", "test_token");
5055            let client = GhHttp {
5056                client: reqwest::Client::new(),
5057                token_resolver: Arc::new(TokenResolver::default_env()),
5058                app: None,
5059                owner_only: false,
5060                cached_username: OnceLock::new(),
5061                api_base: None,
5062            };
5063            (client, guard)
5064        }
5065
5066        fn client_for(server: &MockServer) -> (GhHttp, EnvVarGuard) {
5067            let guard = EnvVarGuard::set("GH_TOKEN", "test_token");
5068            (GhHttp::for_test(server.uri(), None), guard)
5069        }
5070
5071        fn check_run_json(
5072            id: u64,
5073            name: &str,
5074            status: &str,
5075            conclusion: Option<&str>,
5076        ) -> serde_json::Value {
5077            serde_json::json!({
5078                "id": id,
5079                "name": name,
5080                "status": status,
5081                "conclusion": conclusion,
5082            })
5083        }
5084
5085        fn passing_check_runs(count: u64) -> Vec<serde_json::Value> {
5086            (1..=count)
5087                .map(|i| check_run_json(i, &format!("check-{i}"), "completed", Some("success")))
5088                .collect()
5089        }
5090
5091        async fn mock_paginated_check_runs(
5092            server: &MockServer,
5093            sha: &str,
5094            page1: Vec<serde_json::Value>,
5095            page2: Vec<serde_json::Value>,
5096        ) {
5097            let total_count = page1.len() + page2.len();
5098            Mock::given(method("GET"))
5099                .and(path(format!("/repos/o/r/commits/{sha}/check-runs")))
5100                .and(query_param("filter", "latest"))
5101                .and(query_param("per_page", "100"))
5102                .respond_with(
5103                    ResponseTemplate::new(200)
5104                        .set_body_json(serde_json::json!({
5105                            "total_count": total_count,
5106                            "check_runs": page1,
5107                        }))
5108                        .insert_header(
5109                            "Link",
5110                            format!("<{}/check-runs/page2>; rel=\"next\"", server.uri()),
5111                        ),
5112                )
5113                .expect(1)
5114                .mount(server)
5115                .await;
5116
5117            Mock::given(method("GET"))
5118                .and(path("/check-runs/page2"))
5119                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5120                    "total_count": total_count,
5121                    "check_runs": page2,
5122                })))
5123                .expect(1)
5124                .mount(server)
5125                .await;
5126        }
5127
5128        #[tokio::test]
5129        async fn get_all_pages_single_page() {
5130            let server = MockServer::start().await;
5131
5132            Mock::given(method("GET"))
5133                .and(path("/items"))
5134                .respond_with(
5135                    ResponseTemplate::new(200)
5136                        .set_body_json(serde_json::json!([{"id": 1}, {"id": 2}])),
5137                )
5138                .expect(1)
5139                .mount(&server)
5140                .await;
5141
5142            let (gh, _guard) = make_client();
5143            let url = format!("{}/items", server.uri());
5144            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5145
5146            assert_eq!(result.len(), 2);
5147            assert_eq!(result[0]["id"], 1);
5148            assert_eq!(result[1]["id"], 2);
5149        }
5150
5151        #[tokio::test]
5152        async fn get_all_pages_follows_link_next() {
5153            let server = MockServer::start().await;
5154
5155            // Page 1 — includes Link header pointing to page 2
5156            Mock::given(method("GET"))
5157                .and(path("/items"))
5158                .respond_with(
5159                    ResponseTemplate::new(200)
5160                        .set_body_json(serde_json::json!([{"id": 1}]))
5161                        .insert_header(
5162                            "Link",
5163                            format!("<{}/items/page2>; rel=\"next\"", server.uri()),
5164                        ),
5165                )
5166                .expect(1)
5167                .mount(&server)
5168                .await;
5169
5170            // Page 2 — no Link header (last page)
5171            Mock::given(method("GET"))
5172                .and(path("/items/page2"))
5173                .respond_with(
5174                    ResponseTemplate::new(200)
5175                        .set_body_json(serde_json::json!([{"id": 2}, {"id": 3}])),
5176                )
5177                .expect(1)
5178                .mount(&server)
5179                .await;
5180
5181            let (gh, _guard) = make_client();
5182            let url = format!("{}/items", server.uri());
5183            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5184
5185            assert_eq!(result.len(), 3);
5186            assert_eq!(result[0]["id"], 1);
5187            assert_eq!(result[1]["id"], 2);
5188            assert_eq!(result[2]["id"], 3);
5189        }
5190
5191        #[tokio::test]
5192        async fn get_all_pages_stops_when_link_header_absent_on_subsequent_page() {
5193            // Simulates a proxy/transient response that drops the Link header mid-pagination.
5194            // The previous `.unwrap()` would panic here; the fix breaks the loop instead.
5195            let server = MockServer::start().await;
5196
5197            Mock::given(method("GET"))
5198                .and(path("/items"))
5199                .respond_with(
5200                    ResponseTemplate::new(200)
5201                        .set_body_json(serde_json::json!([{"id": 1}]))
5202                        .insert_header(
5203                            "Link",
5204                            format!("<{}/items/page2>; rel=\"next\"", server.uri()),
5205                        ),
5206                )
5207                .expect(1)
5208                .mount(&server)
5209                .await;
5210
5211            // Page 2 response has NO Link header — pagination should stop cleanly.
5212            Mock::given(method("GET"))
5213                .and(path("/items/page2"))
5214                .respond_with(
5215                    ResponseTemplate::new(200).set_body_json(serde_json::json!([{"id": 2}])),
5216                )
5217                .expect(1)
5218                .mount(&server)
5219                .await;
5220
5221            let (gh, _guard) = make_client();
5222            let url = format!("{}/items", server.uri());
5223            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5224
5225            // Must not panic and must return both items collected so far.
5226            assert_eq!(result.len(), 2);
5227        }
5228
5229        #[tokio::test]
5230        async fn get_all_pages_stops_on_malformed_link_header() {
5231            // A malformed Link header (no angle-bracket URL) yields None from parse_link_next,
5232            // which should stop pagination rather than panic.
5233            let server = MockServer::start().await;
5234
5235            Mock::given(method("GET"))
5236                .and(path("/items"))
5237                .respond_with(
5238                    ResponseTemplate::new(200)
5239                        .set_body_json(serde_json::json!([{"id": 1}]))
5240                        .insert_header("Link", "garbage; rel=\"next\""),
5241                )
5242                .expect(1)
5243                .mount(&server)
5244                .await;
5245
5246            let (gh, _guard) = make_client();
5247            let url = format!("{}/items", server.uri());
5248            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5249
5250            // Malformed Link header → pagination stops after first page, no panic.
5251            assert_eq!(result.len(), 1);
5252        }
5253
5254        #[tokio::test]
5255        async fn get_all_pages_returns_error_on_malformed_json_body() {
5256            let server = MockServer::start().await;
5257
5258            Mock::given(method("GET"))
5259                .and(path("/items"))
5260                .respond_with(ResponseTemplate::new(200).set_body_string("not valid json"))
5261                .expect(3)
5262                .mount(&server)
5263                .await;
5264
5265            let (gh, _guard) = make_client();
5266            let url = format!("{}/items", server.uri());
5267            let result = gh.get_all_pages::<serde_json::Value>(&url, &[]).await;
5268
5269            assert!(result.is_err());
5270            let err = result.unwrap_err().to_string();
5271            assert!(
5272                err.contains("JSON decode failed") || err.contains("expected ident"),
5273                "error should mention JSON decode or serde error: {err}"
5274            );
5275        }
5276
5277        // ── conditional request / rate-limit tests ───────────────────────────
5278
5279        /// Restores the global REST limiter and the page cache, both of which these two
5280        /// tests have to poison to exercise the real request path.
5281        struct GlobalStateGuard;
5282
5283        impl Drop for GlobalStateGuard {
5284            fn drop(&mut self) {
5285                if let Ok(mut rl) = REST_RATE_LIMIT.lock() {
5286                    *rl = RateLimit::new();
5287                }
5288                if let Ok(mut cache) = PAGE_CACHE.lock() {
5289                    cache.clear();
5290                }
5291            }
5292        }
5293
5294        #[tokio::test]
5295        async fn get_all_pages_replays_body_on_304() {
5296            let _reset = GlobalStateGuard;
5297            let server = MockServer::start().await;
5298
5299            // First poll: 200 with an ETag.
5300            Mock::given(method("GET"))
5301                .and(path("/issues"))
5302                .and(matchers::header_exists("authorization"))
5303                .and(NotMatcher(matchers::header_exists("if-none-match")))
5304                .respond_with(
5305                    ResponseTemplate::new(200)
5306                        .set_body_json(serde_json::json!([{"number": 1}]))
5307                        .insert_header("ETag", "\"abc123\""),
5308                )
5309                .expect(1)
5310                .mount(&server)
5311                .await;
5312
5313            // Second poll: orch sends If-None-Match, GitHub answers 304 with no body.
5314            Mock::given(method("GET"))
5315                .and(path("/issues"))
5316                .and(matchers::header("if-none-match", "\"abc123\""))
5317                .respond_with(ResponseTemplate::new(304))
5318                .expect(1)
5319                .mount(&server)
5320                .await;
5321
5322            let (gh, _guard) = make_client();
5323            let url = format!("{}/issues", server.uri());
5324
5325            let first: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5326            let second: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5327
5328            assert_eq!(first, second);
5329            assert_eq!(second.len(), 1);
5330            assert_eq!(second[0]["number"], 1);
5331        }
5332
5333        #[tokio::test]
5334        async fn exhausted_quota_skips_further_calls_until_reset() {
5335            let _reset = GlobalStateGuard;
5336            let server = MockServer::start().await;
5337
5338            let reset_at = SystemTime::now()
5339                .duration_since(time::UNIX_EPOCH)
5340                .unwrap()
5341                .as_secs()
5342                + 600;
5343
5344            // One response, and only one: it reports an exhausted core quota, so every
5345            // later call must be skipped locally rather than sent.
5346            Mock::given(method("GET"))
5347                .and(path("/issues"))
5348                .respond_with(
5349                    ResponseTemplate::new(200)
5350                        .set_body_json(serde_json::json!([{"number": 1}]))
5351                        .insert_header("x-ratelimit-remaining", "0")
5352                        .insert_header("x-ratelimit-reset", reset_at.to_string().as_str()),
5353                )
5354                .expect(1)
5355                .mount(&server)
5356                .await;
5357
5358            let (gh, _guard) = make_client();
5359            let url = format!("{}/issues", server.uri());
5360
5361            let first: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5362            assert_eq!(first.len(), 1);
5363
5364            // The next call returns immediately instead of waiting out the 600s window.
5365            let start = Instant::now();
5366            let err = gh
5367                .get_all_pages::<serde_json::Value>(&url, &[("state", "open")])
5368                .await
5369                .unwrap_err();
5370            assert!(
5371                start.elapsed() < Duration::from_secs(1),
5372                "call blocked for {:?} instead of failing fast",
5373                start.elapsed()
5374            );
5375            assert!(err.to_string().contains("rate-limited"), "{err}");
5376
5377            // The engine reports the window from the same state the skip reads.
5378            let m = rate_limit_metrics();
5379            assert_eq!(m.rest_remaining, Some(0));
5380            assert_eq!(m.rest_reset_at, Some(reset_at));
5381            assert!(GhHttp::is_rate_limited().is_some());
5382
5383            // `.expect(1)` on the mock is verified on drop: no second request went out.
5384        }
5385
5386        // ── get_all_pages_from_wrapper tests ─────────────────────────────────
5387
5388        #[tokio::test]
5389        async fn get_all_pages_from_wrapper_single_page() {
5390            // Simulates GitHub's check-runs response: a wrapper object with the
5391            // array nested under a named field.
5392            let server = MockServer::start().await;
5393
5394            Mock::given(method("GET"))
5395                .and(path("/check-runs"))
5396                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5397                    "total_count": 2,
5398                    "check_runs": [{"id": 1, "name": "build"}, {"id": 2, "name": "test"}]
5399                })))
5400                .expect(1)
5401                .mount(&server)
5402                .await;
5403
5404            let (gh, _guard) = make_client();
5405            let url = format!("{}/check-runs", server.uri());
5406            let result: Vec<serde_json::Value> = gh
5407                .get_all_pages_from_wrapper(&url, "check_runs")
5408                .await
5409                .unwrap();
5410
5411            assert_eq!(result.len(), 2);
5412            assert_eq!(result[0]["id"], 1);
5413            assert_eq!(result[1]["id"], 2);
5414        }
5415
5416        #[tokio::test]
5417        async fn get_all_pages_from_wrapper_follows_link_next() {
5418            // Two-page check-runs response (common for repos with >100 distinct check names).
5419            let server = MockServer::start().await;
5420
5421            Mock::given(method("GET"))
5422                .and(path("/check-runs"))
5423                .respond_with(
5424                    ResponseTemplate::new(200)
5425                        .set_body_json(serde_json::json!({
5426                            "total_count": 3,
5427                            "check_runs": [{"id": 1, "name": "build"}]
5428                        }))
5429                        .insert_header(
5430                            "Link",
5431                            format!("<{}/check-runs/page2>; rel=\"next\"", server.uri()),
5432                        ),
5433                )
5434                .expect(1)
5435                .mount(&server)
5436                .await;
5437
5438            Mock::given(method("GET"))
5439                .and(path("/check-runs/page2"))
5440                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5441                    "total_count": 3,
5442                    "check_runs": [{"id": 2, "name": "lint"}, {"id": 3, "name": "test"}]
5443                })))
5444                .expect(1)
5445                .mount(&server)
5446                .await;
5447
5448            let (gh, _guard) = make_client();
5449            let url = format!("{}/check-runs", server.uri());
5450            let result: Vec<serde_json::Value> = gh
5451                .get_all_pages_from_wrapper(&url, "check_runs")
5452                .await
5453                .unwrap();
5454
5455            assert_eq!(result.len(), 3);
5456            assert_eq!(result[0]["id"], 1);
5457            assert_eq!(result[1]["id"], 2);
5458            assert_eq!(result[2]["id"], 3);
5459        }
5460
5461        #[tokio::test]
5462        async fn get_all_pages_from_wrapper_empty_field_returns_empty_vec() {
5463            // When the array field is missing or empty, the function should return
5464            // an empty vec rather than erroring.
5465            let server = MockServer::start().await;
5466
5467            Mock::given(method("GET"))
5468                .and(path("/check-runs"))
5469                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5470                    "total_count": 0,
5471                    "check_runs": []
5472                })))
5473                .expect(1)
5474                .mount(&server)
5475                .await;
5476
5477            let (gh, _guard) = make_client();
5478            let url = format!("{}/check-runs", server.uri());
5479            let result: Vec<serde_json::Value> = gh
5480                .get_all_pages_from_wrapper(&url, "check_runs")
5481                .await
5482                .unwrap();
5483
5484            assert_eq!(result.len(), 0);
5485        }
5486
5487        #[tokio::test]
5488        async fn get_all_pages_from_wrapper_error_on_non_success_status() {
5489            let server = MockServer::start().await;
5490
5491            Mock::given(method("GET"))
5492                .and(path("/check-runs"))
5493                .respond_with(ResponseTemplate::new(422).set_body_string("Unprocessable Entity"))
5494                .expect(1)
5495                .mount(&server)
5496                .await;
5497
5498            let (gh, _guard) = make_client();
5499            let url = format!("{}/check-runs", server.uri());
5500            let result = gh
5501                .get_all_pages_from_wrapper::<serde_json::Value>(&url, "check_runs")
5502                .await;
5503
5504            assert!(result.is_err());
5505            let err = result.unwrap_err().to_string();
5506            assert!(
5507                err.contains("422") || err.contains("failed"),
5508                "error should indicate failure: {err}"
5509            );
5510        }
5511
5512        #[tokio::test]
5513        async fn get_combined_status_counts_a_failure_on_a_later_page() {
5514            let server = MockServer::start().await;
5515            let sha = "abc123";
5516            mock_paginated_check_runs(
5517                &server,
5518                sha,
5519                passing_check_runs(30),
5520                vec![check_run_json(31, "check-31", "completed", Some("failure"))],
5521            )
5522            .await;
5523
5524            let (gh, _guard) = client_for(&server);
5525            let (state, total, passing, failing, pending) = gh
5526                .get_combined_status("o/r", sha, true, None)
5527                .await
5528                .unwrap();
5529
5530            assert_eq!(state, "failure");
5531            assert_eq!(total, 31);
5532            assert_eq!(passing, 30);
5533            assert_eq!(failing, 1);
5534            assert_eq!(pending, 0);
5535        }
5536
5537        #[tokio::test]
5538        async fn get_combined_status_counts_an_in_progress_run_on_a_later_page() {
5539            let server = MockServer::start().await;
5540            let sha = "abc123";
5541            mock_paginated_check_runs(
5542                &server,
5543                sha,
5544                passing_check_runs(30),
5545                vec![check_run_json(31, "check-31", "in_progress", None)],
5546            )
5547            .await;
5548
5549            let (gh, _guard) = client_for(&server);
5550            let (state, total, passing, failing, pending) = gh
5551                .get_combined_status("o/r", sha, true, None)
5552                .await
5553                .unwrap();
5554
5555            assert_eq!(state, "pending");
5556            assert_eq!(total, 31);
5557            assert_eq!(passing, 30);
5558            assert_eq!(failing, 0);
5559            assert_eq!(pending, 1);
5560        }
5561    }
5562
5563    // ── 401 token-refresh tests (wiremock) ────────────────────────────────
5564
5565    #[cfg(test)]
5566    mod auth_retry {
5567        use super::test_client;
5568        use crate::github::token;
5569        use std::env;
5570        use std::sync::Arc;
5571        use std::sync::atomic::{AtomicUsize, Ordering};
5572        use wiremock::matchers::method;
5573        use wiremock::{Mock, MockServer, Request, ResponseTemplate};
5574
5575        fn bad_credentials() -> ResponseTemplate {
5576            ResponseTemplate::new(401).set_body_json(serde_json::json!({
5577                "message": "Bad credentials",
5578                "status": 401
5579            }))
5580        }
5581
5582        #[expect(
5583            clippy::await_holding_lock,
5584            reason = "the env lock stays held across the awaits so tests do not race on GH_TOKEN"
5585        )]
5586        #[tokio::test]
5587        async fn retries_once_with_fresh_token_after_401() {
5588            let _env_guard = token::ENV_LOCK.lock().unwrap();
5589            let prev = env::var_os("GH_TOKEN");
5590            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5591            unsafe { env::set_var("GH_TOKEN", "bad_token") };
5592
5593            let server = MockServer::start().await;
5594            let hits = Arc::new(AtomicUsize::new(0));
5595            let hits_in_handler = Arc::clone(&hits);
5596            Mock::given(method("GET"))
5597                .respond_with(move |_req: &Request| {
5598                    if hits_in_handler.fetch_add(1, Ordering::SeqCst) == 0 {
5599                        // The 401 handler clears the cache and re-resolves; simulate the
5600                        // operator having fixed the env var in the meantime
5601                        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5602                        unsafe { env::set_var("GH_TOKEN", "good_token") };
5603                        bad_credentials()
5604                    } else {
5605                        ResponseTemplate::new(200).set_body_json(serde_json::json!({ "ok": true }))
5606                    }
5607                })
5608                .mount(&server)
5609                .await;
5610
5611            let gh = test_client();
5612            let result: anyhow::Result<serde_json::Value> =
5613                gh.get_json(&format!("{}/x", server.uri())).await;
5614
5615            match prev {
5616                // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5617                Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
5618                // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5619                None => unsafe { env::remove_var("GH_TOKEN") },
5620            }
5621
5622            assert!(
5623                result.is_ok(),
5624                "retry with re-resolved token should succeed: {:?}",
5625                result.err()
5626            );
5627            assert_eq!(hits.load(Ordering::SeqCst), 2, "exactly one retry expected");
5628        }
5629
5630        #[expect(
5631            clippy::await_holding_lock,
5632            reason = "the env lock stays held across the awaits so tests do not race on GH_TOKEN"
5633        )]
5634        #[tokio::test]
5635        async fn double_401_bails_with_distinct_auth_error() {
5636            let _env_guard = token::ENV_LOCK.lock().unwrap();
5637            let prev = env::var_os("GH_TOKEN");
5638            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5639            unsafe { env::set_var("GH_TOKEN", "bad_token") };
5640
5641            let server = MockServer::start().await;
5642            let hits = Arc::new(AtomicUsize::new(0));
5643            let hits_in_handler = Arc::clone(&hits);
5644            Mock::given(method("GET"))
5645                .respond_with(move |_req: &Request| {
5646                    hits_in_handler.fetch_add(1, Ordering::SeqCst);
5647                    bad_credentials()
5648                })
5649                .mount(&server)
5650                .await;
5651
5652            let gh = test_client();
5653            let result: anyhow::Result<serde_json::Value> =
5654                gh.get_json(&format!("{}/x", server.uri())).await;
5655
5656            match prev {
5657                // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5658                Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
5659                // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5660                None => unsafe { env::remove_var("GH_TOKEN") },
5661            }
5662
5663            let err = result.expect_err("persisting 401 must fail").to_string();
5664            assert!(
5665                err.contains("token re-resolved after cache clear but still rejected"),
5666                "expected distinct auth-failure error, got: {err}"
5667            );
5668            assert_eq!(
5669                hits.load(Ordering::SeqCst),
5670                2,
5671                "must retry exactly once, not loop"
5672            );
5673        }
5674    }
5675
5676    #[cfg(test)]
5677    mod contents_and_rulesets {
5678        use super::super::*;
5679        use std::env;
5680        use std::ffi::OsString;
5681        use wiremock::matchers::{method, path, query_param};
5682        use wiremock::{Mock, MockServer, ResponseTemplate};
5683
5684        struct EnvVarGuard {
5685            key: &'static str,
5686            previous: Option<OsString>,
5687        }
5688
5689        impl EnvVarGuard {
5690            fn set(key: &'static str, value: &str) -> Self {
5691                let previous = env::var_os(key);
5692                // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5693                unsafe { env::set_var(key, value) };
5694                Self { key, previous }
5695            }
5696        }
5697
5698        impl Drop for EnvVarGuard {
5699            fn drop(&mut self) {
5700                match self.previous.take() {
5701                    // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5702                    Some(value) => unsafe { env::set_var(self.key, value) },
5703                    // SAFETY: nextest runs each test in its own process, so no other test touches the environment
5704                    None => unsafe { env::remove_var(self.key) },
5705                }
5706            }
5707        }
5708
5709        fn client(server: &MockServer) -> (GhHttp, EnvVarGuard) {
5710            let guard = EnvVarGuard::set("GH_TOKEN", "test_token");
5711            (GhHttp::for_test(server.uri(), None), guard)
5712        }
5713
5714        #[tokio::test]
5715        async fn has_workflow_on_branch_is_false_when_the_directory_is_missing() {
5716            let server = MockServer::start().await;
5717            Mock::given(method("GET"))
5718                .and(path("/repos/o/r/contents/.github/workflows"))
5719                .and(query_param("ref", "main"))
5720                .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
5721                .mount(&server)
5722                .await;
5723            let (gh, _guard) = client(&server);
5724            assert!(!gh.has_workflow_on_branch("o/r", "main").await.unwrap());
5725        }
5726
5727        #[tokio::test]
5728        async fn has_workflow_on_branch_is_true_when_a_yaml_file_exists() {
5729            let server = MockServer::start().await;
5730            Mock::given(method("GET"))
5731                .and(path("/repos/o/r/contents/.github/workflows"))
5732                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
5733                    { "name": "ci.yml", "type": "file" }
5734                ])))
5735                .mount(&server)
5736                .await;
5737            let (gh, _guard) = client(&server);
5738            assert!(gh.has_workflow_on_branch("o/r", "main").await.unwrap());
5739        }
5740
5741        #[tokio::test]
5742        async fn has_file_on_branch_is_false_on_404() {
5743            let server = MockServer::start().await;
5744            Mock::given(method("GET"))
5745                .and(path("/repos/o/r/contents/shipcheck.toml"))
5746                .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
5747                .mount(&server)
5748                .await;
5749            let (gh, _guard) = client(&server);
5750            assert!(
5751                !gh.has_file_on_branch("o/r", "shipcheck.toml", "main")
5752                    .await
5753                    .unwrap()
5754            );
5755        }
5756
5757        #[tokio::test]
5758        async fn create_required_check_ruleset_posts_the_payload() {
5759            let server = MockServer::start().await;
5760            Mock::given(method("POST"))
5761                .and(path("/repos/o/r/rulesets"))
5762                .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
5763                    "id": 1,
5764                    "name": REQUIRED_CHECK_RULESET_NAME
5765                })))
5766                .expect(1)
5767                .mount(&server)
5768                .await;
5769            let (gh, _guard) = client(&server);
5770            gh.create_required_check_ruleset(
5771                "o/r",
5772                &[RequiredStatusCheck {
5773                    context: "test".to_string(),
5774                    integration_id: Some(15368),
5775                }],
5776            )
5777            .await
5778            .unwrap();
5779        }
5780
5781        #[tokio::test]
5782        async fn get_named_ruleset_required_checks_reads_the_named_ruleset() {
5783            let server = MockServer::start().await;
5784            Mock::given(method("GET"))
5785                .and(path("/repos/o/r/rulesets"))
5786                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
5787                    { "id": 8, "name": "other" },
5788                    { "id": 9, "name": REQUIRED_CHECK_RULESET_NAME }
5789                ])))
5790                .mount(&server)
5791                .await;
5792            Mock::given(method("GET"))
5793                .and(path("/repos/o/r/rulesets/9"))
5794                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5795                    "id": 9,
5796                    "name": REQUIRED_CHECK_RULESET_NAME,
5797                    "rules": [{
5798                        "type": "required_status_checks",
5799                        "parameters": {
5800                            "required_status_checks": [
5801                                { "context": "test", "integration_id": 15368 }
5802                            ]
5803                        }
5804                    }]
5805                })))
5806                .mount(&server)
5807                .await;
5808            let (gh, _guard) = client(&server);
5809            let (id, checks) = gh
5810                .get_named_ruleset_required_checks("o/r", REQUIRED_CHECK_RULESET_NAME)
5811                .await
5812                .unwrap()
5813                .expect("ruleset");
5814            assert_eq!(id, 9);
5815            assert_eq!(
5816                checks,
5817                vec![RequiredStatusCheck {
5818                    context: "test".to_string(),
5819                    integration_id: Some(15368),
5820                }]
5821            );
5822        }
5823
5824        #[tokio::test]
5825        async fn get_named_ruleset_required_checks_is_none_when_missing() {
5826            let server = MockServer::start().await;
5827            Mock::given(method("GET"))
5828                .and(path("/repos/o/r/rulesets"))
5829                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
5830                    { "id": 8, "name": "other" }
5831                ])))
5832                .mount(&server)
5833                .await;
5834            let (gh, _guard) = client(&server);
5835            assert!(
5836                gh.get_named_ruleset_required_checks("o/r", REQUIRED_CHECK_RULESET_NAME)
5837                    .await
5838                    .unwrap()
5839                    .is_none()
5840            );
5841        }
5842
5843        #[tokio::test]
5844        async fn update_required_check_ruleset_puts_the_payload() {
5845            let server = MockServer::start().await;
5846            Mock::given(method("PUT"))
5847                .and(path("/repos/o/r/rulesets/9"))
5848                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5849                    "id": 9,
5850                    "name": REQUIRED_CHECK_RULESET_NAME
5851                })))
5852                .expect(1)
5853                .mount(&server)
5854                .await;
5855            let (gh, _guard) = client(&server);
5856            gh.update_required_check_ruleset(
5857                "o/r",
5858                9,
5859                &[RequiredStatusCheck {
5860                    context: "test".to_string(),
5861                    integration_id: Some(15368),
5862                }],
5863            )
5864            .await
5865            .unwrap();
5866        }
5867
5868        #[tokio::test]
5869        async fn get_branch_sha_reads_commit_sha() {
5870            let server = MockServer::start().await;
5871            Mock::given(method("GET"))
5872                .and(path("/repos/o/r/branches/main"))
5873                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5874                    "name": "main",
5875                    "commit": { "sha": "abc123" }
5876                })))
5877                .mount(&server)
5878                .await;
5879            let (gh, _guard) = client(&server);
5880            assert_eq!(gh.get_branch_sha("o/r", "main").await.unwrap(), "abc123");
5881        }
5882    }
5883}