diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 0bfa616a4f..b687c9221a 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -81,6 +81,9 @@ export class GitWorkflowService extends Context.Service< readonly removeWorktree: ( input: VcsRemoveWorktreeInput, ) => Effect.Effect; + readonly deleteLocalBranch: ( + input: GitVcsDriver.GitDeleteLocalBranchInput, + ) => Effect.Effect; readonly createRef: ( input: VcsCreateRefInput, ) => Effect.Effect; @@ -316,6 +319,10 @@ export const make = Effect.gen(function* () { ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe( Effect.andThen(git.removeWorktree(input)), ), + deleteLocalBranch: (input) => + ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe( + Effect.andThen(git.deleteLocalBranch(input)), + ), createRef: (input) => ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe( Effect.andThen(git.createRef(input)), diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index 1917d9f507..6adf039731 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -109,6 +109,7 @@ interface HarnessOptions { readonly fetchRemoteFails?: boolean; readonly resolveRemoteFails?: boolean; readonly removeWorktreeFails?: boolean; + readonly deleteLocalBranchFails?: boolean; readonly createWorktreeGate?: Effect.Effect; } @@ -201,6 +202,11 @@ const makeHarness = (options: HarnessOptions = {}) => { ? (Effect.fail("simulated worktree removal failure") as never) : Effect.void, ); + const deleteLocalBranch = vi.fn((_: unknown) => + options.deleteLocalBranchFails + ? (Effect.fail("simulated local branch deletion failure") as never) + : Effect.void, + ); const fetchRemote = vi.fn((_: unknown) => options.fetchRemoteFails ? (Effect.fail("simulated fetch failure") as never) : Effect.void, ); @@ -317,6 +323,7 @@ const makeHarness = (options: HarnessOptions = {}) => { resolveRemoteTrackingCommit, createWorktree, removeWorktree, + deleteLocalBranch, } satisfies Partial), Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ runForThread, @@ -338,6 +345,7 @@ const makeHarness = (options: HarnessOptions = {}) => { resolveRemoteTrackingCommit, createWorktree, removeWorktree, + deleteLocalBranch, localStatus, runForThread, }; @@ -403,6 +411,7 @@ describe("t3_worktree_handoff", () => { threadId, branch: "feature/handoff", worktreePath: "/worktrees/project/feature/handoff", + expectedWorktreePath: null, }), ); expect(harness.runForThread).toHaveBeenCalledWith({ @@ -724,6 +733,11 @@ describe("t3_worktree_handoff", () => { path: "/worktrees/project/feature/raced", force: true, }); + expect(harness.deleteLocalBranch).toHaveBeenCalledWith({ + cwd: workspaceRoot, + refName: "feature/raced", + force: true, + }); expect(harness.dispatch).not.toHaveBeenCalled(); }); }); @@ -801,6 +815,23 @@ describe("t3_worktree_handoff", () => { const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/rollback-fails" })); expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); expect(harness.removeWorktree).toHaveBeenCalledTimes(1); + expect(harness.deleteLocalBranch).not.toHaveBeenCalled(); + }); + }); + + it.effect("preserves the typed failure when rollback branch deletion also fails", () => { + const harness = makeHarness({ dispatchFails: true, deleteLocalBranchFails: true }); + return Effect.gen(function* () { + const exit = yield* Effect.exit( + runHandoff(harness, { branch: "feature/rollback-branch-fails" }), + ); + expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); + expect(harness.removeWorktree).toHaveBeenCalledTimes(1); + expect(harness.deleteLocalBranch).toHaveBeenCalledWith({ + cwd: workspaceRoot, + refName: "feature/rollback-branch-fails", + force: true, + }); }); }); diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 1053c9cdeb..c287f68b3b 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -269,9 +269,21 @@ const make = Effect.gen(function* () { }).pipe(Effect.as({ status: "failed", detail } as const)); }); - // suspend: build the removal call only if cleanup actually runs. + // suspend: build the rollback only if cleanup actually runs. Removing + // the worktree must succeed before deleting its freshly created branch; + // otherwise the branch may still be checked out there. const removeCreatedWorktree = Effect.suspend(() => - gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }), + gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe( + Effect.andThen( + Effect.suspend(() => + gitWorkflow.deleteLocalBranch({ + cwd: projectCwd, + refName: worktree.worktree.refName, + force: true, + }), + ), + ), + ), ).pipe(Effect.ignoreCause({ log: true })); const recheckAndBind = Effect.gen(function* () { @@ -299,6 +311,7 @@ const make = Effect.gen(function* () { threadId: scope.threadId, branch: worktree.worktree.refName, worktreePath, + expectedWorktreePath: null, }) .pipe( Effect.catchCause((cause) => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ce1d25bacc..373f841f86 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -912,6 +912,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} is deleted.`, }); } + if ( + command.type === "thread.metadata.update" && + command.expectedWorktreePath !== undefined && + command.expectedWorktreePath !== thread.worktreePath + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} worktree changed before the metadata update could be applied.`, + }); + } if (command.type === "thread.archive" && thread.archivedAt !== null) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 10803a5288..a183b732e8 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -588,6 +588,20 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => { branch: "feature/v2", worktreePath: "/tmp/t3-v2-worktree", }); + const staleWorkspaceUpdate = yield* orchestrator + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("runtime-layer-lifecycle-stale-workspace"), + threadId, + branch: "feature/stale", + worktreePath: "/tmp/stale-worktree", + expectedWorktreePath: null, + }) + .pipe(Effect.flip); + assert.instanceOf(staleWorkspaceUpdate, OrchestratorDispatchError); + const projectionAfterStaleWorkspaceUpdate = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projectionAfterStaleWorkspaceUpdate.thread.branch, "feature/v2"); + assert.equal(projectionAfterStaleWorkspaceUpdate.thread.worktreePath, "/tmp/t3-v2-worktree"); yield* orchestrator.dispatch({ type: "thread.runtime-mode.set", commandId: CommandId.make("runtime-layer-lifecycle-runtime"), diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 55aa8f3883..4a01cbb864 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -113,6 +113,12 @@ export interface GitCommitOptions { readonly progress?: GitCommitProgress; } +export interface GitDeleteLocalBranchInput { + readonly cwd: string; + readonly refName: string; + readonly force?: boolean; +} + export interface GitPushResult { status: "pushed" | "skipped_up_to_date"; branch: string; @@ -253,6 +259,9 @@ export class GitVcsDriver extends Context.Service< readonly removeWorktree: ( input: VcsRemoveWorktreeInput, ) => Effect.Effect; + readonly deleteLocalBranch: ( + input: GitDeleteLocalBranchInput, + ) => Effect.Effect; readonly renameBranch: ( input: GitRenameBranchInput, ) => Effect.Effect; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 941d92cdbf..a97e03038a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1130,7 +1130,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { }), ); - it.effect("creates and removes a worktree for a new refName", () => + it.effect("creates and removes a worktree and its new local branch", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); @@ -1153,8 +1153,14 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "feature/worktree"); yield* driver.removeWorktree({ cwd, path: worktreePath }); + yield* driver.deleteLocalBranch({ + cwd, + refName: "feature/worktree", + force: true, + }); const fileSystem = yield* FileSystem.FileSystem; assert.equal(yield* fileSystem.exists(worktreePath), false); + assert.notInclude(yield* driver.listLocalBranchNames(cwd), "feature/worktree"); }), ); }); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index f739c98da2..b19ed322ef 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2596,6 +2596,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); }); + const deleteLocalBranch: GitVcsDriver.GitVcsDriver["Service"]["deleteLocalBranch"] = Effect.fn( + "deleteLocalBranch", + )(function* (input) { + yield* executeGit( + "GitVcsDriver.deleteLocalBranch", + input.cwd, + ["branch", input.force === true ? "-D" : "-d", "--", input.refName], + { + timeoutMs: 10_000, + fallbackErrorDetail: "git branch delete failed", + }, + ); + }); + const renameBranch: GitVcsDriver.GitVcsDriver["Service"]["renameBranch"] = Effect.fn( "renameBranch", )(function* (input) { @@ -2787,6 +2801,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)), setBranchUpstream: (input) => withListRefsInvalidation(input.cwd, setBranchUpstream(input)), removeWorktree: (input) => withListRefsInvalidation(input.cwd, removeWorktree(input)), + deleteLocalBranch: (input) => withListRefsInvalidation(input.cwd, deleteLocalBranch(input)), renameBranch: (input) => withListRefsInvalidation(input.cwd, renameBranch(input)), createRef: (input) => withListRefsInvalidation(input.cwd, createRef(input)), switchRef: (input) => withListRefsInvalidation(input.cwd, switchRef(input)), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index bacaf67022..d1b8986eb5 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1850,6 +1850,7 @@ export const OrchestrationV2Command = Schema.Union([ title: Schema.optional(TrimmedNonEmptyString), branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), }), Schema.Struct({ type: Schema.Literal("thread.runtime-mode.set"),