The best way to control Claude Code, Codex and more from any computer or phone
feat(server): agents land a GitHub stack in one merge (#38973)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 18, 2026 at 23:04 UTC
37f8a5325cdf3de37c2be860c8525ceb9742cbb5
8 files changed
+155
-18
apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
+53
@@ -1020,6 +1020,59 @@ describe("source control tools", () => {
1020
}),
1021
);
1022
1023
+ it.effect("a stack merge pins every open layer up to the PR", () =>
1024
+ Effect.gen(function* () {
1025
+ const actions: Array<PullRequestActionInput> = [];
1026
+ let lowerHead: string | undefined = "bbb";
1027
+ const layer = (number: number, state: "open" | "merged", headSha: string | undefined) => ({
1028
+ number,
1029
+ state,
1030
+ ...(headSha === undefined ? {} : { headSha }),
1031
+ headBranch: `layer-${number}`,
1032
+ });
1033
+ const harness = yield* makeHarness({
1034
+ thread: branchThread,
1035
+ pullRequests: {
1036
+ stack: (_input, options) =>
1037
+ options?.bypassCache !== true
1038
+ ? Effect.die("a merge must not pin heads from the cache")
1039
+ : Effect.succeed({
1040
+ id: "stack-1",
1041
+ number: 7,
1042
+ url: "https://github.com/acme/app/stacks/7",
1043
+ base: "main",
1044
+ layers: [
1045
+ layer(40, "merged", "aaa"),
1046
+ layer(41, "open", lowerHead),
1047
+ layer(42, "open", "stale"),
1048
+ layer(43, "open", "ddd"),
1049
+ ],
1050
+ }),
1051
+ runAction: (input) => Effect.sync(() => void actions.push(input)),
1052
+ summary: () => Effect.succeed({ state: "merged" } as never),
1053
+ },
1054
+ });
1055
+ yield* harness.call("pull_request_merge", { expectedHeadSha: "ccc", stack: true });
1056
+ expect(actions).toMatchObject([
1057
+ {
1058
+ number: 42,
1059
+ action: "merge",
1060
+ stackNumber: 7,
1061
+ expectedStackHeads: [
1062
+ { number: 41, headSha: "bbb" },
1063
+ { number: 42, headSha: "ccc" },
1064
+ ],
1065
+ },
1066
+ ]);
1067
+ lowerHead = undefined;
1068
+ const unpinned = yield* harness
1069
+ .call("pull_request_merge", { expectedHeadSha: "ccc", stack: true })
1070
+ .pipe(Effect.flip);
1071
+ expect(unpinned._tag).toBe("PullRequestForgeError");
1072
+ expect(actions).toHaveLength(1);
1073
+ }),
1074
+ );
1075
+
1076
it.effect("re-running checks reopens a watch that saw its checks finish", () =>
1077
Effect.gen(function* () {
1078
const watch = {
apps/server/src/mcp/toolkits/pullRequests/handlers.ts
+30
@@ -400,6 +400,34 @@ const make = Effect.gen(function* () {
400
const forgeFailure = (error: { readonly message: string }) =>
401
new PullRequestForgeError({ detail: error.message, cause: error });
402
403
+ // Layers below the target are pinned to the heads read here; the host refuses if any moved.
404
+ const stackMergeScope = Effect.fnUntraced(function* (
405
+ ref: PullRequestRef,
406
+ input: { readonly expectedHeadSha: string; readonly auto?: boolean | undefined },
407
+ ) {
408
+ if (input.auto === true)
409
+ return yield* new PullRequestForgeError({ detail: "A stack merge cannot wait with auto." });
410
+ const stack = yield* pullRequests
411
+ .stack(ref, { bypassCache: true })
412
+ .pipe(Effect.mapError(forgeFailure));
413
+ const end = stack?.layers.findIndex((layer) => layer.number === ref.number) ?? -1;
414
+ if (stack === null || end === -1)
415
+ return yield* new PullRequestForgeError({
416
+ detail: `PR #${ref.number} is not in a stack this host can merge. Merge it without stack.`,
417
+ });
418
+ const expectedStackHeads: Array<{ readonly number: number; readonly headSha: string }> = [];
419
+ for (const layer of stack.layers.slice(0, end + 1)) {
420
+ if (layer.state === "merged") continue;
421
+ const headSha = layer.number === ref.number ? input.expectedHeadSha : layer.headSha;
422
+ if (headSha === undefined)
423
+ return yield* new PullRequestForgeError({
424
+ detail: `The host did not report PR #${layer.number}'s head, so the stack cannot be pinned. Try again.`,
425
+ });
426
+ expectedStackHeads.push({ number: layer.number, headSha });
427
+ }
428
+ return { stackNumber: stack.number, expectedStackHeads };
429
+ });
430
+
431
/** A login or org/team, matched to the host's own reviewer id. */
432
const reviewerNamed = (ref: PullRequestRef, name: string) =>
433
pullRequests.reviewerCandidates({ ...ref, query: name }).pipe(
@@ -1131,12 +1159,14 @@ const make = Effect.gen(function* () {
1159
pull_request_merge: McpToolAccess.writesWithCapability((input) =>
1160
Effect.gen(function* () {
1161
const { target, ref } = yield* locate(input);
1162
+ const stack = input.stack === true ? yield* stackMergeScope(ref, input) : {};
1163
yield* pullRequests
1164
.runAction({
1165
...ref,
1166
action: input.auto === true ? "enable-auto-merge" : "merge",
1167
expectedHeadSha: input.expectedHeadSha,
1168
...(input.method === undefined ? {} : { mergeMethod: input.method }),
1169
+ ...stack,
1170
})
1171
.pipe(Effect.mapError(forgeFailure));
1172
const after = yield* pullRequests
apps/server/src/mcp/toolkits/pullRequests/tools.ts
+5
@@ -767,6 +767,11 @@ const MergePullRequestTool = Tool.make("pull_request_merge", {
767
description: "Merge when required checks pass, including later pushes.",
768
}),
769
),
770
+ stack: Schema.optional(
771
+ Schema.Boolean.annotate({
772
+ description: "Merge this PR and every open stack layer below it at once. Not with auto.",
773
+ }),
774
+ ),
775
}),
776
success: MergePullRequestResult,
777
failure: PullRequestToolError,
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 6245,
3
"codexAdditionalContextBytes": 7639,
4
- "mcpToolListJsonBytes": 57204
4
+ "mcpToolListJsonBytes": 57321
5
}
apps/server/src/pullRequest/PullRequestService.ts
+13
-7
@@ -210,7 +210,11 @@ export class PullRequestService extends Context.Service<
210
readonly batchesReads: (input: PullRequestRef) => Effect.Effect<boolean>;
211
readonly stack: (
212
input: PullRequestRef,
213
- options?: { readonly includeDetails?: boolean },
213
+ options?: {
214
+ readonly includeDetails?: boolean;
215
+ /** A merge pins these heads, so it must not read them from the cache. */
216
+ readonly bypassCache?: boolean;
217
+ },
218
) => Effect.Effect<PullRequestStack | null, PullRequestError>;
219
readonly subscribeMerges: Effect.Effect<
220
Stream.Stream<PullRequestMergeEvent>,
@@ -3212,12 +3216,14 @@ export const make = Effect.gen(function* () {
3216
);
3217
3218
const stack: PullRequestService["Service"]["stack"] = (input, options) =>
3215
- persistedRead(
3216
- input,
3217
- `stack:${options?.includeDetails !== false}`,
3218
- stackCodec,
3219
- stackUncached(input, options),
3220
- );
3219
+ options?.bypassCache === true
3220
+ ? stackUncached(input, options)
3221
+ : persistedRead(
3222
+ input,
3223
+ `stack:${options?.includeDetails !== false}`,
3224
+ stackCodec,
3225
+ stackUncached(input, options),
3226
+ );
3227
3228
const listCache = yield* Cache.makeWith(
3229
(key: string) => {
docs/user/source-control.md
+2
-1
@@ -319,7 +319,8 @@ pull requests with the `link_pull_request` tool.
319
320
Agents can also read, open, update, reply on, and merge pull requests in the thread's repository
321
through T3 Code's own tools, which use the same sign-in as the Pull requests page. An agent merges
322
-only the commit it last read: if someone pushed since, the merge is refused.
322
+only the commit it last read: if someone pushed since, the merge is refused. On github.com an
323
+agent can also land a GitHub stack in one merge, like **Merge stack** below.
324
325
Use **Link pull request to thread** in the command palette to keep a pull request with the thread. From a review
326
on the Pull requests page, **Link to thread** lets you search for an active thread. The review header
evals/mcp-tool-use/cases/pull-requests.ndjson
+1
@@ -56,3 +56,4 @@
56
{"id": "ci-failure-read-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "failing CI log read with gh run view", "experience": "Agents fixing a red PR read the failure with gh run view --log-failed or GET actions/jobs/:id/logs, on the user's personal quota, and often paged whole logs.", "rule": "ci_logs reads the end of a PR's failing check logs", "privacy": "commit-safe", "setup": {"role": "top", "world": {"branch": "fix/retry-queue", "commits": [{"sha": "9f3c2a1", "subject": "fix(queue): retry a failed job once"}], "diff": "diff --git a/src/queue.ts b/src/queue.ts\n--- a/src/queue.ts\n+++ b/src/queue.ts\n@@ -4,3 +4,4 @@ export async function run(job: Job) {\n try {\n return await job.execute();\n- } catch {\n+ } catch (error) {\n+ if (job.attempts > 1) throw error;\n return run({ ...job, attempts: job.attempts + 1 });\n", "files": {"src/queue.ts": "export async function run(job: Job) {\n try {\n return await job.execute();\n } catch (error) {\n if (job.attempts > 1) throw error;\n return run({ ...job, attempts: job.attempts + 1 });\n }\n}\n"}, "prs": [{"number": 124, "title": "fix(queue): retry a failed job once", "headRefName": "fix/retry-queue", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "fail", "log": "FAIL src/queue.test.ts > gives up after one retry\nAssertionError: expected 2 calls, got 3\n at src/queue.test.ts:18:5"}]}]}, "shellMocks": [{"match": "git push", "output": "To github.com:acme/app.git\n 9f3c2a1..4d5e6f7 fix/retry-queue -> fix/retry-queue"}]}, "prompt": "CI is red on #124. Find out why and fix it.", "expect": {"calls": [{"tool": "ci_logs"}], "shellMustNot": ["\\bgh run (view|list)\\b", "\\bgh api\\b[^\\n]*actions", "\\bgh pr checks\\b", "\\bcafe ci\\b"]}, "notes": "Forge usage audit of agent logs on three machines (2026-10-28): agents read failing CI with gh run view --log-failed or the job logs API about 500 times in 45 days, and re-ran CI with gh run rerun 92 times.", "maxSteps": 12}
57
{"id": "ci-flake-rerun-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "CI re-run with gh run rerun", "experience": "Asked to re-run a flaky check, agents looked up run ids with gh run list and ran gh run rerun --failed.", "rule": "ci_rerun re-runs a PR's failing checks", "privacy": "commit-safe", "setup": {"role": "top", "world": {"branch": "fix/retry-queue", "commits": [{"sha": "9f3c2a1", "subject": "fix(queue): retry a failed job once"}], "diff": "diff --git a/src/queue.ts b/src/queue.ts\n--- a/src/queue.ts\n+++ b/src/queue.ts\n@@ -4,3 +4,4 @@ export async function run(job: Job) {\n try {\n return await job.execute();\n- } catch {\n+ } catch (error) {\n+ if (job.attempts > 1) throw error;\n return run({ ...job, attempts: job.attempts + 1 });\n", "files": {"src/queue.ts": "export async function run(job: Job) {\n try {\n return await job.execute();\n } catch (error) {\n if (job.attempts > 1) throw error;\n return run({ ...job, attempts: job.attempts + 1 });\n }\n}\n"}, "prs": [{"number": 124, "title": "fix(queue): retry a failed job once", "headRefName": "fix/retry-queue", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "fail", "log": "FAIL src/queue.test.ts > gives up after one retry\nAssertionError: expected 2 calls, got 3\n at src/queue.test.ts:18:5"}]}]}}, "prompt": "The Test failure on #124 is a known flake. Re-run it.", "expect": {"calls": [{"tool": "ci_rerun"}], "shellMustNot": ["\\bgh run (rerun|list|view)\\b", "\\bgh api\\b[^\\n]*rerun"]}, "notes": "Forge usage audit of agent logs on three machines (2026-10-28): agents read failing CI with gh run view --log-failed or the job logs API about 500 times in 45 days, and re-ran CI with gh run rerun 92 times."}
58
{"id": "control-ci-why-no-rerun", "area": "pull-requests", "kind": "control", "pattern": "question about a failing check", "experience": "Control: the user asks why CI failed. Reading the log is right; re-running it was not asked.", "rule": "Re-run only when asked", "privacy": "commit-safe", "setup": {"role": "top", "world": {"branch": "fix/retry-queue", "commits": [{"sha": "9f3c2a1", "subject": "fix(queue): retry a failed job once"}], "diff": "diff --git a/src/queue.ts b/src/queue.ts\n--- a/src/queue.ts\n+++ b/src/queue.ts\n@@ -4,3 +4,4 @@ export async function run(job: Job) {\n try {\n return await job.execute();\n- } catch {\n+ } catch (error) {\n+ if (job.attempts > 1) throw error;\n return run({ ...job, attempts: job.attempts + 1 });\n", "files": {"src/queue.ts": "export async function run(job: Job) {\n try {\n return await job.execute();\n } catch (error) {\n if (job.attempts > 1) throw error;\n return run({ ...job, attempts: job.attempts + 1 });\n }\n}\n"}, "prs": [{"number": 124, "title": "fix(queue): retry a failed job once", "headRefName": "fix/retry-queue", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "fail", "log": "FAIL src/queue.test.ts > gives up after one retry\nAssertionError: expected 2 calls, got 3\n at src/queue.test.ts:18:5"}]}]}}, "prompt": "Why is CI failing on #124? Don't change anything yet.", "expect": {"notCalls": ["ci_rerun", "pull_request_merge"], "shellMustNot": ["\\bgh run rerun\\b"]}, "notes": "Control for ci-flake-rerun-through-gh."}
59
+{"id": "land-stack-in-one-merge", "area": "pull-requests", "kind": "bad", "pattern": "a green, approved stack merged layer by layer or through gh stack merge", "experience": "Asked to land a two-PR stack, the agent had only a one-PR merge tool, so it merged the bottom layer alone, which restarts CI on the layer above, or fell back to gh stack merge in the shell.", "rule": "pull_request_merge stack:true on the top PR merges every layer below it at once.", "privacy": "commit-safe", "setup": {"role": "top", "context": "PR #124 (feature/error-detail, on main) and PR #125 (feature/frozen-host, on top of #124) form a native GitHub stack and are linked to this thread.", "world": {"repo": "acme/app", "branch": "feature/frozen-host", "stack": 300, "linkedPullRequests": [{"number": 124, "state": "open", "title": "feat(server): include the failing step in connection errors"}, {"number": 125, "state": "open", "title": "feat(server): detect a frozen host and say so"}], "prs": [{"number": 124, "title": "feat(server): include the failing step in connection errors", "headRefName": "feature/error-detail", "baseRefName": "main", "headRefOid": "e1d2c3b", "reviewDecision": "APPROVED", "mergeable": "MERGEABLE", "checks": [{"name": "CI", "state": "pass"}]}, {"number": 125, "title": "feat(server): detect a frozen host and say so", "headRefName": "feature/frozen-host", "baseRefName": "feature/error-detail", "headRefOid": "f7e6d5c", "reviewDecision": "APPROVED", "mergeable": "MERGEABLE", "checks": [{"name": "CI", "state": "pass"}]}]}}, "prompt": "Both PRs in the stack are approved and green. Land the stack.", "expect": {"calls": [{"tool": "pull_request_merge", "args": {"stack": true, "expectedHeadSha": "f7e6d5c"}, "argsAnyOf": [{"number": 125}, {"url": "~/pull/125"}, {"number": null, "url": null}]}], "maxCalls": {"pull_request_merge": 1}, "shellMustNot": ["gh stack merge", "gh pr merge", "gh api[^\\n]*/merge"], "callsMustNot": [{"tool": "pull_request_merge", "args": {"auto": true}}]}, "maxSteps": 8, "source": {"request": "juliusmarminge (maintainer) request, 2026-11-18: the PR tools could read stacks but not merge one; layer-by-layer merges restart CI above and can reorder a GitHub stack"}}
evals/mcp-tool-use/run.ts
+50
-9
@@ -294,6 +294,8 @@ const McpToolUseWorld = Schema.StructWithRest(
294
* session. With them, T3's own t3_background_wait handler answers from this world.
295
*/
296
backgroundTasks: Schema.optional(Schema.Array(Schema.String)),
297
+ /** The world's `prs`, bottom first, form one native stack with this number. */
298
+ stack: Schema.optional(Schema.Number),
299
/** PRs already linked to the thread, with the state T3 last saw. */
300
linkedPullRequests: Schema.optional(
301
Schema.Array(
@@ -919,6 +921,8 @@ type Sample = {
921
readonly openedByBranch: Map<string, number>;
922
/** PR changes the agent made through T3's tools, which gh and the host show from then on. */
923
readonly forgeChanges: Array<string>;
924
+ /** PRs pull_request_merge merged, as `repo#number`, which reads show as merged from then on. */
925
+ readonly merged: Set<string>;
926
readonly codeStore: Record<string, unknown>;
927
nextTask: number;
928
/** Threads the agent launched in this sample, by id, so reading one shows its own brief. */
@@ -976,6 +980,7 @@ export const makeSample = (testCase: McpToolUseCase, base: Base): Sample => {
980
linked: new Set([...urls, ...shell.flatMap(createdPullRequests)]),
981
openedByBranch: new Map(),
982
forgeChanges: [],
983
+ merged: new Set(),
984
openedPullRequest:
985
shell
986
.map((entry) => branchPullRequestCreatedBy(entry, testCase.setup.world?.branch))
@@ -1237,9 +1242,13 @@ const linkedEntry = (sample: Sample, url: string) => {
1242
const seeded = sample.testCase.setup.world?.linkedPullRequests?.find(
1243
({ number }) => number === pr.number && pr.repository === sample.repo,
1244
);
1240
- return { ...pr, state: seeded?.state ?? "open", title: seeded?.title ?? null };
1245
+ const state = mergedIn(sample, pr.repository, pr.number) ? "merged" : (seeded?.state ?? "open");
1246
+ return { ...pr, state, title: seeded?.title ?? null };
1247
};
1248
1249
+const mergedIn = (sample: Sample, repository: string, number: unknown) =>
1250
+ sample.merged.has(`${repository.toLowerCase()}#${Number(number)}`);
1251
+
1252
/** The world's PRs. `prs` is free-form world data: number, title, headRefName, checks. */
1253
const worldPullRequests = (sample: Sample) => {
1254
const prs = sample.testCase.setup.world?.prs;
@@ -1430,11 +1439,11 @@ export const t3Default = (
1439
world?.title ?? sample.testCase.setup.world?.commits?.[0]?.subject,
1440
),
1441
body: valueText(world?.body ?? ""),
1433
- state: worldState(world),
1442
+ state: mergedIn(sample, sample.repo, number) ? "merged" : worldState(world),
1443
isDraft: false,
1444
author: "user",
1445
headBranch: valueText(world?.headRefName ?? sample.testCase.setup.world?.branch),
1437
- baseBranch: "main",
1446
+ baseBranch: valueText(world?.baseRefName ?? "main"),
1447
// Only the branch's own PR is at the checkout's latest commit.
1448
headSha:
1449
typeof world?.headRefOid === "string"
@@ -1496,9 +1505,11 @@ export const t3Default = (
1505
}
1506
case "pull_request_list": {
1507
const state = valueText(input.state ?? "open");
1508
+ const stateOf = (pr: Readonly<Record<string, unknown>>) =>
1509
+ mergedIn(sample, sample.repo, pr.number) ? "merged" : worldState(pr);
1510
return {
1511
pullRequests: worldPullRequests(sample)
1501
- .filter((pr) => state === "all" || worldState(pr) === state)
1512
+ .filter((pr) => state === "all" || stateOf(pr) === state)
1513
.map((pr) => ({
1514
number: Number(pr.number),
1515
title: valueText(pr.title),
@@ -1506,7 +1517,7 @@ export const t3Default = (
1517
author: "user",
1518
headBranch: valueText(pr.headRefName),
1519
baseBranch: "main",
1509
- state: worldState(pr),
1520
+ state: stateOf(pr),
1521
isDraft: false,
1522
reviewDecision: null,
1523
checksState: null,
@@ -1525,11 +1536,22 @@ export const t3Default = (
1536
replied: input.body !== undefined,
1537
resolved: typeof input.resolved === "boolean" ? input.resolved : null,
1538
};
1528
- case "pull_request_merge":
1539
+ case "pull_request_merge": {
1540
+ const number = input.number ?? branchPullRequest(sample).number;
1541
+ if (input.auto !== true) {
1542
+ const layers = worldPullRequests(sample).map((pr) => Number(pr.number));
1543
+ const below =
1544
+ input.stack === true && sample.testCase.setup.world?.stack !== undefined
1545
+ ? layers.slice(0, layers.indexOf(Number(number)) + 1)
1546
+ : [];
1547
+ for (const merged of [Number(number), ...below])
1548
+ sample.merged.add(`${sample.repo.toLowerCase()}#${merged}`);
1549
+ }
1550
return {
1530
- ...pullRequest(sample.repo, { number: input.number ?? branchPullRequest(sample).number }),
1551
+ ...pullRequest(sample.repo, { number }),
1552
state: input.auto === true ? "open" : "merged",
1553
};
1554
+ }
1555
case "ci_logs":
1556
case "ci_rerun": {
1557
const { number, checks, named } = selectedWorldChecks(sample, input);
@@ -1595,14 +1617,33 @@ export const t3Default = (
1617
return { ...pr(), watching: false, wasWatching: true };
1618
case "list_thread_pull_requests": {
1619
const states = Array.isArray(input.states) ? input.states : undefined;
1620
+ const layers =
1621
+ sample.testCase.setup.world?.stack === undefined
1622
+ ? []
1623
+ : worldPullRequests(sample).map((pr) => Number(pr.number));
1624
const matching = [...sample.linked]
1599
- .map((url) => ({ ...linkedEntry(sample, url), source: "agent", watching: false }))
1625
+ .map((url) => linkedEntry(sample, url))
1626
+ .map((entry) => {
1627
+ const position =
1628
+ entry.repository.toLowerCase() === sample.repo.toLowerCase()
1629
+ ? layers.indexOf(entry.number) + 1
1630
+ : 0;
1631
+ return {
1632
+ ...entry,
1633
+ source: "agent",
1634
+ watching: false,
1635
+ stack: position === 0 ? null : { kind: "native", position, size: layers.length },
1636
+ };
1637
+ })
1638
.filter((entry) => states === undefined || states.includes(entry.state));
1639
const start = Number(valueText(input.cursor)) || 0;
1640
const end = start + 50;
1641
+ const linkedLayers = layers.filter((number) =>
1642
+ matching.some((entry) => entry.stack !== null && entry.number === number),
1643
+ );
1644
return {
1645
pullRequests: matching.slice(start, end),
1605
- chains: [],
1646
+ chains: linkedLayers.length < 2 ? [] : [{ kind: "native", numbers: linkedLayers }],
1647
nextCursor: end < matching.length ? String(end) : null,
1648
};
1649
}