Skip to main content

orch/github/
http.rs

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