diff --git a/design/github.md b/design/github.md index c5d57b93ee1..d46ccf6cc08 100644 --- a/design/github.md +++ b/design/github.md @@ -80,6 +80,9 @@ also wake a Conversation or run an Event automation. before they merge. When a review is requested and still pending, the PR asks for that review instead, even where the repo allows merging without one. + A PR whose base branch is the head of another open PR gets no merge ask + until that PR merges, because GitHub checks the merge only against the + base branch. A review ask can still come. - When GitHub fails the next-action read for a while (rate limit or outage), Junior syncs the pull request again later, after the rate limit resets. A failed webhook never leaves a stale action in place. diff --git a/packages/junior-github/src/graphql-documents.ts b/packages/junior-github/src/graphql-documents.ts index 7069b6a43de..480ce237ec0 100644 --- a/packages/junior-github/src/graphql-documents.ts +++ b/packages/junior-github/src/graphql-documents.ts @@ -253,15 +253,20 @@ export const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(` * Read what decides the requester's next action on one pull request: its * state, merge state, review requests, latest reviews, and latest comments * and review requests. A review comment reply is a review, so `reviews` - * holds it too. + * holds it too. The open pull requests whose head is the base branch show + * that the base has not merged yet. */ export const PULL_REQUEST_NEXT_ACTION = githubGraphql(` query PullRequestNextAction($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { + defaultBranchRef { name } pullRequest(number: $number) { autoMergeRequest { enabledAt } + baseRefName + baseRef { associatedPullRequests(states: [OPEN]) { totalCount } } commits(last: 1) { nodes { commit { committedDate } } } isDraft + isInMergeQueue mergeStateStatus state title diff --git a/packages/junior-github/src/webhooks/installation-requests.ts b/packages/junior-github/src/webhooks/installation-requests.ts index 6373fc56a55..44659867525 100644 --- a/packages/junior-github/src/webhooks/installation-requests.ts +++ b/packages/junior-github/src/webhooks/installation-requests.ts @@ -534,14 +534,23 @@ const userLoginSchema = z const nextActionSchema = z.object({ data: z.object({ repository: z.object({ + defaultBranchRef: z.object({ name: z.string() }).nullable(), pullRequest: z.object({ autoMergeRequest: z.object({}).nullable(), + // A deleted base branch has no ref. + baseRef: z + .object({ + associatedPullRequests: z.object({ totalCount: z.number() }), + }) + .nullable(), + baseRefName: z.string(), commits: z.object({ nodes: nodesSchema( z.object({ commit: z.object({ committedDate: timestampSchema }) }), ), }), isDraft: z.boolean(), + isInMergeQueue: z.boolean(), mergeStateStatus: z.string(), reviewRequests: z.object({ nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })), @@ -612,9 +621,18 @@ export interface GitHubPullRequestMergeState { activity: GitHubPullRequestActivity[]; /** A person turned on auto-merge, so GitHub merges it without them. */ autoMerge: boolean; + /** + * The base branch is the head branch of another open pull request, so + * this one can merge only after that one. GitHub's merge state checks it + * only against the base branch. A pull request from the default branch, + * such as a sync into a long-lived branch, does not count. + */ + baseOpen: boolean; draft: boolean; /** When the head commit was made, as the time of the last push. */ headCommittedAt?: Date; + /** A person added it to the merge queue, so GitHub merges it. */ + inMergeQueue: boolean; /** * The requester's latest review that approves or requests changes * approves it. Read for drafts too, from the last 100 reviews, because the @@ -691,14 +709,15 @@ export async function loadPullRequestMergeState( body: { ...document, variables: { ...variables, ...extra } }, token: token.token, }); - const readPull = async () => + const readRepository = async () => nextActionSchema.parse(await query(PULL_REQUEST_NEXT_ACTION)).data - .repository.pullRequest; - let pull = await readPull(); + .repository; + const repository = await readRepository(); + let pull = repository.pullRequest; const open = pull.state === "OPEN" && !pull.isDraft; const unknown = (status: string) => status === "UNKNOWN"; if (open && !pull.autoMergeRequest && unknown(pull.mergeStateStatus)) { - pull = await readPull(); + pull = (await readRepository()).pullRequest; } const reviews: Review[] = [...pull.reviews.nodes]; let page = pull.reviews.pageInfo; @@ -761,10 +780,14 @@ export async function loadPullRequestMergeState( const state: GitHubPullRequestMergeState = { activity, autoMerge: Boolean(pull.autoMergeRequest), + baseOpen: + pull.baseRefName !== repository.defaultBranchRef?.name && + (pull.baseRef?.associatedPullRequests.totalCount ?? 0) > 0, draft: pull.isDraft, ...(headCommittedAt ? { headCommittedAt: new Date(headCommittedAt) } : undefined), + inMergeQueue: pull.isInMergeQueue, ...(mergeableState ? { mergeableState } : undefined), requesterApproved: false, requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => diff --git a/packages/junior-github/src/webhooks/pull-request-action.ts b/packages/junior-github/src/webhooks/pull-request-action.ts index a9eb049679e..93611d8e31d 100644 --- a/packages/junior-github/src/webhooks/pull-request-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-action.ts @@ -96,6 +96,10 @@ const ACTION_EVENTS: Record> = { "auto_merge_enabled", "closed", "converted_to_draft", + "dequeued", + // Only a base change, such as GitHub's retarget after the base merged. + "edited", + "enqueued", "ready_for_review", "reopened", "review_request_removed", @@ -121,6 +125,7 @@ const repositorySchema = z.object({ full_name: z.string().min(1) }); const pullRequestWebhookSchema = z.object({ action: z.string(), + changes: z.object({ base: z.unknown().optional() }).optional(), pull_request: z.object({ number: z.number().int().positive() }), repository: repositorySchema, // A team review request has no reviewer person. @@ -168,7 +173,12 @@ export function pullRequestActionTargets( } const actions = ACTION_EVENTS[eventName]; const parsed = pullRequestWebhookSchema.safeParse(body); - if (!actions || !parsed.success || !actions.has(parsed.data.action)) { + if ( + !actions || + !parsed.success || + !actions.has(parsed.data.action) || + (parsed.data.action === "edited" && !parsed.data.changes?.base) + ) { return []; } const reviewer = diff --git a/packages/junior-github/src/webhooks/pull-request-item.ts b/packages/junior-github/src/webhooks/pull-request-item.ts index d8e17f5e32e..65423c8e210 100644 --- a/packages/junior-github/src/webhooks/pull-request-item.ts +++ b/packages/junior-github/src/webhooks/pull-request-item.ts @@ -46,12 +46,21 @@ function closeReason( if (state.autoMerge) { return { reason: "Auto-merge is on.", status: "dismissed" }; } + if (state.inMergeQueue) { + return { reason: "It is in the merge queue.", status: "done" }; + } if (mergeAccess === false) { return { reason: "Only a person with write access can merge it.", status: "dismissed", }; } + if (state.baseOpen) { + return { + reason: "It merges after the pull request below it.", + status: "dismissed", + }; + } return { reason: "The pull request is no longer ready to merge.", status: "dismissed", diff --git a/packages/junior-github/src/webhooks/pull-request-next-action.ts b/packages/junior-github/src/webhooks/pull-request-next-action.ts index 6a7ea94e4e0..d42612202e9 100644 --- a/packages/junior-github/src/webhooks/pull-request-next-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-next-action.ts @@ -117,13 +117,16 @@ export function nextAction( saved: GitHubPullRequestAction | undefined, ): { action?: GitHubPullRequestAction } | undefined { if (state.state !== "open") return {}; - // With auto-merge on, GitHub merges it, so no person needs to. A pending + // With auto-merge on or in the merge queue, GitHub merges it. A pending // review request comes first, even where GitHub requires no review. So - // does the requester's feedback, because Junior acts next. + // does the requester's feedback, because Junior acts next. A pull request + // above an open base merges after that base. const canMerge = requester.mergeAccess && !state.draft && !state.autoMerge && + !state.inMergeQueue && + !state.baseOpen && !state.reviewPending && !requester.feedback; if ( @@ -165,13 +168,13 @@ function isRequested( /** * Whether a pull request whose action is none is in limbo: it waits on * nobody, so Junior asks for the requester's review on GitHub. It is open, - * not a draft, and auto-merge is off. GitHub does not ask the requester - * for a review, and the requester's feedback does not wait for Junior. The - * requester has not reviewed since the last push, other than a comment-only - * review. No reviewer approved it, so it does not wait only on others, and - * no reviewer requests changes, so Junior does not act next. Junior does - * not ask when the requester removed their own review request and no one - * asked them since. + * not a draft, not in the merge queue, and auto-merge is off. GitHub does + * not ask the requester for a review, and the requester's feedback does + * not wait for Junior. The requester has not reviewed since the last push, + * other than a comment-only review. No reviewer approved it, so it does not + * wait only on others, and no reviewer requests changes, so Junior does not + * act next. Junior does not ask when the requester removed their own review + * request and no one asked them since. */ export function inLimbo( state: GitHubPullRequestMergeState, @@ -182,6 +185,7 @@ export function inLimbo( state.state === "open" && !state.draft && !state.autoMerge && + !state.inMergeQueue && !isRequested(state, login) && !requesterFeedback(state, activity) && timeOf(activity.removedAt) <= timeOf(activity.askedAt) && diff --git a/packages/junior-github/tests/pull-request-action-harness.ts b/packages/junior-github/tests/pull-request-action-harness.ts index 34a960fd1f8..7aa52cfcfe4 100644 --- a/packages/junior-github/tests/pull-request-action-harness.ts +++ b/packages/junior-github/tests/pull-request-action-harness.ts @@ -161,10 +161,13 @@ export function pullRequestAction( merged = false, /** The reviewer of a `review_requested` event. */ requestedReviewer?: string, + /** The `changes` of an `edited` event. */ + changes?: Record, ) { return signedRequest( { action, + ...(changes ? { changes } : undefined), ...(requestedReviewer ? { requested_reviewer: { login: requestedReviewer } } : undefined), @@ -189,6 +192,10 @@ export function pullRequestAction( /** GitHub state that the mocked REST and GraphQL APIs return. */ export interface GitHubState { autoMerge?: boolean | undefined; + /** The base branch of the pull request. Defaults to `main`. */ + baseRefName?: string; + /** The head branches of the other open pull requests in the repo. */ + openPullRequestHeads?: string[]; /** Conversation comments on the pull request, oldest first. */ comments?: Array<{ at: string; login: string }>; draft: boolean; @@ -196,6 +203,8 @@ export interface GitHubState { headSha?: string; /** When the head commit was made, as the time of the last push. */ headCommittedAt?: string; + /** A person added the pull request to the merge queue. */ + inMergeQueue?: boolean; /** Each pull request read takes the next value. The last one repeats. */ mergeableStates: Array; /** When set, the next pull request read waits for it. */ @@ -539,13 +548,23 @@ export function mockGitHub(github: GitHubState, requests: string[]) { if (operationName === "PullRequestNextAction") { requests.push("pull"); const mergeableState = await readPull(github); + const baseRefName = github.baseRefName ?? "main"; return HttpResponse.json({ data: { repository: { + defaultBranchRef: { name: "main" }, pullRequest: { autoMergeRequest: github.autoMerge ? { enabledAt: "2026-07-02T00:00:00Z" } : null, + baseRef: { + associatedPullRequests: { + totalCount: (github.openPullRequestHeads ?? []).filter( + (head) => head === baseRefName, + ).length, + }, + }, + baseRefName, commits: { nodes: github.headCommittedAt ? [{ commit: { committedDate: github.headCommittedAt } }] @@ -553,6 +572,7 @@ export function mockGitHub(github: GitHubState, requests: string[]) { }, headRefOid: github.headSha ?? "head-1", isDraft: github.draft, + isInMergeQueue: github.inMergeQueue ?? false, mergeStateStatus: (mergeableState ?? "unknown").toUpperCase(), reviewRequests: { nodes: [ diff --git a/packages/junior-github/tests/pull-request-merge-access.test.ts b/packages/junior-github/tests/pull-request-merge-access.test.ts index 9a439bbae0f..3622d448da8 100644 --- a/packages/junior-github/tests/pull-request-merge-access.test.ts +++ b/packages/junior-github/tests/pull-request-merge-access.test.ts @@ -4,6 +4,7 @@ import { SUBJECT, checkSuiteCompleted, mockGitHub, + pullRequestAction, reviewSubmitted, route, seedJuniorPullRequest, @@ -128,3 +129,230 @@ describe("merge ask access", () => { } }); }); + +// A pull request above another open pull request merges after it, though +// GitHub's merge state checks it only against its base branch. +describe("merge ask above an open base", () => { + beforeEach(() => { + stubGitHubAppEnv(); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("closes a merge ask once the pull request below it opens", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const github: GitHubState = { + baseRefName: "feat/base", + draft: false, + mergeableStates: ["clean"], + merged: false, + reviews: [ + { + state: "APPROVED", + submitted_at: "2026-07-02T12:00:00.000Z", + user: { login: "Requester" }, + }, + ], + state: "open", + }; + mockGitHub(github, []); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + const webhook = route(fixture, calls); + await webhook.handler(checkSuiteCompleted()); + expect(calls).toMatchObject([ + { kind: "upsert", notice: { title: "Ready to merge · #946" } }, + ]); + + github.openPullRequestHeads = ["feat/base"]; + await webhook.handler(checkSuiteCompleted()); + expect(calls.slice(1)).toEqual([ + { + conversationId: "slack:C123:1712345.0001", + input: { + subject: SUBJECT, + reason: "It merges after the pull request below it.", + status: "dismissed", + }, + kind: "close", + }, + ]); + } finally { + await fixture.close(); + } + }); + + it("asks to merge only once the base merges and GitHub retargets the pull request", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + const github: GitHubState = { + baseRefName: "feat/base", + draft: false, + mergeableStates: ["clean"], + merged: false, + openPullRequestHeads: ["feat/base"], + reviews: [ + { + state: "APPROVED", + submitted_at: "2026-07-02T12:00:00.000Z", + user: { login: "Requester" }, + }, + ], + state: "open", + }; + mockGitHub(github, requests); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + const webhook = route(fixture, calls); + await webhook.handler(checkSuiteCompleted()); + expect(calls).toEqual([]); + + // An edit that keeps the base reads nothing. + requests.length = 0; + await webhook.handler( + pullRequestAction("edited", false, undefined, { + title: { from: "Old title" }, + }), + ); + expect(requests).not.toContain("pull"); + + // The base merged, and GitHub moved the pull request onto main. + github.baseRefName = "main"; + github.openPullRequestHeads = []; + await webhook.handler( + pullRequestAction("edited", false, undefined, { + base: { ref: { from: "feat/base" }, sha: { from: "base-1" } }, + }), + ); + expect(calls).toMatchObject([ + { kind: "upsert", notice: { title: "Ready to merge · #946" } }, + ]); + } finally { + await fixture.close(); + } + }); + + it("asks to merge into the default branch when an open pull request syncs it elsewhere", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + mockGitHub( + { + draft: false, + mergeableStates: ["clean"], + merged: false, + // A pull request from main into a long-lived branch. + openPullRequestHeads: ["main"], + reviews: [ + { + state: "APPROVED", + submitted_at: "2026-07-02T12:00:00.000Z", + user: { login: "Requester" }, + }, + ], + state: "open", + }, + [], + ); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + await route(fixture, calls).handler(checkSuiteCompleted()); + expect(calls).toMatchObject([ + { kind: "upsert", notice: { title: "Ready to merge · #946" } }, + ]); + } finally { + await fixture.close(); + } + }); +}); + +// GitHub merges a pull request in the merge queue, so no person needs to. +describe("merge ask in the merge queue", () => { + beforeEach(() => { + stubGitHubAppEnv(); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("closes the merge ask while the pull request is queued, and asks again when it leaves the queue", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + const github: GitHubState = { + draft: false, + mergeableStates: ["clean"], + merged: false, + reviews: [ + { + state: "APPROVED", + submitted_at: "2026-07-02T12:00:00.000Z", + user: { login: "Requester" }, + }, + ], + state: "open", + }; + mockGitHub(github, requests); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + const webhook = route(fixture, calls); + await webhook.handler(checkSuiteCompleted()); + expect(calls).toMatchObject([ + { kind: "upsert", notice: { title: "Ready to merge · #946" } }, + ]); + + github.inMergeQueue = true; + await webhook.handler(pullRequestAction("enqueued")); + expect(calls.slice(1)).toEqual([ + { + conversationId: "slack:C123:1712345.0001", + input: { + subject: SUBJECT, + reason: "It is in the merge queue.", + status: "done", + }, + kind: "close", + }, + ]); + + // A failed merge group takes it out of the queue. + github.inMergeQueue = false; + await webhook.handler(pullRequestAction("dequeued")); + expect(calls.slice(2)).toMatchObject([ + { kind: "upsert", notice: { title: "Ready to merge · #946" } }, + ]); + } finally { + await fixture.close(); + } + }); + + it("does not ask for the requester's review of a queued pull request", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + // The repo requires no review, so a person queued it unreviewed. + mockGitHub( + { + draft: false, + inMergeQueue: true, + mergeableStates: ["clean"], + merged: false, + reviews: [], + state: "open", + }, + requests, + ); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + await route(fixture, calls).handler(checkSuiteCompleted()); + expect(requests).not.toContain("request Requester"); + expect(calls).toEqual([]); + } finally { + await fixture.close(); + } + }); +}); diff --git a/packages/junior-github/tests/pull-request-ready-reviewers.test.ts b/packages/junior-github/tests/pull-request-ready-reviewers.test.ts index 4bafec57a9c..8f7d5cd64b3 100644 --- a/packages/junior-github/tests/pull-request-ready-reviewers.test.ts +++ b/packages/junior-github/tests/pull-request-ready-reviewers.test.ts @@ -270,11 +270,15 @@ describe("review request when a draft is ready", () => { HttpResponse.json({ data: { repository: { + defaultBranchRef: { name: "main" }, pullRequest: { autoMergeRequest: null, + baseRef: null, + baseRefName: "main", commits: { nodes: [] }, headRefOid: "head-1", isDraft: false, + isInMergeQueue: false, mergeStateStatus: "BLOCKED", reviewRequests: { nodes: [] }, reviews: { @@ -295,6 +299,11 @@ describe("review request when a draft is ready", () => { }, }), ), + // The base branch requires no checks. + http.get( + "https://api.github.com/repos/getsentry/junior/rules/branches/main", + () => HttpResponse.json([]), + ), http.post( "https://api.github.com/repos/getsentry/junior/pulls/946/requested_reviewers", async ({ request }) => { diff --git a/packages/junior/tests/integration/github-pull-request-ask.test.ts b/packages/junior/tests/integration/github-pull-request-ask.test.ts index 6c61e916f17..bef6a6f02f3 100644 --- a/packages/junior/tests/integration/github-pull-request-ask.test.ts +++ b/packages/junior/tests/integration/github-pull-request-ask.test.ts @@ -219,11 +219,15 @@ describe("the ask of a Junior pull request", () => { return HttpResponse.json({ data: { repository: { + defaultBranchRef: { name: "main" }, pullRequest: { autoMergeRequest: null, + baseRef: null, + baseRefName: "main", commits: { nodes: [] }, headRefOid: "head-1", isDraft: false, + isInMergeQueue: false, mergeStateStatus: "CLEAN", reviewRequests: { nodes: [] }, reviews: { @@ -364,11 +368,15 @@ describe("the ask of a Junior pull request", () => { return HttpResponse.json({ data: { repository: { + defaultBranchRef: { name: "main" }, pullRequest: { autoMergeRequest: null, + baseRef: null, + baseRefName: "main", commits: { nodes: [] }, headRefOid: "head-1", isDraft: false, + isInMergeQueue: false, mergeStateStatus: "CLEAN", reviewRequests: { nodes: github.approved