From abab14d3f9435ac039054d9e77c7516a9301abeb Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Sun, 23 Aug 2026 00:11:09 -0700 Subject: [PATCH 1/4] fix(host-service): re-check the disk after git worktree remove and keep its error git worktree remove --force --force is not atomic: it can unregister the worktree and then fail partway through its recursive delete (locked file, live writer). The destroy saga trusted the registry read alone, so an unregistered-but-still-on-disk worktree was recorded as removed, the folder was orphaned where no list shows it, and a retry reported success without touching it. The startup reconciler walked the same path, so it spun on such orphans forever. The remove task now keeps git's error instead of discarding it, and the saga re-checks the disk after an unregistered verdict: leftovers inside the managed worktrees root are removed with the same guarded rm the other branches already use, leftovers outside it are left with a warning, and failure messages carry git's actual error. Fixes #6730 --- .../trpc/router/workspace-cleanup/git-ops.ts | 2 +- .../workspace-cleanup/workspace-cleanup.ts | 40 +++++- .../host-service/src/workers/tasks/git.ts | 21 ++- .../test/workspace-cleanup.test.ts | 120 +++++++++++++++++- 4 files changed, 170 insertions(+), 13 deletions(-) diff --git a/packages/host-service/src/trpc/router/workspace-cleanup/git-ops.ts b/packages/host-service/src/trpc/router/workspace-cleanup/git-ops.ts index 31fc4098447..954211657a9 100644 --- a/packages/host-service/src/trpc/router/workspace-cleanup/git-ops.ts +++ b/packages/host-service/src/trpc/router/workspace-cleanup/git-ops.ts @@ -61,7 +61,7 @@ export const cleanupGitOps = { repoPath: string; worktreePath: string; gitEnv: GitTaskEnv; - }): Promise<{ stillRegistered: boolean }> { + }): Promise<{ stillRegistered: boolean; removeError?: string }> { // Generous timeout: removal recursively deletes the worktree // directory, which can take a while for large trees (node_modules // etc.). diff --git a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts index 3d02582d329..9c3df2266c2 100644 --- a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts +++ b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts @@ -514,8 +514,9 @@ async function runDestroyPhases( // treat that like "still registered" and block rather than risk // orphaning disk past the archive commit point. let stillRegistered = true; + let removeError: string | undefined; try { - ({ stillRegistered } = await cleanupGitOps.removeWorktree({ + ({ stillRegistered, removeError } = await cleanupGitOps.removeWorktree({ repoPath: project.repoPath, worktreePath: local.worktreePath, gitEnv: repoGitEnv, @@ -533,9 +534,44 @@ async function runDestroyPhases( // retryable instead of orphaning disk past the commit point. throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: `Failed to remove worktree at ${local.worktreePath}`, + message: `Failed to remove worktree at ${local.worktreePath}${ + removeError ? `: ${removeError}` : "" + }`, }); } + if (existsSync(local.worktreePath)) { + // Unregistered is not removed: git's unregistration and its + // recursive delete are not atomic, so `remove --force --force` + // can drop the registration and still fail partway through + // deleting files (locked file, live writer). Trusting the + // registry alone silently orphaned the folder — no list shows + // it, and a retry reports success without touching it (#6730). + // Fall back to the same guarded direct removal the other + // branches use. + const worktreeBaseDir = + project.worktreeBaseDir ?? getHostWorktreeBaseDir(ctx); + if ( + !isInsideProjectWorktreesRoot( + local.worktreePath, + project.id, + worktreeBaseDir, + ) + ) { + warnings.push( + `Worktree at ${local.worktreePath} is no longer registered with git, but its folder is outside the managed worktrees root and was left on disk`, + ); + } else { + try { + await rm(local.worktreePath, { recursive: true, force: true }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: `Worktree at ${local.worktreePath} is no longer registered with git, but its folder could not be removed: ${removeError ?? message}`, + }); + } + } + } worktreeRemoved = true; } } diff --git a/packages/host-service/src/workers/tasks/git.ts b/packages/host-service/src/workers/tasks/git.ts index 46139db65bf..963a10b5642 100644 --- a/packages/host-service/src/workers/tasks/git.ts +++ b/packages/host-service/src/workers/tasks/git.ts @@ -197,7 +197,7 @@ export const gitWorktreeStateTask = defineWorkerTask< export const gitWorktreeRemoveTask = defineWorkerTask< { repoPath: string; worktreePath: string; gitEnv: GitTaskEnv }, - { stillRegistered: boolean } + { stillRegistered: boolean; removeError?: string } >({ type: "git/removeWorktree", // This task outlives its caller's budget in the field (HOST-SERVICE-17, @@ -214,15 +214,21 @@ export const gitWorktreeRemoveTask = defineWorkerTask< // (macOS `/var` → `/private/var`) still matches its registration. // `realpathSync.native` is a blocking syscall, hence its own phase. const target = normalizeWorktreePath(worktreePath); - // Best-effort: the registry read below is authoritative, not the - // command's locale- and version-dependent exit text. `--force --force` - // also unregisters a worktree whose directory is already gone, so no - // separate prune (which would clobber other stale worktrees' metadata) - // is needed. + // The registry read below decides "registered or not" (the command's + // exit text is locale- and version-dependent), but registration is + // not the whole story: git can unregister the worktree and still fail + // partway through its recursive delete (#6730). Keep the error — it + // is the only record of why files were left behind — and let the + // caller re-check the disk. `--force --force` also unregisters a + // worktree whose directory is already gone, so no separate prune + // (which would clobber other stale worktrees' metadata) is needed. reportPhase?.("worktree-remove"); + let removeError: string | undefined; await git .raw(["worktree", "remove", "--force", "--force", target]) - .catch(() => {}); + .catch((err: unknown) => { + removeError = err instanceof Error ? err.message : String(err); + }); // A `worktree list` failure throws out of the task: the post-remove // state is unknown and the caller must not treat it as removed. reportPhase?.("worktree-list"); @@ -231,6 +237,7 @@ export const gitWorktreeRemoveTask = defineWorkerTask< stillRegistered: parseWorktreeList(raw).some( (w) => normalizeWorktreePath(w.path) === target, ), + removeError, }; }, }); diff --git a/packages/host-service/test/workspace-cleanup.test.ts b/packages/host-service/test/workspace-cleanup.test.ts index 79e122b1db2..65a6b719641 100644 --- a/packages/host-service/test/workspace-cleanup.test.ts +++ b/packages/host-service/test/workspace-cleanup.test.ts @@ -1,5 +1,6 @@ import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test"; import { + existsSync, mkdirSync, mkdtempSync, rmSync, @@ -26,7 +27,7 @@ type WorkspaceRow = { pullRequestId?: string | null; archivedAt?: number | null; }; -type ProjectRow = { id: string; repoPath: string }; +type ProjectRow = { id: string; repoPath: string; worktreeBaseDir?: string }; type WorktreeState = { hasChanges: boolean; hasUnpushedCommits: boolean }; @@ -40,7 +41,10 @@ interface ContextSpec { worktreeState?: WorktreeState | (() => Promise); // Simulates ctx.git()/env-resolution failure ("failed to open repo"). resolveGitEnvThrows?: boolean; - removeWorktree?: () => Promise<{ stillRegistered: boolean }>; + removeWorktree?: () => Promise<{ + stillRegistered: boolean; + removeError?: string; + }>; deleteBranch?: () => Promise<{ deleted: boolean }>; // Simulates sqlite failure at the archive UPDATE — the commit point. dbUpdateThrows?: boolean | "once"; @@ -118,7 +122,10 @@ function makeCtx(spec: ContextSpec): HostServiceContext & { }, select: () => ({ from: () => ({ - where: () => ({ all: terminalSelectAll }), + // `.all` serves the terminal-session sweep; `.get` serves + // getHostWorktreeBaseDir when a spec sets no per-project + // worktreeBaseDir ("no host settings row" shape). + where: () => ({ all: terminalSelectAll, get: () => undefined }), }), }), update: () => ({ @@ -416,6 +423,113 @@ describe("workspaceCleanup.destroy cleanup ordering", () => { } }); + test("git unregisters the worktree but the folder survives: destroy removes it", async () => { + // git's `worktree remove --force --force` is not atomic: it can drop + // the registration and then fail partway through its recursive delete + // (locked file, live writer). The registry read then says "removed" + // while the directory is still on disk (#6730). + const base = mkdtempSync(join(tmpdir(), "worktrees-base-")); + const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-")); + const worktree = join(base, "p-1", "wt-partial"); + mkdirSync(worktree, { recursive: true }); + writeFileSync(join(worktree, "leftover.txt"), "still here"); + try { + const ctx = makeCtx({ + workspace: { + id: "ws-1", + projectId: "p-1", + worktreePath: worktree, + branch: "feature", + }, + project: { id: "p-1", repoPath: repo, worktreeBaseDir: base }, + removeWorktree: async () => ({ + stillRegistered: false, + removeError: + "error: failed to delete 'wt-partial': Operation not permitted", + }), + }); + const caller = workspaceCleanupRouter.createCaller(ctx); + + const result = await caller.destroy({ + workspaceId: "ws-1", + deleteBranch: false, + force: true, + }); + expect(result.success).toBe(true); + expect(result.worktreeRemoved).toBe(true); + expect(existsSync(worktree)).toBe(false); + } finally { + rmSync(base, { recursive: true, force: true }); + rmSync(repo, { recursive: true, force: true }); + } + }); + + test("unregistered leftover outside the managed root is left on disk with a warning", async () => { + const tmp = mkdtempSync(join(tmpdir(), "workspace-delete-")); + const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-")); + try { + const ctx = makeCtx({ + workspace: { + id: "ws-1", + projectId: "p-1", + worktreePath: tmp, + branch: "feature", + }, + // No worktreeBaseDir: the default root is under the home dir, + // so this tmp path falls outside it and must not be rm'd. + project: { id: "p-1", repoPath: repo }, + removeWorktree: async () => ({ stillRegistered: false }), + }); + const caller = workspaceCleanupRouter.createCaller(ctx); + + const result = await caller.destroy({ + workspaceId: "ws-1", + deleteBranch: false, + force: true, + }); + expect(result.success).toBe(true); + expect(existsSync(tmp)).toBe(true); + expect( + result.warnings.some((warning) => warning.includes("left on disk")), + ).toBe(true); + } finally { + rmSync(tmp, { recursive: true, force: true }); + rmSync(repo, { recursive: true, force: true }); + } + }); + + test("still-registered failure surfaces git's own error", async () => { + const tmp = mkdtempSync(join(tmpdir(), "workspace-delete-")); + const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-")); + try { + const ctx = makeCtx({ + workspace: { + id: "ws-1", + projectId: "p-1", + worktreePath: tmp, + branch: "feature", + }, + project: { id: "p-1", repoPath: repo }, + removeWorktree: async () => ({ + stillRegistered: true, + removeError: "Operation not permitted", + }), + }); + const caller = workspaceCleanupRouter.createCaller(ctx); + + await expect( + caller.destroy({ + workspaceId: "ws-1", + deleteBranch: false, + force: true, + }), + ).rejects.toThrow(/Operation not permitted/); + } finally { + rmSync(tmp, { recursive: true, force: true }); + rmSync(repo, { recursive: true, force: true }); + } + }); + test("worktree removal task failure blocks local delete (post-remove state unknown)", async () => { const tmp = mkdtempSync(join(tmpdir(), "workspace-delete-")); // The repo must exist on disk: a missing repo directory now takes the From ba91e8fe38a34a7fb97ba9eaa6de0fc5d72d1c55 Mon Sep 17 00:00:00 2001 From: Sahil Jagtap Date: Sun, 23 Aug 2026 00:43:56 -0700 Subject: [PATCH 2/4] fix(host-service): report worktreeRemoved from final disk state and keep both errors in the fallback message --- .../trpc/router/workspace-cleanup/workspace-cleanup.ts | 9 +++++++-- packages/host-service/test/workspace-cleanup.test.ts | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts index 9c3df2266c2..8e35835c742 100644 --- a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts +++ b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts @@ -567,12 +567,17 @@ async function runDestroyPhases( const message = err instanceof Error ? err.message : String(err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: `Worktree at ${local.worktreePath} is no longer registered with git, but its folder could not be removed: ${removeError ?? message}`, + message: `Worktree at ${local.worktreePath} is no longer registered with git, but its folder could not be removed: ${message}${ + removeError ? ` (git worktree remove: ${removeError})` : "" + }`, }); } } } - worktreeRemoved = true; + // The outside-root branch above leaves the folder in place, so + // report removal from the final disk state rather than assuming + // this path always cleared it (#6785 review). + worktreeRemoved = !existsSync(local.worktreePath); } } diff --git a/packages/host-service/test/workspace-cleanup.test.ts b/packages/host-service/test/workspace-cleanup.test.ts index 65a6b719641..edbd1f347ba 100644 --- a/packages/host-service/test/workspace-cleanup.test.ts +++ b/packages/host-service/test/workspace-cleanup.test.ts @@ -489,6 +489,9 @@ describe("workspaceCleanup.destroy cleanup ordering", () => { }); expect(result.success).toBe(true); expect(existsSync(tmp)).toBe(true); + // The folder is still on disk, so the result must not claim the + // worktree was removed (#6785 review). + expect(result.worktreeRemoved).toBe(false); expect( result.warnings.some((warning) => warning.includes("left on disk")), ).toBe(true); From 19d351081bff368e1582c562774e9db3c954f3ba Mon Sep 17 00:00:00 2001 From: Kiet Ho Date: Wed, 2 Sep 2026 23:14:11 -0700 Subject: [PATCH 3/4] fix(host-service): trim git error text and re-check the worktree dir with isMissingDirectory Claude-Session: https://claude.ai/code/session_01Y3NuTkFsVqfSLU6sXdRm45 --- .../trpc/router/workspace-cleanup/workspace-cleanup.ts | 8 +++++--- packages/host-service/src/workers/tasks/git.ts | 6 +++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts index 8e35835c742..c1f685a48a9 100644 --- a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts +++ b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts @@ -539,7 +539,7 @@ async function runDestroyPhases( }`, }); } - if (existsSync(local.worktreePath)) { + if (!isMissingDirectory(local.worktreePath)) { // Unregistered is not removed: git's unregistration and its // recursive delete are not atomic, so `remove --force --force` // can drop the registration and still fail partway through @@ -576,8 +576,10 @@ async function runDestroyPhases( } // The outside-root branch above leaves the folder in place, so // report removal from the final disk state rather than assuming - // this path always cleared it (#6785 review). - worktreeRemoved = !existsSync(local.worktreePath); + // this path always cleared it (#6785 review). `isMissingDirectory` + // rather than `existsSync`: a leftover this process cannot read + // still exists, and must not be reported as removed. + worktreeRemoved = isMissingDirectory(local.worktreePath); } } diff --git a/packages/host-service/src/workers/tasks/git.ts b/packages/host-service/src/workers/tasks/git.ts index 963a10b5642..c6fa023f006 100644 --- a/packages/host-service/src/workers/tasks/git.ts +++ b/packages/host-service/src/workers/tasks/git.ts @@ -227,7 +227,11 @@ export const gitWorktreeRemoveTask = defineWorkerTask< await git .raw(["worktree", "remove", "--force", "--force", target]) .catch((err: unknown) => { - removeError = err instanceof Error ? err.message : String(err); + removeError = (err instanceof Error ? err.message : String(err)).trim(); + console.warn("[git/removeWorktree] git worktree remove failed", { + target, + error: removeError, + }); }); // A `worktree list` failure throws out of the task: the post-remove // state is unknown and the caller must not treat it as removed. From 010b5a54cc5b352660274ea58f142dc7027a8f1d Mon Sep 17 00:00:00 2001 From: Kiet Ho Date: Thu, 3 Sep 2026 16:50:19 -0700 Subject: [PATCH 4/4] fix(host-service): treat a dangling symlink at the worktree path as a leftover to remove MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The post-unregister recheck used statSync, which follows a final symlink: a dangling link at the worktree path read as absent, was skipped by the fallback rm, and the delete reported worktreeRemoved while the entry was still in the managed root. Recheck with lstatSync instead, and report removal from the same no-follow check. The root guard's fallback for an unresolvable leaf returned the raw resolved path, so a base that itself sits behind a symlink (macOS /var → /private/var) never shared a prefix with a dangling leaf and the guard refused it. Canonicalise the parent and re-append the leaf. Tried and dropped: maxRetries on the fallback rm. Under Node the retry applies at every directory level, so a locked file three levels deep stalls the delete for minutes (25s at depth 1, 102s at depth 2). The delete stays fail-fast and retryable from the UI. Claude-Session: https://claude.ai/code/session_01CDvtST7CRtMrDYxQ4mGgo8 --- .../workspace-cleanup/workspace-cleanup.ts | 23 ++++-- .../shared/worktree-paths.test.ts | 22 +++++ .../shared/worktree-paths.ts | 20 ++++- .../test/workspace-cleanup.test.ts | 80 +++++++++++++++++++ 4 files changed, 137 insertions(+), 8 deletions(-) diff --git a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts index c1f685a48a9..4909aa5440c 100644 --- a/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts +++ b/packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts @@ -1,4 +1,4 @@ -import { existsSync, statSync } from "node:fs"; +import { existsSync, lstatSync, statSync } from "node:fs"; import { rm } from "node:fs/promises"; import { sanitizePromptForPty } from "@superset/shared/agent-prompt-launch"; import { TRPCError } from "@trpc/server"; @@ -365,6 +365,16 @@ function isMissingDirectory(path: string): boolean { } } +/** Like isMissingDirectory, but does not follow a final symlink: a dangling + * link at the worktree path is still an entry to remove, not an absence. */ +function isMissingPath(path: string): boolean { + try { + return lstatSync(path, { throwIfNoEntry: false }) === undefined; + } catch { + return false; + } +} + function archiveReasonFor( ctx: HostServiceContext, local: { pullRequestId: string | null }, @@ -539,7 +549,7 @@ async function runDestroyPhases( }`, }); } - if (!isMissingDirectory(local.worktreePath)) { + if (!isMissingPath(local.worktreePath)) { // Unregistered is not removed: git's unregistration and its // recursive delete are not atomic, so `remove --force --force` // can drop the registration and still fail partway through @@ -576,10 +586,11 @@ async function runDestroyPhases( } // The outside-root branch above leaves the folder in place, so // report removal from the final disk state rather than assuming - // this path always cleared it (#6785 review). `isMissingDirectory` - // rather than `existsSync`: a leftover this process cannot read - // still exists, and must not be reported as removed. - worktreeRemoved = isMissingDirectory(local.worktreePath); + // this path always cleared it (#6785 review). `isMissingPath` + // rather than `existsSync`: a leftover this process cannot read, + // or a dangling symlink, still exists and must not be reported + // as removed. + worktreeRemoved = isMissingPath(local.worktreePath); } } diff --git a/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.test.ts b/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.test.ts index 02564163135..b6b73d6dd49 100644 --- a/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.test.ts +++ b/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.test.ts @@ -37,6 +37,28 @@ describe("isInsideProjectWorktreesRoot", () => { ).toBe(false); }); + test("accepts a dangling symlink leaf under a base that itself sits behind a symlink", () => { + // tmpdir() on macOS is /var/..., a symlink to /private/var/...: the + // base canonicalises to /private/var while an unresolvable leaf used + // to fall back to its /var/... spelling and never share the prefix. + const base = tmp("wt-base-"); + mkdirSync(join(base, "proj"), { recursive: true }); + symlinkSync(join(base, "gone"), join(base, "proj", "feature")); + expect( + isInsideProjectWorktreesRoot(join(base, "proj", "feature"), "proj", base), + ).toBe(true); + }); + + test("rejects a leaf symlink that points out of the base", () => { + const base = tmp("wt-base-"); + const outside = tmp("wt-outside-"); + mkdirSync(join(base, "proj"), { recursive: true }); + symlinkSync(outside, join(base, "proj", "feature")); + expect( + isInsideProjectWorktreesRoot(join(base, "proj", "feature"), "proj", base), + ).toBe(false); + }); + test("rejects a worktree under a project root that is a symlink out of the base", () => { const base = tmp("wt-base-"); const outside = tmp("wt-outside-"); diff --git a/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.ts b/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.ts index c50d1293aaa..0fe845b464a 100644 --- a/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.ts +++ b/packages/host-service/src/trpc/router/workspace-creation/shared/worktree-paths.ts @@ -1,6 +1,14 @@ import { realpathSync } from "node:fs"; import { homedir } from "node:os"; -import { isAbsolute, join, normalize, resolve, sep } from "node:path"; +import { + basename, + dirname, + isAbsolute, + join, + normalize, + resolve, + sep, +} from "node:path"; import { TRPCError } from "@trpc/server"; // Kept outside the primary checkout so editors, file watchers, and @@ -68,7 +76,15 @@ function normalizePath(p: string): string { try { return realpathSync(p); } catch { - return resolve(p); + // A dangling or unreadable leaf still has a real parent. Canonicalise + // that so the leaf compares against the same prefix as a base that + // sits behind a symlink (macOS `/var` → `/private/var`). + const abs = resolve(p); + try { + return join(realpathSync(dirname(abs)), basename(abs)); + } catch { + return abs; + } } } diff --git a/packages/host-service/test/workspace-cleanup.test.ts b/packages/host-service/test/workspace-cleanup.test.ts index edbd1f347ba..b7a8e4a0f0c 100644 --- a/packages/host-service/test/workspace-cleanup.test.ts +++ b/packages/host-service/test/workspace-cleanup.test.ts @@ -1,6 +1,7 @@ import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test"; import { existsSync, + lstatSync, mkdirSync, mkdtempSync, rmSync, @@ -464,6 +465,85 @@ describe("workspaceCleanup.destroy cleanup ordering", () => { } }); + test("git unregisters the worktree and leaves a dangling symlink: destroy removes the link", async () => { + // A dangling link is not an absence: a stat-based recheck follows the + // link, sees nothing, and reports the worktree removed while the entry + // is still in the managed root. + const base = mkdtempSync(join(tmpdir(), "worktrees-base-")); + const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-")); + const worktree = join(base, "p-1", "wt-dangling"); + mkdirSync(join(base, "p-1"), { recursive: true }); + symlinkSync(join(base, "gone-target"), worktree); + try { + expect(existsSync(worktree)).toBe(false); + expect(lstatSync(worktree, { throwIfNoEntry: false })).toBeDefined(); + const ctx = makeCtx({ + workspace: { + id: "ws-1", + projectId: "p-1", + worktreePath: worktree, + branch: "feature", + }, + project: { id: "p-1", repoPath: repo, worktreeBaseDir: base }, + removeWorktree: async () => ({ stillRegistered: false }), + }); + const caller = workspaceCleanupRouter.createCaller(ctx); + + const result = await caller.destroy({ + workspaceId: "ws-1", + deleteBranch: false, + force: true, + }); + expect(result.success).toBe(true); + expect(result.worktreeRemoved).toBe(true); + expect(lstatSync(worktree, { throwIfNoEntry: false })).toBeUndefined(); + } finally { + rmSync(base, { recursive: true, force: true }); + rmSync(repo, { recursive: true, force: true }); + } + }); + + test("worktree path is a symlink into the managed root: destroy removes the link, not through it", async () => { + const base = mkdtempSync(join(tmpdir(), "worktrees-base-")); + const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-")); + const outside = mkdtempSync(join(tmpdir(), "workspace-delete-outside-")); + const worktree = join(base, "p-1", "wt-link"); + mkdirSync(join(base, "p-1"), { recursive: true }); + writeFileSync(join(outside, "user-data.txt"), "keep me"); + symlinkSync(outside, worktree); + try { + const ctx = makeCtx({ + workspace: { + id: "ws-1", + projectId: "p-1", + worktreePath: worktree, + branch: "feature", + }, + project: { id: "p-1", repoPath: repo, worktreeBaseDir: base }, + removeWorktree: async () => ({ stillRegistered: false }), + }); + const caller = workspaceCleanupRouter.createCaller(ctx); + + const result = await caller.destroy({ + workspaceId: "ws-1", + deleteBranch: false, + force: true, + }); + expect(result.success).toBe(true); + // The link resolves outside the managed root, so the root guard + // refuses it and the target's contents are untouched. + expect(result.worktreeRemoved).toBe(false); + expect(existsSync(join(outside, "user-data.txt"))).toBe(true); + expect( + result.warnings.some((warning) => warning.includes("left on disk")), + ).toBe(true); + } finally { + rmSync(base, { recursive: true, force: true }); + rmSync(repo, { recursive: true, force: true }); + rmSync(outside, { recursive: true, force: true }); + } + }); + test("unregistered leftover outside the managed root is left on disk with a warning", async () => { const tmp = mkdtempSync(join(tmpdir(), "workspace-delete-")); const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-"));