Skip to content

Commit 1264c20

Browse files
fix(server): worktree launches refuse branch names an existing branch blocks (pingdotgg#29328)
1 parent 6464729 commit 1264c20

8 files changed

Lines changed: 252 additions & 66 deletions

File tree

‎apps/server/src/mcp/toolkits/project/handlers.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,44 @@ it.effect("a launch into a new worktree creates nothing when its base ref has no
604604
}),
605605
);
606606

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+
607645
it.effect("a retried worktree launch replays after its base ref is gone", () =>
608646
Effect.gen(function* () {
609647
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];

‎apps/server/src/mcp/toolkits/project/handlers.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,28 @@ function projectFailure(error: Project.ProjectServiceError) {
4848
return new OrchestratorMcpFailure({ code: "invalid_request", message });
4949
}
5050

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+
5173
/** Require project worktrees so launches cannot target arbitrary host directories. */
5274
const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (
5375
workspaceRoot: string,
@@ -160,7 +182,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
160182
if (provider !== undefined)
161183
yield* OrchestrationMcp.requireAdvertisedModel(provider, model);
162184
}
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.
164186
const strategy = input.workspaceStrategy;
165187
if (!replaying && strategy?.type === "worktree")
166188
yield* ThreadLaunch.ThreadLaunchService.pipe(
@@ -171,14 +193,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
171193
(error) =>
172194
new OrchestratorMcpFailure({
173195
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)}`,
182197
}),
183198
),
184199
);

‎apps/server/src/orchestration-v2/ThreadLaunchService.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ function makeHarness(options: HarnessOptions = {}) {
213213
resolveWorktreeBaseRemote: () => Effect.succeed({ remoteName: "origin", branchName: "main" }),
214214
remoteExists: options.remoteExists ?? (() => Effect.succeed(true)),
215215
remoteBranchExists: () => Effect.succeed(true),
216+
listLocalBranchNames: () => Effect.succeed([]),
216217
removeWorktree,
217218
deleteLocalBranch,
218219
...options.git,
@@ -2516,6 +2517,40 @@ it.effect.each([
25162517
}),
25172518
);
25182519

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+
25192554
it.effect("replays an accepted send after the project disables the instance", () => {
25202555
const harness = makeHarness();
25212556
const layerFiles = ServerConfig.layerTest(process.cwd(), { prefix: "t3-send-retry-" }).pipe(

‎apps/server/src/orchestration-v2/ThreadLaunchService.ts‎

Lines changed: 64 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,20 @@ export class ThreadLaunchBaseRefError extends Schema.TaggedError<ThreadLaunchBas
166166
}
167167
}
168168

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+
169183
export class ThreadLaunchNotRepositoryError extends Schema.TaggedError<ThreadLaunchNotRepositoryError>()(
170184
"ThreadLaunchNotRepositoryError",
171185
{
@@ -188,10 +202,16 @@ export class ThreadLaunchService extends Context.Service<
188202
ThreadLaunchResult,
189203
ThreadLaunchError | ThreadManagement.ThreadManagementProviderInstanceDisabledError
190204
>;
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. */
192206
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+
>;
195215
readonly retryPreparation: (
196216
input: ThreadLaunchPreparationInput,
197217
) => Effect.Effect<
@@ -279,6 +299,12 @@ const make = Effect.gen(function* () {
279299
// launch() turns a Scratch worktree request into a root launch.
280300
if (strategy.type !== "worktree" || (yield* managedFolders.isScratchProject(input.projectId)))
281301
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+
}
282308
const project = Option.getOrUndefined(
283309
yield* projects.getById(input.projectId).pipe(Effect.orElseSucceed(() => Option.none())),
284310
);
@@ -293,29 +319,44 @@ const make = Effect.gen(function* () {
293319
projectTitle: project.title,
294320
workspaceRoot: cwd,
295321
});
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)
313340
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,
317344
baseRef,
318345
});
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+
});
319360
});
320361

321362
const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,7 @@ it.effect.each(["bare", "unborn"] as const)(
609609
assert.equal(Result.isSuccess(result), state === "bare");
610610
if (Result.isFailure(result)) {
611611
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");
613613
}
614614
assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
615615
assert.isFalse(spawnedArgs.some((args) => args[0] === "symbolic-ref"));
@@ -1973,7 +1973,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
19731973

19741974
it.effect.each([
19751975
{ 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" },
19771977
{ action: "switch", detail: "git checkout failed" },
19781978
])(
19791979
"reports a missing ref during $action with stable, redacted diagnostics",
@@ -4874,6 +4874,28 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
48744874
}),
48754875
);
48764876

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+
48774899
// regression: #28354 a failed worktree add left its new branch behind and blocked retries
48784900
it.effect("removes the new branch when the worktree cannot be added", () =>
48794901
Effect.gen(function* () {

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,8 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFai
450450
[/would clobber existing tag/i, "tag_would_be_clobbered"],
451451
[/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],
452452
[/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"],
453455
// The same prefix also reports permission errors, which retrying cannot fix.
454456
[/could not lock config file .+: File exists/i, "config_locked"],
455457
[
@@ -4388,7 +4390,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
43884390
yield* createBranchAt(
43894391
"GitVcsDriver.createWorktree.createBranch",
43904392
{ cwd: input.cwd, branch: newRefName, startPoint: input.refName },
4391-
"git worktree add failed",
4393+
"git branch failed",
43924394
);
43934395
}
43944396
const checkoutRef = newRefName ?? input.refName;

0 commit comments

Comments
 (0)