Skip to main content

orch/github/
http.rs

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