The best way to control Claude Code, Codex and more from any computer or phone
fix(gitlab): merge requests can delete their source branch (#30453)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>
Antony committed
Nov 6, 2026 at 01:39 UTC
b871551ee25a284367797cf651fad8a30cc4e4a7
6 files changed
+366
-4
packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+109
@@ -87,6 +87,23 @@ function mergeRequestJson(overrides: Record<string, unknown>): string {
87
});
88
}
89
90
+function sourceBranchJson(overrides: Record<string, unknown>): string {
91
+ return JSON.stringify({
92
+ data: {
93
+ project: {
94
+ mergeRequest: {
95
+ state: "merged",
96
+ sourceBranch: "feat/page",
97
+ diffHeadSha: "head",
98
+ sourceProject: { fullPath: "acme/web" },
99
+ userPermissions: { removeSourceBranch: true },
100
+ ...overrides,
101
+ },
102
+ },
103
+ },
104
+ });
105
+}
106
+
107
function argsOfCall(index: number): ReadonlyArray<string> {
108
return callAt(index).args;
109
}
@@ -1465,6 +1482,98 @@ layer("GitLabPullRequestCli.layer", (it) => {
1482
}),
1483
);
1484
1485
+ it.effect.each([
1486
+ { answer: sourceBranchJson({}), expected: true },
1487
+ { answer: "not json", expected: false },
1488
+ ])("asks GitLab whether a merged merge request's branch can be deleted", ({ answer, expected }) =>
1489
+ Effect.gen(function* () {
1490
+ mockedExecute
1491
+ .mockReturnValueOnce(Effect.succeed(output(mergeRequestJson({ state: "merged" }))))
1492
+ .mockReturnValueOnce(Effect.succeed(labelPermission))
1493
+ .mockReturnValueOnce(Effect.succeed(output(answer)));
1494
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1495
+
1496
+ const detail = yield* cli.getMergeRequestDetail({
1497
+ cwd: "/w",
1498
+ repository: "acme/web",
1499
+ number: 7,
1500
+ });
1501
+
1502
+ expect(detail.viewerCanDeleteBranch).toBe(expected);
1503
+ expect(argsOfCall(2)).toContain("graphql");
1504
+ }),
1505
+ );
1506
+
1507
+ it.effect("deletes the source branch in the source project once its head is the merged one", () =>
1508
+ Effect.gen(function* () {
1509
+ mockedExecute
1510
+ .mockReturnValueOnce(
1511
+ Effect.succeed(output(sourceBranchJson({ sourceProject: { fullPath: "fork/web" } }))),
1512
+ )
1513
+ .mockReturnValueOnce(
1514
+ Effect.succeed(
1515
+ output(
1516
+ JSON.stringify({
1517
+ default: false,
1518
+ commit: { id: "head", authored_date: "2026-11-03T20:29:40.000-07:00" },
1519
+ }),
1520
+ ),
1521
+ ),
1522
+ )
1523
+ .mockReturnValueOnce(Effect.succeed(output("")));
1524
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1525
+
1526
+ yield* cli.runMergeRequestAction({
1527
+ cwd: "/w",
1528
+ repository: "acme/web",
1529
+ number: 7,
1530
+ action: "delete-branch",
1531
+ });
1532
+
1533
+ expect(argsOfCall(1)).toEqual(["api", "projects/fork%2Fweb/repository/branches/feat%2Fpage"]);
1534
+ expect(argsOfCall(2)).toEqual([
1535
+ "api",
1536
+ "projects/fork%2Fweb/repository/branches/feat%2Fpage",
1537
+ "--method",
1538
+ "DELETE",
1539
+ "--header",
1540
+ "If-Unmodified-Since: Wed, 04 Nov 2026 03:29:40 GMT",
1541
+ ]);
1542
+ }),
1543
+ );
1544
+
1545
+ it.effect.each([
1546
+ { reason: "open", source: { state: "opened" }, branch: undefined },
1547
+ { reason: "open", source: { state: "locked" }, branch: undefined },
1548
+ {
1549
+ reason: "not-allowed",
1550
+ source: { userPermissions: { removeSourceBranch: false } },
1551
+ branch: undefined,
1552
+ },
1553
+ { reason: "default-branch", source: {}, branch: { default: true, commit: { id: "head" } } },
1554
+ { reason: "head-changed", source: {}, branch: { default: false, commit: { id: "newer" } } },
1555
+ ])("refuses to delete the source branch when it is $reason", ({ reason, source, branch }) =>
1556
+ Effect.gen(function* () {
1557
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(sourceBranchJson(source))));
1558
+ if (branch !== undefined) {
1559
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify(branch))));
1560
+ }
1561
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1562
+
1563
+ const error = yield* cli
1564
+ .runMergeRequestAction({
1565
+ cwd: "/w",
1566
+ repository: "acme/web",
1567
+ number: 7,
1568
+ action: "delete-branch",
1569
+ })
1570
+ .pipe(Effect.flip);
1571
+
1572
+ expect(error).toMatchObject({ _tag: "GitLabBranchDeletionRefusedError", reason });
1573
+ expect(mockedExecute).toHaveBeenCalledTimes(branch === undefined ? 1 : 2);
1574
+ }),
1575
+ );
1576
+
1577
it.effect("reads who has access to the project and who is already on the merge request", () =>
1578
Effect.gen(function* () {
1579
mockedExecute
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+146
-1
@@ -1,8 +1,10 @@
1
import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
2
import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils";
3
import * as Context from "effect/Context";
4
+import * as DateTime from "effect/DateTime";
5
import * as Effect from "effect/Effect";
6
import * as Layer from "effect/Layer";
7
+import * as Option from "effect/Option";
8
import * as Result from "effect/Result";
9
import * as Schema from "effect/Schema";
10
import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";
@@ -33,6 +35,7 @@ import * as GitLabCli from "./GitLabCli.ts";
35
import {
36
AWARD_EMOJI_GRAPHQL_QUERY,
37
decodeAwardEmojiJson,
38
+ decodeBranchJson,
39
decodeCommitDiffRefsJson,
40
decodeCommitsJson,
41
decodeDiffRefsJson,
@@ -53,6 +56,7 @@ import {
56
decodeProjectUsersJson,
57
decodeRepositoryBlobsJson,
58
decodeReviewDecisionsJson,
59
+ decodeSourceBranchJson,
60
decodeTriggerJobChecksJson,
61
decodeViewerJson,
62
gitLabAwardName,
@@ -62,6 +66,7 @@ import {
66
MERGE_REQUEST_STATS_GRAPHQL_QUERY,
67
REPOSITORY_BLOBS_GRAPHQL_QUERY,
68
REVIEW_DECISIONS_GRAPHQL_QUERY,
69
+ SOURCE_BRANCH_GRAPHQL_QUERY,
70
type GitLabDiffRefs,
71
type GitLabMergeRequestDetail,
72
type GitLabMergeRequestListItem,
@@ -193,6 +198,41 @@ export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<G
198
}
199
}
200
201
+export class GitLabBranchDeletionRefusedError extends Schema.TaggedError<GitLabBranchDeletionRefusedError>()(
202
+ "GitLabBranchDeletionRefusedError",
203
+ {
204
+ command: Schema.Literal("glab"),
205
+ cwd: Schema.String,
206
+ number: Schema.Int,
207
+ reason: Schema.Literals([
208
+ "open",
209
+ "not-allowed",
210
+ "source-unavailable",
211
+ "default-branch",
212
+ "head-changed",
213
+ ]),
214
+ },
215
+) {
216
+ get detail(): string {
217
+ switch (this.reason) {
218
+ case "open":
219
+ return `Close or merge merge request !${this.number} before deleting its source branch.`;
220
+ case "not-allowed":
221
+ return "GitLab does not let you delete this source branch. It may be protected, or you may not be able to push to it.";
222
+ case "source-unavailable":
223
+ return `GitLab did not report a source project for merge request !${this.number}.`;
224
+ case "default-branch":
225
+ return "The source branch is its project's default branch and cannot be deleted here.";
226
+ case "head-changed":
227
+ return "The source branch has new commits and was not deleted.";
228
+ }
229
+ }
230
+
231
+ override get message(): string {
232
+ return `GitLab CLI failed in deleteSourceBranch: ${this.detail}`;
233
+ }
234
+}
235
+
236
export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLabelError>()(
237
"GitLabUnknownLabelError",
238
{
@@ -212,6 +252,7 @@ export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLab
252
253
export type GitLabPullRequestCliError =
254
| GitLabCli.GitLabCliError
255
+ | GitLabBranchDeletionRefusedError
256
| GitLabMergeRequestReadError
257
| GitLabUnknownLabelError
258
| GitLabDiffCursorError
@@ -657,6 +698,7 @@ export const make = Effect.gen(function* () {
698
readonly path: string;
699
readonly method?: string;
700
readonly stdin?: string;
701
+ readonly headers?: ReadonlyArray<string>;
702
readonly maxOutputBytes?: number;
703
readonly timeoutMs?: number;
704
}) =>
@@ -671,6 +713,7 @@ export const make = Effect.gen(function* () {
713
...(input.stdin === undefined
714
? []
715
: ["--input", "-", "--header", "Content-Type: application/json"]),
716
+ ...(input.headers ?? []).flatMap((header) => ["--header", header]),
717
],
718
...(input.stdin === undefined ? {} : { stdin: input.stdin }),
719
...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
@@ -1281,6 +1324,88 @@ export const make = Effect.gen(function* () {
1324
),
1325
);
1326
1327
+ const sourceBranch = (input: {
1328
+ readonly cwd: string;
1329
+ readonly host?: string | undefined;
1330
+ readonly repository: string;
1331
+ readonly number: number;
1332
+ }) =>
1333
+ graphqlRead({
1334
+ cwd: input.cwd,
1335
+ host: input.host,
1336
+ operation: "getSourceBranch",
1337
+ query: SOURCE_BRANCH_GRAPHQL_QUERY,
1338
+ variables: { fullPath: input.repository, iid: String(input.number) },
1339
+ decode: decodeSourceBranchJson,
1340
+ });
1341
+
1342
+ const deleteSourceBranch = Effect.fn("GitLabPullRequestCli.deleteSourceBranch")(
1343
+ function* (input: {
1344
+ readonly cwd: string;
1345
+ readonly host?: string | undefined;
1346
+ readonly repository: string;
1347
+ readonly number: number;
1348
+ }) {
1349
+ const refuse = (reason: GitLabBranchDeletionRefusedError["reason"]) =>
1350
+ new GitLabBranchDeletionRefusedError({
1351
+ command: "glab",
1352
+ cwd: input.cwd,
1353
+ number: input.number,
1354
+ reason,
1355
+ });
1356
+ const source = yield* sourceBranch(input);
1357
+ if (source === null) {
1358
+ return yield* new GitLabMergeRequestReadError({
1359
+ command: "glab",
1360
+ cwd: input.cwd,
1361
+ operation: "getSourceBranch",
1362
+ cause: new Error("GitLab reported no merge request."),
1363
+ });
1364
+ }
1365
+ if (source.open) return yield* refuse("open");
1366
+ if (!source.canDelete) return yield* refuse("not-allowed");
1367
+ if (source.sourceProject === null || source.headSha === null) {
1368
+ return yield* refuse("source-unavailable");
1369
+ }
1370
+ const path = `projects/${projectPath(source.sourceProject)}/repository/branches/${encodeURIComponent(source.branch)}`;
1371
+ const branch = yield* api({ cwd: input.cwd, host: input.host, path }).pipe(
1372
+ Effect.flatMap((result) => {
1373
+ const decoded = decodeBranchJson(result.stdout.trim());
1374
+ return Result.isSuccess(decoded)
1375
+ ? Effect.succeed(decoded.success)
1376
+ : Effect.fail(
1377
+ new GitLabMergeRequestReadError({
1378
+ command: "glab",
1379
+ cwd: input.cwd,
1380
+ operation: "getSourceBranch",
1381
+ cause: decoded.failure,
1382
+ }),
1383
+ );
1384
+ }),
1385
+ );
1386
+ if (branch.isDefault) return yield* refuse("default-branch");
1387
+ if (branch.headSha !== source.headSha) return yield* refuse("head-changed");
1388
+ // GitLab's branch delete takes no expected SHA. It answers 412 when the head's authored
1389
+ // date is newer than If-Unmodified-Since, which catches a commit pushed after this read but
1390
+ // not a force-push of an older-dated commit (a rebase keeps author dates).
1391
+ const authoredAt =
1392
+ branch.headAuthoredDate === null ? Option.none() : DateTime.make(branch.headAuthoredDate);
1393
+ yield* api({
1394
+ cwd: input.cwd,
1395
+ host: input.host,
1396
+ path,
1397
+ method: "DELETE",
1398
+ ...(Option.isNone(authoredAt)
1399
+ ? {}
1400
+ : {
1401
+ headers: [
1402
+ `If-Unmodified-Since: ${DateTime.toDateUtc(authoredAt.value).toUTCString()}`,
1403
+ ],
1404
+ }),
1405
+ });
1406
+ },
1407
+ );
1408
+
1409
const mergeRequestStats = (input: {
1410
readonly cwd: string;
1411
readonly host?: string | undefined;
@@ -1472,7 +1597,26 @@ export const make = Effect.gen(function* () {
1597
[mergeRequestDetail(input), labelPermission(input)],
1598
{ concurrency: 2 },
1599
);
1475
- const detail = { ...read, viewerCanEditLabels };
1600
+ // Only a closed or merged merge request offers its branch for deletion, so an open one,
1601
+ // the page most often read, skips the extra query.
1602
+ const detail =
1603
+ read.state === "open"
1604
+ ? { ...read, viewerCanEditLabels }
1605
+ : {
1606
+ ...read,
1607
+ viewerCanEditLabels,
1608
+ viewerCanDeleteBranch: yield* sourceBranch(input).pipe(
1609
+ Effect.map((source) => source?.canDelete === true),
1610
+ // The answer gates one optional action; an unusable CLI or account still surfaces.
1611
+ Effect.catchIf(
1612
+ (cause) =>
1613
+ cause._tag !== "GitLabCliUnavailableError" &&
1614
+ cause._tag !== "GitLabCliAuthenticationError" &&
1615
+ cause._tag !== "GitLabCliRateLimitError",
1616
+ () => Effect.succeed(false),
1617
+ ),
1618
+ ),
1619
+ };
1620
if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail;
1621
const downstream = yield* triggerJobChecks({
1622
cwd: input.cwd,
@@ -1820,6 +1964,7 @@ export const make = Effect.gen(function* () {
1964
// `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
1965
// no flag for is asked of GitLab directly through the same `api` passthrough the rest of
1966
// this module writes with.
1967
+ if (input.action === "delete-branch") return yield* deleteSourceBranch(input);
1968
if (input.action === "disable-auto-merge") {
1969
const result = yield* api({
1970
cwd: input.cwd,
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+8
-1
@@ -123,7 +123,13 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
123
124
describe("gitLabViewerPermissions", () => {
125
it("offers everything to a viewer GitLab says can merge", () => {
126
- expect(gitLabViewerPermissions({ viewerCanMerge: true, viewerCanEditLabels: true })).toEqual({
126
+ expect(
127
+ gitLabViewerPermissions({
128
+ viewerCanMerge: true,
129
+ viewerCanDeleteBranch: true,
130
+ viewerCanEditLabels: true,
131
+ }),
132
+ ).toEqual({
133
actions: [
134
"merge",
135
"ready",
@@ -133,6 +139,7 @@ describe("gitLabViewerPermissions", () => {
139
"update-branch",
140
"enable-auto-merge",
141
"disable-auto-merge",
142
+ "delete-branch",
143
],
144
comment: true,
145
resolve: true,
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+6
-2
@@ -27,6 +27,7 @@ const CAPABILITIES: PullRequestCapabilities = {
27
comment: true,
28
actions: [...definition.changeRequestActions],
29
mergeMethods: ["merge", "squash", "rebase"],
30
+ deleteBranch: true,
31
// GitLab has no merge-target-into-source operation.
32
updateMethods: ["rebase"],
33
search: true,
@@ -66,11 +67,14 @@ const MERGE_ACTIONS: ReadonlySet<string> = new Set([
67
/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
68
export function gitLabViewerPermissions(input: {
69
readonly viewerCanMerge: boolean;
70
+ readonly viewerCanDeleteBranch?: boolean;
71
readonly viewerCanEditLabels?: boolean | undefined;
72
}): PullRequestViewerPermissions {
73
return {
72
- actions: CAPABILITIES.actions.filter(
73
- (action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
74
+ actions: CAPABILITIES.actions.filter((action) =>
75
+ action === "delete-branch"
76
+ ? input.viewerCanDeleteBranch === true
77
+ : !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
78
),
79
comment: true,
80
resolve: true,
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+96
@@ -201,6 +201,8 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
201
readonly reviewers: ReadonlyArray<PullRequestActor>;
202
readonly checks: ReadonlyArray<PullRequestCheck>;
203
readonly viewerCanMerge: boolean;
204
+ /** Read only for a closed or merged merge request; absent on an open one. */
205
+ readonly viewerCanDeleteBranch?: boolean;
206
/** Set by the detail read, which asks GraphQL; REST carries no label permission. */
207
readonly viewerCanEditLabels?: boolean;
208
readonly reviewerIds: ReadonlyArray<number>;
@@ -1067,6 +1069,100 @@ export function decodeRepositoryBlobsJson(
1069
return Result.succeed(blobs);
1070
}
1071
1072
+export const SOURCE_BRANCH_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
1073
+ project(fullPath: $fullPath) {
1074
+ mergeRequest(iid: $iid) {
1075
+ state sourceBranch diffHeadSha
1076
+ sourceProject { fullPath }
1077
+ userPermissions { removeSourceBranch }
1078
+ }
1079
+ }
1080
+}`;
1081
+
1082
+const RawSourceBranchSchema = Schema.Struct({
1083
+ data: Schema.Struct({
1084
+ project: Schema.NullOr(
1085
+ Schema.Struct({
1086
+ mergeRequest: Schema.NullOr(
1087
+ Schema.Struct({
1088
+ state: Schema.String,
1089
+ sourceBranch: Schema.String,
1090
+ diffHeadSha: Schema.optional(Schema.NullOr(Schema.String)),
1091
+ sourceProject: Schema.optional(
1092
+ Schema.NullOr(Schema.Struct({ fullPath: Schema.String })),
1093
+ ),
1094
+ userPermissions: Schema.optional(
1095
+ Schema.NullOr(
1096
+ Schema.Struct({
1097
+ removeSourceBranch: Schema.optional(Schema.NullOr(Schema.Boolean)),
1098
+ }),
1099
+ ),
1100
+ ),
1101
+ }),
1102
+ ),
1103
+ }),
1104
+ ),
1105
+ }),
1106
+});
1107
+
1108
+const decodeSourceBranch = decodeJsonResult(RawSourceBranchSchema);
1109
+
1110
+export interface GitLabSourceBranch {
1111
+ readonly open: boolean;
1112
+ readonly branch: string;
1113
+ readonly headSha: string | null;
1114
+ /** Null when the source project is gone or hidden from the viewer, as a deleted fork is. */
1115
+ readonly sourceProject: string | null;
1116
+ /** GitLab's own answer: false once the branch is gone, protected, or out of the viewer's reach. */
1117
+ readonly canDelete: boolean;
1118
+}
1119
+
1120
+export function decodeSourceBranchJson(
1121
+ raw: string,
1122
+): Result.Result<GitLabSourceBranch | null, DecodeFailure> {
1123
+ return Result.map(decodeSourceBranch(raw), (decoded) => {
1124
+ const mergeRequest = decoded.data.project?.mergeRequest;
1125
+ if (mergeRequest == null) return null;
1126
+ return {
1127
+ // `locked` is GitLab's transient state while a merge runs, so only these two are settled.
1128
+ open: mergeRequest.state !== "merged" && mergeRequest.state !== "closed",
1129
+ branch: mergeRequest.sourceBranch,
1130
+ headSha: trimmed(mergeRequest.diffHeadSha),
1131
+ sourceProject: mergeRequest.sourceProject?.fullPath ?? null,
1132
+ canDelete: mergeRequest.userPermissions?.removeSourceBranch === true,
1133
+ };
1134
+ });
1135
+}
1136
+
1137
+const decodeBranch = decodeJsonResult(
1138
+ Schema.Struct({
1139
+ default: Schema.optional(Schema.NullOr(Schema.Boolean)),
1140
+ commit: Schema.optional(
1141
+ Schema.NullOr(
1142
+ Schema.Struct({
1143
+ id: Schema.String,
1144
+ authored_date: Schema.optional(Schema.NullOr(Schema.String)),
1145
+ }),
1146
+ ),
1147
+ ),
1148
+ }),
1149
+);
1150
+
1151
+export function decodeBranchJson(raw: string): Result.Result<
1152
+ {
1153
+ readonly isDefault: boolean;
1154
+ readonly headSha: string | null;
1155
+ readonly headAuthoredDate: string | null;
1156
+ },
1157
+ DecodeFailure
1158
+> {
1159
+ return Result.map(decodeBranch(raw), (branch) => ({
1160
+ isDefault: branch.default === true,
1161
+ headSha: trimmed(branch.commit?.id),
1162
+ headAuthoredDate: trimmed(branch.commit?.authored_date),
1163
+ }));
1164
+}
1165
+
1166
export const MERGE_MESSAGES_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
1167
project(fullPath: $fullPath) {
1168
mergeRequest(iid: $iid) { title squashOnMerge defaultMergeCommitMessage defaultSquashCommitMessage }
packages/source-control-gitlab/src/shared/definition.ts
+1
@@ -56,6 +56,7 @@ export const definition = defineSourceControl({
56
"update-branch",
57
"enable-auto-merge",
58
"disable-auto-merge",
59
+ "delete-branch",
60
] as const),
61
checkoutCommand: ({ number }) => `glab mr checkout ${number}`,
62
changeRequestCloseCommand: /\bglab\s+mr\s+(?:merge|close)\b/u,