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