Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions design/github.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 6 additions & 1 deletion packages/junior-github/src/graphql-documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 27 additions & 4 deletions packages/junior-github/src/webhooks/installation-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) =>
Expand Down
12 changes: 11 additions & 1 deletion packages/junior-github/src/webhooks/pull-request-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ const ACTION_EVENTS: Record<string, ReadonlySet<string>> = {
"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",
Expand All @@ -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.
Expand Down Expand Up @@ -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 =
Expand Down
9 changes: 9 additions & 0 deletions packages/junior-github/src/webhooks/pull-request-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
22 changes: 13 additions & 9 deletions packages/junior-github/src/webhooks/pull-request-next-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand All @@ -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) &&
Expand Down
20 changes: 20 additions & 0 deletions packages/junior-github/tests/pull-request-action-harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>,
) {
return signedRequest(
{
action,
...(changes ? { changes } : undefined),
...(requestedReviewer
? { requested_reviewer: { login: requestedReviewer } }
: undefined),
Expand All @@ -189,13 +192,19 @@ 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;
/** The commit at the head of the pull request. */
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<string | null>;
/** When set, the next pull request read waits for it. */
Expand Down Expand Up @@ -539,20 +548,31 @@ 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 } }]
: [],
},
headRefOid: github.headSha ?? "head-1",
isDraft: github.draft,
isInMergeQueue: github.inMergeQueue ?? false,
mergeStateStatus: (mergeableState ?? "unknown").toUpperCase(),
reviewRequests: {
nodes: [
Expand Down
Loading
Loading