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!("{GITHUB_API}/repos/{repo}/issues/{number}"))
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!("{GITHUB_API}/repos/{repo}/issues/comments");
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!("{GITHUB_API}/repos/{repo}/issues/{issue_number}/comments");
1933        self.get_all_pages(&url, &[("per_page", "100")]).await
1934    }
1935
1936    /// Get the current authenticated username (cached after first call).
1937    pub async fn get_whoami(&self) -> anyhow::Result<String> {
1938        if let Some(cached) = self.cached_username.get() {
1939            return Ok(cached.clone());
1940        }
1941
1942        // An installation token cannot read `GET /user`, and the owner is the identity mentions name
1943        let mut owner = self.clone();
1944        owner.owner_only = true;
1945        let user: serde_json::Value = owner.get_json(&format!("{GITHUB_API}/user")).await?;
1946        let username = user
1947            .get("login")
1948            .and_then(|v| v.as_str())
1949            .map(String::from)
1950            .ok_or_else(|| anyhow::anyhow!("failed to get current user"))?;
1951
1952        let _ = self.cached_username.set(username.clone());
1953        Ok(username)
1954    }
1955
1956    /// Get PR number by branch name.
1957    pub async fn get_pr_number(&self, repo: &str, branch: &str) -> anyhow::Result<Option<u64>> {
1958        let owner = repo
1959            .split('/')
1960            .next()
1961            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {}", repo))?;
1962        let head = format!("{}:{}", owner, branch);
1963
1964        let url = format!("{GITHUB_API}/repos/{repo}/pulls");
1965        let prs: Vec<serde_json::Value> = self
1966            .get_with_query(
1967                &url,
1968                &[("head", &head), ("state", "open"), ("per_page", "1")],
1969            )
1970            .await?;
1971
1972        if prs.is_empty() {
1973            return Ok(None);
1974        }
1975        prs[0]
1976            .get("number")
1977            .and_then(|n| n.as_u64())
1978            .ok_or_else(|| anyhow::anyhow!("PR missing number field"))
1979            .map(Some)
1980    }
1981
1982    /// Create a new pull request.
1983    ///
1984    /// # Arguments
1985    /// * `repo` - Repository in "owner/repo" format
1986    /// * `title` - PR title
1987    /// * `body` - PR body/description
1988    /// * `head` - Branch name to create PR from
1989    /// * `base` - Base branch to merge into (e.g., "main")
1990    ///
1991    /// Returns the created PR's URL on success.
1992    pub async fn create_pr(
1993        &self,
1994        repo: &str,
1995        title: &str,
1996        body: &str,
1997        head: &str,
1998        base: &str,
1999    ) -> anyhow::Result<String> {
2000        use reqwest::header;
2001
2002        let body = redact_posted_body(body);
2003        let url = format!("{}/repos/{repo}/pulls", self.api_root());
2004        Self::check_backoff(&url)?;
2005
2006        #[derive(Serialize)]
2007        struct CreatePullRequest<'a> {
2008            title: &'a str,
2009            body: &'a str,
2010            head: &'a str,
2011            base: &'a str,
2012        }
2013
2014        let payload = CreatePullRequest {
2015            title,
2016            body: &body,
2017            head,
2018            base,
2019        };
2020
2021        let auth = self.auth_header(&url).await?;
2022        let make_req = || {
2023            Ok(self
2024                .client
2025                .post(&url)
2026                .header(header::AUTHORIZATION, auth.clone())
2027                .header(header::ACCEPT, "application/vnd.github+json")
2028                .header(header::USER_AGENT, "orch")
2029                .header("X-GitHub-Api-Version", "2022-11-28")
2030                .json(&payload))
2031        };
2032        let response = self.send_with_retries(make_req, false).await?;
2033        let status = response.status();
2034        let text = response.text().await.unwrap_or_default();
2035        if !status.is_success() {
2036            Self::maybe_record_rate_limit_from_body(status, &text);
2037            anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
2038        }
2039
2040        let pr: serde_json::Value = serde_json::from_str(&text)?;
2041        pr.get("html_url")
2042            .and_then(|v| v.as_str())
2043            .map(String::from)
2044            .ok_or_else(|| anyhow::anyhow!("failed to get PR URL from response: {:?}", pr))
2045    }
2046
2047    /// Get the repository's default branch from the GitHub API.
2048    ///
2049    /// Used as a fallback when local git detection yields an invalid base
2050    /// branch for PR creation.
2051    pub async fn get_default_branch(&self, repo: &str) -> anyhow::Result<String> {
2052        let url = format!("{GITHUB_API}/repos/{repo}");
2053        let resp: serde_json::Value = self.get_json(&url).await?;
2054        resp.get("default_branch")
2055            .and_then(|v| v.as_str())
2056            .map(String::from)
2057            .ok_or_else(|| anyhow::anyhow!("default_branch missing from repo response"))
2058    }
2059
2060    /// Get PR details by PR number.
2061    /// Returns the full PR object including the `mergeable` field.
2062    pub async fn get_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<GitHubPullRequest> {
2063        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}");
2064        self.get_json(&url).await
2065    }
2066
2067    /// Fetch the merged/state for multiple PRs in a single GraphQL query.
2068    ///
2069    /// Returns a map of pr_number → (merged, state).
2070    /// PRs that fail to fetch are silently omitted from the result.
2071    pub async fn batch_get_pr_states(
2072        &self,
2073        repo: &str,
2074        pr_numbers: &[u64],
2075    ) -> anyhow::Result<std::collections::HashMap<u64, (bool, String)>> {
2076        if pr_numbers.is_empty() {
2077            return Ok(std::collections::HashMap::new());
2078        }
2079
2080        let (owner, name) = repo
2081            .split_once('/')
2082            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {}", repo))?;
2083
2084        // GitHub GraphQL complexity limit: chunk at 50 to avoid slow/rejected queries.
2085        const CHUNK_SIZE: usize = 50;
2086        let mut result = std::collections::HashMap::new();
2087
2088        for chunk in pr_numbers.chunks(CHUNK_SIZE) {
2089            let aliases: String = chunk
2090                .iter()
2091                .map(|n| format!("pr{n}: pullRequest(number: {n}) {{ merged state }}"))
2092                .collect::<Vec<_>>()
2093                .join("\n  ");
2094
2095            let query = format!(
2096                r#"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"#
2097            );
2098
2099            let resp = self
2100                .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
2101                .await?;
2102            let repo_data = resp
2103                .pointer("/data/repository")
2104                .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
2105
2106            for n in chunk {
2107                if let Some(pr) = repo_data.get(format!("pr{n}")) {
2108                    let merged = pr.get("merged").and_then(|v| v.as_bool()).unwrap_or(false);
2109                    let state = pr
2110                        .get("state")
2111                        .and_then(|v| v.as_str())
2112                        .unwrap_or("UNKNOWN")
2113                        .to_lowercase();
2114                    result.insert(*n, (merged, state));
2115                }
2116            }
2117        }
2118
2119        Ok(result)
2120    }
2121
2122    /// Batch-fetch state and labels for multiple GitHub issues in a single GraphQL request.
2123    ///
2124    /// Returns a map of issue number (as string) → `(state, labels)` where state is
2125    /// lowercase ("open" / "closed") to match the REST API convention used elsewhere.
2126    pub async fn batch_get_issue_states(
2127        &self,
2128        repo: &str,
2129        issue_numbers: &[u64],
2130        caller_context: &str,
2131    ) -> anyhow::Result<std::collections::HashMap<String, (String, Vec<String>)>> {
2132        if issue_numbers.is_empty() {
2133            return Ok(std::collections::HashMap::new());
2134        }
2135
2136        let (valid_issue_numbers, invalid_issue_numbers) =
2137            sanitize_github_issue_numbers(issue_numbers);
2138        if !invalid_issue_numbers.is_empty() {
2139            tracing::warn!(
2140                repo,
2141                caller_context,
2142                invalid_issue_numbers = ?invalid_issue_numbers,
2143                total_supplied = issue_numbers.len(),
2144                "dropping invalid GitHub issue numbers before batch issue-state GraphQL query"
2145            );
2146        }
2147        if valid_issue_numbers.is_empty() {
2148            return Ok(std::collections::HashMap::new());
2149        }
2150
2151        let (owner, name) = repo
2152            .split_once('/')
2153            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {}", repo))?;
2154
2155        // GitHub GraphQL complexity limit: chunk at 50 to avoid slow/rejected queries.
2156        const CHUNK_SIZE: usize = 50;
2157        let mut result = std::collections::HashMap::new();
2158
2159        for chunk in valid_issue_numbers.chunks(CHUNK_SIZE) {
2160            let aliases: String = chunk
2161                .iter()
2162                .map(|n| {
2163                    format!("issue{n}: issue(number: {n}) {{ state labels(first: 100) {{ nodes {{ name }} }} }}")
2164                })
2165                .collect::<Vec<_>>()
2166                .join(" ");
2167
2168            let query = format!(
2169                r#"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"#
2170            );
2171
2172            let resp = self
2173                .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
2174                .await?;
2175            let repo_data = resp
2176                .pointer("/data/repository")
2177                .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
2178
2179            for n in chunk {
2180                if let Some(issue) = repo_data.get(format!("issue{n}")) {
2181                    let state = issue
2182                        .get("state")
2183                        .and_then(|v| v.as_str())
2184                        .unwrap_or("UNKNOWN")
2185                        .to_lowercase();
2186                    let labels: Vec<String> = issue
2187                        .pointer("/labels/nodes")
2188                        .and_then(|v| v.as_array())
2189                        .map(|arr| {
2190                            arr.iter()
2191                                .filter_map(|l| {
2192                                    l.get("name").and_then(|nm| nm.as_str()).map(String::from)
2193                                })
2194                                .collect()
2195                        })
2196                        .unwrap_or_default();
2197                    result.insert(n.to_string(), (state, labels));
2198                }
2199            }
2200        }
2201        Ok(result)
2202    }
2203
2204    /// Required status checks for a branch from classic protection and from rulesets
2205    pub async fn get_required_status_check_contexts(
2206        &self,
2207        repo: &str,
2208        branch: &str,
2209    ) -> anyhow::Result<Vec<RequiredStatusCheck>> {
2210        let branch = urlencoding::encode(branch);
2211        let classic_url = format!("{GITHUB_API}/repos/{repo}/branches/{branch}/protection");
2212        let rules_url = format!("{GITHUB_API}/repos/{repo}/rules/branches/{branch}");
2213
2214        let classic_fut = self.get_json::<serde_json::Value>(&classic_url);
2215        let rules_fut = self.get_all_pages::<serde_json::Value>(&rules_url, &[("per_page", "100")]);
2216        let (classic_resp, rules_resp) = tokio::join!(classic_fut, rules_fut);
2217
2218        let classic = match classic_resp {
2219            Ok(value) => parse_classic_required_status_checks(&value),
2220            Err(e) => {
2221                if is_no_branch_protection_error(&e.to_string()) {
2222                    Vec::new()
2223                } else {
2224                    return Err(e);
2225                }
2226            }
2227        };
2228
2229        let ruleset = match rules_resp {
2230            Ok(rules) => parse_ruleset_required_status_checks(&rules),
2231            Err(e) => {
2232                if e.to_string().contains("404") {
2233                    Vec::new()
2234                } else {
2235                    return Err(e);
2236                }
2237            }
2238        };
2239
2240        Ok(merge_required_status_checks(classic, ruleset))
2241    }
2242
2243    /// Get commit status contexts for a SHA.
2244    pub async fn get_commit_status_contexts(
2245        &self,
2246        repo: &str,
2247        sha: &str,
2248    ) -> anyhow::Result<Vec<(String, String)>> {
2249        let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}/status?per_page=100");
2250        // The /commits/{sha}/status endpoint returns a wrapper object:
2251        // { "state": "pending", "total_count": N, "statuses": [...] }
2252        // Use get_all_pages_from_wrapper to follow pagination and extract the
2253        // `statuses` array across pages so we don't silently truncate at 100.
2254        let statuses: Vec<serde_json::Value> =
2255            self.get_all_pages_from_wrapper(&url, "statuses").await?;
2256
2257        Ok(statuses
2258            .into_iter()
2259            .filter_map(|status| {
2260                let context = status.get("context").and_then(|v| v.as_str())?;
2261                let state = status.get("state").and_then(|v| v.as_str())?;
2262                Some((context.to_string(), state.to_string()))
2263            })
2264            .collect())
2265    }
2266
2267    fn combined_status_state(
2268        total: u64,
2269        failing: u64,
2270        pending: u64,
2271        has_workflows: bool,
2272        mergeable_state: Option<&str>,
2273    ) -> String {
2274        if failing > 0 {
2275            "failure".to_string()
2276        } else if pending > 0 {
2277            "pending".to_string()
2278        } else if total == 0 && has_workflows {
2279            // No check runs yet. If GitHub already reports mergeable_state="clean"
2280            // the PR is ready (e.g. all workflows use paths-ignore and skipped this
2281            // commit). Treating it as pending would stall auto-merge forever.
2282            if mergeable_state == Some("clean") {
2283                "success".to_string()
2284            } else {
2285                "pending".to_string()
2286            }
2287        } else {
2288            "success".to_string()
2289        }
2290    }
2291
2292    /// Return `true` when the repository has at least one GitHub Actions workflow.
2293    ///
2294    /// This is used to distinguish repos that genuinely have no CI configured from
2295    /// repos where CI exists but GitHub has not surfaced any runs yet.
2296    pub async fn has_workflows(&self, repo: &str) -> anyhow::Result<bool> {
2297        let url = format!("{GITHUB_API}/repos/{repo}/actions/workflows?per_page=1");
2298        let resp = self.get_json::<serde_json::Value>(&url).await;
2299        match resp {
2300            Ok(value) => Ok(value
2301                .get("workflows")
2302                .and_then(|v| v.as_array())
2303                .map(|workflows| !workflows.is_empty())
2304                .unwrap_or(false)),
2305            Err(e) => {
2306                let err = e.to_string();
2307                if err.contains("404") {
2308                    Ok(false)
2309                } else {
2310                    Err(e)
2311                }
2312            }
2313        }
2314    }
2315
2316    /// Get check runs for a PR head SHA.
2317    pub async fn get_check_runs(
2318        &self,
2319        repo: &str,
2320        sha: &str,
2321    ) -> anyhow::Result<Vec<GitHubCheckRun>> {
2322        // Use `filter=latest` so GitHub returns only the most recent check run
2323        // per check name. Without this, the API returns all runs (oldest
2324        // first) and callers that pick the first match may observe a stale
2325        // failed run when a newer run with the same name has succeeded.
2326        //
2327        // Use `per_page=100` and manual pagination via `get_all_pages_from_wrapper`
2328        // because this endpoint returns a *wrapper object* — `{ "total_count": N,
2329        // "check_runs": [...] }` — rather than a raw JSON array.  `get_all_pages`
2330        // cannot be used here because it calls `serde_json::from_str::<Vec<T>>`
2331        // which would fail on an object body.
2332        let url = format!(
2333            "{GITHUB_API}/repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100"
2334        );
2335        self.get_all_pages_from_wrapper(&url, "check_runs").await
2336    }
2337
2338    /// Get annotations for a specific check run.
2339    ///
2340    /// Returns the list of annotations attached to the check run, including
2341    /// billing failure messages ("The job was not started because recent account
2342    /// payments have failed …") that GitHub surfaces as annotations rather than
2343    /// as a distinct CI conclusion value.
2344    pub async fn get_check_run_annotations(
2345        &self,
2346        repo: &str,
2347        check_run_id: u64,
2348    ) -> anyhow::Result<Vec<GitHubAnnotation>> {
2349        let url = format!("{GITHUB_API}/repos/{repo}/check-runs/{check_run_id}/annotations");
2350        self.get_all_pages(&url, &[("per_page", "100")]).await
2351    }
2352
2353    /// Get reviews for a PR.
2354    pub async fn get_pr_reviews(
2355        &self,
2356        repo: &str,
2357        pr_number: u64,
2358    ) -> anyhow::Result<Vec<GitHubReview>> {
2359        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/reviews");
2360        self.get_all_pages(&url, &[("per_page", "100")]).await
2361    }
2362
2363    /// Get the committer timestamp for a specific commit SHA.
2364    ///
2365    /// Returns an ISO-8601 string, e.g. `"2024-01-15T12:00:00Z"`.
2366    /// Used to determine whether the branch has been updated since a review was submitted.
2367    pub async fn get_commit_timestamp(&self, repo: &str, sha: &str) -> anyhow::Result<String> {
2368        let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}");
2369        let value: serde_json::Value = self.get_json(&url).await?;
2370        value
2371            .pointer("/commit/committer/date")
2372            .and_then(|v| v.as_str())
2373            .map(|s| s.to_string())
2374            .ok_or_else(|| anyhow::anyhow!("commit {sha} has no committer date"))
2375    }
2376
2377    /// Update the body of a pull request.
2378    pub async fn update_pr_body(
2379        &self,
2380        repo: &str,
2381        pr_number: u64,
2382        body: &str,
2383    ) -> anyhow::Result<()> {
2384        let body = redact_posted_body(body);
2385        let url = format!("{}/repos/{repo}/pulls/{pr_number}", self.api_root());
2386        let payload = serde_json::json!({ "body": body });
2387        self.patch_json_raw(&url, &payload).await?;
2388        Ok(())
2389    }
2390
2391    /// Close a pull request without merging it.
2392    pub async fn close_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2393        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}");
2394        let payload = serde_json::json!({ "state": "closed" });
2395        self.patch_json_raw(&url, &payload).await?;
2396        Ok(())
2397    }
2398
2399    /// How many commits the head is missing from `base` (GitHub's `behind_by`).
2400    ///
2401    /// Zero means the head already contains the current base tip, so its checks
2402    /// ran against the code the merge would produce.
2403    pub async fn compare_behind_by(
2404        &self,
2405        repo: &str,
2406        base: &str,
2407        head_sha: &str,
2408    ) -> anyhow::Result<u64> {
2409        let url = format!("{GITHUB_API}/repos/{repo}/compare/{base}...{head_sha}");
2410        let body: serde_json::Value = self.get_json(&url).await?;
2411        parse_behind_by(&body)
2412    }
2413
2414    /// Close a GitHub issue.
2415    pub async fn close_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
2416        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
2417        let payload = serde_json::json!({ "state": "closed" });
2418        self.patch_json_raw(&url, &payload).await?;
2419        Ok(())
2420    }
2421
2422    /// Reopen a closed GitHub issue.
2423    pub async fn reopen_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
2424        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
2425        let payload = serde_json::json!({ "state": "open" });
2426        self.patch_json_raw(&url, &payload).await?;
2427        Ok(())
2428    }
2429
2430    /// Check if a user is a collaborator.
2431    pub async fn is_collaborator(&self, repo: &str, username: &str) -> anyhow::Result<bool> {
2432        let url = format!("{GITHUB_API}/repos/{repo}/collaborators/{username}");
2433        Self::check_backoff(&url)?;
2434        let auth = self.auth_header(&url).await?;
2435        let make_req = || {
2436            Ok(self
2437                .client
2438                .get(&url)
2439                .header(header::AUTHORIZATION, auth.clone())
2440                .header(header::ACCEPT, "application/vnd.github+json")
2441                .header("X-GitHub-Api-Version", "2022-11-28"))
2442        };
2443        let resp = self.send_with_retries(make_req, false).await?;
2444        let status = resp.status();
2445        if status == StatusCode::NO_CONTENT {
2446            Ok(true)
2447        } else if status == StatusCode::NOT_FOUND {
2448            Ok(false)
2449        } else {
2450            let body = resp.text().await.unwrap_or_default();
2451            anyhow::bail!("GitHub API collaborator check failed ({status}): {body}");
2452        }
2453    }
2454
2455    /// Add a sub-issue relationship via GraphQL.
2456    pub async fn add_sub_issue(
2457        &self,
2458        parent_node_id: &str,
2459        child_node_id: &str,
2460    ) -> anyhow::Result<()> {
2461        let query = format!(
2462            r#"mutation {{
2463                addSubIssue(input: {{issueId: "{}", subIssueId: "{}"}}) {{
2464                    issue {{ number }}
2465                    subIssue {{ number }}
2466                }}
2467            }}"#,
2468            parent_node_id, child_node_id
2469        );
2470        self.graphql_with_headers(&query, &["GraphQL-Features:sub_issues"])
2471            .await?;
2472        Ok(())
2473    }
2474
2475    /// Link an issue to a branch using GraphQL.
2476    ///
2477    /// Creates a "Development" sidebar link in GitHub that connects the issue
2478    /// to the branch, similar to `gh issue develop`.
2479    ///
2480    /// # Arguments
2481    /// * `repo` - Repository in "owner/repo" format
2482    /// * `issue_number` - The issue number to link
2483    /// * `branch` - The branch name to link the issue to
2484    ///
2485    /// Returns the linked branch ID on success.
2486    pub async fn link_issue_to_branch(
2487        &self,
2488        repo: &str,
2489        issue_number: u64,
2490        branch: &str,
2491    ) -> anyhow::Result<String> {
2492        let parts: Vec<&str> = repo.split('/').collect();
2493        if parts.len() != 2 {
2494            anyhow::bail!("invalid repo format: expected 'owner/repo', got '{}'", repo);
2495        }
2496        let (owner, repo_name) = (parts[0], parts[1]);
2497
2498        // First, get the repository and issue node IDs
2499        let query = r#"query($owner: String!, $name: String!, $number: Int!) {
2500                repository(owner: $owner, name: $name) {
2501                    id
2502                    issue(number: $number) {
2503                        id
2504                    }
2505                }
2506            }"#;
2507        let vars = serde_json::json!({
2508            "owner": owner,
2509            "name": repo_name,
2510            "number": issue_number,
2511        });
2512
2513        let result = self.graphql_with_vars(query, vars).await?;
2514
2515        let repo_id = result
2516            .pointer("/data/repository/id")
2517            .and_then(|v| v.as_str())
2518            .ok_or_else(|| anyhow::anyhow!("failed to get repository node ID"))?;
2519
2520        let issue_id = result
2521            .pointer("/data/repository/issue/id")
2522            .and_then(|v| v.as_str())
2523            .ok_or_else(|| anyhow::anyhow!("failed to get issue node ID"))?;
2524
2525        // Fetch branch ref to get the commit OID required by createLinkedBranch
2526        let branch_query = r#"query($owner: String!, $name: String!, $ref: String!) {
2527                repository(owner: $owner, name: $name) {
2528                    ref(qualifiedName: $ref) {
2529                        target {
2530                            oid
2531                        }
2532                    }
2533                }
2534            }"#;
2535        let branch_vars = serde_json::json!({
2536            "owner": owner,
2537            "name": repo_name,
2538            "ref": format!("refs/heads/{}", branch),
2539        });
2540
2541        let branch_result = self.graphql_with_vars(branch_query, branch_vars).await?;
2542        let branch_oid = branch_result
2543            .pointer("/data/repository/ref/target/oid")
2544            .and_then(|v| v.as_str());
2545
2546        // If branch doesn't exist yet, use the default branch OID.
2547        // createLinkedBranch will create the branch at that OID AND link it.
2548        let branch_oid = match branch_oid {
2549            Some(oid) => oid.to_string(),
2550            None => {
2551                // Get default branch OID as the base for the new branch
2552                let default_query = r#"query($owner: String!, $name: String!) {
2553                        repository(owner: $owner, name: $name) {
2554                            defaultBranchRef {
2555                                target {
2556                                    oid
2557                                }
2558                            }
2559                        }
2560                    }"#;
2561                let default_vars = serde_json::json!({
2562                    "owner": owner,
2563                    "name": repo_name,
2564                });
2565                let default_result = self.graphql_with_vars(default_query, default_vars).await?;
2566                match default_result
2567                    .pointer("/data/repository/defaultBranchRef/target/oid")
2568                    .and_then(|v| v.as_str())
2569                {
2570                    Some(oid) => {
2571                        tracing::debug!(
2572                            repo,
2573                            issue_number,
2574                            branch,
2575                            "branch not found, using default branch OID to create and link"
2576                        );
2577                        oid.to_string()
2578                    }
2579                    None => {
2580                        return Ok(format!("unlinked:{}", branch));
2581                    }
2582                }
2583            }
2584        };
2585
2586        // Use createLinkedBranch mutation to link the issue to the existing branch.
2587        // Required fields: issueId, repositoryId, name (branch name), oid (commit SHA).
2588        let mutation = r#"mutation($issueId: ID!, $repositoryId: ID!, $name: String!, $oid: GitObjectID!) {
2589                createLinkedBranch(input: {
2590                    issueId: $issueId
2591                    repositoryId: $repositoryId
2592                    name: $name
2593                    oid: $oid
2594                }) {
2595                    linkedBranch {
2596                        id
2597                        ref {
2598                            name
2599                        }
2600                    }
2601                }
2602            }"#;
2603        let mutation_vars = serde_json::json!({
2604            "issueId": issue_id,
2605            "repositoryId": repo_id,
2606            "name": branch,
2607            "oid": branch_oid,
2608        });
2609
2610        let link_result = self.graphql_with_vars(mutation, mutation_vars).await;
2611
2612        match link_result {
2613            Ok(result) => {
2614                let linked_branch_id = result
2615                    .pointer("/data/createLinkedBranch/linkedBranch/id")
2616                    .and_then(|v| v.as_str())
2617                    .map(String::from);
2618
2619                if let Some(id) = linked_branch_id {
2620                    tracing::info!(
2621                        repo,
2622                        issue_number,
2623                        branch,
2624                        "linked issue to branch via GraphQL API"
2625                    );
2626                    Ok(id)
2627                } else {
2628                    // Branch may already be linked - check for errors
2629                    let errors = result
2630                        .get("errors")
2631                        .and_then(|e| e.as_array())
2632                        .cloned()
2633                        .unwrap_or_default();
2634
2635                    if errors.iter().any(|e| {
2636                        e.get("message")
2637                            .and_then(|m| m.as_str())
2638                            .map(|m| m.contains("already"))
2639                            .unwrap_or(false)
2640                    }) {
2641                        tracing::debug!(
2642                            repo,
2643                            issue_number,
2644                            branch,
2645                            "issue already linked to branch"
2646                        );
2647                        Ok(format!("already_linked:{}", branch))
2648                    } else {
2649                        anyhow::bail!("failed to link issue to branch: {:?}", result)
2650                    }
2651                }
2652            }
2653            Err(e) => {
2654                // Check if it's a "already exists" type error
2655                let err_str = format!("{}", e);
2656                if err_str.contains("already") || err_str.contains("existing") {
2657                    tracing::debug!(
2658                        repo,
2659                        issue_number,
2660                        branch,
2661                        "issue already linked to branch (error check)"
2662                    );
2663                    Ok(format!("already_linked:{}", branch))
2664                } else {
2665                    Err(e)
2666                }
2667            }
2668        }
2669    }
2670
2671    /// Merge a PR using the REST API (squash merge).
2672    /// GitHub rejects it when the PR head is no longer `head_sha`, the commit CI was checked against
2673    pub async fn merge_pr(
2674        &self,
2675        repo: &str,
2676        pr_number: u64,
2677        delete_branch: bool,
2678        head_sha: &str,
2679    ) -> anyhow::Result<()> {
2680        if !is_full_commit_sha(head_sha) {
2681            anyhow::bail!("merge_pr requires the full head sha, got {head_sha:?}");
2682        }
2683        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/merge");
2684        Self::check_backoff(&url)?;
2685        let payload = merge_pr_body(head_sha);
2686        let auth = self.auth_header(&url).await?;
2687        let make_req = || {
2688            Ok(self
2689                .client
2690                .put(&url)
2691                .json(&payload)
2692                .header(header::AUTHORIZATION, auth.clone())
2693                .header(header::ACCEPT, "application/vnd.github+json")
2694                .header("X-GitHub-Api-Version", "2022-11-28"))
2695        };
2696        let resp = self.send_with_retries(make_req, false).await?;
2697        let status = resp.status();
2698        if !status.is_success() {
2699            let body = resp.text().await.unwrap_or_default();
2700            anyhow::bail!("GitHub PR merge failed ({status}): {body}");
2701        }
2702        Self::record_success();
2703
2704        // Delete branch if requested
2705        if delete_branch {
2706            // Get the head ref (branch name) from the PR
2707            let pr: serde_json::Value = self
2708                .get_json(&format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}"))
2709                .await?;
2710            if let Some(ref_name) = pr.pointer("/head/ref").and_then(|v| v.as_str()) {
2711                let del_url = format!("{GITHUB_API}/repos/{repo}/git/refs/heads/{ref_name}");
2712                if let Err(e) = self.delete(&del_url).await {
2713                    let err_str = e.to_string();
2714                    if err_str.contains("Reference does not exist") {
2715                        tracing::debug!(
2716                            ref_name,
2717                            "branch already gone (GitHub auto-deleted on merge)"
2718                        );
2719                    } else {
2720                        tracing::warn!(ref_name, err = %e, "failed to delete branch after merge");
2721                    }
2722                }
2723            }
2724        }
2725        Ok(())
2726    }
2727
2728    /// Update a PR's branch by merging the latest base branch into it
2729    /// (equivalent of the "Update branch" button on GitHub, or `gh pr
2730    /// update-branch`). Produces a new merge commit on the head branch,
2731    /// which re-triggers CI — used to give a PR a chance to pick up a fix
2732    /// that landed on the base branch after the PR's last CI run failed.
2733    pub async fn update_pr_branch(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2734        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/update-branch");
2735        Self::check_backoff(&url)?;
2736        let auth = self.auth_header(&url).await?;
2737        let make_req = || {
2738            Ok(self
2739                .client
2740                .put(&url)
2741                .header(header::AUTHORIZATION, auth.clone())
2742                .header(header::ACCEPT, "application/vnd.github+json")
2743                .header("X-GitHub-Api-Version", "2022-11-28"))
2744        };
2745        let resp = self.send_with_retries(make_req, false).await?;
2746        let status = resp.status();
2747        if !status.is_success() {
2748            let body = resp.text().await.unwrap_or_default();
2749            Self::maybe_record_rate_limit_from_body(status, &body);
2750            anyhow::bail!("GitHub PR update-branch failed ({status}): {body}");
2751        }
2752        Self::record_success();
2753        Ok(())
2754    }
2755
2756    /// Enable auto-merge on a PR via GraphQL.
2757    ///
2758    /// GitHub will automatically merge the PR once all required checks pass.
2759    pub async fn enable_auto_merge(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2760        let parts: Vec<&str> = repo.split('/').collect();
2761        if parts.len() != 2 {
2762            anyhow::bail!("invalid repo format: {repo}");
2763        }
2764        let (owner, repo_name) = (parts[0], parts[1]);
2765
2766        // First get the PR node ID
2767        let pr_query = r#"query($owner: String!, $name: String!, $number: Int!) {
2768            repository(owner: $owner, name: $name) {
2769                pullRequest(number: $number) { id }
2770            }
2771        }"#;
2772        let body = self
2773            .graphql_with_vars(
2774                pr_query,
2775                serde_json::json!({
2776                    "owner": owner,
2777                    "name": repo_name,
2778                    "number": pr_number,
2779                }),
2780            )
2781            .await?;
2782        let pr_id = body
2783            .pointer("/data/repository/pullRequest/id")
2784            .and_then(|v| v.as_str())
2785            .ok_or_else(|| anyhow::anyhow!("could not get PR node ID"))?
2786            .to_string();
2787
2788        // Enable auto-merge with squash
2789        let mutation = r#"mutation($prId: ID!) {
2790            enablePullRequestAutoMerge(input: {pullRequestId: $prId, mergeMethod: SQUASH}) {
2791                pullRequest { autoMergeRequest { enabledAt } }
2792            }
2793        }"#;
2794        let body = self
2795            .graphql_with_vars(mutation, serde_json::json!({ "prId": pr_id }))
2796            .await?;
2797        if let Some(errors) = body.get("errors") {
2798            anyhow::bail!("enable auto-merge GraphQL error: {errors}");
2799        }
2800
2801        tracing::info!(repo, pr_number, "auto-merge enabled on PR");
2802        Ok(())
2803    }
2804
2805    /// Get sub-issues via GraphQL (paginated).
2806    pub async fn get_sub_issues(&self, repo: &str, number: &str) -> anyhow::Result<Vec<u64>> {
2807        let parts: Vec<&str> = repo.split('/').collect();
2808        if parts.len() != 2 {
2809            anyhow::bail!("invalid repo format: expected 'owner/repo', got '{}'", repo);
2810        }
2811        let (owner, repo_name) = (parts[0], parts[1]);
2812        let number = match parse_positive_issue_number(number) {
2813            Ok(number) => number,
2814            Err(e) => {
2815                tracing::debug!(repo, issue = number, ?e, "skipping sub-issues lookup");
2816                return Ok(Vec::new());
2817            }
2818        };
2819
2820        let mut all_numbers: Vec<u64> = Vec::new();
2821        let mut cursor: Option<String> = None;
2822        let page_size = 100;
2823        let max_pages = 50;
2824        let mut page_count = 0;
2825
2826        loop {
2827            page_count += 1;
2828            if page_count > max_pages {
2829                tracing::warn!(
2830                    repo,
2831                    number,
2832                    "get_sub_issues hit max page limit ({max_pages})"
2833                );
2834                break;
2835            }
2836
2837            let (query, vars) = if let Some(ref c) = cursor {
2838                (
2839                    r#"query($owner: String!, $name: String!, $number: Int!, $first: Int!, $after: String!) {
2840                    repository(owner: $owner, name: $name) {
2841                        issue(number: $number) {
2842                            subIssues(first: $first, after: $after) {
2843                                nodes { number }
2844                                pageInfo { hasNextPage endCursor }
2845                            }
2846                        }
2847                    }
2848                }"#,
2849                    serde_json::json!({
2850                        "owner": owner,
2851                        "name": repo_name,
2852                        "number": number,
2853                        "first": page_size,
2854                        "after": c,
2855                    }),
2856                )
2857            } else {
2858                (
2859                    r#"query($owner: String!, $name: String!, $number: Int!, $first: Int!) {
2860                    repository(owner: $owner, name: $name) {
2861                        issue(number: $number) {
2862                            subIssues(first: $first) {
2863                                nodes { number }
2864                                pageInfo { hasNextPage endCursor }
2865                            }
2866                        }
2867                    }
2868                }"#,
2869                    serde_json::json!({
2870                        "owner": owner,
2871                        "name": repo_name,
2872                        "number": number,
2873                        "first": page_size,
2874                    }),
2875                )
2876            };
2877
2878            let result = self
2879                .graphql_with_headers_and_vars(query, &["GraphQL-Features:sub_issues"], vars)
2880                .await?;
2881
2882            let sub_issues_data = result
2883                .get("data")
2884                .and_then(|d| d.get("repository"))
2885                .and_then(|r| r.get("issue"))
2886                .and_then(|i| i.get("subIssues"));
2887
2888            let nodes = sub_issues_data
2889                .and_then(|s| s.get("nodes"))
2890                .and_then(|n| n.as_array());
2891
2892            match nodes {
2893                Some(nodes) => {
2894                    let numbers: Vec<u64> = nodes
2895                        .iter()
2896                        .filter_map(|n| n.get("number").and_then(|num| num.as_u64()))
2897                        .collect();
2898                    all_numbers.extend(numbers);
2899                }
2900                None => break,
2901            }
2902
2903            let page_info = sub_issues_data.and_then(|s| s.get("pageInfo"));
2904            let has_next = page_info
2905                .and_then(|p| p.get("hasNextPage"))
2906                .and_then(|h| h.as_bool())
2907                .unwrap_or(false);
2908
2909            if !has_next {
2910                break;
2911            }
2912
2913            cursor = page_info
2914                .and_then(|p| p.get("endCursor"))
2915                .and_then(|c| c.as_str())
2916                .map(|s| s.to_string());
2917        }
2918
2919        Ok(all_numbers)
2920    }
2921
2922    /// Get combined CI check status for a git ref.
2923    pub async fn get_combined_status(
2924        &self,
2925        repo: &str,
2926        git_ref: &str,
2927        has_workflows: bool,
2928        mergeable_state: Option<&str>,
2929    ) -> anyhow::Result<(String, u64, u64, u64, u64)> {
2930        let url = format!("{GITHUB_API}/repos/{repo}/commits/{git_ref}/check-runs");
2931        let resp: serde_json::Value = self.get_json(&url).await?;
2932
2933        let runs = resp
2934            .get("check_runs")
2935            .and_then(|v| v.as_array())
2936            .cloned()
2937            .unwrap_or_default();
2938
2939        let mut passing = 0u64;
2940        let mut failing = 0u64;
2941        let mut pending = 0u64;
2942
2943        for run in &runs {
2944            let conclusion = run.get("conclusion").and_then(|v| v.as_str()).unwrap_or("");
2945            let status = run
2946                .get("status")
2947                .and_then(|v| v.as_str())
2948                .unwrap_or("queued");
2949
2950            match status {
2951                "completed" => {
2952                    if conclusion.is_empty() {
2953                        pending += 1;
2954                    } else if matches!(conclusion, "success" | "neutral" | "skipped") {
2955                        passing += 1;
2956                    } else {
2957                        failing += 1;
2958                    }
2959                }
2960                _ => pending += 1,
2961            }
2962        }
2963
2964        let total = runs.len() as u64;
2965        let state =
2966            Self::combined_status_state(total, failing, pending, has_workflows, mergeable_state);
2967
2968        Ok((state, total, passing, failing, pending))
2969    }
2970
2971    /// Rerun the latest failed workflow run for a given workflow name and branch.
2972    ///
2973    /// Finds the most recent failed (or cancelled) run of `workflow_name` on
2974    /// `branch` triggered by a `push` event, then calls the GitHub Actions
2975    /// rerun endpoint so the **same check run** on the commit flips green.
2976    pub async fn rerun_failed_workflow(
2977        &self,
2978        repo: &str,
2979        workflow_name: &str,
2980        branch: &str,
2981    ) -> anyhow::Result<()> {
2982        // List recent runs for this branch, filtered to push events
2983        let url = format!(
2984            "{GITHUB_API}/repos/{repo}/actions/runs?branch={branch}&event=push&per_page=10"
2985        );
2986        let resp: serde_json::Value = self.get_json(&url).await?;
2987        let runs = resp["workflow_runs"]
2988            .as_array()
2989            .ok_or_else(|| anyhow::anyhow!("no workflow_runs array in response"))?;
2990
2991        // Find the latest failed/cancelled run matching the workflow name
2992        let run_id = runs
2993            .iter()
2994            .find(|r| {
2995                r["name"].as_str() == Some(workflow_name)
2996                    && matches!(
2997                        r["conclusion"].as_str(),
2998                        Some("failure") | Some("cancelled")
2999                    )
3000            })
3001            .and_then(|r| r["id"].as_u64())
3002            .ok_or_else(|| {
3003                anyhow::anyhow!(
3004                    "no failed run found for workflow '{}' on branch '{}'",
3005                    workflow_name,
3006                    branch
3007                )
3008            })?;
3009
3010        // POST rerun — no body needed
3011        let rerun_url = format!("{GITHUB_API}/repos/{repo}/actions/runs/{run_id}/rerun");
3012        let auth = self.auth_header(&rerun_url).await?;
3013        let make_req = || {
3014            Ok(self
3015                .client
3016                .post(&rerun_url)
3017                .header(header::AUTHORIZATION, auth.clone())
3018                .header(header::ACCEPT, "application/vnd.github+json")
3019                .header("X-GitHub-Api-Version", "2022-11-28"))
3020        };
3021        let resp = self.send_with_retries(make_req, false).await?;
3022        let status = resp.status();
3023        if !status.is_success() {
3024            let body = resp.text().await.unwrap_or_default();
3025            Self::maybe_record_rate_limit_from_body(status, &body);
3026            anyhow::bail!("GitHub API POST rerun {rerun_url} failed ({status}): {body}");
3027        }
3028
3029        Ok(())
3030    }
3031
3032    /// Fetch reviews, review comments, and issue comments for multiple PRs in a
3033    /// single GraphQL query instead of 4–5 REST calls per PR.
3034    ///
3035    /// Returns a map of `pr_number → PrReviewBatchData`.
3036    /// PRs missing from the response are omitted from the result.
3037    pub async fn batch_fetch_pr_review_data(
3038        &self,
3039        repo: &str,
3040        pr_numbers: &[u64],
3041    ) -> anyhow::Result<std::collections::HashMap<u64, PrReviewBatchData>> {
3042        if pr_numbers.is_empty() {
3043            return Ok(std::collections::HashMap::new());
3044        }
3045
3046        let (owner, name) = repo
3047            .split_once('/')
3048            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {}", repo))?;
3049
3050        // Build one GraphQL alias per PR number.
3051        let aliases: String = pr_numbers
3052            .iter()
3053            .map(|&n| build_pr_review_alias(n))
3054            .collect::<Vec<_>>()
3055            .join("\n");
3056
3057        let query = format!(
3058            r#"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"#
3059        );
3060
3061        let resp = self
3062            .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
3063            .await?;
3064        let repo_data = resp
3065            .pointer("/data/repository")
3066            .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
3067
3068        let mut result = std::collections::HashMap::new();
3069        for &n in pr_numbers {
3070            let Some(pr_data) = repo_data.get(format!("pr{n}")) else {
3071                continue;
3072            };
3073
3074            let merged = pr_data
3075                .get("merged")
3076                .and_then(|v| v.as_bool())
3077                .unwrap_or(false);
3078            let mergeable = match pr_data.get("mergeable").and_then(|v| v.as_str()) {
3079                Some("MERGEABLE") => Some(true),
3080                Some("CONFLICTING") => Some(false),
3081                _ => None, // UNKNOWN or missing
3082            };
3083
3084            let mut reviews: Vec<GitHubReview> = pr_data
3085                .pointer("/reviews/nodes")
3086                .and_then(|v| v.as_array())
3087                .map(|nodes| nodes.iter().filter_map(parse_graphql_review).collect())
3088                .unwrap_or_default();
3089
3090            if connection_has_next_page(pr_data.pointer("/reviews/pageInfo")) {
3091                tracing::warn!(
3092                    pr_number = n,
3093                    fetched = reviews.len(),
3094                    "batch review fetch truncated reviews connection at first page"
3095                );
3096            }
3097
3098            // Ensure deterministic ordering by submitted timestamp (oldest -> newest).
3099            // GraphQL connections do not guarantee a stable sort unless explicitly
3100            // requested. Sort here so consumers can rely on chronological order.
3101            reviews.sort_by(|a, b| a.submitted_at.cmp(&b.submitted_at));
3102
3103            let mut review_comments: Vec<GitHubReviewComment> = pr_data
3104                .pointer("/reviewThreads/nodes")
3105                .and_then(|v| v.as_array())
3106                .map(|threads| {
3107                    threads
3108                        .iter()
3109                        .filter_map(|thread| {
3110                            thread
3111                                .pointer("/comments/nodes")
3112                                .and_then(|v| v.as_array())
3113                                .map(|nodes| {
3114                                    nodes
3115                                        .iter()
3116                                        .filter_map(parse_graphql_review_comment)
3117                                        .collect::<Vec<_>>()
3118                                })
3119                        })
3120                        .flatten()
3121                        .collect()
3122                })
3123                .unwrap_or_default();
3124
3125            if connection_has_next_page(pr_data.pointer("/reviewThreads/pageInfo")) {
3126                tracing::warn!(
3127                    pr_number = n,
3128                    fetched_threads = pr_data
3129                        .pointer("/reviewThreads/nodes")
3130                        .and_then(|v| v.as_array())
3131                        .map_or(0, |threads| threads.len()),
3132                    "batch review fetch truncated reviewThreads connection at first page"
3133                );
3134            }
3135            if pr_data
3136                .pointer("/reviewThreads/nodes")
3137                .and_then(|v| v.as_array())
3138                .is_some_and(|threads| {
3139                    threads.iter().any(|thread| {
3140                        connection_has_next_page(thread.pointer("/comments/pageInfo"))
3141                    })
3142                })
3143            {
3144                tracing::warn!(
3145                    pr_number = n,
3146                    "batch review fetch truncated one or more review thread comment connections"
3147                );
3148            }
3149
3150            // Sort inline review comments by created_at (oldest -> newest) so
3151            // callers can process them deterministically.
3152            review_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
3153
3154            let mut issue_comments: Vec<GitHubComment> = pr_data
3155                .pointer("/comments/nodes")
3156                .and_then(|v| v.as_array())
3157                .map(|nodes| {
3158                    nodes
3159                        .iter()
3160                        .filter_map(parse_graphql_issue_comment)
3161                        .collect()
3162                })
3163                .unwrap_or_default();
3164
3165            if let Some(cursor) = connection_end_cursor(pr_data.pointer("/comments/pageInfo")) {
3166                issue_comments.extend(
3167                    self.fetch_pr_issue_comments_after(owner, name, n, Some(cursor))
3168                        .await?,
3169                );
3170            }
3171
3172            // Sort issue-level comments by created_at (oldest -> newest). The
3173            // review poll logic expects chronological ordering and may iterate
3174            // in reverse to find the latest comments — so ensure a consistent
3175            // ordering here regardless of GraphQL's default.
3176            issue_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
3177
3178            result.insert(
3179                n,
3180                PrReviewBatchData {
3181                    merged,
3182                    head_sha: pr_data
3183                        .get("headRefOid")
3184                        .and_then(|v| v.as_str())
3185                        .unwrap_or_default()
3186                        .to_string(),
3187                    mergeable,
3188                    reviews,
3189                    review_comments,
3190                    issue_comments,
3191                },
3192            );
3193        }
3194
3195        Ok(result)
3196    }
3197
3198    async fn fetch_pr_issue_comments_after(
3199        &self,
3200        owner: &str,
3201        name: &str,
3202        pr_number: u64,
3203        mut cursor: Option<String>,
3204    ) -> anyhow::Result<Vec<GitHubComment>> {
3205        let mut comments = Vec::new();
3206        let mut page_count = 0;
3207        let max_pages = 50;
3208
3209        while let Some(current_cursor) = cursor.take() {
3210            page_count += 1;
3211            if page_count > max_pages {
3212                tracing::warn!(
3213                    pr_number,
3214                    fetched = comments.len(),
3215                    "stopping PR issue comment pagination after max page limit"
3216                );
3217                break;
3218            }
3219
3220            let (query, vars) =
3221                build_pr_issue_comments_page_query(owner, name, pr_number, &current_cursor);
3222            let resp = self.graphql_with_vars(&query, vars).await?;
3223            let comments_data = resp
3224                .pointer("/data/repository/pullRequest/comments")
3225                .ok_or_else(|| {
3226                    anyhow::anyhow!(
3227                        "missing /data/repository/pullRequest/comments in GraphQL response"
3228                    )
3229                })?;
3230
3231            comments.extend(
3232                comments_data
3233                    .get("nodes")
3234                    .and_then(|v| v.as_array())
3235                    .into_iter()
3236                    .flatten()
3237                    .filter_map(parse_graphql_issue_comment),
3238            );
3239
3240            cursor = connection_end_cursor(comments_data.get("pageInfo"));
3241        }
3242
3243        Ok(comments)
3244    }
3245
3246    /// Check the latest automated review comment on a PR.
3247    pub async fn get_automated_review_status(
3248        &self,
3249        repo: &str,
3250        pr_number: u64,
3251    ) -> anyhow::Result<Option<String>> {
3252        let comments = self.list_comments(repo, &pr_number.to_string()).await?;
3253
3254        // Find the most recent automated review comment authored by a collaborator or the App
3255        let app_login = super::app::bot_login().await;
3256        let mut newest: Option<&crate::github::types::GitHubComment> = None;
3257        for c in &comments {
3258            if !c.body.starts_with("## Automated Review") {
3259                continue;
3260            }
3261            let trusted = match app_login.as_deref() {
3262                Some(app) if super::app::same_login(&c.user.login, app) => Ok(true),
3263                _ => self.is_collaborator(repo, &c.user.login).await,
3264            };
3265            match trusted {
3266                Ok(true) => match newest {
3267                    None => newest = Some(c),
3268                    Some(prev) => {
3269                        if c.created_at > prev.created_at {
3270                            newest = Some(c);
3271                        }
3272                    }
3273                },
3274                Ok(false) => {
3275                    tracing::warn!(
3276                        user = %c.user.login,
3277                        pr_number,
3278                        "ignoring automated review comment from non-collaborator"
3279                    );
3280                    continue;
3281                }
3282                Err(e) => {
3283                    tracing::debug!(
3284                        user = %c.user.login,
3285                        error = %e,
3286                        "failed to check collaborator status, skipping comment"
3287                    );
3288                    continue;
3289                }
3290            }
3291        }
3292
3293        match newest {
3294            Some(c) => {
3295                let first_line = c.body.lines().next().unwrap_or("");
3296                if first_line.contains("Automated Review \u{2014} Approve") {
3297                    Ok(Some("approve".to_string()))
3298                } else if first_line.contains("Automated Review \u{2014} Changes Requested") {
3299                    Ok(Some("changes_requested".to_string()))
3300                } else {
3301                    Ok(None)
3302                }
3303            }
3304            None => Ok(None),
3305        }
3306    }
3307}
3308
3309/// Read `behind_by` out of a compare response.
3310///
3311/// A missing field is an error, not zero: treating an unreadable response as
3312/// "head is up to date" would let a stale PR merge
3313fn parse_behind_by(body: &serde_json::Value) -> anyhow::Result<u64> {
3314    body.get("behind_by")
3315        .and_then(|v| v.as_u64())
3316        .ok_or_else(|| anyhow::anyhow!("compare response has no numeric behind_by field"))
3317}
3318
3319/// A branch protection read that means "no protection": 404 "Branch not protected", or the 403
3320/// GitHub returns for private repos on the Free plan
3321fn is_no_branch_protection_error(err: &str) -> bool {
3322    err.contains("404")
3323        || (err.contains("403")
3324            && err.contains("Upgrade to GitHub Pro or make this repository public"))
3325}
3326
3327/// Classic protection prefers `checks` (includes `app_id`) and falls back to `contexts`
3328fn parse_classic_required_status_checks(value: &serde_json::Value) -> Vec<RequiredStatusCheck> {
3329    if let Some(checks) = value
3330        .pointer("/required_status_checks/checks")
3331        .and_then(|v| v.as_array())
3332    {
3333        let parsed: Vec<RequiredStatusCheck> =
3334            checks.iter().filter_map(parse_classic_check).collect();
3335        if !parsed.is_empty() {
3336            return parsed;
3337        }
3338    }
3339
3340    value
3341        .pointer("/required_status_checks/contexts")
3342        .and_then(|v| v.as_array())
3343        .map(|contexts| {
3344            contexts
3345                .iter()
3346                .filter_map(|context| {
3347                    context.as_str().map(|s| RequiredStatusCheck {
3348                        context: s.to_string(),
3349                        integration_id: None,
3350                    })
3351                })
3352                .collect()
3353        })
3354        .unwrap_or_default()
3355}
3356
3357fn parse_classic_check(check: &serde_json::Value) -> Option<RequiredStatusCheck> {
3358    let context = check.get("context")?.as_str()?.to_string();
3359    let integration_id = check
3360        .get("app_id")
3361        .and_then(|v| v.as_i64())
3362        .filter(|&id| id > 0);
3363    Some(RequiredStatusCheck {
3364        context,
3365        integration_id,
3366    })
3367}
3368
3369/// Collect `required_status_checks` entries from every active `required_status_checks` rule
3370fn parse_ruleset_required_status_checks(rules: &[serde_json::Value]) -> Vec<RequiredStatusCheck> {
3371    let mut out = Vec::new();
3372    for rule in rules {
3373        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3374            continue;
3375        }
3376        let Some(checks) = rule
3377            .pointer("/parameters/required_status_checks")
3378            .or_else(|| rule.get("required_status_checks"))
3379            .and_then(|v| v.as_array())
3380        else {
3381            continue;
3382        };
3383        for check in checks {
3384            let Some(context) = check.get("context").and_then(|v| v.as_str()) else {
3385                continue;
3386            };
3387            let integration_id = check
3388                .get("integration_id")
3389                .and_then(|v| v.as_i64())
3390                .filter(|&id| id > 0);
3391            out.push(RequiredStatusCheck {
3392                context: context.to_string(),
3393                integration_id,
3394            });
3395        }
3396    }
3397    out
3398}
3399
3400fn merge_required_status_checks(
3401    mut checks: Vec<RequiredStatusCheck>,
3402    extra: Vec<RequiredStatusCheck>,
3403) -> Vec<RequiredStatusCheck> {
3404    checks.extend(extra);
3405    let mut seen = std::collections::HashSet::new();
3406    checks.retain(|c| seen.insert((c.context.clone(), c.integration_id)));
3407    checks
3408}
3409
3410fn sanitize_github_issue_numbers(issue_numbers: &[u64]) -> (Vec<u64>, Vec<u64>) {
3411    let mut valid = Vec::with_capacity(issue_numbers.len());
3412    let mut invalid = Vec::new();
3413    for &issue_number in issue_numbers {
3414        if issue_number == 0 {
3415            invalid.push(issue_number);
3416        } else {
3417            valid.push(issue_number);
3418        }
3419    }
3420    (valid, invalid)
3421}
3422
3423// ── Public metrics ───────────────────────────────────────────────────
3424
3425/// Snapshot of GitHub API rate-limit metrics.
3426#[derive(Debug, Clone)]
3427pub struct RateLimitMetrics {
3428    /// Total 403/429 rate-limit responses received (REST + GraphQL combined).
3429    pub hits: u64,
3430    /// Calls skipped because the quota was low or a backoff was active.
3431    pub skipped_calls: u64,
3432    /// Current REST remaining quota (None if not yet observed).
3433    pub rest_remaining: Option<u32>,
3434    /// UTC epoch second when the REST window resets (None if not yet observed).
3435    pub rest_reset_at: Option<u64>,
3436    /// Current GraphQL remaining quota (None if not yet observed).
3437    pub graphql_remaining: Option<u32>,
3438    /// Total 5xx server error responses received (REST + GraphQL combined).
3439    pub five_xx_hits: u64,
3440}
3441
3442/// Return a snapshot of GitHub API rate-limit metrics.
3443pub fn rate_limit_metrics() -> RateLimitMetrics {
3444    let (rest_remaining, rest_reset_at) = REST_RATE_LIMIT
3445        .lock()
3446        .ok()
3447        .map(|rl| (rl.remaining, rl.reset_at))
3448        .unwrap_or((None, None));
3449    let graphql_remaining = GRAPHQL_RATE_LIMIT.lock().ok().and_then(|rl| rl.remaining);
3450    RateLimitMetrics {
3451        hits: METRIC_RATE_LIMIT_HITS.load(Ordering::Relaxed),
3452        skipped_calls: METRIC_PROACTIVE_THROTTLES.load(Ordering::Relaxed),
3453        rest_remaining,
3454        rest_reset_at,
3455        graphql_remaining,
3456        five_xx_hits: METRIC_5XX_HITS.load(Ordering::Relaxed),
3457    }
3458}
3459
3460// ── Link header parser ───────────────────────────────────────────────
3461
3462/// Parse the `Link` header to find the `rel="next"` URL.
3463fn parse_link_next(headers: &header::HeaderMap) -> Option<String> {
3464    let link = headers.get("link")?.to_str().ok()?;
3465    for part in link.split(',') {
3466        let part = part.trim();
3467        if part.contains("rel=\"next\"") {
3468            // Extract URL between < and >
3469            let start = part.find('<')? + 1;
3470            let end = part.find('>')?;
3471            if start >= end {
3472                return None;
3473            }
3474            return Some(part[start..end].to_string());
3475        }
3476    }
3477    None
3478}
3479
3480/// Return the hex color string for a given `status:*` label.
3481pub fn status_label_color(label: &str) -> &'static str {
3482    match label {
3483        "status:new" => "0e8a16",
3484        "status:routed" => "1d76db",
3485        "status:in_progress" => "fbca04",
3486        "status:done" => "6f42c1",
3487        "status:blocked" => "d73a4a",
3488        "status:in_review" => "0075ca",
3489        "status:needs_review" => "e4e669",
3490        "status:waiting" => "5319e7",
3491        _ => "c5def5",
3492    }
3493}
3494
3495// ── Batch GraphQL helpers ─────────────────────────────────────────────
3496
3497/// Data fetched for one PR by [`GhHttp::batch_fetch_pr_review_data`].
3498#[derive(Debug, Clone, Default)]
3499pub struct PrReviewBatchData {
3500    /// True when the pull request was merged.
3501    pub merged: bool,
3502    /// Head commit of the pull request, empty when GitHub did not return it.
3503    pub head_sha: String,
3504    /// `Some(true)` = MERGEABLE, `Some(false)` = CONFLICTING, `None` = UNKNOWN.
3505    pub mergeable: Option<bool>,
3506    /// All reviews submitted on the PR.
3507    pub reviews: Vec<GitHubReview>,
3508    /// All inline review comments (from all review threads).
3509    pub review_comments: Vec<GitHubReviewComment>,
3510    /// All issue-level comments on the PR.
3511    pub issue_comments: Vec<GitHubComment>,
3512}
3513
3514/// Build a GraphQL alias fragment for one pull request, fetching all data
3515/// needed by the review poll loop in a single batch request.
3516fn build_pr_review_alias(n: u64) -> String {
3517    format!(
3518        r#"pr{n}: pullRequest(number: {n}) {{
3519  merged
3520  mergeable
3521  headRefOid
3522  reviews(first: 50) {{
3523    nodes {{
3524      databaseId
3525      author {{ login }}
3526      body
3527      state
3528      url
3529      submittedAt
3530      commit {{ oid }}
3531    }}
3532    pageInfo {{ hasNextPage }}
3533  }}
3534  reviewThreads(first: 50) {{
3535    nodes {{
3536      comments(first: 20) {{
3537        nodes {{
3538          databaseId
3539          author {{ login }}
3540          body
3541          path
3542          line
3543          originalLine
3544          commit {{ oid }}
3545          originalCommit {{ oid }}
3546          url
3547          createdAt
3548          updatedAt
3549          replyTo {{ databaseId }}
3550          diffHunk
3551        }}
3552        pageInfo {{ hasNextPage }}
3553      }}
3554    }}
3555    pageInfo {{ hasNextPage }}
3556  }}
3557  comments(first: 50) {{
3558    nodes {{
3559      databaseId
3560      author {{ login }}
3561      body
3562      createdAt
3563      updatedAt
3564      url
3565    }}
3566    pageInfo {{ hasNextPage endCursor }}
3567  }}
3568}}"#
3569    )
3570}
3571
3572fn build_pr_issue_comments_page_query(
3573    owner: &str,
3574    name: &str,
3575    pr_number: u64,
3576    after_cursor: &str,
3577) -> (String, serde_json::Value) {
3578    let query = r#"query($owner: String!, $name: String!, $number: Int!, $after: String!) {
3579  repository(owner: $owner, name: $name) {
3580    pullRequest(number: $number) {
3581      comments(first: 100, after: $after) {
3582        nodes {
3583          databaseId
3584          author { login }
3585          body
3586          createdAt
3587          updatedAt
3588          url
3589        }
3590        pageInfo { hasNextPage endCursor }
3591      }
3592    }
3593  }
3594}"#
3595    .to_string();
3596    let vars = serde_json::json!({
3597        "owner": owner,
3598        "name": name,
3599        "number": pr_number,
3600        "after": after_cursor,
3601    });
3602    (query, vars)
3603}
3604
3605fn connection_has_next_page(page_info: Option<&serde_json::Value>) -> bool {
3606    page_info
3607        .and_then(|v| v.get("hasNextPage"))
3608        .and_then(|v| v.as_bool())
3609        .unwrap_or(false)
3610}
3611
3612fn connection_end_cursor(page_info: Option<&serde_json::Value>) -> Option<String> {
3613    if !connection_has_next_page(page_info) {
3614        return None;
3615    }
3616
3617    page_info
3618        .and_then(|v| v.get("endCursor"))
3619        .and_then(|v| v.as_str())
3620        .map(str::to_owned)
3621}
3622
3623fn parse_graphql_review(node: &serde_json::Value) -> Option<GitHubReview> {
3624    use super::types::GitHubUser;
3625    Some(GitHubReview {
3626        id: node.get("databaseId").and_then(|v| v.as_u64())?,
3627        user: GitHubUser {
3628            login: node
3629                .pointer("/author/login")
3630                .and_then(|v| v.as_str())?
3631                .to_string(),
3632        },
3633        body: node.get("body").and_then(|v| v.as_str()).map(String::from),
3634        state: node.get("state").and_then(|v| v.as_str())?.to_string(),
3635        html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
3636        submitted_at: node
3637            .get("submittedAt")
3638            .and_then(|v| v.as_str())
3639            .unwrap_or("")
3640            .to_string(),
3641        commit_id: node
3642            .pointer("/commit/oid")
3643            .and_then(|v| v.as_str())
3644            .map(String::from),
3645    })
3646}
3647
3648fn parse_graphql_review_comment(node: &serde_json::Value) -> Option<GitHubReviewComment> {
3649    use super::types::GitHubUser;
3650    Some(GitHubReviewComment {
3651        id: node.get("databaseId").and_then(|v| v.as_u64())?,
3652        user: GitHubUser {
3653            login: node
3654                .pointer("/author/login")
3655                .and_then(|v| v.as_str())?
3656                .to_string(),
3657        },
3658        body: node.get("body").and_then(|v| v.as_str())?.to_string(),
3659        path: node
3660            .get("path")
3661            .and_then(|v| v.as_str())
3662            .unwrap_or("")
3663            .to_string(),
3664        line: node.get("line").and_then(|v| v.as_u64()).map(|v| v as u32),
3665        original_line: node
3666            .get("originalLine")
3667            .and_then(|v| v.as_u64())
3668            .map(|v| v as u32),
3669        commit_id: node
3670            .pointer("/commit/oid")
3671            .and_then(|v| v.as_str())
3672            .unwrap_or("")
3673            .to_string(),
3674        original_commit_id: node
3675            .pointer("/originalCommit/oid")
3676            .and_then(|v| v.as_str())
3677            .unwrap_or("")
3678            .to_string(),
3679        html_url: node
3680            .get("url")
3681            .and_then(|v| v.as_str())
3682            .unwrap_or("")
3683            .to_string(),
3684        created_at: node
3685            .get("createdAt")
3686            .and_then(|v| v.as_str())
3687            .unwrap_or("")
3688            .to_string(),
3689        updated_at: node
3690            .get("updatedAt")
3691            .and_then(|v| v.as_str())
3692            .unwrap_or("")
3693            .to_string(),
3694        in_reply_to_id: node.pointer("/replyTo/databaseId").and_then(|v| v.as_u64()),
3695        diff_hunk: node
3696            .get("diffHunk")
3697            .and_then(|v| v.as_str())
3698            .map(String::from),
3699    })
3700}
3701
3702fn parse_graphql_issue_comment(node: &serde_json::Value) -> Option<GitHubComment> {
3703    use super::types::GitHubUser;
3704    Some(GitHubComment {
3705        id: node.get("databaseId").and_then(|v| v.as_u64())?,
3706        body: node.get("body").and_then(|v| v.as_str())?.to_string(),
3707        user: GitHubUser {
3708            login: node
3709                .pointer("/author/login")
3710                .and_then(|v| v.as_str())?
3711                .to_string(),
3712        },
3713        created_at: node
3714            .get("createdAt")
3715            .and_then(|v| v.as_str())
3716            .unwrap_or("")
3717            .to_string(),
3718        updated_at: node
3719            .get("updatedAt")
3720            .and_then(|v| v.as_str())
3721            .map(String::from),
3722        html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
3723        issue_url: None,
3724        author_association: None,
3725    })
3726}
3727
3728#[cfg(test)]
3729mod tests {
3730    use super::*;
3731    use tokio::io::{AsyncReadExt, AsyncWriteExt};
3732    use tokio::net::TcpListener;
3733
3734    #[test]
3735    fn repo_from_url_names_the_repository_or_nothing() {
3736        let api = "https://api.github.com";
3737        assert_eq!(
3738            repo_from_url(&format!("{api}/repos/me/a/pulls/9")).as_deref(),
3739            Some("me/a")
3740        );
3741        assert_eq!(
3742            repo_from_url(&format!("{api}/repos/org/b?per_page=1")).as_deref(),
3743            Some("org/b")
3744        );
3745        assert_eq!(
3746            repo_from_url(&format!("{api}/repos/org/b")).as_deref(),
3747            Some("org/b")
3748        );
3749        assert_eq!(repo_from_url(&format!("{api}/graphql")), None);
3750        assert_eq!(repo_from_url(&format!("{api}/user")), None);
3751        assert_eq!(repo_from_url(&format!("{api}/repos/only-owner")), None);
3752    }
3753
3754    #[test]
3755    fn no_branch_protection_errors() {
3756        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.\"}";
3757        assert!(is_no_branch_protection_error(free_plan));
3758        assert!(is_no_branch_protection_error(
3759            "failed (404 Not Found): {\"message\":\"Branch not protected\"}"
3760        ));
3761        assert!(!is_no_branch_protection_error(
3762            "failed (403 Forbidden): {\"message\":\"Resource not accessible\"}"
3763        ));
3764    }
3765
3766    #[test]
3767    fn parse_classic_required_status_checks_reads_checks_app_id() {
3768        let value = serde_json::json!({
3769            "required_status_checks": {
3770                "contexts": ["ci/test"],
3771                "checks": [{ "context": "ci/test", "app_id": 42 }]
3772            }
3773        });
3774        assert_eq!(
3775            parse_classic_required_status_checks(&value),
3776            vec![RequiredStatusCheck {
3777                context: "ci/test".to_string(),
3778                integration_id: Some(42),
3779            }]
3780        );
3781    }
3782
3783    #[test]
3784    fn parse_classic_required_status_checks_falls_back_to_contexts() {
3785        let value = serde_json::json!({
3786            "required_status_checks": {
3787                "contexts": ["ci/test", "lint"]
3788            }
3789        });
3790        assert_eq!(
3791            parse_classic_required_status_checks(&value),
3792            vec![
3793                RequiredStatusCheck {
3794                    context: "ci/test".to_string(),
3795                    integration_id: None,
3796                },
3797                RequiredStatusCheck {
3798                    context: "lint".to_string(),
3799                    integration_id: None,
3800                }
3801            ]
3802        );
3803    }
3804
3805    #[test]
3806    fn parse_classic_required_status_checks_empty_when_unprotected() {
3807        assert!(parse_classic_required_status_checks(&serde_json::json!({})).is_empty());
3808    }
3809
3810    #[test]
3811    fn parse_ruleset_required_status_checks_reads_integration_id() {
3812        let rules = vec![
3813            serde_json::json!({ "type": "pull_request" }),
3814            serde_json::json!({
3815                "type": "required_status_checks",
3816                "parameters": {
3817                    "required_status_checks": [
3818                        { "context": "ci/test", "integration_id": 42 },
3819                        { "context": "lint" }
3820                    ]
3821                }
3822            }),
3823        ];
3824        assert_eq!(
3825            parse_ruleset_required_status_checks(&rules),
3826            vec![
3827                RequiredStatusCheck {
3828                    context: "ci/test".to_string(),
3829                    integration_id: Some(42),
3830                },
3831                RequiredStatusCheck {
3832                    context: "lint".to_string(),
3833                    integration_id: None,
3834                }
3835            ]
3836        );
3837    }
3838
3839    #[test]
3840    fn parse_ruleset_required_status_checks_treats_zero_integration_id_as_any_app() {
3841        let rules = vec![serde_json::json!({
3842            "type": "required_status_checks",
3843            "parameters": {
3844                "required_status_checks": [{ "context": "ci/test", "integration_id": 0 }]
3845            }
3846        })];
3847        assert_eq!(
3848            parse_ruleset_required_status_checks(&rules),
3849            vec![RequiredStatusCheck {
3850                context: "ci/test".to_string(),
3851                integration_id: None,
3852            }]
3853        );
3854    }
3855
3856    #[test]
3857    fn merge_required_status_checks_dedupes_identical_pairs() {
3858        let classic = vec![RequiredStatusCheck {
3859            context: "ci/test".to_string(),
3860            integration_id: None,
3861        }];
3862        let ruleset = vec![
3863            RequiredStatusCheck {
3864                context: "ci/test".to_string(),
3865                integration_id: None,
3866            },
3867            RequiredStatusCheck {
3868                context: "ci/test".to_string(),
3869                integration_id: Some(42),
3870            },
3871        ];
3872        assert_eq!(
3873            merge_required_status_checks(classic, ruleset),
3874            vec![
3875                RequiredStatusCheck {
3876                    context: "ci/test".to_string(),
3877                    integration_id: None,
3878                },
3879                RequiredStatusCheck {
3880                    context: "ci/test".to_string(),
3881                    integration_id: Some(42),
3882                }
3883            ]
3884        );
3885    }
3886
3887    #[test]
3888    fn parse_behind_by_reads_compare_status() {
3889        // A head behind the base must not merge: its checks ran against old code.
3890        let behind = serde_json::json!({"status": "behind", "behind_by": 3, "ahead_by": 0});
3891        assert_eq!(parse_behind_by(&behind).unwrap(), 3);
3892        let diverged = serde_json::json!({"status": "diverged", "behind_by": 1, "ahead_by": 2});
3893        assert_eq!(parse_behind_by(&diverged).unwrap(), 1);
3894        let ahead = serde_json::json!({"status": "ahead", "behind_by": 0, "ahead_by": 2});
3895        assert_eq!(parse_behind_by(&ahead).unwrap(), 0);
3896        // An unreadable response is an error, never a permissive zero.
3897        assert!(parse_behind_by(&serde_json::json!({"status": "ahead"})).is_err());
3898    }
3899
3900    async fn spawn_truncated_body_server(body_prefix: &'static str) -> String {
3901        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
3902        let addr = listener.local_addr().unwrap();
3903
3904        tokio::spawn(async move {
3905            let (mut socket, _) = listener.accept().await.unwrap();
3906            let mut buf = [0u8; 4096];
3907            let _ = socket.read(&mut buf).await;
3908
3909            let declared_len = body_prefix.len() + 32;
3910            let response = format!(
3911                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {declared_len}\r\nconnection: close\r\n\r\n{body_prefix}"
3912            );
3913            socket.write_all(response.as_bytes()).await.unwrap();
3914            socket.shutdown().await.unwrap();
3915        });
3916
3917        format!("http://{addr}")
3918    }
3919
3920    #[test]
3921    fn merge_pr_body_pins_the_head_sha() {
3922        let sha = "0123456789abcdef0123456789abcdef01234567";
3923        let body = merge_pr_body(sha);
3924        assert_eq!(body["merge_method"], "squash");
3925        assert_eq!(body["sha"], sha);
3926        assert!(is_full_commit_sha(sha));
3927        assert!(!is_full_commit_sha("abc"));
3928        assert!(!is_full_commit_sha(""));
3929    }
3930
3931    fn test_client() -> GhHttp {
3932        GhHttp {
3933            client: reqwest::Client::new(),
3934            token_resolver: Arc::new(crate::github::token::TokenResolver::default_env()),
3935            app: None,
3936            owner_only: false,
3937            cached_username: OnceLock::new(),
3938            api_base: None,
3939        }
3940    }
3941
3942    /// Verify `GhHttp::new()` returns `Ok` and does not panic on construction.
3943    ///
3944    /// This test guards against regressions where `GhHttp::new()` might panic
3945    /// (e.g., if TLS initialisation fails or the builder API changes).
3946    #[test]
3947    fn gh_http_new_returns_ok() {
3948        let result = GhHttp::new();
3949        assert!(
3950            result.is_ok(),
3951            "GhHttp::new() must not panic and must return Ok; got: {:?}",
3952            result.err()
3953        );
3954    }
3955
3956    #[test]
3957    fn batch_get_issue_states_query_includes_labels_pagination() {
3958        let issue_numbers = [1u64, 2, 3];
3959
3960        let aliases: String = issue_numbers
3961            .iter()
3962            .map(|n| {
3963                format!("issue{n}: issue(number: {n}) {{ state labels(first: 100) {{ nodes {{ name }} }} }}")
3964            })
3965            .collect::<Vec<_>>()
3966            .join(" ");
3967
3968        let query = format!(
3969            r#"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"#
3970        );
3971        assert!(query.contains("$owner"));
3972        assert!(query.contains("$name"));
3973        assert!(query.contains("issue1: issue(number: 1)"));
3974        assert!(query.contains("issue3: issue(number: 3)"));
3975        assert!(query.contains("labels(first: 100)"));
3976    }
3977
3978    #[test]
3979    fn parse_positive_issue_number_accepts_positive_values() {
3980        assert_eq!(parse_positive_issue_number("42").unwrap(), 42);
3981    }
3982
3983    #[test]
3984    fn parse_positive_issue_number_rejects_zero() {
3985        let err = parse_positive_issue_number("0").unwrap_err().to_string();
3986        assert!(err.contains("invalid issue number: 0"));
3987    }
3988
3989    #[test]
3990    fn parse_positive_issue_number_rejects_internal_ids() {
3991        let err = parse_positive_issue_number("internal:5")
3992            .unwrap_err()
3993            .to_string();
3994        assert!(err.contains("invalid issue number: internal:5"));
3995    }
3996
3997    #[test]
3998    fn pr_review_batch_query_includes_page_info_for_nested_connections() {
3999        let query = build_pr_review_alias(42);
4000
4001        assert!(query.contains("reviews(first: 50)"));
4002        assert!(query.contains("reviews(first: 50) {\n    nodes"));
4003        assert!(query.contains("pageInfo { hasNextPage }"));
4004        assert!(query.contains("reviewThreads(first: 50)"));
4005        assert!(query.contains("comments(first: 20)"));
4006        assert!(query.contains("pageInfo { hasNextPage endCursor }"));
4007        assert!(query.contains("updatedAt"));
4008    }
4009
4010    #[test]
4011    fn pr_issue_comments_page_query_uses_cursor_pagination() {
4012        let (query, vars) = build_pr_issue_comments_page_query("owner", "repo", 42, "cursor123");
4013
4014        assert!(query.contains("pullRequest(number: $number)"));
4015        assert!(query.contains("comments(first: 100, after: $after)"));
4016        assert!(query.contains("pageInfo { hasNextPage endCursor }"));
4017        assert!(query.contains("updatedAt"));
4018        assert_eq!(vars["owner"], "owner");
4019        assert_eq!(vars["name"], "repo");
4020        assert_eq!(vars["number"], 42);
4021        assert_eq!(vars["after"], "cursor123");
4022    }
4023
4024    #[test]
4025    fn connection_end_cursor_only_returns_cursor_when_more_pages_exist() {
4026        let page_info = serde_json::json!({
4027            "hasNextPage": true,
4028            "endCursor": "cursor123"
4029        });
4030        assert_eq!(
4031            connection_end_cursor(Some(&page_info)),
4032            Some("cursor123".to_string())
4033        );
4034
4035        let final_page = serde_json::json!({
4036            "hasNextPage": false,
4037            "endCursor": "cursor456"
4038        });
4039        assert_eq!(connection_end_cursor(Some(&final_page)), None);
4040    }
4041
4042    #[test]
4043    fn status_label_colors_match_bash_palette() {
4044        assert_eq!(status_label_color("status:new"), "0e8a16");
4045        assert_eq!(status_label_color("status:routed"), "1d76db");
4046        assert_eq!(status_label_color("status:in_progress"), "fbca04");
4047        assert_eq!(status_label_color("status:done"), "6f42c1");
4048        assert_eq!(status_label_color("status:blocked"), "d73a4a");
4049        assert_eq!(status_label_color("status:in_review"), "0075ca");
4050        assert_eq!(status_label_color("status:needs_review"), "e4e669");
4051    }
4052
4053    #[test]
4054    fn unknown_label_gets_default_color() {
4055        assert_eq!(status_label_color("agent:claude"), "c5def5");
4056        assert_eq!(status_label_color("enhancement"), "c5def5");
4057        assert_eq!(status_label_color(""), "c5def5");
4058    }
4059
4060    #[test]
4061    fn parse_link_next_finds_next_url() {
4062        let mut headers = header::HeaderMap::new();
4063        headers.insert(
4064            "link",
4065            "<https://api.github.com/repos/foo/bar/issues?page=2>; rel=\"next\", <https://api.github.com/repos/foo/bar/issues?page=5>; rel=\"last\""
4066                .parse()
4067                .unwrap(),
4068        );
4069        assert_eq!(
4070            parse_link_next(&headers),
4071            Some("https://api.github.com/repos/foo/bar/issues?page=2".to_string())
4072        );
4073    }
4074
4075    #[test]
4076    fn parse_link_next_none_when_no_next() {
4077        let mut headers = header::HeaderMap::new();
4078        headers.insert(
4079            "link",
4080            "<https://api.github.com/repos/foo/bar/issues?page=1>; rel=\"prev\""
4081                .parse()
4082                .unwrap(),
4083        );
4084        assert_eq!(parse_link_next(&headers), None);
4085    }
4086
4087    #[test]
4088    fn parse_link_next_none_when_missing() {
4089        let headers = header::HeaderMap::new();
4090        assert_eq!(parse_link_next(&headers), None);
4091    }
4092
4093    #[test]
4094    fn parse_link_next_none_when_malformed() {
4095        let mut headers = header::HeaderMap::new();
4096        // Malformed: no angle-bracket URL, just garbage
4097        headers.insert("link", "garbage; rel=\"next\"".parse().unwrap());
4098        assert_eq!(parse_link_next(&headers), None);
4099    }
4100
4101    #[test]
4102    fn parse_link_next_none_when_gt_before_lt() {
4103        let mut headers = header::HeaderMap::new();
4104        headers.insert("link", ">junk; rel=\"next\"; <url>".parse().unwrap());
4105        assert_eq!(parse_link_next(&headers), None); // should not panic
4106    }
4107
4108    #[test]
4109    fn parse_link_next_none_when_empty_url() {
4110        let mut headers = header::HeaderMap::new();
4111        headers.insert("link", "<>; rel=\"next\"".parse().unwrap());
4112        assert_eq!(parse_link_next(&headers), None);
4113    }
4114
4115    fn make_rl(base_secs: u64, max_secs: u64) -> RateLimit {
4116        RateLimit {
4117            remaining: None,
4118            reset_at: None,
4119            backoff_until: None,
4120            backoff_delay: Duration::ZERO,
4121            backoff_base: Duration::from_secs(base_secs),
4122            backoff_max: Duration::from_secs(max_secs),
4123            throttle_threshold: 10,
4124        }
4125    }
4126
4127    #[test]
4128    fn rate_limit_inactive_by_default() {
4129        let rl = make_rl(30, 900);
4130        assert!(rl.is_active().is_none());
4131    }
4132
4133    #[test]
4134    fn rate_limit_backoff_activates() {
4135        let mut rl = make_rl(5, 60);
4136        rl.record_rate_limit();
4137        assert!(rl.is_active().is_some());
4138        assert_eq!(rl.backoff_delay, Duration::from_secs(5));
4139    }
4140
4141    #[test]
4142    fn rate_limit_backoff_doubles() {
4143        let mut rl = make_rl(5, 60);
4144        rl.record_rate_limit();
4145        assert_eq!(rl.backoff_delay, Duration::from_secs(5));
4146        rl.record_rate_limit();
4147        assert_eq!(rl.backoff_delay, Duration::from_secs(10));
4148        rl.record_rate_limit();
4149        assert_eq!(rl.backoff_delay, Duration::from_secs(20));
4150    }
4151
4152    #[test]
4153    fn rate_limit_backoff_caps_at_max() {
4154        let mut rl = make_rl(30, 60);
4155        rl.record_rate_limit(); // 30
4156        rl.record_rate_limit(); // 60
4157        rl.record_rate_limit(); // capped at 60
4158        assert_eq!(rl.backoff_delay, Duration::from_secs(60));
4159    }
4160
4161    #[test]
4162    fn rate_limit_success_resets() {
4163        let mut rl = make_rl(5, 60);
4164        rl.record_rate_limit();
4165        assert!(rl.is_active().is_some());
4166        rl.record_success();
4167        assert!(rl.is_active().is_none());
4168        assert_eq!(rl.backoff_delay, Duration::ZERO);
4169    }
4170
4171    #[test]
4172    fn page_cache_key_separates_types_and_queries() {
4173        let a = page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "open")])).unwrap();
4174        let b = page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "closed")])).unwrap();
4175        let c = page_cache_key::<serde_json::Value>("/issues", Some(&[("state", "open")])).unwrap();
4176        assert_ne!(a, b);
4177        assert_ne!(a, c);
4178        assert_eq!(
4179            a,
4180            page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "open")])).unwrap()
4181        );
4182    }
4183
4184    /// `since` is derived from the clock, so the key would never recur.
4185    #[test]
4186    fn page_cache_key_skips_since_filtered_requests() {
4187        assert!(page_cache_key::<GitHubIssue>(
4188            "/issues",
4189            Some(&[("state", "closed"), ("since", "2026-10-01T00:00:00Z")])
4190        )
4191        .is_none());
4192        // Also when it arrives embedded in a Link: next URL.
4193        assert!(
4194            page_cache_key::<GitHubIssue>("/issues?since=2026-10-01T00:00:00Z&page=2", None)
4195                .is_none()
4196        );
4197    }
4198
4199    /// A limiter with no quota left and a reset an hour out: the check must return an
4200    /// error straight away. Sleeping here is what froze the tick loop for 504s.
4201    #[test]
4202    fn low_quota_fails_fast_instead_of_waiting_for_reset() {
4203        let mut rl = make_rl(30, 900);
4204        rl.remaining = Some(0);
4205        rl.reset_at = Some(
4206            std::time::SystemTime::now()
4207                .duration_since(std::time::UNIX_EPOCH)
4208                .unwrap()
4209                .as_secs()
4210                + 3600,
4211        );
4212        let cell = Mutex::new(rl);
4213
4214        let start = Instant::now();
4215        let err = check_rate_limit_backoff(&cell, "REST").unwrap_err();
4216        assert!(
4217            start.elapsed() < Duration::from_secs(1),
4218            "check blocked for {:?}",
4219            start.elapsed()
4220        );
4221        assert!(err.to_string().contains("rate-limited"), "{err}");
4222    }
4223
4224    /// Quota above the reserve is not a reason to skip the call.
4225    #[test]
4226    fn healthy_quota_passes_the_check() {
4227        let mut rl = make_rl(30, 900);
4228        rl.remaining = Some(4000);
4229        rl.reset_at = Some(u64::MAX / 2);
4230        let cell = Mutex::new(rl);
4231        assert!(check_rate_limit_backoff(&cell, "REST").is_ok());
4232    }
4233
4234    #[test]
4235    fn rate_limit_proactive_pause() {
4236        let mut rl = make_rl(30, 900);
4237        // Simulate: 0 remaining (below default threshold of 10), reset 60s in the future
4238        rl.remaining = Some(0);
4239        let future_epoch = std::time::SystemTime::now()
4240            .duration_since(std::time::UNIX_EPOCH)
4241            .unwrap()
4242            .as_secs()
4243            + 60;
4244        rl.reset_at = Some(future_epoch);
4245        let pause = rl.is_active();
4246        assert!(pause.is_some());
4247        // Should be roughly 60 seconds (within tolerance, +1s buffer added)
4248        assert!(pause.unwrap().as_secs() <= 62);
4249    }
4250
4251    #[test]
4252    fn rate_limit_proactive_pause_threshold() {
4253        let mut rl = make_rl(30, 900);
4254        // remaining=15 is above default threshold of 10 — no proactive wait
4255        rl.remaining = Some(15);
4256        let future_epoch = std::time::SystemTime::now()
4257            .duration_since(std::time::UNIX_EPOCH)
4258            .unwrap()
4259            .as_secs()
4260            + 60;
4261        rl.reset_at = Some(future_epoch);
4262        assert!(rl.is_active().is_none());
4263
4264        // remaining=5 is below threshold — proactive wait activates
4265        rl.remaining = Some(5);
4266        assert!(rl.is_active().is_some());
4267    }
4268
4269    #[test]
4270    fn combined_status_state_treats_empty_checks_as_pending_when_workflows_exist() {
4271        // No check runs yet and GitHub hasn't said it's clean → pending (wait for CI to queue)
4272        assert_eq!(
4273            GhHttp::combined_status_state(0, 0, 0, true, None),
4274            "pending"
4275        );
4276        // No workflows configured → no need to wait
4277        assert_eq!(
4278            GhHttp::combined_status_state(0, 0, 0, false, None),
4279            "success"
4280        );
4281        // Failing check → failure regardless
4282        assert_eq!(
4283            GhHttp::combined_status_state(3, 1, 0, true, None),
4284            "failure"
4285        );
4286        // paths-ignore filtered out all workflows: no check runs but GitHub says "clean"
4287        assert_eq!(
4288            GhHttp::combined_status_state(0, 0, 0, true, Some("clean")),
4289            "success"
4290        );
4291        // mergeable_state is dirty/blocked — still pending even with has_workflows
4292        assert_eq!(
4293            GhHttp::combined_status_state(0, 0, 0, true, Some("dirty")),
4294            "pending"
4295        );
4296    }
4297
4298    #[test]
4299    fn batch_is_pr_merged_by_branch_errors_when_repository_data_missing() {
4300        let resp = serde_json::json!({
4301            "data": {},
4302            "errors": [{ "message": "Something went wrong" }],
4303        });
4304
4305        let err_text = GhHttp::parse_batch_pr_merged_response(&resp, &["branch".to_string()])
4306            .unwrap_err()
4307            .to_string();
4308        assert!(err_text.contains("missing /data/repository in GraphQL response"));
4309        assert!(err_text.contains("Something went wrong"));
4310    }
4311
4312    #[test]
4313    fn rate_limit_uses_reset_at_for_backoff() {
4314        let mut rl = make_rl(30, 900);
4315        // Set reset_at to 45s in the future
4316        let future_epoch = std::time::SystemTime::now()
4317            .duration_since(std::time::UNIX_EPOCH)
4318            .unwrap()
4319            .as_secs()
4320            + 45;
4321        rl.reset_at = Some(future_epoch);
4322        rl.record_rate_limit();
4323        // Backoff should use reset_at (~46s) not the base (30s)
4324        assert!(rl.backoff_delay.as_secs() >= 45);
4325        assert!(rl.backoff_delay.as_secs() <= 47);
4326    }
4327
4328    #[tokio::test]
4329    async fn send_with_retries_propagates_make_req_error() {
4330        let guard = std::env::var_os("GH_TOKEN");
4331        std::env::set_var("GH_TOKEN", "test_token");
4332        let gh = test_client();
4333        let result = gh
4334            .send_with_retries(
4335                || Err(anyhow::anyhow!("simulated request clone failure")),
4336                false,
4337            )
4338            .await;
4339        assert!(result.is_err());
4340        let err = result.unwrap_err().to_string();
4341        assert_eq!(err, "simulated request clone failure");
4342        match guard {
4343            Some(v) => std::env::set_var("GH_TOKEN", v),
4344            None => std::env::remove_var("GH_TOKEN"),
4345        }
4346    }
4347
4348    /// A transport-level failure (connection refused — GitHub never reached)
4349    /// must exhaust retries without tripping the shared "github:5xx" circuit
4350    /// breaker: that breaker is read by the routing-phase skip and other
4351    /// subsystems as a signal specifically about GitHub's health, which a
4352    /// local connectivity blip says nothing about.
4353    #[tokio::test]
4354    async fn send_with_retries_transport_error_does_not_trip_5xx_breaker() {
4355        let guard = std::env::var_os("GH_TOKEN");
4356        std::env::set_var("GH_TOKEN", "test_token");
4357
4358        // Bind then immediately drop a listener to get a port nothing is
4359        // listening on, so connecting reliably fails with "connection refused"
4360        // rather than depending on an external unreachable host.
4361        let addr = {
4362            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4363            listener.local_addr().unwrap()
4364        };
4365        let url = format!("http://{addr}/");
4366
4367        let gh = test_client();
4368        let make_req = || Ok(gh.client.get(&url));
4369        let result = gh.send_with_retries(make_req, false).await;
4370
4371        assert!(result.is_err());
4372        assert!(
4373            !crate::engine::cooldown::is_agent_in_cooldown("github:5xx"),
4374            "transport error must not trip the github:5xx circuit breaker"
4375        );
4376        assert!(crate::engine::cooldown::cooldown_until("github:5xx").is_none());
4377
4378        match guard {
4379            Some(v) => std::env::set_var("GH_TOKEN", v),
4380            None => std::env::remove_var("GH_TOKEN"),
4381        }
4382    }
4383
4384    #[tokio::test]
4385    async fn post_json_raw_propagates_body_read_errors_on_success() {
4386        let guard = std::env::var_os("GH_TOKEN");
4387        std::env::set_var("GH_TOKEN", "test_token");
4388        let server_url = spawn_truncated_body_server("{").await;
4389        let gh = test_client();
4390
4391        let result = gh
4392            .post_json_raw(
4393                &format!("{server_url}/post"),
4394                &serde_json::json!({"ok": true}),
4395            )
4396            .await;
4397
4398        let err = result.unwrap_err().to_string();
4399        assert!(
4400            !err.contains("EOF while parsing a value"),
4401            "should surface the body read error, got: {err}"
4402        );
4403        assert!(
4404            err.contains("error decoding response body")
4405                || err.contains("request or response body error")
4406                || err.contains("end of file before message length reached"),
4407            "expected a transport/body read error, got: {err}"
4408        );
4409
4410        match guard {
4411            Some(v) => std::env::set_var("GH_TOKEN", v),
4412            None => std::env::remove_var("GH_TOKEN"),
4413        }
4414    }
4415
4416    #[tokio::test]
4417    async fn patch_json_raw_propagates_body_read_errors_on_success() {
4418        let guard = std::env::var_os("GH_TOKEN");
4419        std::env::set_var("GH_TOKEN", "test_token");
4420        let server_url = spawn_truncated_body_server("{").await;
4421        let gh = test_client();
4422
4423        let result = gh
4424            .patch_json_raw(
4425                &format!("{server_url}/patch"),
4426                &serde_json::json!({"ok": true}),
4427            )
4428            .await;
4429
4430        let err = result.unwrap_err().to_string();
4431        assert!(
4432            !err.contains("EOF while parsing a value"),
4433            "should surface the body read error, got: {err}"
4434        );
4435        assert!(
4436            err.contains("error decoding response body")
4437                || err.contains("request or response body error")
4438                || err.contains("end of file before message length reached"),
4439            "expected a transport/body read error, got: {err}"
4440        );
4441
4442        match guard {
4443            Some(v) => std::env::set_var("GH_TOKEN", v),
4444            None => std::env::remove_var("GH_TOKEN"),
4445        }
4446    }
4447
4448    #[tokio::test]
4449    async fn graphql_request_propagates_body_read_errors_on_success() {
4450        let guard = std::env::var_os("GH_TOKEN");
4451        std::env::set_var("GH_TOKEN", "test_token");
4452        let server_url = spawn_truncated_body_server("{").await;
4453        let gh = test_client();
4454        let query = "query { viewer { login } }";
4455
4456        let result = gh
4457            .graphql_request_to_url(
4458                &format!("{server_url}/graphql"),
4459                query,
4460                &[],
4461                Some(serde_json::json!({"k": "v"})),
4462            )
4463            .await;
4464
4465        let err = result.unwrap_err().to_string();
4466        assert!(
4467            !err.contains("EOF while parsing a value"),
4468            "should surface the body read error, got: {err}"
4469        );
4470        assert!(
4471            err.contains("error decoding response body")
4472                || err.contains("request or response body error")
4473                || err.contains("end of file before message length reached"),
4474            "expected a transport/body read error, got: {err}"
4475        );
4476
4477        match guard {
4478            Some(v) => std::env::set_var("GH_TOKEN", v),
4479            None => std::env::remove_var("GH_TOKEN"),
4480        }
4481    }
4482
4483    // ── get_all_pages integration tests (wiremock) ────────────────────────
4484
4485    #[cfg(test)]
4486    mod pagination {
4487        use super::super::*;
4488        use std::ffi::OsString;
4489        use std::sync::Arc;
4490        use wiremock::matchers::{method, path};
4491        use wiremock::{matchers, Match, Mock, MockServer, Request, ResponseTemplate};
4492
4493        /// wiremock has no negated matcher, and the first poll must be matched on the
4494        /// absence of `If-None-Match` to tell it apart from the conditional one.
4495        struct NotMatcher<M>(M);
4496
4497        impl<M: Match> Match for NotMatcher<M> {
4498            fn matches(&self, request: &Request) -> bool {
4499                !self.0.matches(request)
4500            }
4501        }
4502
4503        struct EnvVarGuard {
4504            key: &'static str,
4505            previous: Option<OsString>,
4506        }
4507
4508        impl EnvVarGuard {
4509            fn set(key: &'static str, value: &str) -> Self {
4510                let previous = std::env::var_os(key);
4511                std::env::set_var(key, value);
4512                Self { key, previous }
4513            }
4514        }
4515
4516        impl Drop for EnvVarGuard {
4517            fn drop(&mut self) {
4518                match self.previous.take() {
4519                    Some(value) => std::env::set_var(self.key, value),
4520                    None => std::env::remove_var(self.key),
4521                }
4522            }
4523        }
4524
4525        /// Build a minimal GhHttp pointing at a wiremock server.
4526        /// The token resolver reads GH_TOKEN; we set it to a dummy value.
4527        fn make_client() -> (GhHttp, EnvVarGuard) {
4528            // Ensure a token is available so auth_header() doesn't bail.
4529            let guard = EnvVarGuard::set("GH_TOKEN", "test_token");
4530            let client = GhHttp {
4531                client: reqwest::Client::new(),
4532                token_resolver: Arc::new(crate::github::token::TokenResolver::default_env()),
4533                app: None,
4534                owner_only: false,
4535                cached_username: OnceLock::new(),
4536                api_base: None,
4537            };
4538            (client, guard)
4539        }
4540
4541        #[tokio::test]
4542        async fn get_all_pages_single_page() {
4543            let server = MockServer::start().await;
4544
4545            Mock::given(method("GET"))
4546                .and(path("/items"))
4547                .respond_with(
4548                    ResponseTemplate::new(200)
4549                        .set_body_json(serde_json::json!([{"id": 1}, {"id": 2}])),
4550                )
4551                .expect(1)
4552                .mount(&server)
4553                .await;
4554
4555            let (gh, _guard) = make_client();
4556            let url = format!("{}/items", server.uri());
4557            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4558
4559            assert_eq!(result.len(), 2);
4560            assert_eq!(result[0]["id"], 1);
4561            assert_eq!(result[1]["id"], 2);
4562        }
4563
4564        #[tokio::test]
4565        async fn get_all_pages_follows_link_next() {
4566            let server = MockServer::start().await;
4567
4568            // Page 1 — includes Link header pointing to page 2
4569            Mock::given(method("GET"))
4570                .and(path("/items"))
4571                .respond_with(
4572                    ResponseTemplate::new(200)
4573                        .set_body_json(serde_json::json!([{"id": 1}]))
4574                        .insert_header(
4575                            "Link",
4576                            format!("<{}/items/page2>; rel=\"next\"", server.uri()),
4577                        ),
4578                )
4579                .expect(1)
4580                .mount(&server)
4581                .await;
4582
4583            // Page 2 — no Link header (last page)
4584            Mock::given(method("GET"))
4585                .and(path("/items/page2"))
4586                .respond_with(
4587                    ResponseTemplate::new(200)
4588                        .set_body_json(serde_json::json!([{"id": 2}, {"id": 3}])),
4589                )
4590                .expect(1)
4591                .mount(&server)
4592                .await;
4593
4594            let (gh, _guard) = make_client();
4595            let url = format!("{}/items", server.uri());
4596            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4597
4598            assert_eq!(result.len(), 3);
4599            assert_eq!(result[0]["id"], 1);
4600            assert_eq!(result[1]["id"], 2);
4601            assert_eq!(result[2]["id"], 3);
4602        }
4603
4604        #[tokio::test]
4605        async fn get_all_pages_stops_when_link_header_absent_on_subsequent_page() {
4606            // Simulates a proxy/transient response that drops the Link header mid-pagination.
4607            // The previous `.unwrap()` would panic here; the fix breaks the loop instead.
4608            let server = MockServer::start().await;
4609
4610            Mock::given(method("GET"))
4611                .and(path("/items"))
4612                .respond_with(
4613                    ResponseTemplate::new(200)
4614                        .set_body_json(serde_json::json!([{"id": 1}]))
4615                        .insert_header(
4616                            "Link",
4617                            format!("<{}/items/page2>; rel=\"next\"", server.uri()),
4618                        ),
4619                )
4620                .expect(1)
4621                .mount(&server)
4622                .await;
4623
4624            // Page 2 response has NO Link header — pagination should stop cleanly.
4625            Mock::given(method("GET"))
4626                .and(path("/items/page2"))
4627                .respond_with(
4628                    ResponseTemplate::new(200).set_body_json(serde_json::json!([{"id": 2}])),
4629                )
4630                .expect(1)
4631                .mount(&server)
4632                .await;
4633
4634            let (gh, _guard) = make_client();
4635            let url = format!("{}/items", server.uri());
4636            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4637
4638            // Must not panic and must return both items collected so far.
4639            assert_eq!(result.len(), 2);
4640        }
4641
4642        #[tokio::test]
4643        async fn get_all_pages_stops_on_malformed_link_header() {
4644            // A malformed Link header (no angle-bracket URL) yields None from parse_link_next,
4645            // which should stop pagination rather than panic.
4646            let server = MockServer::start().await;
4647
4648            Mock::given(method("GET"))
4649                .and(path("/items"))
4650                .respond_with(
4651                    ResponseTemplate::new(200)
4652                        .set_body_json(serde_json::json!([{"id": 1}]))
4653                        .insert_header("Link", "garbage; rel=\"next\""),
4654                )
4655                .expect(1)
4656                .mount(&server)
4657                .await;
4658
4659            let (gh, _guard) = make_client();
4660            let url = format!("{}/items", server.uri());
4661            let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4662
4663            // Malformed Link header → pagination stops after first page, no panic.
4664            assert_eq!(result.len(), 1);
4665        }
4666
4667        #[tokio::test]
4668        async fn get_all_pages_returns_error_on_malformed_json_body() {
4669            let server = MockServer::start().await;
4670
4671            Mock::given(method("GET"))
4672                .and(path("/items"))
4673                .respond_with(ResponseTemplate::new(200).set_body_string("not valid json"))
4674                .expect(3)
4675                .mount(&server)
4676                .await;
4677
4678            let (gh, _guard) = make_client();
4679            let url = format!("{}/items", server.uri());
4680            let result = gh.get_all_pages::<serde_json::Value>(&url, &[]).await;
4681
4682            assert!(result.is_err());
4683            let err = result.unwrap_err().to_string();
4684            assert!(
4685                err.contains("JSON decode failed") || err.contains("expected ident"),
4686                "error should mention JSON decode or serde error: {}",
4687                err
4688            );
4689        }
4690
4691        // ── conditional request / rate-limit tests ───────────────────────────
4692
4693        /// Restores the global REST limiter and the page cache, both of which these two
4694        /// tests have to poison to exercise the real request path.
4695        struct GlobalStateGuard;
4696
4697        impl Drop for GlobalStateGuard {
4698            fn drop(&mut self) {
4699                if let Ok(mut rl) = REST_RATE_LIMIT.lock() {
4700                    *rl = RateLimit::new();
4701                }
4702                if let Ok(mut cache) = PAGE_CACHE.lock() {
4703                    cache.clear();
4704                }
4705            }
4706        }
4707
4708        #[tokio::test]
4709        async fn get_all_pages_replays_body_on_304() {
4710            let _reset = GlobalStateGuard;
4711            let server = MockServer::start().await;
4712
4713            // First poll: 200 with an ETag.
4714            Mock::given(method("GET"))
4715                .and(path("/issues"))
4716                .and(matchers::header_exists("authorization"))
4717                .and(NotMatcher(matchers::header_exists("if-none-match")))
4718                .respond_with(
4719                    ResponseTemplate::new(200)
4720                        .set_body_json(serde_json::json!([{"number": 1}]))
4721                        .insert_header("ETag", "\"abc123\""),
4722                )
4723                .expect(1)
4724                .mount(&server)
4725                .await;
4726
4727            // Second poll: orch sends If-None-Match, GitHub answers 304 with no body.
4728            Mock::given(method("GET"))
4729                .and(path("/issues"))
4730                .and(matchers::header("if-none-match", "\"abc123\""))
4731                .respond_with(ResponseTemplate::new(304))
4732                .expect(1)
4733                .mount(&server)
4734                .await;
4735
4736            let (gh, _guard) = make_client();
4737            let url = format!("{}/issues", server.uri());
4738
4739            let first: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4740            let second: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4741
4742            assert_eq!(first, second);
4743            assert_eq!(second.len(), 1);
4744            assert_eq!(second[0]["number"], 1);
4745        }
4746
4747        #[tokio::test]
4748        async fn exhausted_quota_skips_further_calls_until_reset() {
4749            let _reset = GlobalStateGuard;
4750            let server = MockServer::start().await;
4751
4752            let reset_at = std::time::SystemTime::now()
4753                .duration_since(std::time::UNIX_EPOCH)
4754                .unwrap()
4755                .as_secs()
4756                + 600;
4757
4758            // One response, and only one: it reports an exhausted core quota, so every
4759            // later call must be skipped locally rather than sent.
4760            Mock::given(method("GET"))
4761                .and(path("/issues"))
4762                .respond_with(
4763                    ResponseTemplate::new(200)
4764                        .set_body_json(serde_json::json!([{"number": 1}]))
4765                        .insert_header("x-ratelimit-remaining", "0")
4766                        .insert_header("x-ratelimit-reset", reset_at.to_string().as_str()),
4767                )
4768                .expect(1)
4769                .mount(&server)
4770                .await;
4771
4772            let (gh, _guard) = make_client();
4773            let url = format!("{}/issues", server.uri());
4774
4775            let first: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4776            assert_eq!(first.len(), 1);
4777
4778            // The next call returns immediately instead of waiting out the 600s window.
4779            let start = Instant::now();
4780            let err = gh
4781                .get_all_pages::<serde_json::Value>(&url, &[("state", "open")])
4782                .await
4783                .unwrap_err();
4784            assert!(
4785                start.elapsed() < Duration::from_secs(1),
4786                "call blocked for {:?} instead of failing fast",
4787                start.elapsed()
4788            );
4789            assert!(err.to_string().contains("rate-limited"), "{err}");
4790
4791            // The engine reports the window from the same state the skip reads.
4792            let m = rate_limit_metrics();
4793            assert_eq!(m.rest_remaining, Some(0));
4794            assert_eq!(m.rest_reset_at, Some(reset_at));
4795            assert!(GhHttp::is_rate_limited().is_some());
4796
4797            // `.expect(1)` on the mock is verified on drop: no second request went out.
4798        }
4799
4800        // ── get_all_pages_from_wrapper tests ─────────────────────────────────
4801
4802        #[tokio::test]
4803        async fn get_all_pages_from_wrapper_single_page() {
4804            // Simulates GitHub's check-runs response: a wrapper object with the
4805            // array nested under a named field.
4806            let server = MockServer::start().await;
4807
4808            Mock::given(method("GET"))
4809                .and(path("/check-runs"))
4810                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
4811                    "total_count": 2,
4812                    "check_runs": [{"id": 1, "name": "build"}, {"id": 2, "name": "test"}]
4813                })))
4814                .expect(1)
4815                .mount(&server)
4816                .await;
4817
4818            let (gh, _guard) = make_client();
4819            let url = format!("{}/check-runs", server.uri());
4820            let result: Vec<serde_json::Value> = gh
4821                .get_all_pages_from_wrapper(&url, "check_runs")
4822                .await
4823                .unwrap();
4824
4825            assert_eq!(result.len(), 2);
4826            assert_eq!(result[0]["id"], 1);
4827            assert_eq!(result[1]["id"], 2);
4828        }
4829
4830        #[tokio::test]
4831        async fn get_all_pages_from_wrapper_follows_link_next() {
4832            // Two-page check-runs response (common for repos with >100 distinct check names).
4833            let server = MockServer::start().await;
4834
4835            Mock::given(method("GET"))
4836                .and(path("/check-runs"))
4837                .respond_with(
4838                    ResponseTemplate::new(200)
4839                        .set_body_json(serde_json::json!({
4840                            "total_count": 3,
4841                            "check_runs": [{"id": 1, "name": "build"}]
4842                        }))
4843                        .insert_header(
4844                            "Link",
4845                            format!("<{}/check-runs/page2>; rel=\"next\"", server.uri()),
4846                        ),
4847                )
4848                .expect(1)
4849                .mount(&server)
4850                .await;
4851
4852            Mock::given(method("GET"))
4853                .and(path("/check-runs/page2"))
4854                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
4855                    "total_count": 3,
4856                    "check_runs": [{"id": 2, "name": "lint"}, {"id": 3, "name": "test"}]
4857                })))
4858                .expect(1)
4859                .mount(&server)
4860                .await;
4861
4862            let (gh, _guard) = make_client();
4863            let url = format!("{}/check-runs", server.uri());
4864            let result: Vec<serde_json::Value> = gh
4865                .get_all_pages_from_wrapper(&url, "check_runs")
4866                .await
4867                .unwrap();
4868
4869            assert_eq!(result.len(), 3);
4870            assert_eq!(result[0]["id"], 1);
4871            assert_eq!(result[1]["id"], 2);
4872            assert_eq!(result[2]["id"], 3);
4873        }
4874
4875        #[tokio::test]
4876        async fn get_all_pages_from_wrapper_empty_field_returns_empty_vec() {
4877            // When the array field is missing or empty, the function should return
4878            // an empty vec rather than erroring.
4879            let server = MockServer::start().await;
4880
4881            Mock::given(method("GET"))
4882                .and(path("/check-runs"))
4883                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
4884                    "total_count": 0,
4885                    "check_runs": []
4886                })))
4887                .expect(1)
4888                .mount(&server)
4889                .await;
4890
4891            let (gh, _guard) = make_client();
4892            let url = format!("{}/check-runs", server.uri());
4893            let result: Vec<serde_json::Value> = gh
4894                .get_all_pages_from_wrapper(&url, "check_runs")
4895                .await
4896                .unwrap();
4897
4898            assert_eq!(result.len(), 0);
4899        }
4900
4901        #[tokio::test]
4902        async fn get_all_pages_from_wrapper_error_on_non_success_status() {
4903            let server = MockServer::start().await;
4904
4905            Mock::given(method("GET"))
4906                .and(path("/check-runs"))
4907                .respond_with(ResponseTemplate::new(422).set_body_string("Unprocessable Entity"))
4908                .expect(1)
4909                .mount(&server)
4910                .await;
4911
4912            let (gh, _guard) = make_client();
4913            let url = format!("{}/check-runs", server.uri());
4914            let result = gh
4915                .get_all_pages_from_wrapper::<serde_json::Value>(&url, "check_runs")
4916                .await;
4917
4918            assert!(result.is_err());
4919            let err = result.unwrap_err().to_string();
4920            assert!(
4921                err.contains("422") || err.contains("failed"),
4922                "error should indicate failure: {err}"
4923            );
4924        }
4925    }
4926
4927    // ── 401 token-refresh tests (wiremock) ────────────────────────────────
4928
4929    #[cfg(test)]
4930    mod auth_retry {
4931        use super::test_client;
4932        use std::sync::atomic::{AtomicUsize, Ordering};
4933        use std::sync::Arc;
4934        use wiremock::matchers::method;
4935        use wiremock::{Mock, MockServer, Request, ResponseTemplate};
4936
4937        fn bad_credentials() -> ResponseTemplate {
4938            ResponseTemplate::new(401).set_body_json(serde_json::json!({
4939                "message": "Bad credentials",
4940                "status": 401
4941            }))
4942        }
4943
4944        #[allow(clippy::await_holding_lock)]
4945        #[tokio::test]
4946        async fn retries_once_with_fresh_token_after_401() {
4947            let _env_guard = crate::github::token::ENV_LOCK.lock().unwrap();
4948            let prev = std::env::var_os("GH_TOKEN");
4949            std::env::set_var("GH_TOKEN", "bad_token");
4950
4951            let server = MockServer::start().await;
4952            let hits = Arc::new(AtomicUsize::new(0));
4953            let hits_in_handler = hits.clone();
4954            Mock::given(method("GET"))
4955                .respond_with(move |_req: &Request| {
4956                    if hits_in_handler.fetch_add(1, Ordering::SeqCst) == 0 {
4957                        // The 401 handler clears the cache and re-resolves; simulate the
4958                        // operator having fixed the env var in the meantime
4959                        std::env::set_var("GH_TOKEN", "good_token");
4960                        bad_credentials()
4961                    } else {
4962                        ResponseTemplate::new(200).set_body_json(serde_json::json!({ "ok": true }))
4963                    }
4964                })
4965                .mount(&server)
4966                .await;
4967
4968            let gh = test_client();
4969            let result: anyhow::Result<serde_json::Value> =
4970                gh.get_json(&format!("{}/x", server.uri())).await;
4971
4972            match prev {
4973                Some(v) => std::env::set_var("GH_TOKEN", v),
4974                None => std::env::remove_var("GH_TOKEN"),
4975            }
4976
4977            assert!(
4978                result.is_ok(),
4979                "retry with re-resolved token should succeed: {:?}",
4980                result.err()
4981            );
4982            assert_eq!(hits.load(Ordering::SeqCst), 2, "exactly one retry expected");
4983        }
4984
4985        #[allow(clippy::await_holding_lock)]
4986        #[tokio::test]
4987        async fn double_401_bails_with_distinct_auth_error() {
4988            let _env_guard = crate::github::token::ENV_LOCK.lock().unwrap();
4989            let prev = std::env::var_os("GH_TOKEN");
4990            std::env::set_var("GH_TOKEN", "bad_token");
4991
4992            let server = MockServer::start().await;
4993            let hits = Arc::new(AtomicUsize::new(0));
4994            let hits_in_handler = hits.clone();
4995            Mock::given(method("GET"))
4996                .respond_with(move |_req: &Request| {
4997                    hits_in_handler.fetch_add(1, Ordering::SeqCst);
4998                    bad_credentials()
4999                })
5000                .mount(&server)
5001                .await;
5002
5003            let gh = test_client();
5004            let result: anyhow::Result<serde_json::Value> =
5005                gh.get_json(&format!("{}/x", server.uri())).await;
5006
5007            match prev {
5008                Some(v) => std::env::set_var("GH_TOKEN", v),
5009                None => std::env::remove_var("GH_TOKEN"),
5010            }
5011
5012            let err = result.expect_err("persisting 401 must fail").to_string();
5013            assert!(
5014                err.contains("token re-resolved after cache clear but still rejected"),
5015                "expected distinct auth-failure error, got: {err}"
5016            );
5017            assert_eq!(
5018                hits.load(Ordering::SeqCst),
5019                2,
5020                "must retry exactly once, not loop"
5021            );
5022        }
5023    }
5024
5025    // ── secret redaction on posted bodies (wiremock) ─────────────────────
5026
5027    mod leak_redaction {
5028        use super::test_client;
5029        use super::GhHttp;
5030        use std::sync::{Arc, Mutex};
5031        use wiremock::matchers::{method, path};
5032        use wiremock::{Mock, MockServer, Request, ResponseTemplate};
5033
5034        const TOKEN: &str = "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij";
5035
5036        fn leaky_body() -> String {
5037            format!("agent notes mentioning {TOKEN}")
5038        }
5039
5040        fn client_for(server: &MockServer) -> GhHttp {
5041            let mut gh = test_client();
5042            gh.api_base = Some(server.uri());
5043            gh
5044        }
5045
5046        fn posted_json_body(raw: &str) -> String {
5047            let payload: serde_json::Value =
5048                serde_json::from_str(raw).expect("request body is JSON");
5049            payload["body"]
5050                .as_str()
5051                .expect("payload has a string body")
5052                .to_string()
5053        }
5054
5055        fn assert_token_redacted(raw: &str) {
5056            assert!(
5057                !raw.contains(TOKEN),
5058                "planted token must not appear in the request payload, got: {raw}"
5059            );
5060            let body = posted_json_body(raw);
5061            assert!(
5062                body.contains("[REDACTED:github_token]"),
5063                "redacted marker missing from posted body: {body}"
5064            );
5065            assert!(
5066                body.contains("potential secret(s) detected and redacted"),
5067                "security notice missing from posted body: {body}"
5068            );
5069        }
5070
5071        #[allow(clippy::await_holding_lock)]
5072        #[tokio::test]
5073        async fn add_comment_redacts_github_token() {
5074            let _env_guard = crate::github::token::ENV_LOCK.lock().unwrap();
5075            let prev = std::env::var_os("GH_TOKEN");
5076            std::env::set_var("GH_TOKEN", "test_token");
5077
5078            let server = MockServer::start().await;
5079            let captured = Arc::new(Mutex::new(None::<String>));
5080            let captured_in_handler = captured.clone();
5081            Mock::given(method("POST"))
5082                .and(path("/repos/owner/repo/issues/1/comments"))
5083                .respond_with(move |req: &Request| {
5084                    *captured_in_handler.lock().unwrap() =
5085                        Some(String::from_utf8_lossy(&req.body).into_owned());
5086                    ResponseTemplate::new(201).set_body_json(serde_json::json!({ "id": 1 }))
5087                })
5088                .expect(1)
5089                .mount(&server)
5090                .await;
5091
5092            let gh = client_for(&server);
5093            gh.add_comment("owner/repo", "1", &leaky_body())
5094                .await
5095                .expect("add_comment should succeed");
5096
5097            match prev {
5098                Some(v) => std::env::set_var("GH_TOKEN", v),
5099                None => std::env::remove_var("GH_TOKEN"),
5100            }
5101
5102            let raw = captured
5103                .lock()
5104                .unwrap()
5105                .clone()
5106                .expect("add_comment must send a request body");
5107            assert_token_redacted(&raw);
5108        }
5109
5110        #[allow(clippy::await_holding_lock)]
5111        #[tokio::test]
5112        async fn create_pr_redacts_github_token() {
5113            let _env_guard = crate::github::token::ENV_LOCK.lock().unwrap();
5114            let prev = std::env::var_os("GH_TOKEN");
5115            std::env::set_var("GH_TOKEN", "test_token");
5116
5117            let server = MockServer::start().await;
5118            let captured = Arc::new(Mutex::new(None::<String>));
5119            let captured_in_handler = captured.clone();
5120            Mock::given(method("POST"))
5121                .and(path("/repos/owner/repo/pulls"))
5122                .respond_with(move |req: &Request| {
5123                    *captured_in_handler.lock().unwrap() =
5124                        Some(String::from_utf8_lossy(&req.body).into_owned());
5125                    ResponseTemplate::new(201).set_body_json(serde_json::json!({
5126                        "html_url": "https://github.com/owner/repo/pull/1"
5127                    }))
5128                })
5129                .expect(1)
5130                .mount(&server)
5131                .await;
5132
5133            let gh = client_for(&server);
5134            gh.create_pr("owner/repo", "title", &leaky_body(), "head", "main")
5135                .await
5136                .expect("create_pr should succeed");
5137
5138            match prev {
5139                Some(v) => std::env::set_var("GH_TOKEN", v),
5140                None => std::env::remove_var("GH_TOKEN"),
5141            }
5142
5143            let raw = captured
5144                .lock()
5145                .unwrap()
5146                .clone()
5147                .expect("create_pr must send a request body");
5148            assert_token_redacted(&raw);
5149        }
5150
5151        #[allow(clippy::await_holding_lock)]
5152        #[tokio::test]
5153        async fn update_pr_body_redacts_github_token() {
5154            let _env_guard = crate::github::token::ENV_LOCK.lock().unwrap();
5155            let prev = std::env::var_os("GH_TOKEN");
5156            std::env::set_var("GH_TOKEN", "test_token");
5157
5158            let server = MockServer::start().await;
5159            let captured = Arc::new(Mutex::new(None::<String>));
5160            let captured_in_handler = captured.clone();
5161            Mock::given(method("PATCH"))
5162                .and(path("/repos/owner/repo/pulls/7"))
5163                .respond_with(move |req: &Request| {
5164                    *captured_in_handler.lock().unwrap() =
5165                        Some(String::from_utf8_lossy(&req.body).into_owned());
5166                    ResponseTemplate::new(200).set_body_json(serde_json::json!({}))
5167                })
5168                .expect(1)
5169                .mount(&server)
5170                .await;
5171
5172            let gh = client_for(&server);
5173            gh.update_pr_body("owner/repo", 7, &leaky_body())
5174                .await
5175                .expect("update_pr_body should succeed");
5176
5177            match prev {
5178                Some(v) => std::env::set_var("GH_TOKEN", v),
5179                None => std::env::remove_var("GH_TOKEN"),
5180            }
5181
5182            let raw = captured
5183                .lock()
5184                .unwrap()
5185                .clone()
5186                .expect("update_pr_body must send a request body");
5187            assert_token_redacted(&raw);
5188        }
5189    }
5190}