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: 2 additions & 1 deletion apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatc
left.remarkIds.join("\n") === right.remarkIds.join("\n") &&
left.conflicting === right.conflicting &&
left.wakes === right.wakes &&
left.checksAwaitedSince === right.checksAwaitedSince
left.checksAwaitedSince === right.checksAwaitedSince &&
left.mergeQueueRemovedAt === right.mergeQueueRemovedAt
);
}

Expand Down
34 changes: 34 additions & 0 deletions apps/server/src/orchestration-v2/pullRequestWatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,40 @@ describe("evaluatePullRequestWatch", () => {
);
});

it("tells the agent once when the merge queue takes it out, not for older or its own removals", () => {
const removed = (at: string, by = "github-merge-queue"): Partial<Detail> => ({
mergeQueueRemoval: { at, reason: "merge_conflict", by },
});
const first = evaluatePullRequestWatch(
watch(),
detail(removed("2026-10-02T12:05:00Z")),
noRemarks,
);
assert.deepEqual(first.changes, [{ kind: "left-merge-queue", reason: "merge_conflict" }]);
const wake = pullRequestWatchMessage({
number: 278,
url: "https://github.com/o/r/pull/278",
headSha: "d2bcd96b8e",
report: first,
standing: standing(),
});
assert.include(wake.text, "- The merge queue took it out without merging: merge conflict.");
assert.equal(wake.notification.outcome, "failed");
assert.equal(wake.notification.summary, "#278: left the merge queue");

const sameRemoval = detail(removed("2026-10-02T12:05:00Z"));
assert.deepEqual(evaluatePullRequestWatch(first.next, sameRemoval, noRemarks).changes, []);
const requeuedAndRemoved = detail(removed("2026-10-02T12:30:00Z"));
assert.deepEqual(evaluatePullRequestWatch(first.next, requeuedAndRemoved, noRemarks).changes, [
{ kind: "left-merge-queue", reason: "merge_conflict" },
]);

const beforeWatch = detail(removed("2026-10-02T11:55:00Z"));
assert.deepEqual(evaluatePullRequestWatch(watch(), beforeWatch, noRemarks).changes, []);
const byAgent = detail(removed("2026-10-02T12:05:00Z", "Agent-User"));
assert.deepEqual(evaluatePullRequestWatch(watch(), byAgent, noRemarks).changes, []);
});

it("does not spend the comment wake limit on check results", () => {
const tired = watch({ headSha: "aaaaaaaaaa", wakes: PULL_REQUEST_WATCH_WAKE_LIMIT - 1 });
const result = evaluatePullRequestWatch(
Expand Down
32 changes: 29 additions & 3 deletions apps/server/src/orchestration-v2/pullRequestWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ export type PullRequestWatchChange =
| { readonly kind: "checks-passed"; readonly count: number; readonly required: boolean }
| { readonly kind: "remarks"; readonly remarks: ReadonlyArray<PullRequestComment> }
| { readonly kind: "no-checks"; readonly minutes: number }
| { readonly kind: "conflicting" };
| { readonly kind: "conflicting" }
| { readonly kind: "left-merge-queue"; readonly reason: string | null };

export interface PullRequestWatchReport {
readonly changes: ReadonlyArray<PullRequestWatchChange>;
Expand All @@ -79,7 +80,13 @@ export function evaluatePullRequestWatch(
watch: ThreadPullRequestWatch,
detail: Pick<
PullRequestDetail,
"capabilities" | "headSha" | "checks" | "mergeability" | "viewer" | "author"
| "capabilities"
| "headSha"
| "checks"
| "mergeability"
| "viewer"
| "author"
| "mergeQueueRemoval"
>,
remarks: ReadonlyArray<PullRequestComment> | null,
now: number,
Expand Down Expand Up @@ -185,6 +192,16 @@ export function evaluatePullRequestWatch(
const conflicting =
detail.mergeability === "unknown" ? toldConflict : detail.mergeability === "conflicting";

// The queue can take a pull request out and nothing else on it changes, so the removal itself
// is the news. One from before the watch, or one the agent made itself, is not.
const removal = detail.mergeQueueRemoval ?? null;
const removedAfter = Date.parse(watch.mergeQueueRemovedAt ?? watch.startedAt);
const newRemoval = removal !== null && Date.parse(removal.at) > removedAfter ? removal : null;
if (newRemoval !== null && newRemoval.by?.toLowerCase() !== own) {
changes.push({ kind: "left-merge-queue", reason: newRemoval.reason });
}
const mergeQueueRemovedAt = newRemoval?.at ?? watch.mergeQueueRemovedAt;

const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks");
const progress = headMoved || (changes.length > 0 && !commentsOnly);
const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0);
Expand All @@ -202,6 +219,7 @@ export function evaluatePullRequestWatch(
conflicting,
wakes,
checksAwaitedSince,
...(mergeQueueRemovedAt === undefined ? {} : { mergeQueueRemovedAt }),
},
exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
};
Expand Down Expand Up @@ -259,6 +277,10 @@ function changeLines(
];
case "conflicting":
return [`- The branch now conflicts with ${context.baseBranch}.`];
case "left-merge-queue":
return [
`- The merge queue took it out without merging${change.reason === null ? "" : `: ${change.reason.replaceAll("_", " ")}`}.`,
];
}
}

Expand All @@ -268,6 +290,7 @@ const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
remarks: "new comments",
"no-checks": "no checks reported",
conflicting: "merge conflict",
"left-merge-queue": "left the merge queue",
};

export interface PullRequestStanding extends Pick<
Expand Down Expand Up @@ -338,7 +361,10 @@ export function pullRequestWatchMessage(input: {
: "Look into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.",
].join("\n");
const failed = changes.some(
(change) => change.kind === "checks-failed" || change.kind === "conflicting",
(change) =>
change.kind === "checks-failed" ||
change.kind === "conflicting" ||
change.kind === "left-merge-queue",
);
const summary = changes.map((change) => SUMMARY[change.kind]);
if (exhausted) summary.push("stopped watching");
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/pullRequest/PullRequestService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1859,6 +1859,9 @@ export const make = Effect.gen(function* () {
...(changeRequest.workflowApprovalsRequired === undefined
? {}
: { workflowApprovalsRequired: changeRequest.workflowApprovalsRequired }),
...(changeRequest.mergeQueueRemoval === undefined
? {}
: { mergeQueueRemoval: changeRequest.mergeQueueRemoval }),
})),
),
),
Expand Down
15 changes: 15 additions & 0 deletions packages/contracts/src/pullRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,16 @@ export const PullRequestReportStateInput = Schema.Struct({
});
export type PullRequestReportStateInput = typeof PullRequestReportStateInput.Type;

/** A merge queue taking a pull request out without merging it. */
export const PullRequestMergeQueueRemoval = Schema.Struct({
at: IsoDateTime,
/** The host's reason, such as GitHub's `merge_conflict`; null when it gives none. */
reason: Schema.NullOr(TrimmedNonEmptyString),
/** Who took it out, usually the queue's own bot; null when the host does not say. */
by: Schema.NullOr(TrimmedNonEmptyString),
});
export type PullRequestMergeQueueRemoval = typeof PullRequestMergeQueueRemoval.Type;

export const PullRequestDetail = Schema.Struct({
provider: SourceControlProviderKind,
capabilities: PullRequestCapabilities,
Expand Down Expand Up @@ -637,6 +647,11 @@ export const PullRequestDetail = Schema.Struct({
autoMergeMethod: Schema.optional(PullRequestMergeMethod),
workflowApprovalsRequired: Schema.optional(NonNegativeInt),
maintainerCanModify: Schema.optional(Schema.Boolean),
/**
* The merge queue's latest removal, when it did not merge the pull request. Null when the last
* removal merged it or there was none; absent when the host does not report merge queues.
*/
mergeQueueRemoval: Schema.optional(Schema.NullOr(PullRequestMergeQueueRemoval)),
});
export type PullRequestDetail = typeof PullRequestDetail.Type;

Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/threadPullRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export const ThreadPullRequestWatch = Schema.Struct({
* none did. Null once either happened; absent on watches saved before it existed.
*/
checksAwaitedSince: Schema.optional(Schema.NullOr(IsoDateTime)),
/** The last merge queue removal the agent was told about; absent until there is one. */
mergeQueueRemovedAt: Schema.optional(IsoDateTime),
});
export type ThreadPullRequestWatch = typeof ThreadPullRequestWatch.Type;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type {
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestMergeQueueRemoval,
PullRequestMergeability,
PullRequestOmittedFileStat,
PullRequestReaction,
Expand Down Expand Up @@ -210,6 +211,7 @@ export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
readonly autoMergeEnabled?: boolean;
readonly autoMergeMethod?: PullRequestMergeMethod;
readonly workflowApprovalsRequired?: number;
readonly mergeQueueRemoval?: PullRequestMergeQueueRemoval | null;
}

export interface ProviderChangeRequestActivity {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1461,6 +1461,7 @@ export const make = Effect.gen(function* () {
number: input.number,
headRef: `refs/pull/${input.number}/head`,
required: asksRequired(input.host),
mergeQueue: asksRequired(input.host),
requestedReviewers,
});
return SourceControlRateLimit.Interactive.pipe(
Expand Down Expand Up @@ -1744,7 +1745,8 @@ export const make = Effect.gen(function* () {
(input) => {
const lookup = pullRequestLookup(input);
if (lookup === null) return Effect.succeed(null);
return GraphQLResolver.request(lookup, watchFingerprintResolver).pipe(
const variables = { ...lookup, mergeQueue: asksRequired(input.host) };
return GraphQLResolver.request(variables, watchFingerprintResolver).pipe(
Effect.map((result) => {
const pullRequest = result.repository?.pullRequest;
return pullRequest == null ? null : toPullRequestWatchFingerprint(pullRequest);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,48 @@ describe("pull request detail decoding", () => {
pullRequest?: Record<string, unknown>,
) => expectSuccess(decodePullRequestCoreJson(coreJson(rollup, pullRequest)));

it.each([
["not asked for, as on Enterprise", {}, undefined],
["never removed", { timelineItems: { nodes: [] } }, null],
[
"removed by the queue",
{
timelineItems: {
nodes: [
{
__typename: "RemovedFromMergeQueueEvent",
createdAt: "2026-07-05T00:00:00Z",
reason: "merge_conflict",
actor: { __typename: "Bot", login: "github-merge-queue" },
},
],
},
},
{ at: "2026-07-05T00:00:00Z", reason: "merge_conflict", by: "github-merge-queue" },
],
[
"merged by the queue",
{
timelineItems: {
nodes: [
{
__typename: "RemovedFromMergeQueueEvent",
createdAt: "2026-07-05T00:00:00Z",
reason: "merged",
actor: { __typename: "Bot", login: "github-merge-queue" },
},
],
},
},
null,
],
])(
"reads the merge queue's latest removal that did not merge: %s",
(_case, pullRequest, removal) => {
expect(detailOf([], pullRequest).mergeQueueRemoval).toEqual(removal);
},
);

it.each([
[{}, true],
[{ viewerDidAuthor: false }, false],
Expand Down Expand Up @@ -1819,4 +1861,23 @@ describe("pull request watch fingerprints", () => {
expect(summaryEdited.status).toBe(before.status);
expect(replied.remarks).not.toBe(before.remarks);
});

it("moves status when the merge queue drops the pull request, and only when asked", () => {
const pullRequest = (removals?: number) => ({
state: "OPEN",
mergeable: "MERGEABLE",
headRefOid: "abc123",
comments: { totalCount: 0, nodes: [] },
reviews: { totalCount: 0, nodes: [] },
reviewThreads: { totalCount: 0 },
commits: { nodes: [] },
...(removals === undefined ? {} : { timelineItems: { filteredCount: removals } }),
});
const status = (removals?: number) =>
toPullRequestWatchFingerprint(decodeWatched(pullRequest(removals))).status;

expect(status(1)).not.toBe(status(0));
expect(status(0)).not.toBe(status());
expect(status()).not.toContain("queue-removals");
});
});
29 changes: 29 additions & 0 deletions packages/source-control-github/src/server/gitHubPullRequestJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
PullRequestLabel,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestMergeQueueRemoval,
PullRequestOmittedFileStat,
PullRequestMergeability,
PullRequestReaction,
Expand Down Expand Up @@ -1010,6 +1011,9 @@ export function toPullRequestWatchFingerprint(
pr.headRefOid,
stateCounts(contexts?.checkRunCountsByState ?? null),
stateCounts(contexts?.statusContextCountsByState ?? null),
...(pr.timelineItems === undefined
? []
: [`queue-removals:${pr.timelineItems.filteredCount}`]),
].join(" "),
remarks: [
pr.comments.totalCount,
Expand All @@ -1028,6 +1032,8 @@ export interface GitHubPullRequestCore extends GitHubPullRequestDetail {
readonly viewerAccess: GitHubViewerAccess & GitHubRepositoryAccess;
readonly comparison: GitHubBaseComparison | null;
readonly checksTruncated: boolean;
/** Absent when the read did not ask, as on Enterprise servers. */
readonly mergeQueueRemoval?: PullRequestMergeQueueRemoval | null;
}

type CoreRequestedReviewer = NonNullable<
Expand All @@ -1036,6 +1042,28 @@ type CoreRequestedReviewer = NonNullable<
>["nodes"]
>[number];

type CoreTimeline = NonNullable<
NonNullable<PullRequestCore.Result["repository"]>["pullRequest"]
>["timelineItems"];

/** GitHub's queue also logs a removal when it merges; only one that did not merge is news. */
function toMergeQueueRemoval(
timeline: CoreTimeline,
): Pick<GitHubPullRequestCore, "mergeQueueRemoval"> {
if (timeline === undefined) return {};
const event = nodesOf(timeline).findLast(
(node) => node.__typename === "RemovedFromMergeQueueEvent",
);
if (event === undefined || event.__typename !== "RemovedFromMergeQueueEvent") {
return { mergeQueueRemoval: null };
}
const reason = trimmed(event.reason);
if (reason?.toLowerCase() === "merged") return { mergeQueueRemoval: null };
return {
mergeQueueRemoval: { at: event.createdAt, reason, by: trimmed(event.actor?.login) },
};
}

export function toPullRequestCore(result: PullRequestCore.Result): GitHubPullRequestCore | null {
const repository = result.repository;
const pr = repository?.pullRequest;
Expand Down Expand Up @@ -1098,6 +1126,7 @@ export function toPullRequestCore(result: PullRequestCore.Result): GitHubPullReq
viewerCanUpdate: pr.viewerCanUpdateBranch,
},
checksTruncated: contexts?.pageInfo.hasNextPage === true,
...toMergeQueueRemoval(pr.timelineItems),
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,22 @@ query PullRequestStackMembership($owner: String!, $name: String!, $number: Int!)
# edit moves `updatedAt`, so an edit to an old comment on a long pull request is still in the page.
# Reviews have no such order: an edit to a review older than the last hundred waits for the
# watch's periodic full read, as do edits to comments inside review threads.
query PullRequestWatchFingerprint($owner: String!, $name: String!, $number: Int!) {
# A merge queue can drop a pull request without touching its head, checks or comments, so the
# count of queue removals is in the fingerprint too (github.com only, like isRequired).
query PullRequestWatchFingerprint(
$owner: String!
$name: String!
$number: Int!
$mergeQueue: Boolean!
) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
state
mergeable
headRefOid
timelineItems(itemTypes: [REMOVED_FROM_MERGE_QUEUE_EVENT]) @include(if: $mergeQueue) {
filteredCount
}
comments(first: 100, orderBy: { field: UPDATED_AT, direction: DESC }) {
totalCount
nodes {
Expand Down
Loading
Loading