Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.).
Expand Down
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When the worktree path is a dangling symlink, this branch's entry check and the new isMissingPath disagree. existsSync() follows the link and returns false, so worktreeRemoved = !existsSync(local.worktreePath) (line ~470) reports the symlink as already gone, while the new isMissingPath correctly treats it as a leftover. If resolveGitEnv then fails and worktreeRemoved is already true, the code only pushes a warning, repoGitEnv stays null, and the if (repoGitEnv) block that would remove the link never runs — destroy returns worktreeRemoved: true with the symlink still present inside the managed root. That contradicts the PR's goal of no orphaned entries, and the case is exactly the dangling-symlink scenario commit 010b5a5 targets. Make the entry check use the same non-following semantics as isMissingPath.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts, line 370:

<comment>When the worktree path is a dangling symlink, this branch's entry check and the new isMissingPath disagree. existsSync() follows the link and returns false, so `worktreeRemoved = !existsSync(local.worktreePath)` (line ~470) reports the symlink as already gone, while the new isMissingPath correctly treats it as a leftover. If `resolveGitEnv` then fails and `worktreeRemoved` is already true, the code only pushes a warning, `repoGitEnv` stays null, and the `if (repoGitEnv)` block that would remove the link never runs — destroy returns `worktreeRemoved: true` with the symlink still present inside the managed root. That contradicts the PR's goal of no orphaned entries, and the case is exactly the dangling-symlink scenario commit 010b5a54 targets. Make the entry check use the same non-following semantics as isMissingPath.</comment>

<file context>
@@ -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;
</file context>

try {
return lstatSync(path, { throwIfNoEntry: false }) === undefined;
} catch {
return false;
}
}

function archiveReasonFor(
ctx: HostServiceContext,
local: { pullRequestId: string | null },
Expand Down Expand Up @@ -514,8 +524,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,
Expand All @@ -533,10 +544,53 @@ 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}` : ""
}`,
});
}
worktreeRemoved = true;
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
// 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`,
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
try {
await rm(local.worktreePath, { recursive: true, force: true });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Protect this fallback deletion from ancestor replacement between the root check and rm. A concurrent symlink swap can redirect recursive removal outside the managed root; use a no-follow or descriptor-based deletion that keeps validation and removal confined to the approved root.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts, line 565:

<comment>Protect this fallback deletion from ancestor replacement between the root check and `rm`. A concurrent symlink swap can redirect recursive removal outside the managed root; use a no-follow or descriptor-based deletion that keeps validation and removal confined to the approved root.</comment>

<file context>
@@ -533,10 +534,52 @@ async function runDestroyPhases(
+					);
+				} else {
+					try {
+						await rm(local.worktreePath, { recursive: true, force: true });
+					} catch (err) {
+						const message = err instanceof Error ? err.message : String(err);
</file context>

} 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: ${message}${
removeError ? ` (git worktree remove: ${removeError})` : ""
}`,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
}
// 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). `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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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-");
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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;
}
}
}

Expand Down
25 changes: 18 additions & 7 deletions packages/host-service/src/workers/tasks/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -214,15 +214,25 @@ 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)).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.
reportPhase?.("worktree-list");
Expand All @@ -231,6 +241,7 @@ export const gitWorktreeRemoveTask = defineWorkerTask<
stillRegistered: parseWorktreeList(raw).some(
(w) => normalizeWorktreePath(w.path) === target,
),
removeError,
};
},
});
Expand Down
Loading