The best way to control Claude Code, Codex and more from any computer or phone
fix(server): worktree launches refuse branch names an existing branch blocks (#29328)
Julius Marminge committed
Nov 11, 2026 at 14:13 UTC
1264c206aee0dce805d6279809118bc091f29d2f
8 files changed
+252
-66
apps/server/src/mcp/toolkits/project/handlers.test.ts
+38
@@ -604,6 +604,44 @@ it.effect("a launch into a new worktree creates nothing when its base ref has no
604
}),
605
);
606
607
+it.effect("a launch into a new worktree creates nothing when its branch collides", () =>
608
+ Effect.gen(function* () {
609
+ const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
610
+ const { projectId, dependencies } = clientLaunchHarness({
611
+ runtimeModeCeiling: "auto",
612
+ launched,
613
+ checkWorktreeBase: ({ projectId, workspaceStrategy }) =>
614
+ Effect.fail(
615
+ new ThreadLaunch.ThreadLaunchBranchConflictError({
616
+ projectId,
617
+ projectTitle: "Client target",
618
+ branch: workspaceStrategy.branch ?? "",
619
+ conflictingBranch: "werkstatt",
620
+ }),
621
+ ),
622
+ });
623
+ const toolkit = yield* ProjectToolkit.pipe(
624
+ Effect.provide(
625
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
626
+ ),
627
+ );
628
+ const refused = (yield* toolkit
629
+ .handle("t3_thread_launch", {
630
+ title: "Fix",
631
+ projectId,
632
+ workspaceStrategy: { type: "worktree", baseRef: "main", branch: "werkstatt/baseline" },
633
+ })
634
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies))).at(-1)?.result;
635
+
636
+ expect(refused).toMatchObject({
637
+ code: "invalid_request",
638
+ message:
639
+ 'Branch "werkstatt/baseline" cannot be created in project "Client target": branch "werkstatt" exists. No thread was created. Use a name that does not nest under or contain an existing branch, such as "werkstatt-baseline".',
640
+ });
641
+ expect(launched).toHaveLength(0);
642
+ }),
643
+);
644
+
645
it.effect("a retried worktree launch replays after its base ref is gone", () =>
646
Effect.gen(function* () {
647
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
apps/server/src/mcp/toolkits/project/handlers.ts
+24
-9
@@ -48,6 +48,28 @@ function projectFailure(error: Project.ProjectServiceError) {
48
return new OrchestratorMcpFailure({ code: "invalid_request", message });
49
}
50
51
+function worktreeCheckHint(
52
+ error:
53
+ | ThreadLaunch.ThreadLaunchBaseRefError
54
+ | ThreadLaunch.ThreadLaunchBranchConflictError
55
+ | ThreadLaunch.ThreadLaunchNotRepositoryError,
56
+ strategy: { readonly startFromOrigin?: boolean | undefined },
57
+) {
58
+ if (error._tag === "ThreadLaunchNotRepositoryError")
59
+ return `Use workspaceStrategy: {type: "root"}, or pass the projectId of a Git repository.`;
60
+ if (error._tag === "ThreadLaunchBranchConflictError") {
61
+ const sibling = error.branch.replaceAll("/", "-");
62
+ return `Use a name that does not nest under or contain an existing branch${
63
+ sibling === error.branch ? "" : `, such as "${sibling}"`
64
+ }.`;
65
+ }
66
+ return `Pass a branch, tag, or commit that exists there${
67
+ strategy.startFromOrigin === true
68
+ ? "; the project has no usable remote to fetch it from."
69
+ : ", or set startFromOrigin:true if it exists only on a remote."
70
+ }`;
71
+}
72
+
73
/** Require project worktrees so launches cannot target arbitrary host directories. */
74
const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (
75
workspaceRoot: string,
@@ -160,7 +182,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
182
if (provider !== undefined)
183
yield* OrchestrationMcp.requireAdvertisedModel(provider, model);
184
}
163
- // Reject unresolved base refs before accepting a launch; worktree provisioning happens later.
185
+ // Reject unresolved base refs and blocked branch names before accepting a launch; worktree provisioning happens later.
186
const strategy = input.workspaceStrategy;
187
if (!replaying && strategy?.type === "worktree")
188
yield* ThreadLaunch.ThreadLaunchService.pipe(
@@ -171,14 +193,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
193
(error) =>
194
new OrchestratorMcpFailure({
195
code: "invalid_request",
174
- message:
175
- error._tag === "ThreadLaunchNotRepositoryError"
176
- ? `${error.message} No thread was created. Use workspaceStrategy: {type: "root"}, or pass the projectId of a Git repository.`
177
- : `${error.message} No thread was created. Pass a branch, tag, or commit that exists there${
178
- strategy.startFromOrigin === true
179
- ? "; the project has no usable remote to fetch it from."
180
- : ", or set startFromOrigin:true if it exists only on a remote."
181
- }`,
196
+ message: `${error.message} No thread was created. ${worktreeCheckHint(error, strategy)}`,
197
}),
198
),
199
);
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+35
@@ -213,6 +213,7 @@ function makeHarness(options: HarnessOptions = {}) {
213
resolveWorktreeBaseRemote: () => Effect.succeed({ remoteName: "origin", branchName: "main" }),
214
remoteExists: options.remoteExists ?? (() => Effect.succeed(true)),
215
remoteBranchExists: () => Effect.succeed(true),
216
+ listLocalBranchNames: () => Effect.succeed([]),
217
removeWorktree,
218
deleteLocalBranch,
219
...options.git,
@@ -2516,6 +2517,40 @@ it.effect.each([
2517
}),
2518
);
2519
2520
+it.effect.each([
2521
+ { requested: "werkstatt/baseline", blocking: "werkstatt" },
2522
+ { requested: "foo", blocking: "foo/bar" },
2523
+])("refuses a new worktree branch $requested that collides with branch $blocking", (testCase) =>
2524
+ Effect.gen(function* () {
2525
+ const harness = makeHarness({
2526
+ hasCommit: () => Effect.succeed(true),
2527
+ git: { listLocalBranchNames: () => Effect.succeed(["main", "werkstatt", "foo/bar"]) },
2528
+ });
2529
+ yield* Effect.gen(function* () {
2530
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
2531
+ const workspace = { type: "worktree" as const, baseRef: "main", branch: testCase.requested };
2532
+ const commandId = CommandId.make("launch:branch-conflict");
2533
+ const check = (branch: string) =>
2534
+ launches.checkWorktreeBase({
2535
+ commandId,
2536
+ projectId,
2537
+ workspaceStrategy: { ...workspace, branch },
2538
+ });
2539
+ yield* check("werkstatt-baseline");
2540
+ const error = yield* check(testCase.requested).pipe(Effect.flip);
2541
+ assert.deepInclude(error, {
2542
+ _tag: "ThreadLaunchBranchConflictError",
2543
+ branch: testCase.requested,
2544
+ conflictingBranch: testCase.blocking,
2545
+ });
2546
+ yield* launches.launch(
2547
+ launchInput({ command: commandId, thread: "thread:branch-conflict", workspace }),
2548
+ );
2549
+ yield* check(testCase.requested);
2550
+ }).pipe(Effect.provide(harness.layer));
2551
+ }),
2552
+);
2553
+
2554
it.effect("replays an accepted send after the project disables the instance", () => {
2555
const harness = makeHarness();
2556
const layerFiles = ServerConfig.layerTest(process.cwd(), { prefix: "t3-send-retry-" }).pipe(
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+64
-23
@@ -166,6 +166,20 @@ export class ThreadLaunchBaseRefError extends Schema.TaggedError<ThreadLaunchBas
166
}
167
}
168
169
+export class ThreadLaunchBranchConflictError extends Schema.TaggedError<ThreadLaunchBranchConflictError>()(
170
+ "ThreadLaunchBranchConflictError",
171
+ {
172
+ projectId: ProjectId,
173
+ projectTitle: Schema.String,
174
+ branch: Schema.String,
175
+ conflictingBranch: Schema.String,
176
+ },
177
+) {
178
+ override get message(): string {
179
+ return `Branch "${this.branch}" cannot be created in project "${this.projectTitle}": branch "${this.conflictingBranch}" exists.`;
180
+ }
181
+}
182
+
183
export class ThreadLaunchNotRepositoryError extends Schema.TaggedError<ThreadLaunchNotRepositoryError>()(
184
"ThreadLaunchNotRepositoryError",
185
{
@@ -188,10 +202,16 @@ export class ThreadLaunchService extends Context.Service<
202
ThreadLaunchResult,
203
ThreadLaunchError | ThreadManagement.ThreadManagementProviderInstanceDisabledError
204
>;
191
- /** Check before creation for early errors; launch otherwise accepts and reports base failures inside the thread. */
205
+ /** Check a new worktree's base ref and branch name before creation for early errors; launch otherwise accepts and reports these failures inside the thread. */
206
readonly checkWorktreeBase: (
193
- input: Pick<ThreadLaunchInput, "projectId" | "workspaceStrategy">,
194
- ) => Effect.Effect<void, ThreadLaunchBaseRefError | ThreadLaunchNotRepositoryError>;
207
+ input: Pick<ThreadLaunchInput, "projectId" | "workspaceStrategy"> & {
208
+ /** Skips the check when this launch was already accepted, so its retry replays. */
209
+ readonly commandId?: CommandId;
210
+ },
211
+ ) => Effect.Effect<
212
+ void,
213
+ ThreadLaunchBaseRefError | ThreadLaunchBranchConflictError | ThreadLaunchNotRepositoryError
214
+ >;
215
readonly retryPreparation: (
216
input: ThreadLaunchPreparationInput,
217
) => Effect.Effect<
@@ -279,6 +299,12 @@ const make = Effect.gen(function* () {
299
// launch() turns a Scratch worktree request into a root launch.
300
if (strategy.type !== "worktree" || (yield* managedFolders.isScratchProject(input.projectId)))
301
return;
302
+ if (input.commandId !== undefined) {
303
+ const receipt = yield* receipts
304
+ .getByCommandId(input.commandId)
305
+ .pipe(Effect.orElseSucceed(() => Option.none()));
306
+ if (Option.isSome(receipt) && receipt.value.status === "accepted") return;
307
+ }
308
const project = Option.getOrUndefined(
309
yield* projects.getById(input.projectId).pipe(Effect.orElseSucceed(() => Option.none())),
310
);
@@ -293,29 +319,44 @@ const make = Effect.gen(function* () {
319
projectTitle: project.title,
320
workspaceRoot: cwd,
321
});
296
- // `:/text` is a commit search, which cannot be asked for a commit type.
297
- if (strategy.baseRef.startsWith(":")) return;
298
- const { baseRef } = strategy;
299
- const unresolved = yield* Effect.gen(function* () {
300
- // `git worktree add` reads `-` as the previous checkout.
301
- if (yield* git.hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef }))
302
- return undefined;
303
- if (
304
- strategy.startFromOrigin === true &&
305
- (yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef })) !== null
306
- )
307
- return undefined;
308
- // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists.
309
- if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return undefined;
310
- return (yield* git.hasCommit({ cwd, refName: "HEAD" })) ? project : undefined;
311
- }).pipe(Effect.orElseSucceed(() => undefined));
312
- if (unresolved !== undefined)
322
+ const { baseRef, branch } = strategy;
323
+ const baseResolves =
324
+ // `:/text` is a commit search, which cannot be asked for a commit type.
325
+ baseRef.startsWith(":") ||
326
+ (yield* Effect.gen(function* () {
327
+ // `git worktree add` reads `-` as the previous checkout.
328
+ if (yield* git.hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef }))
329
+ return true;
330
+ if (
331
+ strategy.startFromOrigin === true &&
332
+ (yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef })) !== null
333
+ )
334
+ return true;
335
+ // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists.
336
+ if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return true;
337
+ return !(yield* git.hasCommit({ cwd, refName: "HEAD" }));
338
+ }).pipe(Effect.orElseSucceed(() => true)));
339
+ if (!baseResolves)
340
return yield* new ThreadLaunchBaseRefError({
314
- projectId: unresolved.id,
315
- projectTitle: unresolved.title,
316
- workspaceRoot: unresolved.workspaceRoot,
341
+ projectId: project.id,
342
+ projectTitle: project.title,
343
+ workspaceRoot: project.workspaceRoot,
344
baseRef,
345
});
346
+ // Provisioning flattens temporary names that collide, so only explicit names are refused.
347
+ if (branch === undefined || isTemporaryWorktreeBranch(branch)) return;
348
+ const conflictingBranch = (yield* git
349
+ .listLocalBranchNames(cwd)
350
+ .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).find(
351
+ (existing) => existing.startsWith(`${branch}/`) || branch.startsWith(`${existing}/`),
352
+ );
353
+ if (conflictingBranch !== undefined)
354
+ return yield* new ThreadLaunchBranchConflictError({
355
+ projectId: project.id,
356
+ projectTitle: project.title,
357
+ branch,
358
+ conflictingBranch,
359
+ });
360
});
361
362
const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
apps/server/src/vcs/GitVcsDriverCore.test.ts
+24
-2
@@ -609,7 +609,7 @@ it.effect.each(["bare", "unborn"] as const)(
609
assert.equal(Result.isSuccess(result), state === "bare");
610
if (Result.isFailure(result)) {
611
assert.equal(result.failure.operation, "GitVcsDriver.createWorktree.createBranch");
612
- assert.equal(result.failure.detail, "git worktree add failed");
612
+ assert.equal(result.failure.detail, "git branch failed");
613
}
614
assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
615
assert.isFalse(spawnedArgs.some((args) => args[0] === "symbolic-ref"));
@@ -1973,7 +1973,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
1973
1974
it.effect.each([
1975
{ action: "worktree add", detail: "git worktree add failed" },
1976
- { action: "worktree add -b", detail: "git worktree add failed" },
1976
+ { action: "worktree add -b", detail: "git branch failed" },
1977
{ action: "switch", detail: "git checkout failed" },
1978
])(
1979
"reports a missing ref during $action with stable, redacted diagnostics",
@@ -4874,6 +4874,28 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4874
}),
4875
);
4876
4877
+ it.effect("explains a new branch that collides with an existing branch namespace", () =>
4878
+ Effect.gen(function* () {
4879
+ const cwd = yield* makeTmpDir();
4880
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
4881
+ yield* git(cwd, ["branch", "werkstatt"]);
4882
+ const path = yield* Path.Path;
4883
+ const driver = yield* GitVcsDriver.GitVcsDriver;
4884
+ const error = yield* driver
4885
+ .createWorktree({
4886
+ cwd,
4887
+ path: path.join(yield* makeTmpDir("git-worktrees-"), "conflict"),
4888
+ refName: initialBranch,
4889
+ newRefName: "werkstatt/baseline",
4890
+ })
4891
+ .pipe(Effect.flip);
4892
+
4893
+ assert.equal(error._tag, "GitCommandError");
4894
+ assert.equal(error.operation, "GitVcsDriver.createWorktree.createBranch");
4895
+ assert.equal(error.reason, "ref_name_conflict");
4896
+ }),
4897
+ );
4898
+
4899
// regression: #28354 a failed worktree add left its new branch behind and blocked retries
4900
it.effect("removes the new branch when the worktree cannot be added", () =>
4901
Effect.gen(function* () {
apps/server/src/vcs/GitVcsDriverCore.ts
+3
-1
@@ -450,6 +450,8 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFai
450
[/would clobber existing tag/i, "tag_would_be_clobbered"],
451
[/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],
452
[/a branch named .+ already exists/i, "branch_already_exists"],
453
+ // A ref cannot nest under an existing ref, nor contain one.
454
+ [/'refs\/[^'\n]+' exists; cannot create 'refs\//i, "ref_name_conflict"],
455
// The same prefix also reports permission errors, which retrying cannot fix.
456
[/could not lock config file .+: File exists/i, "config_locked"],
457
[
@@ -4388,7 +4390,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4390
yield* createBranchAt(
4391
"GitVcsDriver.createWorktree.createBranch",
4392
{ cwd: input.cwd, branch: newRefName, startPoint: input.refName },
4391
- "git worktree add failed",
4393
+ "git branch failed",
4394
);
4395
}
4396
const checkoutRef = newRefName ?? input.refName;
apps/server/src/ws.ts
+63
-31
@@ -2108,38 +2108,49 @@ export const layerWsRpc = (
2108
Effect.andThen(
2109
startup
2110
.enqueueCommand(
2111
- ThreadMessageIntake.launchThread({
2112
- commandId: input.commandId,
2113
- ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
2114
- ...(input.reuseExistingThread === undefined
2115
- ? {}
2116
- : { reuseExistingThread: input.reuseExistingThread }),
2117
- projectId: input.projectId,
2118
- title: input.title,
2119
- ...(input.generateTitle === undefined
2120
- ? {}
2121
- : { generateTitle: input.generateTitle }),
2122
- modelSelection: input.modelSelection,
2123
- runtimeMode: input.runtimeMode,
2124
- interactionMode: input.interactionMode,
2125
- workspaceStrategy: input.workspaceStrategy,
2126
- ...(input.initialMessage === undefined
2127
- ? {}
2128
- : {
2129
- initialMessage: {
2130
- ...(input.initialMessage.messageId === undefined
2131
- ? {}
2132
- : { messageId: input.initialMessage.messageId }),
2133
- text: input.initialMessage.text,
2134
- attachments: input.initialMessage.attachments,
2135
- ...(input.initialMessage.context === undefined
2136
- ? {}
2137
- : { context: input.initialMessage.context }),
2138
- },
2111
+ threadLaunch
2112
+ .checkWorktreeBase({
2113
+ commandId: input.commandId,
2114
+ projectId: input.projectId,
2115
+ workspaceStrategy: input.workspaceStrategy,
2116
+ })
2117
+ .pipe(
2118
+ Effect.andThen(
2119
+ ThreadMessageIntake.launchThread({
2120
+ commandId: input.commandId,
2121
+ ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
2122
+ ...(input.reuseExistingThread === undefined
2123
+ ? {}
2124
+ : { reuseExistingThread: input.reuseExistingThread }),
2125
+ projectId: input.projectId,
2126
+ title: input.title,
2127
+ ...(input.generateTitle === undefined
2128
+ ? {}
2129
+ : { generateTitle: input.generateTitle }),
2130
+ modelSelection: input.modelSelection,
2131
+ runtimeMode: input.runtimeMode,
2132
+ interactionMode: input.interactionMode,
2133
+ workspaceStrategy: input.workspaceStrategy,
2134
+ ...(input.initialMessage === undefined
2135
+ ? {}
2136
+ : {
2137
+ initialMessage: {
2138
+ ...(input.initialMessage.messageId === undefined
2139
+ ? {}
2140
+ : { messageId: input.initialMessage.messageId }),
2141
+ text: input.initialMessage.text,
2142
+ attachments: input.initialMessage.attachments,
2143
+ ...(input.initialMessage.context === undefined
2144
+ ? {}
2145
+ : { context: input.initialMessage.context }),
2146
+ },
2147
+ }),
2148
+ createdBy: "user",
2149
+ creationSource: input.creationSource ?? "web",
2150
}),
2140
- createdBy: "user",
2141
- creationSource: input.creationSource ?? "web",
2142
- }).pipe(Effect.provide(intakeContext)),
2151
+ ),
2152
+ Effect.provide(intakeContext),
2153
+ ),
2154
)
2155
.pipe(
2156
// A resumed launch is a retry of one already counted.
@@ -2193,6 +2204,27 @@ export const layerWsRpc = (
2204
message: cause.message,
2205
cause,
2206
}),
2207
+ ThreadLaunchBaseRefError: (cause) =>
2208
+ new OrchestrationV2ThreadLaunchError({
2209
+ commandId: input.commandId,
2210
+ projectId: input.projectId,
2211
+ message: cause.message,
2212
+ cause,
2213
+ }),
2214
+ ThreadLaunchBranchConflictError: (cause) =>
2215
+ new OrchestrationV2ThreadLaunchError({
2216
+ commandId: input.commandId,
2217
+ projectId: input.projectId,
2218
+ message: cause.message,
2219
+ cause,
2220
+ }),
2221
+ ThreadLaunchNotRepositoryError: (cause) =>
2222
+ new OrchestrationV2ThreadLaunchError({
2223
+ commandId: input.commandId,
2224
+ projectId: input.projectId,
2225
+ message: cause.message,
2226
+ cause,
2227
+ }),
2228
}),
2229
),
2230
),
packages/contracts/src/git.ts
+1
@@ -363,6 +363,7 @@ export const GitCommandFailureReason = Schema.Literals([
363
"path_already_exists",
364
"push_rejected_by_remote",
365
"push_rejected_non_fast_forward",
366
+ "ref_name_conflict",
367
"ref_not_found",
368
"remote_unreachable",
369
"tag_would_be_clobbered",