From f731109fa28a8104f09b1333e0fb9b797bb529ad Mon Sep 17 00:00:00 2001 From: "ROB-PC\\robho" Date: Mon, 9 Nov 2026 14:07:40 +0000 Subject: [PATCH 1/5] fix(server): agents can release their own worktree with t3_worktree_release An agent had no supported way to drop its thread's worktree once its work was done, so it ran `git worktree remove` by hand. On Windows that failed on long paths and on the folder its own session held, and the thread stayed bound to the merged branch, so the next turn recreated the checkout. t3_worktree_release refuses on uncommitted changes or commits on no remote or other branch unless forced, clears the thread's binding (which detaches the session), then removes the worktree in the background once the session has exited, through the driver's removeWorktree and with retries while Windows still holds the folder. It optionally deletes the local branch and keeps a worktree another thread still uses. t3_worktree_status now reports a bound worktree whose folder is gone as missing. Fixes #33370 Co-Authored-By: Claude Opus 5.5 --- .../server/src/mcp/WorktreeMcpService.test.ts | 282 +++++++++++++++++- apps/server/src/mcp/WorktreeMcpService.ts | 259 ++++++++++++++-- .../src/mcp/toolkits/worktree/handlers.ts | 7 + .../server/src/mcp/toolkits/worktree/tools.ts | 18 ++ .../src/provider/AgentContextBudget.test.ts | 2 + packages/client-runtime/src/t3ToolSummary.ts | 7 + .../src/work-log/presentation.ts | 1 + packages/contracts/src/worktreeMcp.ts | 28 ++ packages/shared/src/t3McpToolPresentation.ts | 5 + 9 files changed, 572 insertions(+), 37 deletions(-) diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index 3dc7cc2bcc77a..fcd0a9c1ea800 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -5,9 +5,11 @@ import { CommandId, EnvironmentId, type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadShell, type Project, ProjectId, ProviderInstanceId, + ProviderSessionId, ThreadId, WorktreeMcpHandoffInput, } from "@t3tools/contracts"; @@ -21,8 +23,10 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ServerConfig from "../config.ts"; import { @@ -76,7 +80,12 @@ const makeProjection = (overrides: ThreadFixture = {}): OrchestrationV2ThreadPro deletedAt: null, ...overrides, }, - }) as OrchestrationV2ThreadProjection; + providerSessions: [ + { + id: ProviderSessionId.make("provider-session-worktree-test"), + }, + ], + }) as unknown as OrchestrationV2ThreadProjection; const project: Project = { id: projectId, @@ -91,6 +100,9 @@ const project: Project = { interface HarnessOptions { readonly git?: Partial; + readonly gitDriver?: Partial; + readonly isLive?: ProviderSessionManager.ProviderSessionManagerV2["Service"]["isLive"]; + readonly otherThreadWorktreePaths?: ReadonlyArray; readonly thread?: ThreadFixture | null; readonly threadReadError?: "projection" | "dispatch"; readonly capabilities?: ReadonlySet; @@ -116,6 +128,8 @@ interface HarnessOptions { readonly deleteLocalBranchFails?: boolean; readonly createWorktreeGate?: Effect.Effect; readonly existsFails?: boolean; + readonly dirty?: boolean; + readonly project?: Partial; } const makeHarness = (options: HarnessOptions = {}) => { @@ -183,7 +197,7 @@ const makeHarness = (options: HarnessOptions = {}) => { ? (Effect.fail("simulated project read failure") as never) : Effect.succeed( id === projectId && options.projectMissing !== true - ? Option.some(project) + ? Option.some({ ...project, ...options.project }) : Option.none(), ), ); @@ -244,7 +258,7 @@ const makeHarness = (options: HarnessOptions = {}) => { hasPrimaryRemote: true, isDefaultRef: false, refName: options.currentBranch === undefined ? "dev" : options.currentBranch, - hasWorkingTreeChanges: false, + hasWorkingTreeChanges: options.dirty === true, workingTree: { files: [], insertions: 0, deletions: 0 }, }), ); @@ -281,6 +295,16 @@ const makeHarness = (options: HarnessOptions = {}) => { Layer.mock(ThreadManagementService.ThreadManagementService)({ dispatch, getThreadRecords, + listProjectThreads: () => + Effect.succeed( + (options.otherThreadWorktreePaths ?? []).map( + (worktreePath, index) => + ({ + id: ThreadId.make(`thread-sharing-${index}`), + worktreePath, + }) as OrchestrationV2ThreadShell, + ), + ), } satisfies Partial), Layer.mock(ProjectService.ProjectService)({ getById, @@ -307,6 +331,20 @@ const makeHarness = (options: HarnessOptions = {}) => { deleteLocalBranch, ...options.git, } satisfies Partial), + Layer.mock(GitVcsDriver.GitVcsDriver)({ + execute: () => + Effect.succeed({ + exitCode: 0 as GitVcsDriver.ExecuteGitResult["exitCode"], + stdout: "0\n", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }), + ...options.gitDriver, + } satisfies Partial), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + isLive: options.isLive ?? (() => Effect.succeed(false)), + } satisfies Partial), Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ runForThread, } satisfies Partial), @@ -376,6 +414,15 @@ const runStatus = (harness: ReturnType) => return yield* service.status(harness.scope); }).pipe(Effect.provide(harness.layer)); +const runRelease = ( + harness: ReturnType, + input: Parameters[1] = {}, +) => + Effect.gen(function* () { + const service = yield* WorktreeMcpService.WorktreeMcpService; + return yield* service.release(harness.scope, input); + }).pipe(Effect.provide(harness.layer)); + const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput); describe("t3_worktree_handoff", () => { @@ -680,23 +727,232 @@ describe("t3_worktree_handoff", () => { }); }); -describe("t3_worktree_status", () => { - it.effect("reports an attached thread's worktree and branch", () => { - const harness = makeHarness({ - thread: { - worktreePath: "/worktrees/project/existing", - branch: "feature/existing", - }, - projectNewWorktreesStartFromOrigin: true, - }); +describe("t3_worktree_release", () => { + const releaseGitLayer = GitVcsDriver.layer.pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "release-git-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + + it.effect("refuses unpushed commits, then removes the worktree and branch once pushed", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const git = yield* GitVcsDriver.GitVcsDriver; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "release-unpushed-" }); + const cwd = `${directory}/repo`; + const remote = `${directory}/remote.git`; + const worktreePath = `${directory}/worktree`; + yield* fs.makeDirectory(cwd); + const command = (at: string, args: string[]) => + git.execute({ operation: "release-test", cwd: at, args }); + yield* command(cwd, ["init", "-b", "main"]); + yield* command(cwd, ["config", "user.name", "Test"]); + yield* command(cwd, ["config", "user.email", "test@example.test"]); + yield* command(cwd, ["commit", "--allow-empty", "-m", "base"]); + yield* command(cwd, ["init", "--bare", remote]); + yield* command(cwd, ["remote", "add", "origin", remote]); + yield* command(cwd, ["push", "-u", "origin", "main"]); + yield* command(cwd, ["worktree", "add", "-b", "feature/done", worktreePath]); + yield* command(worktreePath, ["commit", "--allow-empty", "-m", "work"]); + + const branchDeleted = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + project: { workspaceRoot: cwd }, + gitDriver: { execute: git.execute }, + git: { + localStatus: () => + Effect.succeed({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "feature/done", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + removeWorktree: git.removeWorktree, + deleteLocalBranch: (input) => + git + .deleteLocalBranch(input) + .pipe(Effect.ensuring(Deferred.succeed(branchDeleted, undefined))), + }, + }); + + const refused = yield* Effect.exit(runRelease(harness, { deleteBranch: true })); + expectTypedFailure(refused, { _tag: "WorktreeMcpFailure", code: "unsaved_work" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + + yield* command(worktreePath, ["push", "-u", "origin", "feature/done"]); + const result = yield* runRelease(harness, { deleteBranch: true }); + expect(result).toMatchObject({ worktreePath, branch: "feature/done", removal: "scheduled" }); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: "thread.metadata.update", + worktreePath: null, + branch: null, + expectedWorktreePath: worktreePath, + }), + ); + + yield* Deferred.await(branchDeleted); + expect(yield* fs.exists(worktreePath)).toBe(false); + expect((yield* command(cwd, ["branch", "--list", "feature/done"])).stdout).toBe(""); + }).pipe(Effect.scoped, Effect.provide(releaseGitLayer)), + ); + + it.effect("waits for the caller's provider session to exit before removing", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-session-" }); + const firstCheck = yield* Deferred.make(); + const removed = yield* Deferred.make(); + let liveChecks = 0; + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + isLive: () => Deferred.succeed(firstCheck, undefined).pipe(Effect.as(++liveChecks === 1)), + git: { + removeWorktree: () => Deferred.succeed(removed, undefined).pipe(Effect.asVoid), + }, + }); + + yield* runRelease(harness); + yield* Deferred.await(firstCheck); + expect(yield* Deferred.isDone(removed)).toBe(false); + + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(removed); + expect(liveChecks).toBe(2); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("retries a removal that the folder's last process briefly blocks", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-busy-" }); + const firstAttempt = yield* Deferred.make(); + const removed = yield* Deferred.make(); + let attempts = 0; + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + git: { + removeWorktree: () => + Effect.suspend(() => + ++attempts === 1 + ? Deferred.succeed(firstAttempt, undefined).pipe( + Effect.andThen(Effect.fail("EBUSY" as never)), + ) + : Deferred.succeed(removed, undefined).pipe(Effect.asVoid), + ), + }, + }); + + yield* runRelease(harness); + yield* Deferred.await(firstAttempt); + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(removed); + expect(attempts).toBe(2); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("refuses uncommitted changes unless forced", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-dirty-" }); + const removed = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/dirty" }, + dirty: true, + git: { + removeWorktree: (input) => Deferred.succeed(removed, input).pipe(Effect.asVoid), + }, + }); + + const refused = yield* Effect.exit(runRelease(harness)); + expectTypedFailure(refused, { _tag: "WorktreeMcpFailure", code: "unsaved_work" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + + yield* runRelease(harness, { force: true }); + expect(yield* Deferred.await(removed)).toMatchObject({ path: worktreePath, force: true }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps a worktree that another thread still uses", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-shared-" }); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/shared" }, + otherThreadWorktreePaths: [worktreePath], + dirty: true, + }); + + const result = yield* runRelease(harness); + expect(result.removal).toBe("kept-shared"); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ worktreePath: null }), + ); + expect(harness.localStatus).not.toHaveBeenCalled(); + expect(harness.removeWorktree).not.toHaveBeenCalled(); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("clears the binding of a worktree whose folder is already gone", () => + Effect.gen(function* () { + const removed = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath: "/worktrees/project/removed-by-hand", branch: "feature/gone" }, + git: { + removeWorktree: () => Deferred.succeed(removed, undefined).pipe(Effect.asVoid), + }, + }); + + const result = yield* runRelease(harness); + expect(result.removal).toBe("already-gone"); + expect(harness.localStatus).not.toHaveBeenCalled(); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ worktreePath: null, branch: null }), + ); + // Git still holds the worktree's metadata; removal prunes it. + yield* Deferred.await(removed); + }), + ); + + it.effect("fails when the thread has no worktree", () => { + const harness = makeHarness(); return Effect.gen(function* () { + const exit = yield* Effect.exit(runRelease(harness)); + expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "not_in_worktree" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + }); + }); +}); + +describe("t3_worktree_status", () => { + it.effect("reports an attached thread's worktree and branch", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "worktree-status-" }); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/existing" }, + projectNewWorktreesStartFromOrigin: true, + }); const result = yield* runStatus(harness); expect(result).toMatchObject({ attached: true, - worktreePath: "/worktrees/project/existing", + worktreePath, + missing: false, branch: "feature/existing", defaultStartFromOrigin: true, }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reports a bound worktree whose folder is gone as missing", () => { + const harness = makeHarness({ + thread: { worktreePath: "/worktrees/project/removed-by-hand", branch: "feature/gone" }, + }); + return Effect.gen(function* () { + const result = yield* runStatus(harness); + expect(result).toMatchObject({ attached: true, missing: true }); }); }); }); diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 5d73b864d356b..83645231ac79a 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -3,10 +3,13 @@ import { type GitCommandError, MessageId, type ProjectId, + type ProviderSessionId, WorktreeMcpFailure, type WorktreeMcpContinuationStatus, type WorktreeMcpHandoffInput, type WorktreeMcpHandoffResult, + type WorktreeMcpReleaseInput, + type WorktreeMcpReleaseResult, type WorktreeMcpSetupScriptStatus, type WorktreeMcpStatusResult, type VcsListRefsInput, @@ -21,12 +24,15 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import type * as PlatformError from "effect/PlatformError"; +import * as Schedule from "effect/Schedule"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts"; @@ -37,6 +43,10 @@ export class WorktreeMcpService extends Context.Service< scope: McpInvocationScope, input: WorktreeMcpHandoffInput, ) => Effect.Effect; + readonly release: ( + scope: McpInvocationScope, + input: WorktreeMcpReleaseInput, + ) => Effect.Effect; readonly status: ( scope: McpInvocationScope, ) => Effect.Effect; @@ -66,6 +76,9 @@ const asOperationFailed = (prefix: string) => failure("operation_failed", `${prefix}: ${errorMessage(error)}`), ); +// Covers a provider session that takes a while to exit, and Windows processes that briefly hold the folder. +const RELEASE_RETRY = { times: 60, schedule: Schedule.spaced("2 seconds") } as const; + const make = Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; const fileSystem = yield* FileSystem.FileSystem; @@ -73,18 +86,20 @@ const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const serverSettings = yield* ServerSettings.ServerSettingsService; const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const gitDriver = yield* GitVcsDriver.GitVcsDriver; + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - // Serialize handoffs per thread to avoid creating two worktrees and orphaning one. - const handoffThreadsInFlight = new Set(); + // Serialize handoffs and releases per thread to avoid creating two worktrees and orphaning one. + const threadsInFlight = new Set(); const requireThreadScope = (scope: McpInvocationScope) => scope.thread === undefined ? Effect.fail( failure( "thread_credential_required", - "Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.", + "Worktree handoff, release, and status act as the calling T3 thread, so they need an agent running inside T3 Code.", ), ) : Effect.succeed(scope as McpThreadInvocationScope); @@ -96,8 +111,11 @@ const make = Effect.gen(function* () { failure("capability_denied", "This MCP credential does not grant worktree capabilities."), ); - const loadThread = (scope: McpThreadInvocationScope) => - threadManagement.getThreadRecords(scope.thread.threadId, []).pipe( + const loadThread = ( + scope: McpThreadInvocationScope, + fields: ReadonlyArray<"providerSessions"> = [], + ) => + threadManagement.getThreadRecords(scope.thread.threadId, fields).pipe( Effect.mapError((error) => error._tag === "OrchestratorProjectionError" ? failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`) @@ -397,25 +415,209 @@ const make = Effect.gen(function* () { function* (callerScope, input) { yield* requireCapability(callerScope); const scope = yield* requireThreadScope(callerScope); - // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart. - return yield* Effect.uninterruptibleMask((restore) => - Effect.suspend(() => { - if (handoffThreadsInFlight.has(scope.thread.threadId)) { - return Effect.fail( - failure( - "handoff_in_progress", - `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`, - ), - ); - } - handoffThreadsInFlight.add(scope.thread.threadId); - return restore(performHandoff(scope, input)).pipe( - Effect.ensuring( - Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)), + return yield* exclusive(scope, performHandoff(scope, input)); + }, + ); + + // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart. + const exclusive = ( + scope: McpThreadInvocationScope, + effect: Effect.Effect, + ): Effect.Effect => + Effect.uninterruptibleMask((restore) => + Effect.suspend(() => { + if (threadsInFlight.has(scope.thread.threadId)) { + return Effect.fail( + failure( + "handoff_in_progress", + `A worktree handoff or release is already in progress for thread '${scope.thread.threadId}'.`, ), ); - }), + } + threadsInFlight.add(scope.thread.threadId); + return restore(effect).pipe( + Effect.ensuring(Effect.sync(() => threadsInFlight.delete(scope.thread.threadId))), + ); + }), + ); + + // Runs detached: the binding change ends the caller's session, and on Windows its process holds the folder until it exits. + const removeReleasedWorktree = Effect.fn("WorktreeMcpService.removeReleasedWorktree")( + function* (input: { + readonly projectCwd: string; + readonly worktreePath: string; + readonly branch: string | null; + readonly providerSessionIds: ReadonlyArray; + readonly force: boolean; + readonly deleteBranch: boolean; + }) { + // Removal still runs if a session outlasts the wait; its own retries cover a brief hold. + yield* Effect.forEach(input.providerSessionIds, providerSessions.isLive).pipe( + Effect.filterOrFail( + (live) => !live.includes(true), + () => "provider session is still open", + ), + Effect.retry(RELEASE_RETRY), + Effect.ignore, + ); + yield* gitWorkflow + .removeWorktree({ cwd: input.projectCwd, path: input.worktreePath, force: input.force }) + .pipe(Effect.retry(RELEASE_RETRY)); + if (input.deleteBranch && input.branch !== null) { + yield* gitWorkflow.deleteLocalBranch({ + cwd: input.projectCwd, + refName: input.branch, + force: true, + }); + } + yield* vcsStatusBroadcaster + .refreshStatus(input.projectCwd) + .pipe(Effect.ignoreCause({ log: true })); + }, + (effect, input) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("worktree release could not remove the worktree", { + worktreePath: input.worktreePath, + detail: errorMessage(Cause.squash(cause)), + }), + ), + ), + ); + + const performRelease = Effect.fn("WorktreeMcpService.performRelease")(function* ( + scope: McpThreadInvocationScope, + input: WorktreeMcpReleaseInput, + ) { + const projection = yield* loadThread(scope, ["providerSessions"]); + const worktreePath = projection.thread.worktreePath; + if (worktreePath === null) { + return yield* failure( + "not_in_worktree", + `Thread '${scope.thread.threadId}' is not attached to a worktree.`, + ); + } + const project = yield* loadProject(scope, projection.thread.projectId); + const projectCwd = project.workspaceRoot; + if (worktreePath === projectCwd) { + return yield* failure( + "invalid_request", + `Thread '${scope.thread.threadId}' runs in the project root, not a separate worktree.`, ); + } + const force = input.force === true; + const exists = yield* fileSystem + .exists(worktreePath) + .pipe(asOperationFailed("Unable to check the worktree folder")); + // Subagent threads can share the parent's checkout. + const sharedWith = (yield* threadManagement + .listProjectThreads({ projectId: project.id, includeSubagents: true }) + .pipe(asOperationFailed("Unable to list the project's threads"))).filter( + (thread) => thread.worktreePath === worktreePath && thread.id !== scope.thread.threadId, + ).length; + + let branch = projection.thread.branch; + if (exists && sharedWith === 0) { + const status = yield* gitWorkflow + .localStatus({ cwd: worktreePath }) + .pipe(asOperationFailed("Unable to read the worktree's git status")); + branch = status.refName ?? branch; + if (!force && status.hasWorkingTreeChanges) { + return yield* failure( + "unsaved_work", + `Worktree '${worktreePath}' has uncommitted changes. Commit and push them, or pass force: true to discard them.`, + ); + } + if (!force) { + // Commits only this checkout reaches: on no remote and no other local branch. + const unpushed = yield* gitDriver + .execute({ + operation: "WorktreeMcpService.countUnpushedCommits", + cwd: worktreePath, + args: [ + "rev-list", + "--count", + "HEAD", + "--not", + ...(status.refName === null ? [] : [`--exclude=${status.refName}`]), + "--branches", + "--remotes", + ], + }) + .pipe( + Effect.map((result) => Number.parseInt(result.stdout.trim(), 10)), + asOperationFailed("Unable to count unpushed commits"), + ); + if (unpushed > 0) { + return yield* failure( + "unsaved_work", + `Worktree '${worktreePath}' has ${unpushed} commit${unpushed === 1 ? "" : "s"} on no remote or other branch. Push them, or pass force: true to discard them.`, + ); + } + } + } + + const commandId = yield* random.uuidV4().pipe( + Effect.map((uuid) => + CommandId.make( + [ + "command", + "mcp", + encodeURIComponent(scope.thread.providerSessionId), + "worktree-release", + uuid, + ].join(":"), + ), + ), + Effect.orDie, + ); + const removal: WorktreeMcpReleaseResult["removal"] = + sharedWith > 0 ? "kept-shared" : exists ? "scheduled" : "already-gone"; + + // The binding change detaches the caller, so schedule removal in the same uninterruptible step. + return yield* Effect.uninterruptible( + Effect.gen(function* () { + // Clearing the binding also stops the next turn from recreating the checkout. + yield* threadManagement + .dispatch({ + type: "thread.metadata.update", + commandId, + threadId: scope.thread.threadId, + branch: null, + worktreePath: null, + expectedWorktreePath: worktreePath, + }) + .pipe(asOperationFailed("Unable to re-point the thread at the project root")); + if (removal !== "kept-shared") { + // A folder already gone can still leave Git metadata to prune and a branch to delete. + yield* removeReleasedWorktree({ + projectCwd, + worktreePath, + branch, + providerSessionIds: projection.providerSessions.map((session) => session.id), + force, + deleteBranch: input.deleteBranch === true, + }).pipe(Effect.forkDetach); + } + const result: WorktreeMcpReleaseResult = { + worktreePath, + branch, + removal, + note: + removal === "kept-shared" + ? `Released. The thread now runs in the project root and this session ends shortly after this call. The worktree stays because ${sharedWith} other thread${sharedWith === 1 ? " uses" : "s use"} it.` + : "Released. The thread now runs in the project root and this session ends shortly after this call. T3 removes the worktree once the session has left it. A folder it cannot remove shows up in the storage cleanup report.", + }; + return result; + }), + ); + }); + + const release: WorktreeMcpService["Service"]["release"] = Effect.fn("WorktreeMcpService.release")( + function* (callerScope, input) { + yield* requireCapability(callerScope); + const scope = yield* requireThreadScope(callerScope); + return yield* exclusive(scope, performRelease(scope, input)); }, ); @@ -428,9 +630,16 @@ const make = Effect.gen(function* () { const defaultStartFromOrigin = yield* readDefaultStartFromOrigin(project.id); + // Storage cleanup and manual removal leave the binding behind. + const worktreePath = projection.thread.worktreePath; + const missing = + worktreePath !== null && + !(yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true))); + const result: WorktreeMcpStatusResult = { - attached: projection.thread.worktreePath !== null, - worktreePath: projection.thread.worktreePath, + attached: worktreePath !== null, + worktreePath, + missing, branch: projection.thread.branch, projectWorkspaceRoot: project.workspaceRoot, defaultStartFromOrigin, @@ -450,7 +659,7 @@ const make = Effect.gen(function* () { return yield* gitWorkflow.listRefs({ ...refs, cwd }); }); - return WorktreeMcpService.of({ handoff, status, listRefs }); + return WorktreeMcpService.of({ handoff, release, status, listRefs }); }); export const layer: Layer.Layer< @@ -462,6 +671,8 @@ export const layer: Layer.Layer< | ProjectService.ProjectService | ServerSettings.ServerSettingsService | GitWorkflowService.GitWorkflowService + | GitVcsDriver.GitVcsDriver + | ProviderSessionManager.ProviderSessionManagerV2 | ProjectSetupScriptRunner.ProjectSetupScriptRunner | VcsStatusBroadcaster.VcsStatusBroadcaster > = Layer.effect(WorktreeMcpService, make); diff --git a/apps/server/src/mcp/toolkits/worktree/handlers.ts b/apps/server/src/mcp/toolkits/worktree/handlers.ts index 2e78dd2a4f996..a178d99f032d6 100644 --- a/apps/server/src/mcp/toolkits/worktree/handlers.ts +++ b/apps/server/src/mcp/toolkits/worktree/handlers.ts @@ -46,6 +46,13 @@ const handlers = { return yield* service.handoff(scope, input); }), ), + t3_worktree_release: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const service = yield* WorktreeMcpService.WorktreeMcpService; + return yield* service.release(scope, input); + }), + ), t3_worktree_status: McpToolAccess.readsAsCaller(() => Effect.gen(function* () { const scope = yield* McpInvocationContext.McpInvocationContext; diff --git a/apps/server/src/mcp/toolkits/worktree/tools.ts b/apps/server/src/mcp/toolkits/worktree/tools.ts index ce9dd39f7938f..0c272b435318b 100644 --- a/apps/server/src/mcp/toolkits/worktree/tools.ts +++ b/apps/server/src/mcp/toolkits/worktree/tools.ts @@ -6,6 +6,8 @@ import { VcsListRefsResult, WorktreeMcpHandoffInput, WorktreeMcpHandoffResult, + WorktreeMcpReleaseInput, + WorktreeMcpReleaseResult, WorktreeMcpStatusResult, ThreadId, } from "@t3tools/contracts"; @@ -41,6 +43,21 @@ const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", { .annotate(Tool.OpenWorld, true) .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); +const WorktreeReleaseTool = Tool.make("t3_worktree_release", { + description: + "Remove THIS thread's worktree once its work is done, e.g. PR merged. Never `git worktree remove` it yourself. Moves the thread to the project root; T3 deletes the folder after the session ends. Refuses unsaved or unpushed work unless `force`. Call last in your turn.", + parameters: WorktreeMcpReleaseInput, + success: WorktreeMcpReleaseResult, + failure: WorktreeToolFailure, + failureMode: "return", + dependencies, +}) + .annotate(Tool.Title, "Release thread's git worktree") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, true) + .annotate(Tool.Idempotent, false) + .annotate(Tool.OpenWorld, false); + const WorktreeStatusTool = Tool.make("t3_worktree_status", { description: "Report this thread's worktree: attached or not, path, branch, project root, and the `startFromOrigin` default. Check before `t3_worktree_handoff`.", @@ -86,6 +103,7 @@ const WorktreeListTool = Tool.make("t3_worktree_list", { .annotate(Tool.Destructive, false); export const WorktreeToolkit = Toolkit.make( WorktreeHandoffTool, + WorktreeReleaseTool, WorktreeStatusTool, WorktreeListTool, ); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 2a7d02fc28173..4a63642c8cbe9 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -21,6 +21,7 @@ import { } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; import { ProviderAdapterRegistryV2 } from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import { ProviderSessionManagerV2 } from "../orchestration-v2/ProviderSessionManager.ts"; import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts"; import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts"; import { ThreadSearch } from "../orchestration-v2/ThreadSearch.ts"; @@ -68,6 +69,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(ProjectCloneTracker)({}), Layer.mock(ProjectService)({}), Layer.mock(ProjectSetupScriptRunner)({}), + Layer.mock(ProviderSessionManagerV2)({}), Layer.mock(ProviderAdapterRegistryV2)({}), Layer.mock(ProviderRegistry)({}), Layer.mock(PullRequestReviewGuideService)({}), diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index 107b0bc652555..a757c6cead4b8 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -321,6 +321,13 @@ export function summarizeT3ToolCalls( quantity(countEntities(entityIds("worktreePath")), "worktree"), ); break; + case "worktree-release": + label = phrase( + "Released", + "release", + quantity(countEntities(entityIds("worktreePath")), "worktree"), + ); + break; case "worktree-list": label = phrase("Listed", "list", `workspace branches ${times}`); break; diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index 1b169848e144c..c7157d51f7db0 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -545,6 +545,7 @@ function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction) case "queue-steer": case "question-respond": case "worktree-handoff": + case "worktree-release": case "project-create": case "project-update": case "project-delete": diff --git a/packages/contracts/src/worktreeMcp.ts b/packages/contracts/src/worktreeMcp.ts index 87f45dea27598..3e6019584bdf6 100644 --- a/packages/contracts/src/worktreeMcp.ts +++ b/packages/contracts/src/worktreeMcp.ts @@ -77,6 +77,10 @@ export type WorktreeMcpHandoffResult = typeof WorktreeMcpHandoffResult.Type; export const WorktreeMcpStatusResult = Schema.Struct({ attached: Schema.Boolean, worktreePath: Schema.NullOr(TrimmedNonEmptyString), + missing: Schema.Boolean.annotate({ + description: + "The bound folder is gone. The next turn recreates it; `t3_worktree_release` drops the binding instead.", + }), branch: Schema.NullOr(TrimmedNonEmptyString), projectWorkspaceRoot: TrimmedNonEmptyString, defaultStartFromOrigin: Schema.Boolean.annotate({ @@ -85,6 +89,28 @@ export const WorktreeMcpStatusResult = Schema.Struct({ }); export type WorktreeMcpStatusResult = typeof WorktreeMcpStatusResult.Type; +export const WorktreeMcpReleaseInput = Schema.Struct({ + deleteBranch: Schema.optional( + Schema.Boolean.annotate({ + description: "Also delete the local branch.", + }), + ), + force: Schema.optional( + Schema.Boolean.annotate({ + description: "Discard unsaved and unpushed work.", + }), + ), +}); +export type WorktreeMcpReleaseInput = typeof WorktreeMcpReleaseInput.Type; + +export const WorktreeMcpReleaseResult = Schema.Struct({ + worktreePath: TrimmedNonEmptyString, + branch: Schema.NullOr(TrimmedNonEmptyString), + removal: Schema.Literals(["scheduled", "already-gone", "kept-shared"]), + note: Schema.String, +}); +export type WorktreeMcpReleaseResult = typeof WorktreeMcpReleaseResult.Type; + export class WorktreeMcpFailure extends Schema.TaggedError()( "WorktreeMcpFailure", { @@ -93,6 +119,8 @@ export class WorktreeMcpFailure extends Schema.TaggedError() "thread_not_found", "project_not_found", "already_in_worktree", + "not_in_worktree", + "unsaved_work", "handoff_in_progress", "invalid_request", "operation_failed", diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index a813585b27a6e..22a9083c779c1 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -42,6 +42,7 @@ export type T3McpToolSummaryAction = | "question-respond" | "secret-request" | "worktree-handoff" + | "worktree-release" | "worktree-list" | "worktree-status" | "project-list" @@ -187,6 +188,10 @@ const T3_MCP_TOOLS: Readonly> = { ["Hand off", "Handing off", "Handed off", "thread to a git worktree"], "worktree-handoff", ), + t3_worktree_release: tool( + ["Release", "Releasing", "Released", "the thread's git worktree"], + "worktree-release", + ), t3_worktree_status: tool(["Get", "Getting", "Got", "thread worktree status"], "worktree-status"), preview_status: tool(["Get", "Getting", "Got", "preview browser status"], "browser", "browser"), preview_open: tool( From 6dfeee7c42c28e9c42527f3e49cf6cf3760d69a4 Mon Sep 17 00:00:00 2001 From: "ROB-PC\\robho" Date: Mon, 9 Nov 2026 21:14:51 +0000 Subject: [PATCH 2/5] fix(server): release checks every thread on the worktree and the branch it deletes - Count side chats and archived threads as sharing the worktree, via a shell snapshot filtered by its path, so release never removes a checkout another thread still uses. - With deleteBranch, check the branch itself for unpushed commits from the project root. A detached HEAD or an already removed folder no longer lets a force delete drop them. A branch that is already gone is skipped. - Fail closed when git's commit count is not a number. Co-Authored-By: Claude Opus 5.5 --- .../server/src/mcp/WorktreeMcpService.test.ts | 156 ++++++++++++------ apps/server/src/mcp/WorktreeMcpService.ts | 92 +++++++---- 2 files changed, 167 insertions(+), 81 deletions(-) diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index fcd0a9c1ea800..cd928d3d50eed 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -295,16 +295,22 @@ const makeHarness = (options: HarnessOptions = {}) => { Layer.mock(ThreadManagementService.ThreadManagementService)({ dispatch, getThreadRecords, - listProjectThreads: () => - Effect.succeed( - (options.otherThreadWorktreePaths ?? []).map( - (worktreePath, index) => - ({ - id: ThreadId.make(`thread-sharing-${index}`), - worktreePath, - }) as OrchestrationV2ThreadShell, + getShellSnapshot: (input) => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 1, + threads: (options.otherThreadWorktreePaths ?? []).flatMap((worktreePath, index) => + worktreePath === input?.worktreePath + ? [ + { + id: ThreadId.make(`thread-sharing-${index}`), + worktreePath, + } as OrchestrationV2ThreadShell, + ] + : [], ), - ), + archivedThreads: [], + }), } satisfies Partial), Layer.mock(ProjectService.ProjectService)({ getById, @@ -733,49 +739,58 @@ describe("t3_worktree_release", () => { Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); + // A repository with a pushed main and a worktree on `feature/done` holding one unpushed commit. + const makeReleaseRepo = Effect.fn("makeReleaseRepo")(function* (prefix: string) { + const fs = yield* FileSystem.FileSystem; + const git = yield* GitVcsDriver.GitVcsDriver; + const directory = yield* fs.makeTempDirectoryScoped({ prefix }); + const cwd = `${directory}/repo`; + const remote = `${directory}/remote.git`; + const worktreePath = `${directory}/worktree`; + yield* fs.makeDirectory(cwd); + const command = (at: string, args: string[]) => + git.execute({ operation: "release-test", cwd: at, args }); + yield* command(cwd, ["init", "-b", "main"]); + yield* command(cwd, ["config", "user.name", "Test"]); + yield* command(cwd, ["config", "user.email", "test@example.test"]); + yield* command(cwd, ["commit", "--allow-empty", "-m", "base"]); + yield* command(cwd, ["init", "--bare", remote]); + yield* command(cwd, ["remote", "add", "origin", remote]); + yield* command(cwd, ["push", "-u", "origin", "main"]); + yield* command(cwd, ["worktree", "add", "-b", "feature/done", worktreePath]); + yield* command(worktreePath, ["commit", "--allow-empty", "-m", "work"]); + + const branchDeleted = yield* Deferred.make(); + const removed = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + project: { workspaceRoot: cwd }, + gitDriver: { execute: git.execute }, + git: { + localStatus: () => + Effect.succeed({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "feature/done", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + removeWorktree: (input) => + git.removeWorktree(input).pipe(Effect.ensuring(Deferred.succeed(removed, undefined))), + deleteLocalBranch: (input) => + git + .deleteLocalBranch(input) + .pipe(Effect.ensuring(Deferred.succeed(branchDeleted, undefined))), + }, + }); + return { fs, cwd, worktreePath, command, harness, branchDeleted, removed }; + }); + it.effect("refuses unpushed commits, then removes the worktree and branch once pushed", () => Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const git = yield* GitVcsDriver.GitVcsDriver; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "release-unpushed-" }); - const cwd = `${directory}/repo`; - const remote = `${directory}/remote.git`; - const worktreePath = `${directory}/worktree`; - yield* fs.makeDirectory(cwd); - const command = (at: string, args: string[]) => - git.execute({ operation: "release-test", cwd: at, args }); - yield* command(cwd, ["init", "-b", "main"]); - yield* command(cwd, ["config", "user.name", "Test"]); - yield* command(cwd, ["config", "user.email", "test@example.test"]); - yield* command(cwd, ["commit", "--allow-empty", "-m", "base"]); - yield* command(cwd, ["init", "--bare", remote]); - yield* command(cwd, ["remote", "add", "origin", remote]); - yield* command(cwd, ["push", "-u", "origin", "main"]); - yield* command(cwd, ["worktree", "add", "-b", "feature/done", worktreePath]); - yield* command(worktreePath, ["commit", "--allow-empty", "-m", "work"]); - - const branchDeleted = yield* Deferred.make(); - const harness = makeHarness({ - thread: { worktreePath, branch: "feature/done" }, - project: { workspaceRoot: cwd }, - gitDriver: { execute: git.execute }, - git: { - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/done", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - removeWorktree: git.removeWorktree, - deleteLocalBranch: (input) => - git - .deleteLocalBranch(input) - .pipe(Effect.ensuring(Deferred.succeed(branchDeleted, undefined))), - }, - }); + const { fs, cwd, worktreePath, command, harness, branchDeleted } = + yield* makeReleaseRepo("release-unpushed-"); const refused = yield* Effect.exit(runRelease(harness, { deleteBranch: true })); expectTypedFailure(refused, { _tag: "WorktreeMcpFailure", code: "unsaved_work" }); @@ -799,6 +814,47 @@ describe("t3_worktree_release", () => { }).pipe(Effect.scoped, Effect.provide(releaseGitLayer)), ); + it.effect("keeps an unpushed branch whose worktree folder is already gone", () => + Effect.gen(function* () { + const { cwd, worktreePath, command, harness, removed } = + yield* makeReleaseRepo("release-gone-"); + yield* command(cwd, ["worktree", "remove", "--force", worktreePath]); + + const refused = yield* Effect.exit(runRelease(harness, { deleteBranch: true })); + expectTypedFailure(refused, { _tag: "WorktreeMcpFailure", code: "unsaved_work" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + + const released = yield* runRelease(harness); + expect(released.removal).toBe("already-gone"); + yield* Deferred.await(removed); + expect((yield* command(cwd, ["branch", "--list", "feature/done"])).stdout).not.toBe(""); + }).pipe(Effect.scoped, Effect.provide(releaseGitLayer)), + ); + + it.effect("fails closed when git's commit count is unreadable", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-count-" }); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + gitDriver: { + execute: () => + Effect.succeed({ + exitCode: 0 as GitVcsDriver.ExecuteGitResult["exitCode"], + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }), + }, + }); + + const exit = yield* Effect.exit(runRelease(harness)); + expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("waits for the caller's provider session to exit before removing", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 83645231ac79a..f490da78bb9b2 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -509,13 +509,56 @@ const make = Effect.gen(function* () { const exists = yield* fileSystem .exists(worktreePath) .pipe(asOperationFailed("Unable to check the worktree folder")); - // Subagent threads can share the parent's checkout. - const sharedWith = (yield* threadManagement - .listProjectThreads({ projectId: project.id, includeSubagents: true }) - .pipe(asOperationFailed("Unable to list the project's threads"))).filter( - (thread) => thread.worktreePath === worktreePath && thread.id !== scope.thread.threadId, + // Subagents, side chats, and archived threads can share the checkout. + const sharing = yield* threadManagement + .getShellSnapshot({ worktreePath }) + .pipe(asOperationFailed("Unable to list threads using the worktree")); + const sharedWith = [...sharing.threads, ...sharing.archivedThreads].filter( + (thread) => thread.id !== scope.thread.threadId, ).length; + // Commits `revision` reaches that no remote and no other local branch does; null when it does not resolve. + const countUnpushed = (cwd: string, revision: string, ownBranch: string | null) => + gitDriver + .execute({ + operation: "WorktreeMcpService.countUnpushedCommits", + cwd, + args: [ + "rev-list", + "--count", + revision, + "--not", + ...(ownBranch === null ? [] : [`--exclude=${ownBranch}`]), + "--branches", + "--remotes", + ], + allowNonZeroExit: true, + }) + .pipe( + asOperationFailed("Unable to count unpushed commits"), + Effect.flatMap((result) => { + if (result.exitCode !== 0) return Effect.succeed(null); + const output = result.stdout.trim(); + return /^\d+$/.test(output) + ? Effect.succeed(Number(output)) + : Effect.fail( + failure( + "operation_failed", + "Unable to count unpushed commits: unexpected output.", + ), + ); + }), + ); + const refuseUnpushed = (count: number | null, where: string) => + count !== null && count > 0 + ? Effect.fail( + failure( + "unsaved_work", + `${where} has ${count} commit${count === 1 ? "" : "s"} on no remote or other branch. Push them, or pass force: true to discard them.`, + ), + ) + : Effect.void; + let branch = projection.thread.branch; if (exists && sharedWith === 0) { const status = yield* gitWorkflow @@ -529,34 +572,21 @@ const make = Effect.gen(function* () { ); } if (!force) { - // Commits only this checkout reaches: on no remote and no other local branch. - const unpushed = yield* gitDriver - .execute({ - operation: "WorktreeMcpService.countUnpushedCommits", - cwd: worktreePath, - args: [ - "rev-list", - "--count", - "HEAD", - "--not", - ...(status.refName === null ? [] : [`--exclude=${status.refName}`]), - "--branches", - "--remotes", - ], - }) - .pipe( - Effect.map((result) => Number.parseInt(result.stdout.trim(), 10)), - asOperationFailed("Unable to count unpushed commits"), - ); - if (unpushed > 0) { - return yield* failure( - "unsaved_work", - `Worktree '${worktreePath}' has ${unpushed} commit${unpushed === 1 ? "" : "s"} on no remote or other branch. Push them, or pass force: true to discard them.`, - ); - } + yield* refuseUnpushed( + yield* countUnpushed(worktreePath, "HEAD", status.refName), + `Worktree '${worktreePath}'`, + ); } } + // The branch can hold commits HEAD does not: a detached HEAD, or a folder already gone. + let deleteBranch = input.deleteBranch === true && branch !== null && sharedWith === 0; + if (deleteBranch && branch !== null && !force) { + const unpushed = yield* countUnpushed(projectCwd, `refs/heads/${branch}`, branch); + if (unpushed === null) deleteBranch = false; + yield* refuseUnpushed(unpushed, `Branch '${branch}'`); + } + const commandId = yield* random.uuidV4().pipe( Effect.map((uuid) => CommandId.make( @@ -596,7 +626,7 @@ const make = Effect.gen(function* () { branch, providerSessionIds: projection.providerSessions.map((session) => session.id), force, - deleteBranch: input.deleteBranch === true, + deleteBranch, }).pipe(Effect.forkDetach); } const result: WorktreeMcpReleaseResult = { From 36cb8d7471ae5c6279045f91c833c4e1d547c53e Mon Sep 17 00:00:00 2001 From: "ROB-PC\\robho" Date: Tue, 10 Nov 2026 13:32:50 +0000 Subject: [PATCH 3/5] fix(server): release keeps a worktree another thread bound to while the session ended Co-Authored-By: Claude Opus 5.5 --- .../server/src/mcp/WorktreeMcpService.test.ts | 26 ++++++++++++++++++- apps/server/src/mcp/WorktreeMcpService.ts | 24 ++++++++++------- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index cd928d3d50eed..5b7cc78e3a99c 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -103,6 +103,7 @@ interface HarnessOptions { readonly gitDriver?: Partial; readonly isLive?: ProviderSessionManager.ProviderSessionManagerV2["Service"]["isLive"]; readonly otherThreadWorktreePaths?: ReadonlyArray; + readonly onRefreshStatus?: Effect.Effect; readonly thread?: ThreadFixture | null; readonly threadReadError?: "projection" | "dispatch"; readonly capabilities?: ReadonlySet; @@ -262,7 +263,9 @@ const makeHarness = (options: HarnessOptions = {}) => { workingTree: { files: [], insertions: 0, deletions: 0 }, }), ); - const refreshStatus = vi.fn((_: string) => Effect.die("refreshStatus stub")); + const refreshStatus = vi.fn((_: string) => + (options.onRefreshStatus ?? Effect.void).pipe(Effect.andThen(Effect.die("refreshStatus stub"))), + ); const runForThread = vi.fn((input: { readonly worktreePath: string }) => { switch (options.setupScript ?? "started") { case "no-script": @@ -951,6 +954,27 @@ describe("t3_worktree_release", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.effect("keeps a worktree another thread binds to while the session winds down", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-rebound-" }); + const sharingPaths: Array = []; + const refreshed = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/rebound" }, + otherThreadWorktreePaths: sharingPaths, + isLive: () => Effect.sync(() => sharingPaths.push(worktreePath)).pipe(Effect.as(false)), + onRefreshStatus: Deferred.succeed(refreshed, undefined).pipe(Effect.asVoid), + }); + + const result = yield* runRelease(harness, { deleteBranch: true }); + expect(result.removal).toBe("scheduled"); + yield* Deferred.await(refreshed); + expect(harness.removeWorktree).not.toHaveBeenCalled(); + expect(harness.deleteLocalBranch).not.toHaveBeenCalled(); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("clears the binding of a worktree whose folder is already gone", () => Effect.gen(function* () { const removed = yield* Deferred.make(); diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index f490da78bb9b2..191a6f4089576 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -460,15 +460,21 @@ const make = Effect.gen(function* () { Effect.retry(RELEASE_RETRY), Effect.ignore, ); - yield* gitWorkflow - .removeWorktree({ cwd: input.projectCwd, path: input.worktreePath, force: input.force }) - .pipe(Effect.retry(RELEASE_RETRY)); - if (input.deleteBranch && input.branch !== null) { - yield* gitWorkflow.deleteLocalBranch({ - cwd: input.projectCwd, - refName: input.branch, - force: true, - }); + // A thread can bind to the worktree while the session winds down; this one's binding is already cleared. + const sharing = yield* threadManagement.getShellSnapshot({ + worktreePath: input.worktreePath, + }); + if (sharing.threads.length + sharing.archivedThreads.length === 0) { + yield* gitWorkflow + .removeWorktree({ cwd: input.projectCwd, path: input.worktreePath, force: input.force }) + .pipe(Effect.retry(RELEASE_RETRY)); + if (input.deleteBranch && input.branch !== null) { + yield* gitWorkflow.deleteLocalBranch({ + cwd: input.projectCwd, + refName: input.branch, + force: true, + }); + } } yield* vcsStatusBroadcaster .refreshStatus(input.projectCwd) From 4144953c8f245668c9bacc67bbdfc41aea1b8105 Mon Sep 17 00:00:00 2001 From: "ROB-PC\\robho" Date: Tue, 10 Nov 2026 13:44:57 +0000 Subject: [PATCH 4/5] fix(server): release re-checks the worktree's threads before every removal attempt Co-Authored-By: Claude Opus 5.5 --- .../server/src/mcp/WorktreeMcpService.test.ts | 19 ++++++++-- apps/server/src/mcp/WorktreeMcpService.ts | 38 +++++++++++-------- 2 files changed, 39 insertions(+), 18 deletions(-) diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index 5b7cc78e3a99c..f738b064c1979 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -954,23 +954,36 @@ describe("t3_worktree_release", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("keeps a worktree another thread binds to while the session winds down", () => + it.effect("keeps a worktree another thread binds to between removal attempts", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-rebound-" }); const sharingPaths: Array = []; + let attempts = 0; + const firstAttempt = yield* Deferred.make(); const refreshed = yield* Deferred.make(); const harness = makeHarness({ thread: { worktreePath, branch: "feature/rebound" }, otherThreadWorktreePaths: sharingPaths, - isLive: () => Effect.sync(() => sharingPaths.push(worktreePath)).pipe(Effect.as(false)), + git: { + removeWorktree: () => + Effect.suspend(() => { + attempts++; + sharingPaths.push(worktreePath); + return Deferred.succeed(firstAttempt, undefined).pipe( + Effect.andThen(Effect.fail("EBUSY" as never)), + ); + }), + }, onRefreshStatus: Deferred.succeed(refreshed, undefined).pipe(Effect.asVoid), }); const result = yield* runRelease(harness, { deleteBranch: true }); expect(result.removal).toBe("scheduled"); + yield* Deferred.await(firstAttempt); + yield* TestClock.adjust("2 seconds"); yield* Deferred.await(refreshed); - expect(harness.removeWorktree).not.toHaveBeenCalled(); + expect(attempts).toBe(1); expect(harness.deleteLocalBranch).not.toHaveBeenCalled(); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 191a6f4089576..bad62d6aa94b1 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -460,21 +460,29 @@ const make = Effect.gen(function* () { Effect.retry(RELEASE_RETRY), Effect.ignore, ); - // A thread can bind to the worktree while the session winds down; this one's binding is already cleared. - const sharing = yield* threadManagement.getShellSnapshot({ - worktreePath: input.worktreePath, - }); - if (sharing.threads.length + sharing.archivedThreads.length === 0) { - yield* gitWorkflow - .removeWorktree({ cwd: input.projectCwd, path: input.worktreePath, force: input.force }) - .pipe(Effect.retry(RELEASE_RETRY)); - if (input.deleteBranch && input.branch !== null) { - yield* gitWorkflow.deleteLocalBranch({ - cwd: input.projectCwd, - refName: input.branch, - force: true, - }); - } + // A thread can bind to the worktree while removal waits or retries; this one's binding is already cleared. + const removed = yield* Effect.suspend(() => + threadManagement.getShellSnapshot({ worktreePath: input.worktreePath }), + ).pipe( + Effect.flatMap((sharing) => + sharing.threads.length + sharing.archivedThreads.length > 0 + ? Effect.succeed(false) + : gitWorkflow + .removeWorktree({ + cwd: input.projectCwd, + path: input.worktreePath, + force: input.force, + }) + .pipe(Effect.as(true)), + ), + Effect.retry(RELEASE_RETRY), + ); + if (removed && input.deleteBranch && input.branch !== null) { + yield* gitWorkflow.deleteLocalBranch({ + cwd: input.projectCwd, + refName: input.branch, + force: true, + }); } yield* vcsStatusBroadcaster .refreshStatus(input.projectCwd) From 46ed918b903a4130c8547a884bf9da121cb69fc5 Mon Sep 17 00:00:00 2001 From: "ROB-PC\\robho" Date: Sun, 15 Nov 2026 16:23:13 +0000 Subject: [PATCH 5/5] fix(server): outside MCP clients are not offered t3_worktree_release Main now refuses to build a toolkit that offers a thread-bound tool to outside clients (#32764). Release acts as its calling thread like handoff and status, so it gets the same annotation. Also re-measures the agent context budget after the rebase. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/toolkits/worktree/tools.ts | 3 ++- apps/server/src/provider/agentContextBudget.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/toolkits/worktree/tools.ts b/apps/server/src/mcp/toolkits/worktree/tools.ts index 0c272b435318b..e0e962dc400ce 100644 --- a/apps/server/src/mcp/toolkits/worktree/tools.ts +++ b/apps/server/src/mcp/toolkits/worktree/tools.ts @@ -56,7 +56,8 @@ const WorktreeReleaseTool = Tool.make("t3_worktree_release", { .annotate(Tool.Readonly, false) .annotate(Tool.Destructive, true) .annotate(Tool.Idempotent, false) - .annotate(Tool.OpenWorld, false); + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); const WorktreeStatusTool = Tool.make("t3_worktree_status", { description: diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 0051813371e5b..796df9e702c22 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 49736 + "mcpToolListJsonBytes": 50255 }