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