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