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