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