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