Skip to main content

orch/github/
http.rs

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