Skip to content

Commit d02b4ad

Browse files
committed
fix: protect nested worktree roots during orphan cleanup
1 parent 8f40daa commit d02b4ad

2 files changed

Lines changed: 74 additions & 3 deletions

File tree

‎src/agents/worktrees/service.configured-root.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,45 @@ describe("configured managed worktree root", () => {
134134
await service.remove({ id: record.id, reason: "symlink-root" });
135135
expect((await service.restore({ id: record.id })).path).toBe(record.path);
136136
});
137+
138+
it.each(["nested", "deep", "symlink"])(
139+
"preserves %s custom-root contents during GC, including after a root change",
140+
async (kind) => {
141+
const nestedRoot = path.join(
142+
stateDir,
143+
"worktrees",
144+
"custom",
145+
...(kind === "deep" ? ["deeper"] : []),
146+
);
147+
await fs.mkdir(nestedRoot, { recursive: true });
148+
worktreeRoot = nestedRoot;
149+
if (kind === "symlink") {
150+
worktreeRoot = path.join(root, "linked-nested-root");
151+
await fs.symlink(
152+
nestedRoot,
153+
worktreeRoot,
154+
process.platform === "win32" ? "junction" : "dir",
155+
);
156+
}
157+
const unrelated = path.join(nestedRoot, "unregistered", "keep.txt");
158+
await fs.mkdir(path.dirname(unrelated));
159+
await fs.writeFile(unrelated, "unrelated data\n");
160+
expect((await service.gc()).orphansDeleted).toBe(0);
161+
expect(await fs.readFile(unrelated, "utf8")).toBe("unrelated data\n");
162+
163+
const record = await service.create({ repoRoot: repo, name: "nested", baseRef: "HEAD" });
164+
await fs.writeFile(path.join(record.path, "README.md"), "unsnapshotted edit\n");
165+
for (const nextRoot of [worktreeRoot, path.join(root, "next-root")]) {
166+
worktreeRoot = nextRoot;
167+
expect((await service.gc()).orphansDeleted).toBe(0);
168+
expect(await fs.readFile(path.join(record.path, "README.md"), "utf8")).toBe(
169+
"unsnapshotted edit\n",
170+
);
171+
expect(await fs.readFile(unrelated, "utf8")).toBe("unrelated data\n");
172+
expect(
173+
(await service.list()).find((entry) => entry.id === record.id)?.removedAt,
174+
).toBeUndefined();
175+
}
176+
},
177+
);
137178
});

‎src/agents/worktrees/service.ts‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { getRuntimeConfig, type OpenClawConfig } from "../../config/config.js";
77
import { resolveStateDir } from "../../config/paths.js";
88
import { isMissingPathError, formatErrorMessage } from "../../infra/errors.js";
99
import { root as fsRoot } from "../../infra/fs-safe.js";
10+
import { isPathInside } from "../../infra/path-guards.js";
1011
import { createSubsystemLogger } from "../../logging/subsystem.js";
1112
import {
1213
createStagedInputPathMatcher,
@@ -295,9 +296,13 @@ async function canonicalPathKey(target: string): Promise<string> {
295296
async function shouldPreserveOrphanCandidate(
296297
target: string,
297298
managedPaths: ReadonlySet<string>,
299+
customRoots: ReadonlySet<string>,
298300
): Promise<boolean> {
299301
const targetKey = await canonicalPathKey(target);
300-
if (managedPaths.has(targetKey)) {
302+
if (
303+
managedPaths.has(targetKey) ||
304+
[...customRoots].some((root) => isPathInside(root, targetKey) || isPathInside(targetKey, root))
305+
) {
301306
return true;
302307
}
303308
// Any top-level .git entry marks uncertain user work; broken indirection only
@@ -1734,6 +1739,31 @@ export class ManagedWorktreeService {
17341739
// root can contain unrelated directories; its cleanup is registry-bound above.
17351740
const worktreesRoot = path.join(resolveStateDir(this.env), "worktrees");
17361741
const fingerprints = await fs.readdir(worktreesRoot, { withFileTypes: true }).catch(() => []);
1742+
if (fingerprints.length === 0) {
1743+
return 0;
1744+
}
1745+
const defaultRoot = await canonicalPathKey(worktreesRoot);
1746+
const customRoots = new Set<string>();
1747+
// Retain roots from recorded paths after configuration changes. Canonical
1748+
// overlap protects nested roots and symlink aliases before recursive deletion.
1749+
for (const root of [
1750+
this.getConfig?.().worktreeRoot,
1751+
...records.map((record) => path.dirname(path.dirname(record.path))),
1752+
]) {
1753+
if (!root) {
1754+
continue;
1755+
}
1756+
try {
1757+
const canonical = await canonicalPathKey(root);
1758+
if (canonical !== defaultRoot) {
1759+
customRoots.add(canonical);
1760+
}
1761+
} catch (error) {
1762+
if (!isMissingPathError(error)) {
1763+
throw error;
1764+
}
1765+
}
1766+
}
17371767
let deleted = 0;
17381768
for (const fingerprint of fingerprints) {
17391769
if (!fingerprint.isDirectory()) {
@@ -1742,7 +1772,7 @@ export class ManagedWorktreeService {
17421772
const fingerprintPath = path.join(worktreesRoot, fingerprint.name);
17431773
// A root entry can be a checkout, not a fingerprint container; descending
17441774
// before applying the same preservation rule would expose its contents to deletion.
1745-
if (await shouldPreserveOrphanCandidate(fingerprintPath, managedPaths)) {
1775+
if (await shouldPreserveOrphanCandidate(fingerprintPath, managedPaths, customRoots)) {
17461776
continue;
17471777
}
17481778
const names = await fs.readdir(fingerprintPath, { withFileTypes: true }).catch(() => []);
@@ -1751,7 +1781,7 @@ export class ManagedWorktreeService {
17511781
continue;
17521782
}
17531783
const candidate = path.join(fingerprintPath, name.name);
1754-
if (await shouldPreserveOrphanCandidate(candidate, managedPaths)) {
1784+
if (await shouldPreserveOrphanCandidate(candidate, managedPaths, customRoots)) {
17551785
continue;
17561786
}
17571787
await fs.rm(candidate, { recursive: true, force: true });

0 commit comments

Comments
 (0)