From 4bd79ae0adc37ee37f32c1af585caaa6a3bafb59 Mon Sep 17 00:00:00 2001 From: nullStack65 Date: Sat, 28 Nov 2026 05:46:32 +0000 Subject: [PATCH] fix(server): reconcile detached-HEAD worktrees to null branch Squash-rebase of PR #216 onto current release/native-0.1.10; no behavior change from the original commits. Original authoring trailers: Model gemini-4-hydrogen / Task fix / Agent antigravity Model: claude-opus-5-5 Task: fix Agent: Builder drain parked-PR lane (Claude Code worker F3) Lane: magpie Harness: t3/claude-code Model-family: Claude Model-generation: Opus 5.5 Skills-SHA: unknown (source unavailable) Co-Authored-By: Claude Opus 5.5 --- .../server/src/mcp/WorktreeMcpService.test.ts | 39 ++++ apps/server/src/mcp/WorktreeMcpService.ts | 1 + .../WorktreeBranchSync.test.ts | 174 ++++++++++++++++++ .../orchestration-v2/WorktreeBranchSync.ts | 6 +- packages/contracts/src/worktreeMcp.ts | 3 + 5 files changed, 222 insertions(+), 1 deletion(-) diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index b519d7ac09c3..04875732ade4 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -702,10 +702,49 @@ describe("t3_worktree_status", () => { attached: true, worktreePath: "/worktrees/project/existing", branch: "feature/existing", + detached: false, defaultStartFromOrigin: true, }); }); }); + + it.effect("reports detached HEAD when an attached worktree has branch null", () => { + const harness = makeHarness({ + thread: { + worktreePath: "/worktrees/project/existing", + branch: null, + }, + }); + return Effect.gen(function* () { + const result = yield* runStatus(harness); + expect(result).toMatchObject({ + attached: true, + worktreePath: "/worktrees/project/existing", + branch: null, + detached: true, + defaultStartFromOrigin: false, + }); + }); + }); + + it.effect("reports detached as false when the thread is not attached to a worktree", () => { + const harness = makeHarness({ + thread: { + worktreePath: null, + branch: null, + }, + }); + return Effect.gen(function* () { + const result = yield* runStatus(harness); + expect(result).toMatchObject({ + attached: false, + worktreePath: null, + branch: null, + detached: false, + defaultStartFromOrigin: false, + }); + }); + }); }); describe("t3_worktree_list", () => { diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 92582b24efd6..1a24842b1bf7 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -511,6 +511,7 @@ const make = Effect.gen(function* () { attached: projection.thread.worktreePath !== null, worktreePath: projection.thread.worktreePath, branch: projection.thread.branch, + detached: projection.thread.worktreePath !== null && projection.thread.branch === null, projectWorkspaceRoot: project.workspaceRoot, defaultStartFromOrigin, }; diff --git a/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts b/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts index 14c5b5d2751d..744b9e7ed209 100644 --- a/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts +++ b/apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts @@ -60,6 +60,7 @@ it.effect.each([false, true])( Effect.provide( Layer.mergeAll( FileSystem.layerNoop({ + exists: () => Effect.succeed(true), realPath: (path) => Effect.succeed(path === "/link/worktree" ? "/worktree" : path), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ @@ -108,3 +109,176 @@ it.effect.each([false, true])( ); }, ); + +it.effect( + "reconciles detached HEAD when the worktree exists and clears stale branch metadata", + () => { + let threads: ReadonlyArray = [ + { + id: ThreadId.make("detached-thread"), + branch: "feature/stale", + worktreePath: "/worktree", + } as OrchestrationV2ThreadShell, + ]; + const commands: OrchestrationV2ServerCommand[] = []; + return Effect.gen(function* () { + const reconcile = yield* WorktreeBranchSync.makeReconcile; + yield* reconcile({ cwd: "/worktree", refName: null }); + assert.deepEqual( + commands.map((command) => { + assert.equal(command.type, "thread.metadata.update"); + if (command.type !== "thread.metadata.update") throw new Error("Unexpected command"); + return [ + command.threadId, + command.branch, + command.expectedBranch, + command.expectedWorktreePath, + ]; + }), + [["detached-thread", null, "feature/stale", "/worktree"]], + ); + assert.equal(threads[0]?.branch, null); + }).pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + exists: () => Effect.succeed(true), + realPath: (path) => Effect.succeed(path), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadWorktreePaths: () => + Effect.succeed([ + { threadId: ThreadId.make("detached-thread"), worktreePath: "/worktree" }, + ]), + }), + Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: (cwd) => Effect.succeed(cwd), + currentBranch: () => Effect.succeed(null), + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 2, + snapshotSequence: 0, + threads, + archivedThreads: [], + }), + dispatch: (command) => + Effect.sync(() => { + commands.push(command); + if (command.type === "thread.metadata.update" && command.branch !== undefined) { + const branch = command.branch; + threads = threads.map((thread) => + thread.id === command.threadId && thread.branch === command.expectedBranch + ? { ...thread, branch } + : thread, + ); + } + return { sequence: commands.length, storedEvents: [] }; + }), + }), + ), + ), + ); + }, +); + +it.effect("ignores detached HEAD events when the worktree directory does not exist", () => { + const commands: OrchestrationV2ServerCommand[] = []; + const threads: ReadonlyArray = [ + { + id: ThreadId.make("missing-worktree"), + branch: "feature/stale", + worktreePath: "/worktree", + } as OrchestrationV2ThreadShell, + ]; + return Effect.gen(function* () { + const reconcile = yield* WorktreeBranchSync.makeReconcile; + yield* reconcile({ cwd: "/worktree", refName: null }); + assert.deepEqual(commands, []); + assert.equal(threads[0]?.branch, "feature/stale"); + }).pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + exists: () => Effect.succeed(false), + realPath: (path) => Effect.succeed(path), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadWorktreePaths: () => + Effect.succeed([ + { threadId: ThreadId.make("missing-worktree"), worktreePath: "/worktree" }, + ]), + }), + Layer.mock(GitWorkflowService.GitWorkflowService)({ + currentBranch: () => Effect.succeed(null), + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 2, + snapshotSequence: 0, + threads, + archivedThreads: [], + }), + dispatch: (command) => + Effect.sync(() => { + commands.push(command); + return { sequence: commands.length, storedEvents: [] }; + }), + }), + ), + ), + ); +}); + +it.effect( + "ignores detached HEAD events when the worktree directory is no longer a repository", + () => { + const commands: OrchestrationV2ServerCommand[] = []; + return Effect.gen(function* () { + const reconcile = yield* WorktreeBranchSync.makeReconcile; + yield* reconcile({ cwd: "/worktree", refName: null }); + assert.deepEqual(commands, []); + }).pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + exists: () => Effect.succeed(true), + realPath: (path) => Effect.succeed(path), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadWorktreePaths: () => + Effect.succeed([ + { threadId: ThreadId.make("pruned-worktree"), worktreePath: "/worktree" }, + ]), + }), + Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: () => Effect.succeed(null), + currentBranch: () => Effect.succeed(null), + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 2, + snapshotSequence: 0, + threads: [ + { + id: ThreadId.make("pruned-worktree"), + branch: "feature/kept", + worktreePath: "/worktree", + } as OrchestrationV2ThreadShell, + ], + archivedThreads: [], + }), + dispatch: (command) => + Effect.sync(() => { + commands.push(command); + return { sequence: commands.length, storedEvents: [] }; + }), + }), + ), + ), + ); + }, +); diff --git a/apps/server/src/orchestration-v2/WorktreeBranchSync.ts b/apps/server/src/orchestration-v2/WorktreeBranchSync.ts index 1561a45d0115..27009baff431 100644 --- a/apps/server/src/orchestration-v2/WorktreeBranchSync.ts +++ b/apps/server/src/orchestration-v2/WorktreeBranchSync.ts @@ -21,7 +21,6 @@ export const makeReconcile = Effect.gen(function* () { readonly cwd: string; readonly refName: string | null; }) { - if (input.refName === null) return; const paths = yield* projections.getThreadWorktreePaths({ includeArchived: true }); const matchingPaths = new Set(); for (const worktreePath of new Set(paths.map((thread) => thread.worktreePath))) { @@ -43,6 +42,11 @@ export const makeReconcile = Effect.gen(function* () { thread.worktreePath === matchingThreads.get(thread.id) && thread.branch !== input.refName, ); if (sharing.length === 0) return; + if (input.refName === null) { + if (!(yield* fs.exists(input.cwd))) return; + // currentBranch is also null outside a repository, e.g. a worktree whose admin dir was pruned. + if ((yield* git.repositoryRoot(input.cwd)) === null) return; + } // Status events may queue behind a generated rename or another checkout. if ((yield* git.currentBranch(input.cwd)) !== input.refName) return; for (const thread of sharing) { diff --git a/packages/contracts/src/worktreeMcp.ts b/packages/contracts/src/worktreeMcp.ts index 07b0240bbaf8..577d414cc515 100644 --- a/packages/contracts/src/worktreeMcp.ts +++ b/packages/contracts/src/worktreeMcp.ts @@ -78,6 +78,9 @@ export const WorktreeMcpStatusResult = Schema.Struct({ attached: Schema.Boolean, worktreePath: Schema.NullOr(TrimmedNonEmptyString), branch: Schema.NullOr(GitRefName), + detached: Schema.Boolean.annotate({ + description: "True when the attached worktree is on a detached HEAD (`branch` is `null`).", + }), projectWorkspaceRoot: TrimmedNonEmptyString, defaultStartFromOrigin: Schema.Boolean.annotate({ description: "`startFromOrigin` default for `t3_worktree_handoff`.",