Skip to main content

orch/github/http/
issues.rs

1//! Issue, label, comment and sub-issue calls
2
3use super::{
4    BlockedByPayload, GITHUB_API, GhHttp, READ_TIMEOUT, has_status, is_forbidden_rate_limit,
5    page_cache_etag, page_cache_hit, page_cache_key, page_cache_store, parse_link_next,
6    parse_positive_issue_number, redact_posted_body, sanitize_github_issue_numbers,
7};
8use crate::backends::BlockedByFetch;
9use crate::backends::BlockedByIssue;
10use crate::github::types::{GitHubComment, GitHubIssue};
11use anyhow::Context;
12use reqwest::{Response, StatusCode, header};
13use std::collections::HashMap;
14use urlencoding;
15
16impl GhHttp {
17    /// Verify authentication by fetching the current user.
18    ///
19    /// Returns detailed error messages for common auth failures to help
20    /// users diagnose configuration issues at startup.
21    pub async fn auth_status(&self) -> anyhow::Result<()> {
22        match self
23            .get_json::<serde_json::Value>(&format!("{GITHUB_API}/user"))
24            .await
25        {
26            Ok(_) => Ok(()),
27            Err(e) => {
28                let err_str = e.to_string();
29
30                // Provide helpful error messages for common auth failures
31                if err_str.contains("401") || err_str.contains("Bad credentials") {
32                    anyhow::bail!(
33                        "GitHub authentication failed: Invalid or expired token. \
34                         Check your GH_TOKEN/GITHUB_TOKEN environment variables, \
35                         or gh.auth configuration in ~/.orch/config.yml. \
36                         Run `orch auth check` to verify your setup."
37                    );
38                }
39
40                if err_str.contains("403") && err_str.contains("rate limit") {
41                    anyhow::bail!(
42                        "GitHub API rate limited. Wait before retrying, \
43                         or check your token's rate limit quota."
44                    );
45                }
46
47                Err(e)
48            }
49        }
50    }
51
52    /// Create a GitHub issue.
53    pub async fn create_issue(
54        &self,
55        repo: &str,
56        title: &str,
57        body: &str,
58        labels: &[String],
59    ) -> anyhow::Result<GitHubIssue> {
60        let url = format!("{GITHUB_API}/repos/{repo}/issues");
61        let payload = serde_json::json!({
62            "title": title,
63            "body": body,
64            "labels": labels,
65        });
66        self.post_json(&url, &payload).await
67    }
68
69    /// Replace an issue's title, body and labels.
70    ///
71    /// Labels replace the full set. Callers pass labels they want to keep
72    pub async fn update_issue(
73        &self,
74        repo: &str,
75        number: u64,
76        title: &str,
77        body: &str,
78        labels: &[String],
79    ) -> anyhow::Result<GitHubIssue> {
80        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
81        let payload = serde_json::json!({
82            "title": title,
83            "body": body,
84            "labels": labels,
85        });
86        let text = self.patch_json_raw(&url, &payload).await?;
87        serde_json::from_str(&text)
88            .with_context(|| format!("failed to parse issue update response: {text}"))
89    }
90
91    /// List issues that block `issue_number`.
92    ///
93    /// `GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`.
94    /// GA since 2025-08-21, no preview media type. This call sends
95    /// `X-GitHub-Api-Version: 2026-03-10` and `Accept: application/vnd.github+json`.
96    /// Each page is sent with `If-None-Match` when a prior ETag is known, and a 304
97    /// replays the stored body. 404 and 403 (except rate limit) are `Unavailable`.
98    /// Transport errors and 5xx are `Failed`, so the caller does not drop stored links
99    pub async fn list_blocked_by(
100        &self,
101        repo: &str,
102        issue_number: u64,
103    ) -> anyhow::Result<BlockedByFetch> {
104        let mut next = Some(format!(
105            "{}/repos/{repo}/issues/{issue_number}/dependencies/blocked_by?per_page=100",
106            self.api_root()
107        ));
108        let mut found = Vec::new();
109        while let Some(url) = next.take() {
110            let cache_key = page_cache_key::<BlockedByPayload>(&url, None);
111            let mut cached_etag = cache_key.as_deref().and_then(page_cache_etag);
112            let (body, page_next) = loop {
113                let resp = match self
114                    .dependency_request(&url, reqwest::Method::GET, None, cached_etag.as_deref())
115                    .await
116                {
117                    Ok(resp) => resp,
118                    Err(err) => {
119                        let message = err.to_string();
120                        // `send_with_retries` words a send failure with this marker
121                        if message.contains("(transport error)") {
122                            return Ok(BlockedByFetch::Unreachable(message));
123                        }
124                        return Ok(BlockedByFetch::Failed(message));
125                    }
126                };
127                let status = resp.status();
128                if status == StatusCode::NOT_MODIFIED {
129                    if let Some((body, next_link)) = cache_key.as_deref().and_then(page_cache_hit) {
130                        Self::record_success();
131                        break (body, next_link);
132                    }
133                    // The entry is normally there, since If-None-Match is only sent
134                    // when it is, but the size cap can clear the map in between.
135                    // Dropping the ETag makes the retry unconditional, so the loop
136                    // cannot see a second 304
137                    cached_etag = None;
138                    continue;
139                }
140                if status == StatusCode::NOT_FOUND || status == StatusCode::FORBIDDEN {
141                    let body = resp.text().await.unwrap_or_default();
142                    if is_forbidden_rate_limit(status, &body) {
143                        Self::maybe_record_rate_limit_from_body(status, &body);
144                        return Ok(BlockedByFetch::Failed(body));
145                    }
146                    return Ok(BlockedByFetch::Unavailable);
147                }
148                if !status.is_success() {
149                    let body = resp.text().await.unwrap_or_default();
150                    Self::maybe_record_rate_limit_from_body(status, &body);
151                    return Ok(BlockedByFetch::Failed(format!("{status}: {body}")));
152                }
153                Self::record_success();
154                let page_next = parse_link_next(resp.headers());
155                let etag = resp
156                    .headers()
157                    .get(header::ETAG)
158                    .and_then(|v| v.to_str().ok())
159                    .map(ToString::to_string);
160                let body = match resp.text().await {
161                    Ok(body) => body,
162                    Err(err) => {
163                        return Ok(BlockedByFetch::Failed(format!(
164                            "blocked_by body read failed: {err}"
165                        )));
166                    }
167                };
168                // Cache only a body that parses, or a 304 would replay it forever
169                if serde_json::from_str::<Vec<BlockedByPayload>>(&body).is_ok()
170                    && let (Some(key), Some(etag)) = (cache_key.clone(), etag)
171                {
172                    page_cache_store(key, etag, body.clone(), page_next.clone());
173                }
174                break (body, page_next);
175            };
176            let page: Vec<BlockedByPayload> = match serde_json::from_str(&body) {
177                Ok(page) => page,
178                Err(err) => {
179                    return Ok(BlockedByFetch::Failed(format!(
180                        "blocked_by parse failed: {err}"
181                    )));
182                }
183            };
184            for item in page {
185                if item.number <= 0 {
186                    continue;
187                }
188                let item_repo = item
189                    .repository
190                    .as_ref()
191                    .map(|r| r.full_name.clone())
192                    .filter(|name| !name.is_empty())
193                    .unwrap_or_else(|| repo.to_string());
194                found.push(BlockedByIssue {
195                    github_id: item.id,
196                    repo: item_repo,
197                    number: item.number,
198                    state: item.state,
199                    state_reason: item.state_reason,
200                });
201            }
202            next = page_next;
203        }
204        Ok(BlockedByFetch::Native(found))
205    }
206
207    /// `POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`
208    /// with `{"issue_id": blocking_issue_id}`. Same API version as `list_blocked_by`.
209    /// 201 is success. A body that says the link already exists is also success
210    pub async fn add_blocked_by(
211        &self,
212        repo: &str,
213        issue_number: u64,
214        blocking_issue_id: i64,
215    ) -> anyhow::Result<()> {
216        let url =
217            format!("{GITHUB_API}/repos/{repo}/issues/{issue_number}/dependencies/blocked_by");
218        let resp = self
219            .dependency_request(
220                &url,
221                reqwest::Method::POST,
222                Some(serde_json::json!({ "issue_id": blocking_issue_id })),
223                None,
224            )
225            .await?;
226        let status = resp.status();
227        if status.is_success() {
228            Self::record_success();
229            return Ok(());
230        }
231        let body = resp.text().await.unwrap_or_default();
232        if body.to_ascii_lowercase().contains("already") {
233            return Ok(());
234        }
235        Self::maybe_record_rate_limit_from_body(status, &body);
236        anyhow::bail!("add blocked_by failed ({status}): {body}")
237    }
238
239    /// Remove a blocked-by link. `issue_id` in the path is the blocking issue's database id
240    pub async fn remove_blocked_by(
241        &self,
242        repo: &str,
243        number: u64,
244        blocking_issue_id: u64,
245    ) -> anyhow::Result<()> {
246        let url = format!(
247            "{GITHUB_API}/repos/{repo}/issues/{number}/dependencies/blocked_by/{blocking_issue_id}"
248        );
249        self.delete(&url).await?;
250        Ok(())
251    }
252
253    /// GET or POST an issue-dependency URL with API version 2026-03-10
254    pub(super) async fn dependency_request(
255        &self,
256        url: &str,
257        method: reqwest::Method,
258        body: Option<serde_json::Value>,
259        if_none_match: Option<&str>,
260    ) -> anyhow::Result<Response> {
261        Self::check_backoff(url)?;
262        let auth = self.auth_header(url).await?;
263        let make_req = || {
264            let mut req = self
265                .client
266                .request(method.clone(), url)
267                .header(header::AUTHORIZATION, auth.clone())
268                .header(header::ACCEPT, "application/vnd.github+json")
269                .header("X-GitHub-Api-Version", "2026-03-10");
270            if method == reqwest::Method::GET {
271                req = req.timeout(READ_TIMEOUT);
272            }
273            if let Some(etag) = if_none_match {
274                req = req.header(header::IF_NONE_MATCH, etag);
275            }
276            if let Some(ref payload) = body {
277                req = req.json(payload);
278            }
279            Ok(req)
280        };
281        self.send_with_retries(make_req, false).await
282    }
283
284    /// Get a single issue.
285    pub async fn get_issue(&self, repo: &str, number: &str) -> anyhow::Result<GitHubIssue> {
286        self.get_json(&format!("{}/repos/{repo}/issues/{number}", self.api_root()))
287            .await
288    }
289
290    /// Check whether an issue number refers to a pull request.
291    pub async fn is_pull_request(&self, repo: &str, number: &str) -> bool {
292        self.get_issue(repo, number)
293            .await
294            .is_ok_and(|i| i.pull_request.is_some())
295    }
296
297    /// List issues filtered by a label (paginated).
298    pub async fn list_issues(&self, repo: &str, label: &str) -> anyhow::Result<Vec<GitHubIssue>> {
299        self.list_issues_with_state(repo, label, "open").await
300    }
301
302    /// List issues filtered by a label and issue state (paginated).
303    ///
304    /// `state` is passed directly to the GitHub API: `"open"`, `"closed"`, or `"all"`.
305    pub async fn list_issues_with_state(
306        &self,
307        repo: &str,
308        label: &str,
309        state: &str,
310    ) -> anyhow::Result<Vec<GitHubIssue>> {
311        let url = format!("{GITHUB_API}/repos/{repo}/issues");
312        // An empty label lists every issue
313        let mut query = vec![("state", state), ("per_page", "100")];
314        if !label.is_empty() {
315            query.push(("labels", label));
316        }
317        let all: Vec<GitHubIssue> = self.get_all_pages(&url, &query).await?;
318        // GitHub /issues API returns PRs too — filter them out
319        Ok(all
320            .into_iter()
321            .filter(|i| i.pull_request.is_none())
322            .collect())
323    }
324
325    /// List closed issues updated since `since` (ISO 8601), filtered by label.
326    ///
327    /// Used for dedup checks — prevents re-creating issues that were recently closed.
328    pub async fn list_issues_closed_since(
329        &self,
330        repo: &str,
331        label: &str,
332        since: &str,
333    ) -> anyhow::Result<Vec<GitHubIssue>> {
334        let url = format!("{GITHUB_API}/repos/{repo}/issues");
335        let all: Vec<GitHubIssue> = self
336            .get_all_pages(
337                &url,
338                &[
339                    ("labels", label),
340                    ("state", "closed"),
341                    ("since", since),
342                    ("per_page", "100"),
343                ],
344            )
345            .await?;
346        Ok(all
347            .into_iter()
348            .filter(|i| i.pull_request.is_none())
349            .collect())
350    }
351
352    /// List closed issues updated since `since` (ISO 8601), no label filter.
353    pub async fn list_closed_issues_since(
354        &self,
355        repo: &str,
356        since: &str,
357    ) -> anyhow::Result<Vec<GitHubIssue>> {
358        let url = format!("{GITHUB_API}/repos/{repo}/issues");
359        let all: Vec<GitHubIssue> = self
360            .get_all_pages(
361                &url,
362                &[("state", "closed"), ("since", since), ("per_page", "100")],
363            )
364            .await?;
365        Ok(all
366            .into_iter()
367            .filter(|i| i.pull_request.is_none())
368            .collect())
369    }
370
371    /// List all open issues (no label filter, paginated).
372    ///
373    /// The URL carries no `since`, so it repeats across calls and `get_all_pages` can send
374    /// it conditionally. GitHub answers 304 while nothing changed, which is free quota
375    pub async fn list_all_open_issues(&self, repo: &str) -> anyhow::Result<Vec<GitHubIssue>> {
376        let url = format!("{GITHUB_API}/repos/{repo}/issues");
377        let params = [("state", "open"), ("per_page", "100")];
378        let all: Vec<GitHubIssue> = self.get_all_pages(&url, &params).await?;
379        // GitHub /issues API returns PRs too — filter them out
380        Ok(all
381            .into_iter()
382            .filter(|i| i.pull_request.is_none())
383            .collect())
384    }
385
386    /// List open pull requests (paginated) using the REST pulls endpoint.
387    /// Returns raw JSON values for flexibility in callers.
388    pub async fn list_open_pulls(&self, repo: &str) -> anyhow::Result<Vec<serde_json::Value>> {
389        let url = format!("{GITHUB_API}/repos/{repo}/pulls");
390        let all: Vec<serde_json::Value> = self
391            .get_all_pages(&url, &[("state", "open"), ("per_page", "100")])
392            .await?;
393        Ok(all)
394    }
395
396    /// List all issues (open and closed, no label filter, paginated).
397    ///
398    /// This is more efficient than making separate calls for open and closed.
399    pub async fn list_all_issues(&self, repo: &str) -> anyhow::Result<Vec<GitHubIssue>> {
400        let url = format!("{GITHUB_API}/repos/{repo}/issues");
401        let all: Vec<GitHubIssue> = self
402            .get_all_pages(&url, &[("state", "all"), ("per_page", "100")])
403            .await?;
404        // GitHub /issues API returns PRs too — filter them out
405        Ok(all
406            .into_iter()
407            .filter(|i| i.pull_request.is_none())
408            .collect())
409    }
410
411    /// Add labels to an issue.
412    pub async fn add_labels(
413        &self,
414        repo: &str,
415        number: &str,
416        labels: &[String],
417    ) -> anyhow::Result<()> {
418        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/labels");
419        let payload = serde_json::json!({ "labels": labels });
420        self.post_json_raw(&url, &payload).await?;
421        Ok(())
422    }
423
424    /// Ensure a label exists on the repo, creating it if needed.
425    pub async fn ensure_label(
426        &self,
427        repo: &str,
428        name: &str,
429        color: &str,
430        description: &str,
431    ) -> anyhow::Result<()> {
432        let encoded = urlencoding::encode(name);
433        let get_url = format!("{GITHUB_API}/repos/{repo}/labels/{encoded}");
434
435        // Check if label exists
436        match self.get_bytes(&get_url).await {
437            Ok(_) => return Ok(()),
438            Err(e) if has_status(&e.to_string(), 404) => {
439                tracing::debug!(repo, name, "ensure_label: label not found, creating");
440            }
441            Err(e) => {
442                tracing::warn!(repo, name, err = %e, "ensure_label: GET failed, attempting create");
443            }
444        }
445
446        // Create the label
447        let create_url = format!("{GITHUB_API}/repos/{repo}/labels");
448        let payload = serde_json::json!({
449            "name": name,
450            "color": color,
451            "description": description,
452        });
453
454        match self.post_json_raw(&create_url, &payload).await {
455            Ok(_) => {
456                Self::record_success();
457            }
458            Err(e) => {
459                let msg = e.to_string();
460                if msg.contains("422")
461                    || msg.contains("already_exists")
462                    || msg.contains("Unprocessable")
463                {
464                    tracing::debug!(repo, name, "ensure_label: label already exists (race)");
465                    return Ok(());
466                }
467                // Tolerate creation failures (matches old behavior).
468                tracing::warn!(repo, name, err = %msg, "ensure_label: create failed, continuing");
469            }
470        }
471        Ok(())
472    }
473
474    /// Remove a label from an issue.
475    pub async fn remove_label(&self, repo: &str, number: &str, label: &str) -> anyhow::Result<()> {
476        let encoded = urlencoding::encode(label);
477        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/labels/{encoded}");
478        match self.delete(&url).await {
479            Ok(_) => Ok(()),
480            Err(e) if has_status(&e.to_string(), 404) => {
481                tracing::debug!(repo, number, label, "label already removed (404)");
482                Ok(())
483            }
484            Err(e) => Err(e),
485        }
486    }
487
488    /// Add a comment to an issue.
489    pub async fn add_comment(&self, repo: &str, number: &str, body: &str) -> anyhow::Result<()> {
490        let body = redact_posted_body(body);
491        let url = format!("{}/repos/{repo}/issues/{number}/comments", self.api_root());
492        let payload = serde_json::json!({ "body": body });
493        self.post_json_raw(&url, &payload).await?;
494        Ok(())
495    }
496
497    /// Add a reaction to an issue.
498    ///
499    /// Supported content values: "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes"
500    pub async fn add_reaction(
501        &self,
502        repo: &str,
503        number: &str,
504        content: &str,
505    ) -> anyhow::Result<()> {
506        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/reactions");
507        let payload = serde_json::json!({ "content": content });
508        self.post_json_raw(&url, &payload).await?;
509        Ok(())
510    }
511
512    /// Add a reaction to an issue comment.
513    ///
514    /// Supported content values: "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes"
515    pub async fn add_comment_reaction(
516        &self,
517        repo: &str,
518        comment_id: &str,
519        content: &str,
520    ) -> anyhow::Result<()> {
521        let url = format!("{GITHUB_API}/repos/{repo}/issues/comments/{comment_id}/reactions");
522        let payload = serde_json::json!({ "content": content });
523        self.post_json_raw(&url, &payload).await?;
524        Ok(())
525    }
526
527    /// List comments on an issue.
528    pub async fn list_comments(
529        &self,
530        repo: &str,
531        number: &str,
532    ) -> anyhow::Result<Vec<GitHubComment>> {
533        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/comments");
534        self.get_all_pages(&url, &[("per_page", "100")]).await
535    }
536
537    /// Get issue/PR comments since a given timestamp (paginated).
538    pub async fn get_mentions(
539        &self,
540        repo: &str,
541        since: &str,
542    ) -> anyhow::Result<Vec<GitHubComment>> {
543        let url = format!("{}/repos/{repo}/issues/comments", self.api_root());
544        self.get_all_pages(&url, &[("since", since), ("per_page", "100")])
545            .await
546    }
547
548    /// Get all comments for a specific issue number.
549    pub async fn get_issue_comments(
550        &self,
551        repo: &str,
552        issue_number: u64,
553    ) -> anyhow::Result<Vec<GitHubComment>> {
554        let url = format!(
555            "{}/repos/{repo}/issues/{issue_number}/comments",
556            self.api_root()
557        );
558        self.get_all_pages(&url, &[("per_page", "100")]).await
559    }
560
561    /// Get the current authenticated username (cached after first call).
562    pub async fn get_whoami(&self) -> anyhow::Result<String> {
563        if let Some(cached) = self.cached_username.get() {
564            return Ok(cached.clone());
565        }
566
567        // An installation token cannot read `GET /user`, and the owner is the identity mentions name
568        let mut owner = self.clone();
569        owner.owner_only = true;
570        let user: serde_json::Value = owner.get_json(&format!("{GITHUB_API}/user")).await?;
571        let username = user
572            .get("login")
573            .and_then(|v| v.as_str())
574            .map(String::from)
575            .ok_or_else(|| anyhow::anyhow!("failed to get current user"))?;
576
577        let _ = self.cached_username.set(username.clone());
578        Ok(username)
579    }
580
581    /// Batch-fetch state and labels for multiple GitHub issues in a single GraphQL request.
582    ///
583    /// Returns a map of issue number (as string) → `(state, labels)` where state is
584    /// lowercase ("open" / "closed") to match the REST API convention used elsewhere.
585    pub async fn batch_get_issue_states(
586        &self,
587        repo: &str,
588        issue_numbers: &[u64],
589        caller_context: &str,
590    ) -> anyhow::Result<HashMap<String, (String, Vec<String>)>> {
591        // GitHub GraphQL complexity limit: chunk at 50 to avoid slow/rejected queries.
592        const CHUNK_SIZE: usize = 50;
593
594        if issue_numbers.is_empty() {
595            return Ok(HashMap::new());
596        }
597
598        let (valid_issue_numbers, invalid_issue_numbers) =
599            sanitize_github_issue_numbers(issue_numbers);
600        if !invalid_issue_numbers.is_empty() {
601            tracing::warn!(
602                repo,
603                caller_context,
604                invalid_issue_numbers = ?invalid_issue_numbers,
605                total_supplied = issue_numbers.len(),
606                "dropping invalid GitHub issue numbers before batch issue-state GraphQL query"
607            );
608        }
609        if valid_issue_numbers.is_empty() {
610            return Ok(HashMap::new());
611        }
612
613        let (owner, name) = repo
614            .split_once('/')
615            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
616
617        let mut result = HashMap::new();
618
619        for chunk in valid_issue_numbers.chunks(CHUNK_SIZE) {
620            let aliases: String = chunk
621                .iter()
622                .map(|n| {
623                    format!("issue{n}: issue(number: {n}) {{ state labels(first: 100) {{ nodes {{ name }} }} }}")
624                })
625                .collect::<Vec<_>>()
626                .join(" ");
627
628            let query = format!(
629                r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
630            );
631
632            let resp = self
633                .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
634                .await?;
635            let repo_data = resp
636                .pointer("/data/repository")
637                .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
638
639            for n in chunk {
640                if let Some(issue) = repo_data.get(format!("issue{n}")) {
641                    let state = issue
642                        .get("state")
643                        .and_then(|v| v.as_str())
644                        .unwrap_or("UNKNOWN")
645                        .to_lowercase();
646                    let labels: Vec<String> = issue
647                        .pointer("/labels/nodes")
648                        .and_then(|v| v.as_array())
649                        .map(|arr| {
650                            arr.iter()
651                                .filter_map(|l| {
652                                    l.get("name").and_then(|nm| nm.as_str()).map(String::from)
653                                })
654                                .collect()
655                        })
656                        .unwrap_or_default();
657                    result.insert(n.to_string(), (state, labels));
658                }
659            }
660        }
661        Ok(result)
662    }
663
664    /// Close a GitHub issue.
665    pub async fn close_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
666        let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
667        let payload = serde_json::json!({ "state": "closed" });
668        self.patch_json_raw(&url, &payload).await?;
669        Ok(())
670    }
671
672    /// Reopen a closed GitHub issue.
673    pub async fn reopen_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
674        let url = format!("{}/repos/{repo}/issues/{number}", self.api_root());
675        let payload = serde_json::json!({ "state": "open" });
676        self.patch_json_raw(&url, &payload).await?;
677        Ok(())
678    }
679
680    /// Check if a user is a collaborator.
681    pub async fn is_collaborator(&self, repo: &str, username: &str) -> anyhow::Result<bool> {
682        let url = format!("{GITHUB_API}/repos/{repo}/collaborators/{username}");
683        Self::check_backoff(&url)?;
684        let auth = self.auth_header(&url).await?;
685        let make_req = || {
686            Ok(self
687                .client
688                .get(&url)
689                .timeout(READ_TIMEOUT)
690                .header(header::AUTHORIZATION, auth.clone())
691                .header(header::ACCEPT, "application/vnd.github+json")
692                .header("X-GitHub-Api-Version", "2022-11-28"))
693        };
694        let resp = self.send_with_retries(make_req, false).await?;
695        let status = resp.status();
696        if status == StatusCode::NO_CONTENT {
697            Ok(true)
698        } else if status == StatusCode::NOT_FOUND {
699            Ok(false)
700        } else {
701            let body = resp.text().await.unwrap_or_default();
702            anyhow::bail!("GitHub API collaborator check failed ({status}): {body}");
703        }
704    }
705
706    /// Add a sub-issue relationship via GraphQL.
707    pub async fn add_sub_issue(
708        &self,
709        parent_node_id: &str,
710        child_node_id: &str,
711    ) -> anyhow::Result<()> {
712        let query = format!(
713            r#"mutation {{
714                addSubIssue(input: {{issueId: "{parent_node_id}", subIssueId: "{child_node_id}"}}) {{
715                    issue {{ number }}
716                    subIssue {{ number }}
717                }}
718            }}"#
719        );
720        self.graphql_with_headers(&query, &["GraphQL-Features:sub_issues"])
721            .await?;
722        Ok(())
723    }
724
725    /// Link an issue to a branch using GraphQL.
726    ///
727    /// Creates a "Development" sidebar link in GitHub that connects the issue
728    /// to the branch, similar to `gh issue develop`.
729    ///
730    /// # Arguments
731    /// * `repo` - Repository in "owner/repo" format
732    /// * `issue_number` - The issue number to link
733    /// * `branch` - The branch name to link the issue to
734    ///
735    /// Returns the linked branch ID on success.
736    pub async fn link_issue_to_branch(
737        &self,
738        repo: &str,
739        issue_number: u64,
740        branch: &str,
741    ) -> anyhow::Result<String> {
742        let parts: Vec<&str> = repo.split('/').collect();
743        if parts.len() != 2 {
744            anyhow::bail!("invalid repo format: expected 'owner/repo', got '{repo}'");
745        }
746        let (owner, repo_name) = (parts[0], parts[1]);
747
748        // First, get the repository and issue node IDs
749        let query = r"query($owner: String!, $name: String!, $number: Int!) {
750                repository(owner: $owner, name: $name) {
751                    id
752                    issue(number: $number) {
753                        id
754                    }
755                }
756            }";
757        let vars = serde_json::json!({
758            "owner": owner,
759            "name": repo_name,
760            "number": issue_number,
761        });
762
763        let result = self.graphql_with_vars(query, vars).await?;
764
765        let repo_id = result
766            .pointer("/data/repository/id")
767            .and_then(|v| v.as_str())
768            .ok_or_else(|| anyhow::anyhow!("failed to get repository node ID"))?;
769
770        let issue_id = result
771            .pointer("/data/repository/issue/id")
772            .and_then(|v| v.as_str())
773            .ok_or_else(|| anyhow::anyhow!("failed to get issue node ID"))?;
774
775        // Fetch branch ref to get the commit OID required by createLinkedBranch
776        let branch_query = r"query($owner: String!, $name: String!, $ref: String!) {
777                repository(owner: $owner, name: $name) {
778                    ref(qualifiedName: $ref) {
779                        target {
780                            oid
781                        }
782                    }
783                }
784            }";
785        let branch_vars = serde_json::json!({
786            "owner": owner,
787            "name": repo_name,
788            "ref": format!("refs/heads/{}", branch),
789        });
790
791        let branch_result = self.graphql_with_vars(branch_query, branch_vars).await?;
792        let branch_oid = branch_result
793            .pointer("/data/repository/ref/target/oid")
794            .and_then(|v| v.as_str());
795
796        // If branch doesn't exist yet, use the default branch OID.
797        // createLinkedBranch will create the branch at that OID AND link it.
798        let branch_oid = if let Some(oid) = branch_oid {
799            oid.to_string()
800        } else {
801            // Get default branch OID as the base for the new branch
802            let default_query = r"query($owner: String!, $name: String!) {
803                    repository(owner: $owner, name: $name) {
804                        defaultBranchRef {
805                            target {
806                                oid
807                            }
808                        }
809                    }
810                }";
811            let default_vars = serde_json::json!({
812                "owner": owner,
813                "name": repo_name,
814            });
815            let default_result = self.graphql_with_vars(default_query, default_vars).await?;
816            match default_result
817                .pointer("/data/repository/defaultBranchRef/target/oid")
818                .and_then(|v| v.as_str())
819            {
820                Some(oid) => {
821                    tracing::debug!(
822                        repo,
823                        issue_number,
824                        branch,
825                        "branch not found, using default branch OID to create and link"
826                    );
827                    oid.to_string()
828                }
829                None => {
830                    return Ok(format!("unlinked:{branch}"));
831                }
832            }
833        };
834
835        // Use createLinkedBranch mutation to link the issue to the existing branch.
836        // Required fields: issueId, repositoryId, name (branch name), oid (commit SHA).
837        let mutation = r"mutation($issueId: ID!, $repositoryId: ID!, $name: String!, $oid: GitObjectID!) {
838                createLinkedBranch(input: {
839                    issueId: $issueId
840                    repositoryId: $repositoryId
841                    name: $name
842                    oid: $oid
843                }) {
844                    linkedBranch {
845                        id
846                        ref {
847                            name
848                        }
849                    }
850                }
851            }";
852        let mutation_vars = serde_json::json!({
853            "issueId": issue_id,
854            "repositoryId": repo_id,
855            "name": branch,
856            "oid": branch_oid,
857        });
858
859        let link_result = self.graphql_with_vars(mutation, mutation_vars).await;
860
861        match link_result {
862            Ok(result) => {
863                let linked_branch_id = result
864                    .pointer("/data/createLinkedBranch/linkedBranch/id")
865                    .and_then(|v| v.as_str())
866                    .map(String::from);
867
868                if let Some(id) = linked_branch_id {
869                    tracing::info!(
870                        repo,
871                        issue_number,
872                        branch,
873                        "linked issue to branch via GraphQL API"
874                    );
875                    Ok(id)
876                } else {
877                    // Branch may already be linked - check for errors
878                    let errors = result
879                        .get("errors")
880                        .and_then(|e| e.as_array())
881                        .cloned()
882                        .unwrap_or_default();
883
884                    if errors.iter().any(|e| {
885                        e.get("message")
886                            .and_then(|m| m.as_str())
887                            .is_some_and(|m| m.contains("already"))
888                    }) {
889                        tracing::debug!(
890                            repo,
891                            issue_number,
892                            branch,
893                            "issue already linked to branch"
894                        );
895                        Ok(format!("already_linked:{branch}"))
896                    } else {
897                        anyhow::bail!("failed to link issue to branch: {result:?}")
898                    }
899                }
900            }
901            Err(e) => {
902                // Check if it's a "already exists" type error
903                let err_str = format!("{e}");
904                if err_str.contains("already") || err_str.contains("existing") {
905                    tracing::debug!(
906                        repo,
907                        issue_number,
908                        branch,
909                        "issue already linked to branch (error check)"
910                    );
911                    Ok(format!("already_linked:{branch}"))
912                } else {
913                    Err(e)
914                }
915            }
916        }
917    }
918
919    /// Get sub-issues via GraphQL (paginated).
920    pub async fn get_sub_issues(&self, repo: &str, number: &str) -> anyhow::Result<Vec<u64>> {
921        let parts: Vec<&str> = repo.split('/').collect();
922        if parts.len() != 2 {
923            anyhow::bail!("invalid repo format: expected 'owner/repo', got '{repo}'");
924        }
925        let (owner, repo_name) = (parts[0], parts[1]);
926        let number = match parse_positive_issue_number(number) {
927            Ok(number) => number,
928            Err(e) => {
929                tracing::debug!(repo, issue = number, ?e, "skipping sub-issues lookup");
930                return Ok(Vec::new());
931            }
932        };
933
934        let mut all_numbers: Vec<u64> = Vec::new();
935        let mut cursor: Option<String> = None;
936        let page_size = 100;
937        let max_pages = 50;
938        let mut page_count = 0;
939
940        loop {
941            page_count += 1;
942            if page_count > max_pages {
943                tracing::warn!(
944                    repo,
945                    number,
946                    "get_sub_issues hit max page limit ({max_pages})"
947                );
948                break;
949            }
950
951            let (query, vars) = if let Some(ref c) = cursor {
952                (
953                    r"query($owner: String!, $name: String!, $number: Int!, $first: Int!, $after: String!) {
954                    repository(owner: $owner, name: $name) {
955                        issue(number: $number) {
956                            subIssues(first: $first, after: $after) {
957                                nodes { number }
958                                pageInfo { hasNextPage endCursor }
959                            }
960                        }
961                    }
962                }",
963                    serde_json::json!({
964                        "owner": owner,
965                        "name": repo_name,
966                        "number": number,
967                        "first": page_size,
968                        "after": c,
969                    }),
970                )
971            } else {
972                (
973                    r"query($owner: String!, $name: String!, $number: Int!, $first: Int!) {
974                    repository(owner: $owner, name: $name) {
975                        issue(number: $number) {
976                            subIssues(first: $first) {
977                                nodes { number }
978                                pageInfo { hasNextPage endCursor }
979                            }
980                        }
981                    }
982                }",
983                    serde_json::json!({
984                        "owner": owner,
985                        "name": repo_name,
986                        "number": number,
987                        "first": page_size,
988                    }),
989                )
990            };
991
992            let result = self
993                .graphql_with_headers_and_vars(query, &["GraphQL-Features:sub_issues"], vars)
994                .await?;
995
996            let sub_issues_data = result
997                .get("data")
998                .and_then(|d| d.get("repository"))
999                .and_then(|r| r.get("issue"))
1000                .and_then(|i| i.get("subIssues"));
1001
1002            let nodes = sub_issues_data
1003                .and_then(|s| s.get("nodes"))
1004                .and_then(|n| n.as_array());
1005
1006            match nodes {
1007                Some(nodes) => {
1008                    let numbers: Vec<u64> = nodes
1009                        .iter()
1010                        .filter_map(|n| n.get("number").and_then(serde_json::Value::as_u64))
1011                        .collect();
1012                    all_numbers.extend(numbers);
1013                }
1014                None => break,
1015            }
1016
1017            let page_info = sub_issues_data.and_then(|s| s.get("pageInfo"));
1018            let has_next = page_info
1019                .and_then(|p| p.get("hasNextPage"))
1020                .and_then(serde_json::Value::as_bool)
1021                .unwrap_or(false);
1022
1023            if !has_next {
1024                break;
1025            }
1026
1027            cursor = page_info
1028                .and_then(|p| p.get("endCursor"))
1029                .and_then(|c| c.as_str())
1030                .map(ToString::to_string);
1031        }
1032
1033        Ok(all_numbers)
1034    }
1035}