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