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