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