diff --git a/design/github.md b/design/github.md index d17f31d2905..9739101e1dc 100644 --- a/design/github.md +++ b/design/github.md @@ -83,6 +83,9 @@ also wake a Conversation or run an Event automation. 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. + A PR in the merge queue gets no merge ask, because GitHub merges it. When + the queue removes it because its checks failed, it gets no merge ask until + a push. - An issue that Junior opened is an Inbox item for its GitHub assignees who have a linked account. Assigning a person on GitHub adds them, and unassigning removes them. The item closes when the issue closes or nobody diff --git a/packages/junior-github/src/graphql-documents.ts b/packages/junior-github/src/graphql-documents.ts index 3c46f75ace0..1509f1a6259 100644 --- a/packages/junior-github/src/graphql-documents.ts +++ b/packages/junior-github/src/graphql-documents.ts @@ -275,6 +275,12 @@ export const PULL_REQUEST_NEXT_ACTION = githubGraphql(` headRefOid isDraft isInMergeQueue + queueRemovalOrForcePush: timelineItems(last: 1, itemTypes: [REMOVED_FROM_MERGE_QUEUE_EVENT, HEAD_REF_FORCE_PUSHED_EVENT]) { + nodes { + __typename + ... on RemovedFromMergeQueueEvent { createdAt reason } + } + } mergeStateStatus reviewDecision state diff --git a/packages/junior-github/src/webhooks/installation-requests.ts b/packages/junior-github/src/webhooks/installation-requests.ts index e2a94ca9d63..450effe9dbc 100644 --- a/packages/junior-github/src/webhooks/installation-requests.ts +++ b/packages/junior-github/src/webhooks/installation-requests.ts @@ -27,8 +27,6 @@ import { ADD_REVIEW_REACTION, OPEN_PULL_REQUEST_MERGEABILITY, PULL_REQUEST_CONFLICT_HISTORY, - PULL_REQUEST_NEXT_ACTION, - PULL_REQUEST_REVIEWS_BEFORE, pullRequestCards, pullRequestHeadFacts, pullRequestLifecycles, @@ -629,366 +627,3 @@ export async function loadRepositoryMergeAccess( const { permission } = await loadRepositoryPermission(env, cache, target); return permission === "admin" || permission === "write"; } - -const timestampSchema = z.iso.datetime({ offset: true }); - -// GitHub can return a null node for a deleted or hidden item, so the -// connection lists drop them. -function nodesSchema(node: T) { - return z - .array(node.nullable()) - .transform((items) => - items.filter((item): item is NonNullable => item !== null), - ); -} - -const actorSchema = z - .object({ __typename: z.string(), login: z.string().min(1) }) - .nullable(); -const reviewsSchema = z.object({ - pageInfo: z.object({ - hasPreviousPage: z.boolean(), - startCursor: z.string().nullable(), - }), - nodes: nodesSchema( - z.object({ - author: actorSchema, - state: z.string(), - submittedAt: timestampSchema.nullable(), - }), - ), -}); -const userLoginSchema = z - .object({ __typename: z.string(), login: z.string().min(1).optional() }) - .nullable(); - -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 }) }), - ), - }), - headRefOid: z.string(), - isDraft: z.boolean(), - isInMergeQueue: z.boolean(), - mergeStateStatus: z.string(), - reviewDecision: z - .enum(["APPROVED", "CHANGES_REQUESTED", "REVIEW_REQUIRED"]) - .nullish(), - reviewRequests: z.object({ - nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })), - }), - reviews: reviewsSchema, - state: z.enum(["CLOSED", "MERGED", "OPEN"]), - timelineItems: z.object({ - nodes: nodesSchema( - z.discriminatedUnion("__typename", [ - z.object({ - __typename: z.literal("IssueComment"), - author: actorSchema, - createdAt: timestampSchema, - }), - z.object({ - __typename: z.literal("ReviewRequestedEvent"), - createdAt: timestampSchema, - requestedReviewer: userLoginSchema, - }), - z.object({ - __typename: z.literal("ReviewRequestRemovedEvent"), - actor: actorSchema, - createdAt: timestampSchema, - requestedReviewer: userLoginSchema, - }), - ]), - ), - }), - title: z.string(), - updatedAt: timestampSchema, - url: z.string().url(), - }), - }), - }), -}); - -const reviewsPageSchema = z.object({ - data: z.object({ - repository: z.object({ - pullRequest: z.object({ reviews: reviewsSchema }), - }), - }), -}); - -/** - * One thing that a person or an App did on a pull request: `author` wrote a - * comment or review, and `reviewRequest` asked `login` for a review. `login` - * is the REST login, so a bot ends in `[bot]`. - */ -export interface GitHubPullRequestActivity { - at: Date; - /** - * `author`: a comment or a review by `login`. `reviewRequest`: GitHub - * asked `login` for a review. `reviewRequestRemoved`: `login` removed - * their own review request. - */ - kind: "author" | "reviewRequest" | "reviewRequestRemoved"; - login: string; - /** The state of an `author` review, such as `COMMENTED`. */ - review?: string; -} - -/** The pull request facts that decide its next action. */ -export interface GitHubPullRequestMergeState { - /** - * The latest comments, reviews, and review requests, in no order. GitHub - * returns the latest 100 comments and review requests. - */ - 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; - headSha: string; - /** 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 - * requester marks an approved draft ready. - */ - requesterApproved: boolean; - /** - * GitHub's merge state, such as `clean` or `blocked`. `clean` means that - * the required reviews and every check and status passed, and there are - * no conflicts. Undefined when GitHub has not computed it yet. - */ - mergeableState?: string; - /** Logins of the people whose review GitHub still requests. */ - requestedReviewers: string[]; - /** Logins of the people and Apps whose review GitHub requests. */ - reviewRequestLogins: string[]; - /** - * GitHub still requests a review from a person or a team. A team that - * the App cannot read has no login, so `requestedReviewers` misses it. - */ - reviewPending: boolean; - /** - * Logins of the people whose latest submitted review was not dismissed, - * including a comment-only review. Read only when the pull request is open - * and not a draft. - */ - reviewedBy: string[]; - /** - * `approved` with at least one approval and no reviewer who still - * requests changes. `changesRequested` while a reviewer still requests - * changes. Undefined with neither. Read only when the pull request is - * open and not a draft. - */ - reviewOutcome?: "approved" | "changesRequested"; - /** GitHub's review decision, which a repository with no rule lacks. */ - reviewDecision?: "APPROVED" | "CHANGES_REQUESTED" | "REVIEW_REQUIRED"; - state: "closed" | "merged" | "open"; - title: string; - updatedAt: string; - url: string; -} - -// GraphQL gives a bot's login without the `[bot]` that REST and webhooks add. -function restLogin(actor: { __typename: string; login: string }): string { - return actor.__typename === "Bot" ? `${actor.login}[bot]` : actor.login; -} - -type Review = z.output["nodes"][number]; - -/** - * Read whether a pull request is ready to merge, whether the requester - * changed their review, and who acted on it last, with a read-only token - * and one GraphQL query. GitHub computes the merge state after a change, - * so an unknown state is read once more. A pull request with more than 100 - * reviews reads the older pages too. Each reviewer counts by their latest - * approval, change request, or dismissal. Comments do not change the - * result. - */ -export async function loadPullRequestMergeState( - env: GitHubInstallationEnv, - pullRequest: { number: number; repositoryFullName: string }, - requesterLogin: string | undefined, -): Promise { - const { owner, name } = splitRepository( - pullRequest.repositoryFullName, - "pull request merge state", - ); - const token = await issueInstallationToken({ - ...env, - permissions: { pull_requests: "read" }, - repositories: [name], - }); - const variables = { name, number: pullRequest.number, owner }; - const query = async ( - document: typeof PULL_REQUEST_NEXT_ACTION, - extra?: { before: string }, - ) => - await githubGraphqlRequest({ - body: { ...document, variables: { ...variables, ...extra } }, - token: token.token, - }); - const readRepository = async () => - nextActionSchema.parse(await query(PULL_REQUEST_NEXT_ACTION)).data - .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 readRepository()).pullRequest; - } - const reviews: Review[] = [...pull.reviews.nodes]; - let page = pull.reviews.pageInfo; - // Older pages can hold a reviewer's latest change request. - while (open && page.hasPreviousPage && page.startCursor) { - const older = reviewsPageSchema.parse( - // oxlint-disable-next-line no-await-in-loop -- Each page starts at the cursor of the page after it. - await query(PULL_REQUEST_REVIEWS_BEFORE, { before: page.startCursor }), - ).data.repository.pullRequest.reviews; - reviews.unshift(...older.nodes); - page = older.pageInfo; - } - - const activity: GitHubPullRequestActivity[] = []; - for (const item of pull.timelineItems.nodes) { - if (item.__typename === "IssueComment" && item.author) { - activity.push({ - at: new Date(item.createdAt), - kind: "author", - login: restLogin(item.author), - }); - } else if ( - item.__typename === "ReviewRequestedEvent" && - item.requestedReviewer?.login - ) { - activity.push({ - at: new Date(item.createdAt), - kind: "reviewRequest", - login: item.requestedReviewer.login, - }); - } else if ( - item.__typename === "ReviewRequestRemovedEvent" && - item.requestedReviewer?.login && - item.actor && - restLogin(item.actor).toLowerCase() === - item.requestedReviewer.login.toLowerCase() - ) { - activity.push({ - at: new Date(item.createdAt), - kind: "reviewRequestRemoved", - login: item.requestedReviewer.login, - }); - } - } - for (const review of reviews) { - if (review.author && review.submittedAt) { - activity.push({ - at: new Date(review.submittedAt), - kind: "author", - login: restLogin(review.author), - review: review.state, - }); - } - } - - const mergeableState = unknown(pull.mergeStateStatus) - ? undefined - : pull.mergeStateStatus.toLowerCase(); - const headCommittedAt = pull.commits.nodes[0]?.commit.committedDate; - 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), - headSha: pull.headRefOid, - inMergeQueue: pull.isInMergeQueue, - ...(mergeableState ? { mergeableState } : undefined), - requesterApproved: false, - requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => - request.requestedReviewer?.__typename === "User" && - request.requestedReviewer.login - ? [request.requestedReviewer.login] - : [], - ), - ...(pull.reviewDecision - ? { reviewDecision: pull.reviewDecision } - : undefined), - reviewPending: pull.reviewRequests.nodes.length > 0, - reviewRequestLogins: pull.reviewRequests.nodes.flatMap((request) => - request.requestedReviewer?.login ? [request.requestedReviewer.login] : [], - ), - reviewedBy: [], - state: - pull.state === "MERGED" - ? "merged" - : pull.state === "OPEN" - ? "open" - : "closed", - title: pull.title, - updatedAt: pull.updatedAt, - url: pull.url, - }; - // GitHub lists reviews oldest first, so a later one replaces an earlier. - const latest = new Map(); - for (const review of reviews) { - if ( - review.author && - review.state !== "COMMENTED" && - review.state !== "PENDING" - ) { - latest.set(review.author.login.toLowerCase(), review); - } - } - const login = requesterLogin?.toLowerCase(); - const requesterReview = login ? latest.get(login) : undefined; - state.requesterApproved = requesterReview?.state === "APPROVED"; - if (!open) return state; - - // A dismissed review counts only when it is the person's latest review. - // GitHub keeps their earlier reviews, such as a comment before it. - const latestSubmitted = new Map(); - for (const review of reviews) { - if (review.author && review.submittedAt && review.state !== "PENDING") { - latestSubmitted.set(review.author.login.toLowerCase(), review.state); - } - } - state.reviewedBy = [...latestSubmitted].flatMap(([login, reviewState]) => - reviewState === "DISMISSED" ? [] : [login], - ); - const reviewStates = [...latest.values()].map((review) => review.state); - if (reviewStates.includes("CHANGES_REQUESTED")) { - state.reviewOutcome = "changesRequested"; - } else if (reviewStates.includes("APPROVED")) { - state.reviewOutcome = "approved"; - } - return state; -} diff --git a/packages/junior-github/src/webhooks/pull-request-action.ts b/packages/junior-github/src/webhooks/pull-request-action.ts index 74ebe720e94..16cb11827cf 100644 --- a/packages/junior-github/src/webhooks/pull-request-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-action.ts @@ -77,13 +77,15 @@ import { logFailOpenFailure } from "./fail-open-log.js"; import { GitHubGraphqlError } from "./graphql-request.js"; import { loadGraphqlRateLimitReset, - loadPullRequestMergeState, loadRepositoryMergeAccess, loadReviewAgainReader, requestPullRequestReviewers, type GitHubInstallationEnv, - type GitHubPullRequestMergeState, } from "./installation-requests.js"; +import { + loadPullRequestMergeState, + type GitHubPullRequestMergeState, +} from "./pull-request-merge-state.js"; import { botUserIdFromEmail } from "./ownership.js"; import type { GitHubPullRequestTarget } from "./pull-request-people.js"; diff --git a/packages/junior-github/src/webhooks/pull-request-item.ts b/packages/junior-github/src/webhooks/pull-request-item.ts index 65423c8e210..5587eecd6e7 100644 --- a/packages/junior-github/src/webhooks/pull-request-item.ts +++ b/packages/junior-github/src/webhooks/pull-request-item.ts @@ -20,7 +20,7 @@ import { pullRequestSubject, } from "../inbox-subjects.js"; import type { GitHubReviewAskReason } from "../pull-request-review-again.js"; -import type { GitHubPullRequestMergeState } from "./installation-requests.js"; +import type { GitHubPullRequestMergeState } from "./pull-request-merge-state.js"; type CloseReason = { reason: string; status: "done" | "dismissed" }; diff --git a/packages/junior-github/src/webhooks/pull-request-merge-state.ts b/packages/junior-github/src/webhooks/pull-request-merge-state.ts new file mode 100644 index 00000000000..be2df65aa5e --- /dev/null +++ b/packages/junior-github/src/webhooks/pull-request-merge-state.ts @@ -0,0 +1,403 @@ +/** + * The next-action read of one pull request: what decides the requester's + * next action, read with a webhook installation token. + */ +import * as z from "zod"; +import { issueInstallationToken } from "../credential-support.js"; +import { + PULL_REQUEST_NEXT_ACTION, + PULL_REQUEST_REVIEWS_BEFORE, +} from "../graphql-documents.js"; +import { githubGraphqlRequest } from "./graphql-request.js"; +import { + type GitHubInstallationEnv, + splitRepository, +} from "./installation-requests.js"; + +const timestampSchema = z.iso.datetime({ offset: true }); + +// GitHub can return a null node for a deleted or hidden item, so the +// connection lists drop them. +function nodesSchema(node: T) { + return z + .array(node.nullable()) + .transform((items) => + items.filter((item): item is NonNullable => item !== null), + ); +} + +const actorSchema = z + .object({ __typename: z.string(), login: z.string().min(1) }) + .nullable(); +const reviewsSchema = z.object({ + pageInfo: z.object({ + hasPreviousPage: z.boolean(), + startCursor: z.string().nullable(), + }), + nodes: nodesSchema( + z.object({ + author: actorSchema, + state: z.string(), + submittedAt: timestampSchema.nullable(), + }), + ), +}); +const userLoginSchema = z + .object({ __typename: z.string(), login: z.string().min(1).optional() }) + .nullable(); + +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 }) }), + ), + }), + headRefOid: z.string(), + isDraft: z.boolean(), + isInMergeQueue: z.boolean(), + // A force push can move the head to a commit older than the removal. + queueRemovalOrForcePush: z.object({ + nodes: nodesSchema( + z.discriminatedUnion("__typename", [ + z.object({ + __typename: z.literal("RemovedFromMergeQueueEvent"), + createdAt: timestampSchema, + reason: z.string(), + }), + z.object({ __typename: z.literal("HeadRefForcePushedEvent") }), + ]), + ), + }), + mergeStateStatus: z.string(), + reviewDecision: z + .enum(["APPROVED", "CHANGES_REQUESTED", "REVIEW_REQUIRED"]) + .nullish(), + reviewRequests: z.object({ + nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })), + }), + reviews: reviewsSchema, + state: z.enum(["CLOSED", "MERGED", "OPEN"]), + timelineItems: z.object({ + nodes: nodesSchema( + z.discriminatedUnion("__typename", [ + z.object({ + __typename: z.literal("IssueComment"), + author: actorSchema, + createdAt: timestampSchema, + }), + z.object({ + __typename: z.literal("ReviewRequestedEvent"), + createdAt: timestampSchema, + requestedReviewer: userLoginSchema, + }), + z.object({ + __typename: z.literal("ReviewRequestRemovedEvent"), + actor: actorSchema, + createdAt: timestampSchema, + requestedReviewer: userLoginSchema, + }), + ]), + ), + }), + title: z.string(), + updatedAt: timestampSchema, + url: z.string().url(), + }), + }), + }), +}); + +const reviewsPageSchema = z.object({ + data: z.object({ + repository: z.object({ + pullRequest: z.object({ reviews: reviewsSchema }), + }), + }), +}); + +/** + * One thing that a person or an App did on a pull request: `author` wrote a + * comment or review, and `reviewRequest` asked `login` for a review. `login` + * is the REST login, so a bot ends in `[bot]`. + */ +export interface GitHubPullRequestActivity { + at: Date; + /** + * `author`: a comment or a review by `login`. `reviewRequest`: GitHub + * asked `login` for a review. `reviewRequestRemoved`: `login` removed + * their own review request. + */ + kind: "author" | "reviewRequest" | "reviewRequestRemoved"; + login: string; + /** The state of an `author` review, such as `COMMENTED`. */ + review?: string; +} + +/** The pull request facts that decide its next action. */ +export interface GitHubPullRequestMergeState { + /** + * The latest comments, reviews, and review requests, in no order. GitHub + * returns the latest 100 comments and review requests. + */ + 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; + headSha: string; + /** A person added it to the merge queue, so GitHub merges it. */ + inMergeQueue: boolean; + /** + * The merge queue last removed it because the merge group's checks + * failed, and nothing was pushed since. GitHub's merge state checks only + * the head commit, so it can still say `clean`. + */ + mergeQueueFailed: boolean; + /** + * The requester's latest review that approves or requests changes + * approves it. Read for drafts too, from the last 100 reviews, because the + * requester marks an approved draft ready. + */ + requesterApproved: boolean; + /** + * GitHub's merge state, such as `clean` or `blocked`. `clean` means that + * the required reviews and every check and status passed, and there are + * no conflicts. Undefined when GitHub has not computed it yet. + */ + mergeableState?: string; + /** Logins of the people whose review GitHub still requests. */ + requestedReviewers: string[]; + /** Logins of the people and Apps whose review GitHub requests. */ + reviewRequestLogins: string[]; + /** + * GitHub still requests a review from a person or a team. A team that + * the App cannot read has no login, so `requestedReviewers` misses it. + */ + reviewPending: boolean; + /** + * Logins of the people whose latest submitted review was not dismissed, + * including a comment-only review. Read only when the pull request is open + * and not a draft. + */ + reviewedBy: string[]; + /** + * `approved` with at least one approval and no reviewer who still + * requests changes. `changesRequested` while a reviewer still requests + * changes. Undefined with neither. Read only when the pull request is + * open and not a draft. + */ + reviewOutcome?: "approved" | "changesRequested"; + /** GitHub's review decision, which a repository with no rule lacks. */ + reviewDecision?: "APPROVED" | "CHANGES_REQUESTED" | "REVIEW_REQUIRED"; + state: "closed" | "merged" | "open"; + title: string; + updatedAt: string; + url: string; +} + +// GraphQL gives a bot's login without the `[bot]` that REST and webhooks add. +function restLogin(actor: { __typename: string; login: string }): string { + return actor.__typename === "Bot" ? `${actor.login}[bot]` : actor.login; +} + +type Review = z.output["nodes"][number]; + +/** + * Read whether a pull request is ready to merge, whether the requester + * changed their review, and who acted on it last, with a read-only token + * and one GraphQL query. GitHub computes the merge state after a change, + * so an unknown state is read once more. A pull request with more than 100 + * reviews reads the older pages too. Each reviewer counts by their latest + * approval, change request, or dismissal. Comments do not change the + * result. + */ +export async function loadPullRequestMergeState( + env: GitHubInstallationEnv, + pullRequest: { number: number; repositoryFullName: string }, + requesterLogin: string | undefined, +): Promise { + const { owner, name } = splitRepository( + pullRequest.repositoryFullName, + "pull request merge state", + ); + const token = await issueInstallationToken({ + ...env, + permissions: { pull_requests: "read" }, + repositories: [name], + }); + const variables = { name, number: pullRequest.number, owner }; + const query = async ( + document: typeof PULL_REQUEST_NEXT_ACTION, + extra?: { before: string }, + ) => + await githubGraphqlRequest({ + body: { ...document, variables: { ...variables, ...extra } }, + token: token.token, + }); + const readRepository = async () => + nextActionSchema.parse(await query(PULL_REQUEST_NEXT_ACTION)).data + .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 readRepository()).pullRequest; + } + const reviews: Review[] = [...pull.reviews.nodes]; + let page = pull.reviews.pageInfo; + // Older pages can hold a reviewer's latest change request. + while (open && page.hasPreviousPage && page.startCursor) { + const older = reviewsPageSchema.parse( + // oxlint-disable-next-line no-await-in-loop -- Each page starts at the cursor of the page after it. + await query(PULL_REQUEST_REVIEWS_BEFORE, { before: page.startCursor }), + ).data.repository.pullRequest.reviews; + reviews.unshift(...older.nodes); + page = older.pageInfo; + } + + const activity: GitHubPullRequestActivity[] = []; + for (const item of pull.timelineItems.nodes) { + if (item.__typename === "IssueComment" && item.author) { + activity.push({ + at: new Date(item.createdAt), + kind: "author", + login: restLogin(item.author), + }); + } else if ( + item.__typename === "ReviewRequestedEvent" && + item.requestedReviewer?.login + ) { + activity.push({ + at: new Date(item.createdAt), + kind: "reviewRequest", + login: item.requestedReviewer.login, + }); + } else if ( + item.__typename === "ReviewRequestRemovedEvent" && + item.requestedReviewer?.login && + item.actor && + restLogin(item.actor).toLowerCase() === + item.requestedReviewer.login.toLowerCase() + ) { + activity.push({ + at: new Date(item.createdAt), + kind: "reviewRequestRemoved", + login: item.requestedReviewer.login, + }); + } + } + for (const review of reviews) { + if (review.author && review.submittedAt) { + activity.push({ + at: new Date(review.submittedAt), + kind: "author", + login: restLogin(review.author), + review: review.state, + }); + } + } + + const mergeableState = unknown(pull.mergeStateStatus) + ? undefined + : pull.mergeStateStatus.toLowerCase(); + const headCommittedAt = pull.commits.nodes[0]?.commit.committedDate; + const queueRemoval = pull.queueRemovalOrForcePush.nodes[0]; + 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), + headSha: pull.headRefOid, + inMergeQueue: pull.isInMergeQueue, + mergeQueueFailed: + queueRemoval?.__typename === "RemovedFromMergeQueueEvent" && + queueRemoval.reason === "failed_checks" && + Date.parse(queueRemoval.createdAt) >= + (headCommittedAt ? Date.parse(headCommittedAt) : 0), + ...(mergeableState ? { mergeableState } : undefined), + requesterApproved: false, + requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => + request.requestedReviewer?.__typename === "User" && + request.requestedReviewer.login + ? [request.requestedReviewer.login] + : [], + ), + ...(pull.reviewDecision + ? { reviewDecision: pull.reviewDecision } + : undefined), + reviewPending: pull.reviewRequests.nodes.length > 0, + reviewRequestLogins: pull.reviewRequests.nodes.flatMap((request) => + request.requestedReviewer?.login ? [request.requestedReviewer.login] : [], + ), + reviewedBy: [], + state: + pull.state === "MERGED" + ? "merged" + : pull.state === "OPEN" + ? "open" + : "closed", + title: pull.title, + updatedAt: pull.updatedAt, + url: pull.url, + }; + // GitHub lists reviews oldest first, so a later one replaces an earlier. + const latest = new Map(); + for (const review of reviews) { + if ( + review.author && + review.state !== "COMMENTED" && + review.state !== "PENDING" + ) { + latest.set(review.author.login.toLowerCase(), review); + } + } + const login = requesterLogin?.toLowerCase(); + const requesterReview = login ? latest.get(login) : undefined; + state.requesterApproved = requesterReview?.state === "APPROVED"; + if (!open) return state; + + // A dismissed review counts only when it is the person's latest review. + // GitHub keeps their earlier reviews, such as a comment before it. + const latestSubmitted = new Map(); + for (const review of reviews) { + if (review.author && review.submittedAt && review.state !== "PENDING") { + latestSubmitted.set(review.author.login.toLowerCase(), review.state); + } + } + state.reviewedBy = [...latestSubmitted].flatMap(([login, reviewState]) => + reviewState === "DISMISSED" ? [] : [login], + ); + const reviewStates = [...latest.values()].map((review) => review.state); + if (reviewStates.includes("CHANGES_REQUESTED")) { + state.reviewOutcome = "changesRequested"; + } else if (reviewStates.includes("APPROVED")) { + state.reviewOutcome = "approved"; + } + return state; +} 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 d42612202e9..293c107d6d2 100644 --- a/packages/junior-github/src/webhooks/pull-request-next-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-next-action.ts @@ -7,7 +7,7 @@ import type { GitHubPullRequestAction } from "../db/schema.js"; import type { GitHubPullRequestActivity, GitHubPullRequestMergeState, -} from "./installation-requests.js"; +} from "./pull-request-merge-state.js"; /** Whether two GitHub logins name the same account. */ export function sameLogin(a: string, b: string | undefined): boolean { @@ -120,12 +120,14 @@ export function nextAction( // 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. A pull request - // above an open base merges after that base. + // above an open base merges after that base. One that failed the merge + // queue's checks needs a push before it can merge. const canMerge = requester.mergeAccess && !state.draft && !state.autoMerge && !state.inMergeQueue && + !state.mergeQueueFailed && !state.baseOpen && !state.reviewPending && !requester.feedback; diff --git a/packages/junior-github/src/webhooks/pull-request-ready-reviewers.ts b/packages/junior-github/src/webhooks/pull-request-ready-reviewers.ts index c7bb11e46e2..c4bdb863250 100644 --- a/packages/junior-github/src/webhooks/pull-request-ready-reviewers.ts +++ b/packages/junior-github/src/webhooks/pull-request-ready-reviewers.ts @@ -12,10 +12,10 @@ import type { GitHubDb } from "../db/database.js"; import { readGitHubDraftReviewers } from "../pull-request-requesters/draft-reviewers.js"; import { listGitHubPullRequestOpeners } from "../pull-request-requesters/store.js"; import { - loadPullRequestMergeState, requestPullRequestReviewers, type GitHubInstallationEnv, } from "./installation-requests.js"; +import { loadPullRequestMergeState } from "./pull-request-merge-state.js"; const readyForReviewSchema = z.object({ action: z.literal("ready_for_review"), diff --git a/packages/junior-github/tests/pull-request-action-harness.ts b/packages/junior-github/tests/pull-request-action-harness.ts index dccd8c7e0fe..d3c2c3647ce 100644 --- a/packages/junior-github/tests/pull-request-action-harness.ts +++ b/packages/junior-github/tests/pull-request-action-harness.ts @@ -189,6 +189,24 @@ export function pullRequestAction( ); } +// GitHub returns the later of the last queue removal and force push. +function lastRemovalOrForcePush(github: GitHubState) { + const removal = github.mergeQueueRemoval; + const forcePushedAt = github.forcePushedAt; + if (forcePushedAt && (!removal || forcePushedAt > removal.at)) { + return [{ __typename: "HeadRefForcePushedEvent" }]; + } + return removal + ? [ + { + __typename: "RemovedFromMergeQueueEvent", + createdAt: removal.at, + reason: removal.reason, + }, + ] + : []; +} + /** GitHub state that the mocked REST and GraphQL APIs return. */ export interface GitHubState { autoMerge?: boolean | undefined; @@ -205,6 +223,10 @@ export interface GitHubState { headCommittedAt?: string; /** A person added the pull request to the merge queue. */ inMergeQueue?: boolean; + /** The last time the merge queue removed the pull request, and why. */ + mergeQueueRemoval?: { at: string; reason: string }; + /** When a person last force-pushed the head branch. */ + forcePushedAt?: string; /** Each pull request read takes the next value. The last one repeats. */ mergeableStates: Array; /** When set, the next pull request read waits for it. */ @@ -573,6 +595,9 @@ export function mockGitHub(github: GitHubState, requests: string[]) { headRefOid: github.headSha ?? "head-1", isDraft: github.draft, isInMergeQueue: github.inMergeQueue ?? false, + queueRemovalOrForcePush: { + nodes: lastRemovalOrForcePush(github), + }, 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 3622d448da8..41960fd13ce 100644 --- a/packages/junior-github/tests/pull-request-merge-access.test.ts +++ b/packages/junior-github/tests/pull-request-merge-access.test.ts @@ -319,8 +319,12 @@ describe("merge ask in the merge queue", () => { }, ]); - // A failed merge group takes it out of the queue. + // A person takes it out of the queue. github.inMergeQueue = false; + github.mergeQueueRemoval = { + at: "2026-07-03T12:00:00Z", + reason: "manually_removed", + }; await webhook.handler(pullRequestAction("dequeued")); expect(calls.slice(2)).toMatchObject([ { kind: "upsert", notice: { title: "Ready to merge · #946" } }, @@ -330,6 +334,57 @@ describe("merge ask in the merge queue", () => { } }); + // GitHub's merge state checks only the head commit, so it stays clean. + it.each([ + ["a push", { headCommittedAt: "2026-07-03T13:00:00Z" }], + // The head commit can be older than the removal. + ["a force push", { forcePushedAt: "2026-07-03T13:00:00Z" }], + ] as const)( + "gives no merge ask after the merge queue's checks fail, until %s", + async (_push, push) => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + const github: GitHubState = { + draft: false, + headCommittedAt: "2026-07-02T11:00:00Z", + inMergeQueue: true, + 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(pullRequestAction("enqueued")); + + github.inMergeQueue = false; + github.mergeQueueRemoval = { + at: "2026-07-03T12:00:00Z", + reason: "failed_checks", + }; + await webhook.handler(pullRequestAction("dequeued")); + expect(calls).toEqual([]); + + Object.assign(github, push); + await webhook.handler(checkSuiteCompleted()); + expect(calls).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[] = []; 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 d8ea5107902..e59326c796b 100644 --- a/packages/junior-github/tests/pull-request-ready-reviewers.test.ts +++ b/packages/junior-github/tests/pull-request-ready-reviewers.test.ts @@ -281,6 +281,7 @@ describe("review request when a draft is ready", () => { headRefOid: "head-1", isDraft: false, isInMergeQueue: false, + queueRemovalOrForcePush: { nodes: [] }, mergeStateStatus: "BLOCKED", reviewRequests: { nodes: [] }, reviews: { 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 a4f045c932d..483fb9d6fb4 100644 --- a/packages/junior/tests/integration/github-pull-request-ask.test.ts +++ b/packages/junior/tests/integration/github-pull-request-ask.test.ts @@ -249,6 +249,7 @@ describe("the ask of a Junior pull request", () => { headRefOid: "head-1", isDraft: false, isInMergeQueue: false, + queueRemovalOrForcePush: { nodes: [] }, mergeStateStatus: "CLEAN", reviewRequests: { nodes: [] }, reviews: { @@ -403,6 +404,7 @@ describe("the ask of a Junior pull request", () => { headRefOid: "head-1", isDraft: false, isInMergeQueue: false, + queueRemovalOrForcePush: { nodes: [] }, mergeStateStatus: "CLEAN", reviewRequests: { nodes: !github.requested @@ -641,6 +643,7 @@ describe("the ask of a Junior pull request", () => { headRefOid: "head-1", isDraft: false, isInMergeQueue: false, + queueRemovalOrForcePush: { nodes: [] }, mergeStateStatus: "CLEAN", reviewRequests: { nodes: github.reviewers.map((login) => ({ @@ -873,6 +876,7 @@ describe("the ask of a Junior pull request", () => { headRefOid: "head-1", isDraft: false, isInMergeQueue: false, + queueRemovalOrForcePush: { nodes: [] }, mergeStateStatus: "CLEAN", reviewRequests: { nodes: [...github.reviewers, "copilot"].map((login) => ({ diff --git a/scripts/comment-length-baseline.json b/scripts/comment-length-baseline.json index bea813742f8..cc91e246c5d 100644 --- a/scripts/comment-length-baseline.json +++ b/scripts/comment-length-baseline.json @@ -127,11 +127,11 @@ "packages/junior-github/src/tools/update-pull-request.ts": 8, "packages/junior-github/src/webhooks/check-suite.ts": 2, "packages/junior-github/src/webhooks/event-targets.ts": 6, - "packages/junior-github/src/webhooks/installation-requests.ts": 2, "packages/junior-github/src/webhooks/merge-conflict.ts": 8, "packages/junior-github/src/webhooks/object-cache.ts": 1, "packages/junior-github/src/webhooks/pull-request-item.ts": 5, "packages/junior-github/src/webhooks/pull-request-match-data.ts": 4, + "packages/junior-github/src/webhooks/pull-request-merge-state.ts": 2, "packages/junior-github/src/webhooks/pull-request-next-action.ts": 7, "packages/junior-github/tests/code-index.ts": 2, "packages/junior-google/src/calendar/events.ts": 5,