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