Skip to content

Commit 3e272a3

Browse files
sentry-junior[bot]BYKdcramer
authored
fix(github): Fix merge conflicts only on pull requests people work on (#3383)
Each `pull_request.merge_conflict` event starts a full agent turn. Today every push to the default branch checks every open Junior PR, and each fix pushes a new head SHA, so the next push to main can fire the event again. On busy repos, abandoned PRs got fixed over and over until their 14-day Watch expired. The plugin now decides whether to publish the event. For PRs Junior opened: - **Drafts** never get the event. This applies to every PR, including ones Junior didn't open. - **Active PRs** (a person pushed, reviewed, or commented in the last 2 days, or the PR opened in that time) still get it, but at most once a day and 3 times in total. - **Approved PRs** would be ready to merge except for the conflict, so they get the fix right away: no 2-day window and no daily wait, only the 3-fix limit. The "ready to merge" notice already requires a `clean` merge state, so it doesn't show until after the fix. - **Idle PRs, or PRs past the cap**, get no event and no agent turn. Instead, the plugin adds a review desk notice to the conversation that asked for the PR. The notice closes when the conflict is gone or the PR closes. - **PRs with 3 idle days that aren't approved** get nothing. PRs that Junior didn't open (ones a person watches with `watchEvents`) keep the current behavior, except drafts. There is no new state. For each conflicted Junior PR, the plugin reads its history from GitHub with one GraphQL query (`PULL_REQUEST_CONFLICT_HISTORY`): - `reviewDecision` gives approval on both the webhook path and the heartbeat path. - Commits, reviews, comments, and force pushes by a `User` count as activity. The PR's `createdAt` counts too. - Merge commits and force pushes by a bot count as earlier fixes. The latest one sets the daily wait. - The event key already names the head commit, so a recheck of the same commit, or a webhook and the heartbeat at the same time, deliver one fix. - An open notice with the same dedupe key only gets new content, so repeat checks add no second notice. Other changes: - Plugin heartbeats now get `reviewItems`, like plugin routes. That is how the heartbeat conflict check adds and closes the notice without an agent turn. - The heartbeat GraphQL search now also reads `isDraft` and `title`. - `merge-conflicts.test.ts` went over the 1,000-line limit. The daily reconcile tests moved to `pull-request-reconcile.test.ts`, and the shared webhook and heartbeat harness moved to `tests/plugin-harness.ts`. Open tradeoffs: - A dismissed notice can come back on a later check while the conflict stays and the PR is still in the notice window. Without state, the plugin can't see the dismissal. - Force pushes by Junior for other reasons, such as a restack, also count as fixes, so the cap can come early on stacked PRs. - History reads the last 100 timeline items, so older activity or fixes on a very long PR are not counted. - Junior marks its own draft ready when checks pass, but a conflicted PR gets no new checks. A draft that gets a conflict after Junior's last push stays a draft until a person acts. - `reviewDecision` is null when a repo doesn't require reviews, so on those repos an approval doesn't change anything. - A PR that is only `behind` its base, with no conflict, still gets neither a fix nor the ready notice. <!-- junior-request-attribution:start --> via @BYK, @dcramer. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:slack%3AC0CHB3YHES2%3A1794587008.216409 --> -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0CHB3YHES2%3A1794587008.216409) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0CHB3YHES2%3A1794587008.216409/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Burak Yigit Kaya <[email protected]> Co-authored-by: David Cramer <[email protected]>
1 parent 244021d commit 3e272a3

22 files changed

Lines changed: 1492 additions & 549 deletions

File tree

‎packages/docs/src/content/docs/extend/build-a-plugin.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,8 @@ const role = await ctx.cache.getOrLoad(`role:${repo}:${login}`, async () => ({
443443
Use `ctx.state` for plugin-namespaced durable state. Use
444444
`ctx.agent.dispatch(...)` when the heartbeat needs Junior to run an autonomous
445445
agent task, and `ctx.agent.get(...)` to reconcile that dispatch later. Use
446-
`ctx.events`, `ctx.annotations`, and `ctx.codeChanges` as from a plugin route.
446+
`ctx.events`, `ctx.annotations`, `ctx.codeChanges`, and `ctx.reviewItems` as
447+
from a plugin route.
447448

448449
```ts title="index.ts"
449450
import { defineJuniorPlugin } from "@sentry/junior-plugin-api";

‎packages/docs/src/content/docs/extend/github-plugin.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,26 @@ default guidance tells the agent to merge the base branch, not rebase. For a
595595
pull request in a stack, the guidance tells the agent to restack with
596596
`gh stack rebase`, because a stack merges only with a linear history.
597597

598+
A draft pull request never gets this event. Each event starts an agent turn,
599+
so for a pull request that Junior opened, the event publishes only while
600+
people work on it:
601+
602+
- In the first 2 days after the latest push, review, or comment by a person,
603+
or after the pull request opened, the event publishes at most once a day
604+
and 3 times in total.
605+
- After that, or after the third event, Junior publishes no event. It adds
606+
a review desk notice to the conversation that asked for the pull request.
607+
The notice closes when the conflict is gone.
608+
- After 3 days without activity by a person, Junior does nothing.
609+
- An approved pull request would be ready to merge but for the conflict. It
610+
gets the event after those 2 days too, and without the daily wait, until
611+
the total limit. The ready to merge notice needs a clean merge state, so it
612+
comes after the fix.
613+
614+
Junior stores none of this. For each conflict, it reads the pull request's
615+
timeline and review decision from GitHub. Merges and force pushes by a bot
616+
count as earlier fixes. Each head commit publishes one event.
617+
598618
</details>
599619

600620
#### `release_source`

‎packages/junior-github/skills/github-code/SPEC.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Guide evidence-first GitHub repository work from inspection through a reviewable
1111
- Treat shallow clones as inspection checkouts; deepen before history work; never force-push around missing ancestry.
1212
- Install dependencies with the lockfile frozen mode before verification when needed.
1313
- Finish every code change with a pushed PR, without asking, unless the user opts out or asked for investigation only. Open it as a draft unless the requester asks for a ready PR: opening a PR ready asks its code owners at once, and only the draft Watch checks the changed files against CODEOWNERS. An open scope question goes in the PR body, not in a stop. The Watch of a draft marks it ready when its required checks pass and no decision is open, so open decisions of a draft go in its PR body. A draft whose changed files have CODEOWNERS owners, or whose repo's root AGENTS.md asks for draft PRs or for a person to mark them ready, stays a draft unless the requester said to mark it ready, and Junior tells the requester that it waits for their review.
14-
- After each push to a branch with an open PR, check mergeability. Resolve conflicts without asking, by merging the PR base branch (usually the default branch). Never rebase for this, except in a stack: a stack merges only with a linear history, so stacked PRs restack with `gh stack`. GitHub sends no event for a new conflict, and conflicted PRs get no new checks. The plugin publishes `pull_request.merge_conflict` for a watched PR only when another webhook event arrives for it, so the post-push check stays.
14+
- After each push to a branch with an open PR, check mergeability. Resolve conflicts without asking, by merging the PR base branch (usually the default branch). Never rebase for this, except in a stack: a stack merges only with a linear history, so stacked PRs restack with `gh stack`. GitHub sends no event for a new conflict, and conflicted PRs get no new checks. The plugin publishes `pull_request.merge_conflict` for a watched PR only when another webhook event arrives for it, and for a Junior PR only while people work on it and never for a draft, so the post-push check stays.
1515
- Write conventional PR titles and short plain-English bodies; keep check results out of the PR body.
1616
- Report exact validation and permission failures.
1717
- For 5xx, timeout, and connection failures, and for stalled or unexplained check failures, check GitHub status with `github_getStatus` (or the incidents on a `pull_request.checks.failed` event) before diagnosing. Report a matching incident as the likely cause; with no match, do not blame an outage.

‎packages/junior-github/src/graphql-documents.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,38 @@ export const OPEN_PULL_REQUEST_MERGEABILITY = githubGraphql(`
193193
search(query: $query, type: ISSUE, first: 100, after: $after) {
194194
pageInfo { hasNextPage endCursor }
195195
nodes {
196-
... on PullRequest { number state mergeable headRefOid baseRefName url }
196+
... on PullRequest { number state isDraft mergeable headRefOid baseRefName title url }
197+
}
198+
}
199+
}
200+
`);
201+
202+
/**
203+
* Read what decides a merge conflict fix on one pull request: the review
204+
* decision, when it opened, and its latest pushes, reviews, and comments.
205+
* Pushes have their own window, so comments, which anyone can add, cannot
206+
* push Junior's earlier fixes out of it.
207+
*/
208+
export const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
209+
query PullRequestConflictHistory($owner: String!, $name: String!, $number: Int!) {
210+
repository(owner: $owner, name: $name) {
211+
pullRequest(number: $number) {
212+
createdAt
213+
reviewDecision
214+
pushes: timelineItems(last: 100, itemTypes: [PULL_REQUEST_COMMIT, HEAD_REF_FORCE_PUSHED_EVENT]) {
215+
nodes {
216+
__typename
217+
... on PullRequestCommit { commit { committedDate parents { totalCount } author { user { login } } } }
218+
... on HeadRefForcePushedEvent { createdAt actor { __typename } }
219+
}
220+
}
221+
discussion: timelineItems(last: 50, itemTypes: [PULL_REQUEST_REVIEW, ISSUE_COMMENT]) {
222+
nodes {
223+
__typename
224+
... on PullRequestReview { submittedAt author { __typename } }
225+
... on IssueComment { createdAt author { __typename } }
226+
}
227+
}
197228
}
198229
}
199230
}

‎packages/junior-github/src/merge-conflict-checks/heartbeat.ts‎

Lines changed: 53 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
11
/**
22
* The heartbeat part of merge conflict checks. For each due repository, a
33
* GraphQL search reads the open Junior pull requests with their
4-
* mergeability.
5-
* Only a conflict that a Watch or event automation wants publishes
6-
* `pull_request.merge_conflict`. No agent runs for the check.
4+
* mergeability. Only a conflicted Junior pull request also reads its
5+
* history. Only a conflict that a Watch or event automation wants, and that
6+
* `policy.ts` allows, publishes `pull_request.merge_conflict`. No agent runs
7+
* for the check.
78
*/
89
import type {
910
EventPublisher,
11+
PluginConversationReviewItems,
1012
PluginLogger,
1113
PluginState,
1214
} from "@sentry/junior-plugin-api";
1315
import * as z from "zod";
1416
import type { GitHubDb } from "../db/database.js";
15-
import { gitHubMergeConflictEvents } from "../webhooks/merge-conflict.js";
17+
import {
18+
gitHubMergeConflictEvents,
19+
type GitHubMergeConflict,
20+
type GitHubPullRequestRef,
21+
} from "../webhooks/merge-conflict.js";
22+
import {
23+
applyGitHubConflictPolicy,
24+
closeGitHubConflictNotices,
25+
GITHUB_CONFLICT_GONE_REASON,
26+
} from "./policy.js";
1627
import {
1728
claimGitHubConflictCheck,
1829
listGitHubRepositoriesWithOpenPullRequests,
@@ -43,9 +54,11 @@ const searchNodeSchema = z.union([
4354
z.object({
4455
baseRefName: z.string().min(1),
4556
headRefOid: z.string().min(1),
57+
isDraft: z.boolean(),
4658
mergeable: z.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
4759
number: z.number().int().positive(),
4860
state: z.string(),
61+
title: z.string(),
4962
url: z.string().min(1),
5063
}),
5164
z.object({}).strict(),
@@ -70,7 +83,7 @@ type SearchOpenPullRequests = (input: {
7083

7184
/** Return whether any open pull request still has an unknown answer. */
7285
async function checkRepository(
73-
args: { events: EventPublisher; search: SearchOpenPullRequests },
86+
args: CheckArgs,
7487
repositoryFullName: string,
7588
): Promise<boolean> {
7689
let unknown = false;
@@ -79,23 +92,45 @@ async function checkRepository(
7992
const { search } = searchResponseSchema.parse(
8093
await args.search({ after, repositoryFullName }),
8194
).data;
95+
const mergeable: number[] = [];
8296
for (const node of search.nodes) {
8397
if (!node || !("number" in node) || node.state !== "OPEN") continue;
8498
if (node.mergeable === "UNKNOWN") unknown = true;
99+
if (node.mergeable === "MERGEABLE") mergeable.push(node.number);
85100
if (node.mergeable !== "CONFLICTING") continue;
86-
const events = gitHubMergeConflictEvents({
87-
conflict: {
88-
baseBranch: node.baseRefName,
89-
headSha: node.headRefOid,
90-
url: node.url,
91-
},
92-
number: node.number,
93-
repositoryFullName,
94-
});
101+
const ref = { number: node.number, repositoryFullName };
102+
const conflict: GitHubMergeConflict = {
103+
baseBranch: node.baseRefName,
104+
headSha: node.headRefOid,
105+
url: node.url,
106+
};
107+
const events = gitHubMergeConflictEvents({ ...ref, conflict });
95108
// Conflict events match only `repo` and `pullRequest`.
96109
if (!(await args.events.hasMatch?.(events))) continue;
97-
for (const event of events) await args.events.publish(event);
110+
for (const event of await applyGitHubConflictPolicy({
111+
conflict,
112+
db: args.db,
113+
draft: node.isDraft,
114+
events,
115+
loadHistory: args.loadHistory,
116+
log: args.log,
117+
now: args.now,
118+
ref,
119+
reviewItems: args.reviewItems,
120+
title: node.title,
121+
})) {
122+
await args.events.publish(event);
123+
}
98124
}
125+
await closeGitHubConflictNotices({
126+
db: args.db,
127+
log: args.log,
128+
numbers: mergeable,
129+
reason: GITHUB_CONFLICT_GONE_REASON,
130+
repositoryFullName,
131+
reviewItems: args.reviewItems,
132+
status: "done",
133+
});
99134
if (!search.pageInfo.hasNextPage || !search.pageInfo.endCursor) break;
100135
after = search.pageInfo.endCursor;
101136
}
@@ -105,8 +140,10 @@ async function checkRepository(
105140
interface CheckArgs {
106141
db: GitHubDb;
107142
events: EventPublisher;
108-
log: Pick<PluginLogger, "error">;
143+
loadHistory(ref: GitHubPullRequestRef): Promise<unknown>;
144+
log: Pick<PluginLogger, "error" | "warn">;
109145
now: Date;
146+
reviewItems: PluginConversationReviewItems;
110147
search: SearchOpenPullRequests;
111148
state: PluginState;
112149
}

0 commit comments

Comments
 (0)