Skip to main content

orch/github/http/
pulls.rs

1//! Pull request, merge and review data calls
2
3use super::{GITHUB_API, GhHttp, is_full_commit_sha, merge_pr_body};
4use crate::github::types::GitHubUser;
5use crate::github::types::{GitHubComment, GitHubPullRequest, GitHubReview, GitHubReviewComment};
6use crate::security::redact_posted_body;
7use reqwest::header;
8use serde::Serialize;
9use std::collections::HashMap;
10use std::fmt::Debug;
11use std::fmt::Write as _;
12use urlencoding;
13
14impl GhHttp {
15    /// Whether a merged PR exists whose head ref is `branch`.
16    ///
17    /// The closed-PR list can include a PR for a different branch, so this
18    /// uses [`Self::get_closed_pr_state`], which skips a mismatched `head.ref`
19    pub async fn is_pr_merged(&self, repo: &str, branch: &str) -> anyhow::Result<bool> {
20        Ok(self
21            .get_closed_pr_state(repo, branch)
22            .await?
23            .is_some_and(|(_, merged, _)| merged))
24    }
25
26    /// Get the state of a closed PR for the given branch.
27    ///
28    /// Returns `Some((merged, state))` if a closed PR exists for the branch,
29    /// where `merged` indicates if it was merged and `state` is the PR state ("closed" or "merged").
30    /// Returns `None` if no closed PR exists for the branch.
31    /// Get the state of a closed PR for a given branch.
32    ///
33    /// Returns `Some((pr_number, merged, state))` if a closed PR is found that
34    /// matches the expected branch. Returns `None` if no matching closed PR is found.
35    ///
36    /// Validates that the returned PR's head ref matches the expected branch to
37    /// prevent incorrect merge decisions when multiple PRs exist for the same branch.
38    pub async fn get_closed_pr_state(
39        &self,
40        repo: &str,
41        branch: &str,
42    ) -> anyhow::Result<Option<(u64, bool, String)>> {
43        let owner = repo
44            .split('/')
45            .next()
46            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
47        let head = format!("{owner}:{branch}");
48
49        let url = format!("{}/repos/{repo}/pulls", self.api_root());
50        let prs: Vec<serde_json::Value> = self
51            .get_with_query(
52                &url,
53                &[("head", &head), ("state", "closed"), ("per_page", "5")],
54            )
55            .await?;
56
57        if prs.is_empty() {
58            return Ok(None);
59        }
60
61        // Find the first PR where head ref actually matches our branch
62        // This validates that we're working with the correct PR
63        for pr in prs {
64            let pr_branch = pr
65                .get("head")
66                .and_then(|h| h.get("ref"))
67                .and_then(|r| r.as_str())
68                .unwrap_or("");
69
70            if pr_branch != branch {
71                tracing::debug!(
72                    repo,
73                    branch,
74                    pr_branch,
75                    "skipping PR with mismatched head ref"
76                );
77                continue;
78            }
79
80            let pr_number = pr
81                .get("number")
82                .and_then(serde_json::Value::as_u64)
83                .ok_or_else(|| anyhow::anyhow!("PR missing number field"))?;
84
85            let merged_at = pr.get("merged_at");
86            let merged = merged_at.is_some_and(|v| !v.is_null());
87            let state = pr
88                .get("state")
89                .and_then(|v| v.as_str())
90                .unwrap_or("closed")
91                .to_string();
92
93            return Ok(Some((pr_number, merged, state)));
94        }
95
96        // No PR with matching head ref found
97        Ok(None)
98    }
99
100    /// Batch-check whether the PR for each branch was merged via a single GraphQL query.
101    ///
102    /// Returns a map of branch → merged. Branches with no matching PR are omitted
103    /// (callers should treat missing entries as not merged).
104    pub async fn batch_is_pr_merged_by_branch(
105        &self,
106        repo: &str,
107        branches: &[String],
108    ) -> anyhow::Result<HashMap<String, bool>> {
109        if branches.is_empty() {
110            return Ok(HashMap::new());
111        }
112
113        let (owner, name) = repo
114            .split_once('/')
115            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
116
117        // Build one alias per branch using positional index to avoid GraphQL
118        // alias restrictions on branch names that contain non-identifier chars.
119        // Branch names are passed via variables ($b0, $b1, …) to avoid injection.
120        let mut var_defs = String::new();
121        let mut aliases = String::new();
122        let mut vars = serde_json::json!({ "owner": owner, "name": name });
123        for (i, branch) in branches.iter().enumerate() {
124            let _ = write!(var_defs, ", $b{i}: String!");
125            let _ = write!(
126                aliases,
127                r"b{i}: pullRequests(headRefName: $b{i}, states: [MERGED], last: 1) {{ nodes {{ merged }} }} "
128            );
129            vars[format!("b{i}")] = serde_json::Value::String(branch.clone());
130        }
131
132        let query = format!(
133            r"query($owner: String!, $name: String!{var_defs}) {{
134                repository(owner: $owner, name: $name) {{ {aliases} }}
135            }}"
136        );
137
138        let resp = self.graphql_with_vars(&query, vars).await?;
139
140        // Surface GraphQL partial errors before checking data structure
141        if let Some(errors) = resp.get("errors").and_then(|e| e.as_array())
142            && !errors.is_empty()
143        {
144            let messages: Vec<&str> = errors
145                .iter()
146                .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
147                .collect();
148            tracing::warn!(
149                repo,
150                errors = ?messages,
151                "GraphQL returned errors in batch PR merge check"
152            );
153        }
154
155        Self::parse_batch_pr_merged_response(&resp, branches)
156    }
157
158    pub(super) fn parse_batch_pr_merged_response(
159        resp: &serde_json::Value,
160        branches: &[String],
161    ) -> anyhow::Result<HashMap<String, bool>> {
162        let repo_data = resp.pointer("/data/repository").ok_or_else(|| {
163            // Check for errors array to provide a more helpful error message
164            let error_msg = resp
165                .get("errors")
166                .and_then(|e| e.as_array())
167                .and_then(|arr| arr.first())
168                .and_then(|e| e.get("message"))
169                .and_then(|m| m.as_str())
170                .unwrap_or("no error details");
171            anyhow::anyhow!("missing /data/repository in GraphQL response: {error_msg}")
172        })?;
173
174        let mut result = HashMap::new();
175        for (i, branch) in branches.iter().enumerate() {
176            let alias = format!("b{i}");
177            let merged = repo_data
178                .get(&alias)
179                .and_then(|v| v.get("nodes"))
180                .and_then(|nodes| nodes.as_array())
181                .and_then(|arr| arr.first())
182                .and_then(|node| node.get("merged"))
183                .and_then(serde_json::Value::as_bool)
184                .unwrap_or(false);
185            result.insert(branch.clone(), merged);
186        }
187
188        Ok(result)
189    }
190
191    /// Get PR number by branch name.
192    pub async fn get_pr_number(&self, repo: &str, branch: &str) -> anyhow::Result<Option<u64>> {
193        let owner = repo
194            .split('/')
195            .next()
196            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
197        let head = format!("{owner}:{branch}");
198
199        let url = format!("{GITHUB_API}/repos/{repo}/pulls");
200        let prs: Vec<serde_json::Value> = self
201            .get_with_query(
202                &url,
203                &[("head", &head), ("state", "open"), ("per_page", "1")],
204            )
205            .await?;
206
207        if prs.is_empty() {
208            return Ok(None);
209        }
210        prs[0]
211            .get("number")
212            .and_then(serde_json::Value::as_u64)
213            .ok_or_else(|| anyhow::anyhow!("PR missing number field"))
214            .map(Some)
215    }
216
217    /// Create a new pull request.
218    ///
219    /// # Arguments
220    /// * `repo` - Repository in "owner/repo" format
221    /// * `title` - PR title
222    /// * `body` - PR body/description
223    /// * `head` - Branch name to create PR from
224    /// * `base` - Base branch to merge into (e.g., "main")
225    ///
226    /// Returns the created PR's URL on success.
227    pub async fn create_pr(
228        &self,
229        repo: &str,
230        title: &str,
231        body: &str,
232        head: &str,
233        base: &str,
234    ) -> anyhow::Result<String> {
235        #[derive(Serialize)]
236        struct CreatePullRequest<'a> {
237            title: &'a str,
238            body: &'a str,
239            head: &'a str,
240            base: &'a str,
241        }
242
243        let body = redact_posted_body(body);
244        let url = format!("{}/repos/{repo}/pulls", self.api_root());
245        Self::check_backoff(&url)?;
246
247        let payload = CreatePullRequest {
248            title,
249            body: &body,
250            head,
251            base,
252        };
253
254        let auth = self.auth_header(&url).await?;
255        let make_req = || {
256            Ok(self
257                .client
258                .post(&url)
259                .header(header::AUTHORIZATION, auth.clone())
260                .header(header::ACCEPT, "application/vnd.github+json")
261                .header(header::USER_AGENT, "orch")
262                .header("X-GitHub-Api-Version", "2022-11-28")
263                .json(&payload))
264        };
265        let response = self.send_with_retries(make_req, false).await?;
266        let status = response.status();
267        let text = response.text().await.unwrap_or_default();
268        if !status.is_success() {
269            Self::maybe_record_rate_limit_from_body(status, &text);
270            anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
271        }
272
273        let pr: serde_json::Value = serde_json::from_str(&text)?;
274        pr.get("html_url")
275            .and_then(|v| v.as_str())
276            .map(String::from)
277            .ok_or_else(|| anyhow::anyhow!("failed to get PR URL from response: {pr:?}"))
278    }
279
280    /// Get the repository's default branch from the GitHub API.
281    ///
282    /// Used as a fallback when local git detection yields an invalid base
283    /// branch for PR creation.
284    pub async fn get_default_branch(&self, repo: &str) -> anyhow::Result<String> {
285        let url = format!("{}/repos/{repo}", self.api_root());
286        let resp: serde_json::Value = self.get_json(&url).await?;
287        resp.get("default_branch")
288            .and_then(|v| v.as_str())
289            .map(String::from)
290            .ok_or_else(|| anyhow::anyhow!("default_branch missing from repo response"))
291    }
292
293    /// Get PR details by PR number.
294    /// Returns the full PR object including the `mergeable` field.
295    pub async fn get_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<GitHubPullRequest> {
296        let url = format!("{}/repos/{repo}/pulls/{pr_number}", self.api_root());
297        self.get_json(&url).await
298    }
299
300    /// Fetch the merged/state for multiple PRs in a single GraphQL query.
301    ///
302    /// Returns a map of pr_number → (merged, state).
303    /// PRs that fail to fetch are silently omitted from the result.
304    pub async fn batch_get_pr_states(
305        &self,
306        repo: &str,
307        pr_numbers: &[u64],
308    ) -> anyhow::Result<HashMap<u64, (bool, String)>> {
309        // GitHub GraphQL complexity limit: chunk at 50 to avoid slow/rejected queries.
310        const CHUNK_SIZE: usize = 50;
311
312        if pr_numbers.is_empty() {
313            return Ok(HashMap::new());
314        }
315
316        let (owner, name) = repo
317            .split_once('/')
318            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
319
320        let mut result = HashMap::new();
321
322        for chunk in pr_numbers.chunks(CHUNK_SIZE) {
323            let aliases: String = chunk
324                .iter()
325                .map(|n| format!("pr{n}: pullRequest(number: {n}) {{ merged state }}"))
326                .collect::<Vec<_>>()
327                .join("\n  ");
328
329            let query = format!(
330                r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
331            );
332
333            let resp = self
334                .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
335                .await?;
336            let repo_data = resp
337                .pointer("/data/repository")
338                .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
339
340            for n in chunk {
341                if let Some(pr) = repo_data.get(format!("pr{n}")) {
342                    let merged = pr
343                        .get("merged")
344                        .and_then(serde_json::Value::as_bool)
345                        .unwrap_or(false);
346                    let state = pr
347                        .get("state")
348                        .and_then(|v| v.as_str())
349                        .unwrap_or("UNKNOWN")
350                        .to_lowercase();
351                    result.insert(*n, (merged, state));
352                }
353            }
354        }
355
356        Ok(result)
357    }
358
359    /// SHA of the head commit on `branch`
360    pub async fn get_branch_sha(&self, repo: &str, branch: &str) -> anyhow::Result<String> {
361        let encoded = urlencoding::encode(branch);
362        let url = format!("{}/repos/{repo}/branches/{encoded}", self.api_root());
363        let resp: serde_json::Value = self.get_json(&url).await?;
364        resp.pointer("/commit/sha")
365            .and_then(|v| v.as_str())
366            .map(String::from)
367            .ok_or_else(|| anyhow::anyhow!("branch {branch} has no commit sha"))
368    }
369
370    /// Get reviews for a PR.
371    pub async fn get_pr_reviews(
372        &self,
373        repo: &str,
374        pr_number: u64,
375    ) -> anyhow::Result<Vec<GitHubReview>> {
376        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/reviews");
377        self.get_all_pages(&url, &[("per_page", "100")]).await
378    }
379
380    /// Get the committer timestamp for a specific commit SHA.
381    ///
382    /// Returns an ISO-8601 string, e.g. `"2024-01-15T12:00:00Z"`.
383    /// Used to determine whether the branch has been updated since a review was submitted.
384    pub async fn get_commit_timestamp(&self, repo: &str, sha: &str) -> anyhow::Result<String> {
385        let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}");
386        let value: serde_json::Value = self.get_json(&url).await?;
387        value
388            .pointer("/commit/committer/date")
389            .and_then(|v| v.as_str())
390            .map(ToString::to_string)
391            .ok_or_else(|| anyhow::anyhow!("commit {sha} has no committer date"))
392    }
393
394    /// Update the body of a pull request.
395    pub async fn update_pr_body(
396        &self,
397        repo: &str,
398        pr_number: u64,
399        body: &str,
400    ) -> anyhow::Result<()> {
401        let body = redact_posted_body(body);
402        let url = format!("{}/repos/{repo}/pulls/{pr_number}", self.api_root());
403        let payload = serde_json::json!({ "body": body });
404        self.patch_json_raw(&url, &payload).await?;
405        Ok(())
406    }
407
408    /// Close a pull request without merging it.
409    pub async fn close_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
410        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}");
411        let payload = serde_json::json!({ "state": "closed" });
412        self.patch_json_raw(&url, &payload).await?;
413        Ok(())
414    }
415
416    /// How many commits the head is missing from `base` (GitHub's `behind_by`).
417    ///
418    /// Zero means the head already contains the current base tip, so its checks
419    /// ran against the code the merge would produce.
420    pub async fn compare_behind_by(
421        &self,
422        repo: &str,
423        base: &str,
424        head_sha: &str,
425    ) -> anyhow::Result<u64> {
426        let url = format!("{GITHUB_API}/repos/{repo}/compare/{base}...{head_sha}");
427        let body: serde_json::Value = self.get_json(&url).await?;
428        parse_behind_by(&body)
429    }
430
431    /// Parents, author and committer of a commit
432    pub async fn commit_meta(&self, repo: &str, sha: &str) -> anyhow::Result<CommitMeta> {
433        let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}");
434        let value: serde_json::Value = self.get_json(&url).await?;
435        Ok(parse_commit_meta(&value))
436    }
437
438    /// True when `branch` already contains the commit `sha`
439    pub async fn branch_contains(
440        &self,
441        repo: &str,
442        branch: &str,
443        sha: &str,
444    ) -> anyhow::Result<bool> {
445        let url = format!("{GITHUB_API}/repos/{repo}/compare/{branch}...{sha}");
446        let body: serde_json::Value = self.get_json(&url).await?;
447        body.get("ahead_by")
448            .and_then(serde_json::Value::as_u64)
449            .map(|ahead| ahead == 0)
450            .ok_or_else(|| anyhow::anyhow!("compare response has no numeric ahead_by field"))
451    }
452
453    /// Merge a PR using the REST API (squash merge).
454    /// GitHub rejects it when the PR head is no longer `head_sha`, the commit CI was checked against
455    pub async fn merge_pr(
456        &self,
457        repo: &str,
458        pr_number: u64,
459        delete_branch: bool,
460        head_sha: &str,
461    ) -> anyhow::Result<()> {
462        if !is_full_commit_sha(head_sha) {
463            anyhow::bail!("merge_pr requires the full head sha, got {head_sha:?}");
464        }
465        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/merge");
466        Self::check_backoff(&url)?;
467        let payload = merge_pr_body(head_sha);
468        let auth = self.auth_header(&url).await?;
469        let make_req = || {
470            Ok(self
471                .client
472                .put(&url)
473                .json(&payload)
474                .header(header::AUTHORIZATION, auth.clone())
475                .header(header::ACCEPT, "application/vnd.github+json")
476                .header("X-GitHub-Api-Version", "2022-11-28"))
477        };
478        let resp = self.send_with_retries(make_req, false).await?;
479        let status = resp.status();
480        if !status.is_success() {
481            let body = resp.text().await.unwrap_or_default();
482            anyhow::bail!("GitHub PR merge failed ({status}): {body}");
483        }
484        Self::record_success();
485
486        // Delete branch if requested
487        if delete_branch {
488            // Get the head ref (branch name) from the PR
489            let pr: serde_json::Value = self
490                .get_json(&format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}"))
491                .await?;
492            if let Some(ref_name) = pr.pointer("/head/ref").and_then(|v| v.as_str()) {
493                let del_url = format!("{GITHUB_API}/repos/{repo}/git/refs/heads/{ref_name}");
494                if let Err(e) = self.delete(&del_url).await {
495                    let err_str = e.to_string();
496                    if err_str.contains("Reference does not exist") {
497                        tracing::debug!(
498                            ref_name,
499                            "branch already gone (GitHub auto-deleted on merge)"
500                        );
501                    } else {
502                        tracing::warn!(ref_name, err = %e, "failed to delete branch after merge");
503                    }
504                }
505            }
506        }
507        Ok(())
508    }
509
510    /// Update a PR's branch by merging the latest base branch into it
511    /// (equivalent of the "Update branch" button on GitHub, or `gh pr
512    /// update-branch`). Produces a new merge commit on the head branch,
513    /// which re-triggers CI — used to give a PR a chance to pick up a fix
514    /// that landed on the base branch after the PR's last CI run failed.
515    pub async fn update_pr_branch(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
516        let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/update-branch");
517        Self::check_backoff(&url)?;
518        let auth = self.auth_header(&url).await?;
519        let make_req = || {
520            Ok(self
521                .client
522                .put(&url)
523                .header(header::AUTHORIZATION, auth.clone())
524                .header(header::ACCEPT, "application/vnd.github+json")
525                .header("X-GitHub-Api-Version", "2022-11-28"))
526        };
527        let resp = self.send_with_retries(make_req, false).await?;
528        let status = resp.status();
529        if !status.is_success() {
530            let body = resp.text().await.unwrap_or_default();
531            Self::maybe_record_rate_limit_from_body(status, &body);
532            anyhow::bail!("GitHub PR update-branch failed ({status}): {body}");
533        }
534        Self::record_success();
535        Ok(())
536    }
537
538    /// Enable auto-merge on a PR via GraphQL.
539    ///
540    /// GitHub will automatically merge the PR once all required checks pass.
541    pub async fn enable_auto_merge(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
542        let parts: Vec<&str> = repo.split('/').collect();
543        if parts.len() != 2 {
544            anyhow::bail!("invalid repo format: {repo}");
545        }
546        let (owner, repo_name) = (parts[0], parts[1]);
547
548        // First get the PR node ID
549        let pr_query = r"query($owner: String!, $name: String!, $number: Int!) {
550            repository(owner: $owner, name: $name) {
551                pullRequest(number: $number) { id }
552            }
553        }";
554        let body = self
555            .graphql_with_vars(
556                pr_query,
557                serde_json::json!({
558                    "owner": owner,
559                    "name": repo_name,
560                    "number": pr_number,
561                }),
562            )
563            .await?;
564        let pr_id = body
565            .pointer("/data/repository/pullRequest/id")
566            .and_then(|v| v.as_str())
567            .ok_or_else(|| anyhow::anyhow!("could not get PR node ID"))?
568            .to_string();
569
570        // Enable auto-merge with squash
571        let mutation = r"mutation($prId: ID!) {
572            enablePullRequestAutoMerge(input: {pullRequestId: $prId, mergeMethod: SQUASH}) {
573                pullRequest { autoMergeRequest { enabledAt } }
574            }
575        }";
576        let body = self
577            .graphql_with_vars(mutation, serde_json::json!({ "prId": pr_id }))
578            .await?;
579        if let Some(errors) = body.get("errors") {
580            anyhow::bail!("enable auto-merge GraphQL error: {errors}");
581        }
582
583        tracing::info!(repo, pr_number, "auto-merge enabled on PR");
584        Ok(())
585    }
586
587    /// Fetch reviews, review comments, and issue comments for multiple PRs in a
588    /// single GraphQL query instead of 4–5 REST calls per PR.
589    ///
590    /// Returns a map of `pr_number → PrReviewBatchData`.
591    /// PRs missing from the response are omitted from the result.
592    pub async fn batch_fetch_pr_review_data(
593        &self,
594        repo: &str,
595        pr_numbers: &[u64],
596    ) -> anyhow::Result<HashMap<u64, PrReviewBatchData>> {
597        if pr_numbers.is_empty() {
598            return Ok(HashMap::new());
599        }
600
601        let (owner, name) = repo
602            .split_once('/')
603            .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
604
605        // Build one GraphQL alias per PR number.
606        let aliases: String = pr_numbers
607            .iter()
608            .map(|&n| build_pr_review_alias(n))
609            .collect::<Vec<_>>()
610            .join("\n");
611
612        let query = format!(
613            r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
614        );
615
616        let resp = self
617            .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
618            .await?;
619        let repo_data = resp
620            .pointer("/data/repository")
621            .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
622
623        let mut result = HashMap::new();
624        for &n in pr_numbers {
625            let Some(pr_data) = repo_data.get(format!("pr{n}")) else {
626                continue;
627            };
628
629            let merged = pr_data
630                .get("merged")
631                .and_then(serde_json::Value::as_bool)
632                .unwrap_or(false);
633            let mergeable = match pr_data.get("mergeable").and_then(|v| v.as_str()) {
634                Some("MERGEABLE") => Some(true),
635                Some("CONFLICTING") => Some(false),
636                _ => None, // UNKNOWN or missing
637            };
638
639            let mut reviews: Vec<GitHubReview> = pr_data
640                .pointer("/reviews/nodes")
641                .and_then(|v| v.as_array())
642                .map(|nodes| nodes.iter().filter_map(parse_graphql_review).collect())
643                .unwrap_or_default();
644
645            if connection_has_next_page(pr_data.pointer("/reviews/pageInfo")) {
646                tracing::warn!(
647                    pr_number = n,
648                    fetched = reviews.len(),
649                    "batch review fetch truncated reviews connection at first page"
650                );
651            }
652
653            // Ensure deterministic ordering by submitted timestamp (oldest -> newest).
654            // GraphQL connections do not guarantee a stable sort unless explicitly
655            // requested. Sort here so consumers can rely on chronological order.
656            reviews.sort_by(|a, b| a.submitted_at.cmp(&b.submitted_at));
657
658            let mut review_comments: Vec<GitHubReviewComment> = pr_data
659                .pointer("/reviewThreads/nodes")
660                .and_then(|v| v.as_array())
661                .map(|threads| {
662                    threads
663                        .iter()
664                        .filter_map(|thread| {
665                            thread
666                                .pointer("/comments/nodes")
667                                .and_then(|v| v.as_array())
668                                .map(|nodes| {
669                                    nodes
670                                        .iter()
671                                        .filter_map(parse_graphql_review_comment)
672                                        .collect::<Vec<_>>()
673                                })
674                        })
675                        .flatten()
676                        .collect()
677                })
678                .unwrap_or_default();
679
680            if connection_has_next_page(pr_data.pointer("/reviewThreads/pageInfo")) {
681                tracing::warn!(
682                    pr_number = n,
683                    fetched_threads = pr_data
684                        .pointer("/reviewThreads/nodes")
685                        .and_then(|v| v.as_array())
686                        .map_or(0, Vec::len),
687                    "batch review fetch truncated reviewThreads connection at first page"
688                );
689            }
690            if pr_data
691                .pointer("/reviewThreads/nodes")
692                .and_then(|v| v.as_array())
693                .is_some_and(|threads| {
694                    threads.iter().any(|thread| {
695                        connection_has_next_page(thread.pointer("/comments/pageInfo"))
696                    })
697                })
698            {
699                tracing::warn!(
700                    pr_number = n,
701                    "batch review fetch truncated one or more review thread comment connections"
702                );
703            }
704
705            // Sort inline review comments by created_at (oldest -> newest) so
706            // callers can process them deterministically.
707            review_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
708
709            let mut issue_comments: Vec<GitHubComment> = pr_data
710                .pointer("/comments/nodes")
711                .and_then(|v| v.as_array())
712                .map(|nodes| {
713                    nodes
714                        .iter()
715                        .filter_map(parse_graphql_issue_comment)
716                        .collect()
717                })
718                .unwrap_or_default();
719
720            if let Some(cursor) = connection_end_cursor(pr_data.pointer("/comments/pageInfo")) {
721                issue_comments.extend(
722                    self.fetch_pr_issue_comments_after(owner, name, n, Some(cursor))
723                        .await?,
724                );
725            }
726
727            // Sort issue-level comments by created_at (oldest -> newest). The
728            // review poll logic expects chronological ordering and may iterate
729            // in reverse to find the latest comments — so ensure a consistent
730            // ordering here regardless of GraphQL's default.
731            issue_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
732
733            result.insert(
734                n,
735                PrReviewBatchData {
736                    merged,
737                    head_sha: pr_data
738                        .get("headRefOid")
739                        .and_then(|v| v.as_str())
740                        .unwrap_or_default()
741                        .to_string(),
742                    mergeable,
743                    reviews,
744                    review_comments,
745                    issue_comments,
746                },
747            );
748        }
749
750        Ok(result)
751    }
752
753    async fn fetch_pr_issue_comments_after(
754        &self,
755        owner: &str,
756        name: &str,
757        pr_number: u64,
758        mut cursor: Option<String>,
759    ) -> anyhow::Result<Vec<GitHubComment>> {
760        let mut comments = Vec::new();
761        let mut page_count = 0;
762        let max_pages = 50;
763
764        while let Some(current_cursor) = cursor.take() {
765            page_count += 1;
766            if page_count > max_pages {
767                tracing::warn!(
768                    pr_number,
769                    fetched = comments.len(),
770                    "stopping PR issue comment pagination after max page limit"
771                );
772                break;
773            }
774
775            let (query, vars) =
776                build_pr_issue_comments_page_query(owner, name, pr_number, &current_cursor);
777            let resp = self.graphql_with_vars(&query, vars).await?;
778            let comments_data = resp
779                .pointer("/data/repository/pullRequest/comments")
780                .ok_or_else(|| {
781                    anyhow::anyhow!(
782                        "missing /data/repository/pullRequest/comments in GraphQL response"
783                    )
784                })?;
785
786            comments.extend(
787                comments_data
788                    .get("nodes")
789                    .and_then(|v| v.as_array())
790                    .into_iter()
791                    .flatten()
792                    .filter_map(parse_graphql_issue_comment),
793            );
794
795            cursor = connection_end_cursor(comments_data.get("pageInfo"));
796        }
797
798        Ok(comments)
799    }
800}
801
802/// Read `behind_by` out of a compare response.
803///
804/// A missing field is an error, not zero: treating an unreadable response as
805/// "head is up to date" would let a stale PR merge
806/// A commit's parents, first parent first, and the GitHub accounts behind it
807#[derive(Debug, Default, PartialEq)]
808pub struct CommitMeta {
809    pub parents: Vec<String>,
810    pub author_login: Option<String>,
811    pub committer_login: Option<String>,
812}
813
814pub(super) fn parse_commit_meta(commit: &serde_json::Value) -> CommitMeta {
815    let login = |field: &str| {
816        commit
817            .pointer(&format!("/{field}/login"))
818            .and_then(|v| v.as_str())
819            .map(String::from)
820    };
821    CommitMeta {
822        parents: commit
823            .get("parents")
824            .and_then(|p| p.as_array())
825            .map(|parents| {
826                parents
827                    .iter()
828                    .filter_map(|p| p.get("sha").and_then(|s| s.as_str()).map(String::from))
829                    .collect()
830            })
831            .unwrap_or_default(),
832        author_login: login("author"),
833        committer_login: login("committer"),
834    }
835}
836
837pub(super) fn parse_behind_by(body: &serde_json::Value) -> anyhow::Result<u64> {
838    body.get("behind_by")
839        .and_then(serde_json::Value::as_u64)
840        .ok_or_else(|| anyhow::anyhow!("compare response has no numeric behind_by field"))
841}
842
843/// Data fetched for one PR by [`GhHttp::batch_fetch_pr_review_data`].
844#[derive(Debug, Clone, Default)]
845pub struct PrReviewBatchData {
846    /// True when the pull request was merged.
847    pub merged: bool,
848    /// Head commit of the pull request, empty when GitHub did not return it.
849    pub head_sha: String,
850    /// `Some(true)` = MERGEABLE, `Some(false)` = CONFLICTING, `None` = UNKNOWN.
851    pub mergeable: Option<bool>,
852    /// All reviews submitted on the PR.
853    pub reviews: Vec<GitHubReview>,
854    /// All inline review comments (from all review threads).
855    pub review_comments: Vec<GitHubReviewComment>,
856    /// All issue-level comments on the PR.
857    pub issue_comments: Vec<GitHubComment>,
858}
859
860/// Build a GraphQL alias fragment for one pull request, fetching all data
861/// needed by the review poll loop in a single batch request.
862pub(super) fn build_pr_review_alias(n: u64) -> String {
863    format!(
864        r"pr{n}: pullRequest(number: {n}) {{
865  merged
866  mergeable
867  headRefOid
868  reviews(first: 50) {{
869    nodes {{
870      databaseId
871      author {{ login }}
872      body
873      state
874      url
875      submittedAt
876      commit {{ oid }}
877    }}
878    pageInfo {{ hasNextPage }}
879  }}
880  reviewThreads(first: 50) {{
881    nodes {{
882      comments(first: 20) {{
883        nodes {{
884          databaseId
885          author {{ login }}
886          body
887          path
888          line
889          originalLine
890          commit {{ oid }}
891          originalCommit {{ oid }}
892          url
893          createdAt
894          updatedAt
895          replyTo {{ databaseId }}
896          diffHunk
897        }}
898        pageInfo {{ hasNextPage }}
899      }}
900    }}
901    pageInfo {{ hasNextPage }}
902  }}
903  comments(first: 50) {{
904    nodes {{
905      databaseId
906      author {{ login }}
907      body
908      createdAt
909      updatedAt
910      url
911    }}
912    pageInfo {{ hasNextPage endCursor }}
913  }}
914}}"
915    )
916}
917
918pub(super) fn build_pr_issue_comments_page_query(
919    owner: &str,
920    name: &str,
921    pr_number: u64,
922    after_cursor: &str,
923) -> (String, serde_json::Value) {
924    let query = r"query($owner: String!, $name: String!, $number: Int!, $after: String!) {
925  repository(owner: $owner, name: $name) {
926    pullRequest(number: $number) {
927      comments(first: 100, after: $after) {
928        nodes {
929          databaseId
930          author { login }
931          body
932          createdAt
933          updatedAt
934          url
935        }
936        pageInfo { hasNextPage endCursor }
937      }
938    }
939  }
940}"
941    .to_string();
942    let vars = serde_json::json!({
943        "owner": owner,
944        "name": name,
945        "number": pr_number,
946        "after": after_cursor,
947    });
948    (query, vars)
949}
950
951fn connection_has_next_page(page_info: Option<&serde_json::Value>) -> bool {
952    page_info
953        .and_then(|v| v.get("hasNextPage"))
954        .and_then(serde_json::Value::as_bool)
955        .unwrap_or(false)
956}
957
958pub(super) fn connection_end_cursor(page_info: Option<&serde_json::Value>) -> Option<String> {
959    if !connection_has_next_page(page_info) {
960        return None;
961    }
962
963    page_info
964        .and_then(|v| v.get("endCursor"))
965        .and_then(|v| v.as_str())
966        .map(str::to_owned)
967}
968
969fn parse_graphql_review(node: &serde_json::Value) -> Option<GitHubReview> {
970    Some(GitHubReview {
971        id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
972        user: GitHubUser {
973            login: node
974                .pointer("/author/login")
975                .and_then(|v| v.as_str())?
976                .to_string(),
977        },
978        body: node.get("body").and_then(|v| v.as_str()).map(String::from),
979        state: node.get("state").and_then(|v| v.as_str())?.to_string(),
980        html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
981        submitted_at: node
982            .get("submittedAt")
983            .and_then(|v| v.as_str())
984            .unwrap_or("")
985            .to_string(),
986        commit_id: node
987            .pointer("/commit/oid")
988            .and_then(|v| v.as_str())
989            .map(String::from),
990    })
991}
992
993fn parse_graphql_review_comment(node: &serde_json::Value) -> Option<GitHubReviewComment> {
994    Some(GitHubReviewComment {
995        id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
996        user: GitHubUser {
997            login: node
998                .pointer("/author/login")
999                .and_then(|v| v.as_str())?
1000                .to_string(),
1001        },
1002        body: node.get("body").and_then(|v| v.as_str())?.to_string(),
1003        path: node
1004            .get("path")
1005            .and_then(|v| v.as_str())
1006            .unwrap_or("")
1007            .to_string(),
1008        line: node
1009            .get("line")
1010            .and_then(serde_json::Value::as_u64)
1011            .and_then(|v| u32::try_from(v).ok()),
1012        original_line: node
1013            .get("originalLine")
1014            .and_then(serde_json::Value::as_u64)
1015            .and_then(|v| u32::try_from(v).ok()),
1016        commit_id: node
1017            .pointer("/commit/oid")
1018            .and_then(|v| v.as_str())
1019            .unwrap_or("")
1020            .to_string(),
1021        original_commit_id: node
1022            .pointer("/originalCommit/oid")
1023            .and_then(|v| v.as_str())
1024            .unwrap_or("")
1025            .to_string(),
1026        html_url: node
1027            .get("url")
1028            .and_then(|v| v.as_str())
1029            .unwrap_or("")
1030            .to_string(),
1031        created_at: node
1032            .get("createdAt")
1033            .and_then(|v| v.as_str())
1034            .unwrap_or("")
1035            .to_string(),
1036        updated_at: node
1037            .get("updatedAt")
1038            .and_then(|v| v.as_str())
1039            .unwrap_or("")
1040            .to_string(),
1041        in_reply_to_id: node
1042            .pointer("/replyTo/databaseId")
1043            .and_then(serde_json::Value::as_u64),
1044        diff_hunk: node
1045            .get("diffHunk")
1046            .and_then(|v| v.as_str())
1047            .map(String::from),
1048    })
1049}
1050
1051fn parse_graphql_issue_comment(node: &serde_json::Value) -> Option<GitHubComment> {
1052    Some(GitHubComment {
1053        id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
1054        body: node.get("body").and_then(|v| v.as_str())?.to_string(),
1055        user: GitHubUser {
1056            login: node
1057                .pointer("/author/login")
1058                .and_then(|v| v.as_str())?
1059                .to_string(),
1060        },
1061        created_at: node
1062            .get("createdAt")
1063            .and_then(|v| v.as_str())
1064            .unwrap_or("")
1065            .to_string(),
1066        updated_at: node
1067            .get("updatedAt")
1068            .and_then(|v| v.as_str())
1069            .map(String::from),
1070        html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
1071        issue_url: None,
1072        author_association: None,
1073    })
1074}