Skip to content

Commit 7aa31a2

Browse files
fix(worktrees): preserve registered roots during orphan cleanup
Classify direct and nested checkout roots through Git worktree registration before recursive orphan cleanup, including unborn and canonicalized paths. Fail closed when checkout metadata cannot be inspected. Co-authored-by: 李琪0668001400 <[email protected]> Punchcard-Session: amber-meadow-timber-8r
1 parent a20746e commit 7aa31a2

2 files changed

Lines changed: 202 additions & 9 deletions

File tree

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import { execFile } from "node:child_process";
2+
import fs from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { promisify } from "node:util";
6+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
7+
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
8+
import { listGitWorktrees } from "./git.js";
9+
import { ManagedWorktreeService } from "./service.js";
10+
11+
const execFileAsync = promisify(execFile);
12+
13+
async function git(cwd: string, ...args: string[]): Promise<string> {
14+
const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], {
15+
encoding: "utf8",
16+
});
17+
return stdout.trim();
18+
}
19+
20+
describe("ManagedWorktreeService orphan reconciliation", () => {
21+
let root: string;
22+
let repo: string;
23+
let stateDir: string;
24+
let env: NodeJS.ProcessEnv;
25+
let service: ManagedWorktreeService;
26+
let branchOrdinal = 0;
27+
28+
beforeEach(async () => {
29+
root = await fs.mkdtemp(
30+
path.join(await fs.realpath(os.tmpdir()), "openclaw-worktree-orphans-"),
31+
);
32+
repo = path.join(root, "repo");
33+
stateDir = path.join(root, "state");
34+
await fs.mkdir(repo, { recursive: true });
35+
await fs.mkdir(stateDir, { recursive: true });
36+
await git(repo, "init", "-b", "main");
37+
await git(repo, "config", "user.name", "OpenClaw Test");
38+
await git(repo, "config", "user.email", "[email protected]");
39+
await fs.writeFile(path.join(repo, "README.md"), "base\n");
40+
await git(repo, "add", "README.md");
41+
await git(repo, "commit", "-m", "initial");
42+
env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
43+
service = new ManagedWorktreeService({ env });
44+
});
45+
46+
afterEach(async () => {
47+
closeOpenClawStateDatabaseForTest();
48+
await fs.rm(root, { recursive: true, force: true });
49+
});
50+
51+
async function addRegisteredWorktree(
52+
target: string,
53+
kind: "committed" | "unborn",
54+
): Promise<void> {
55+
const branch = `orphan-reconcile-${branchOrdinal++}`;
56+
await fs.mkdir(path.dirname(target), { recursive: true });
57+
if (kind === "unborn") {
58+
await git(repo, "worktree", "add", "--orphan", "-b", branch, target);
59+
} else {
60+
await git(repo, "worktree", "add", "-b", branch, target, "HEAD");
61+
}
62+
await fs.mkdir(path.join(target, "payload"), { recursive: true });
63+
await fs.writeFile(path.join(target, "payload", "keep.txt"), `${kind}\n`);
64+
}
65+
66+
async function expectRegisteredWorktreePreserved(
67+
target: string,
68+
kind: "committed" | "unborn",
69+
): Promise<void> {
70+
const result = await service.gc();
71+
72+
expect(result.orphansDeleted).toBe(0);
73+
await expect(fs.readFile(path.join(target, "payload", "keep.txt"), "utf8")).resolves.toBe(
74+
`${kind}\n`,
75+
);
76+
const canonicalTarget = await fs.realpath(target);
77+
const listed = await listGitWorktrees(repo);
78+
await expect(
79+
Promise.all(listed.map(async (entry) => await fs.realpath(entry.path))),
80+
).resolves.toContain(canonicalTarget);
81+
}
82+
83+
it("preserves a committed worktree directly under the worktrees root", async () => {
84+
const target = path.join(stateDir, "worktrees", "direct-committed");
85+
await addRegisteredWorktree(target, "committed");
86+
87+
await expectRegisteredWorktreePreserved(target, "committed");
88+
});
89+
90+
it("preserves an unborn worktree directly under the worktrees root", async () => {
91+
const target = path.join(stateDir, "worktrees", "direct-unborn");
92+
await addRegisteredWorktree(target, "unborn");
93+
94+
await expectRegisteredWorktreePreserved(target, "unborn");
95+
});
96+
97+
it("preserves a committed worktree under a fingerprint directory", async () => {
98+
const target = path.join(stateDir, "worktrees", "fingerprint", "nested-committed");
99+
await addRegisteredWorktree(target, "committed");
100+
101+
await expectRegisteredWorktreePreserved(target, "committed");
102+
});
103+
104+
it("preserves an unborn worktree under a fingerprint directory", async () => {
105+
const target = path.join(stateDir, "worktrees", "fingerprint", "nested-unborn");
106+
await addRegisteredWorktree(target, "unborn");
107+
108+
await expectRegisteredWorktreePreserved(target, "unborn");
109+
});
110+
111+
it("deletes unregistered debris under a fingerprint directory", async () => {
112+
const debris = path.join(stateDir, "worktrees", "fingerprint", "debris");
113+
await fs.mkdir(debris, { recursive: true });
114+
await fs.writeFile(path.join(debris, "remove.txt"), "debris\n");
115+
116+
const result = await service.gc();
117+
118+
expect(result.orphansDeleted).toBe(1);
119+
await expect(fs.stat(debris)).rejects.toMatchObject({ code: "ENOENT" });
120+
});
121+
122+
it("defers cleanup when checkout metadata cannot be inspected", async () => {
123+
const target = path.join(stateDir, "worktrees", "fingerprint", "broken-checkout");
124+
await fs.mkdir(path.join(target, "payload"), { recursive: true });
125+
await fs.writeFile(path.join(target, ".git"), "gitdir: /missing/openclaw-worktree-control\n");
126+
await fs.writeFile(path.join(target, "payload", "keep.txt"), "uncertain\n");
127+
128+
await expect(service.gc()).rejects.toThrow("git worktree list");
129+
await expect(fs.readFile(path.join(target, "payload", "keep.txt"), "utf8")).resolves.toBe(
130+
"uncertain\n",
131+
);
132+
});
133+
134+
it.skipIf(process.platform === "win32")(
135+
"canonicalizes a symlinked state root before matching registered paths",
136+
async () => {
137+
const realStateDir = path.join(root, "real-state");
138+
const linkedStateDir = path.join(root, "linked-state");
139+
await fs.mkdir(realStateDir);
140+
await fs.symlink(realStateDir, linkedStateDir, "dir");
141+
env = { ...process.env, OPENCLAW_STATE_DIR: linkedStateDir };
142+
service = new ManagedWorktreeService({ env });
143+
const target = path.join(realStateDir, "worktrees", "fingerprint", "nested-via-symlink");
144+
await addRegisteredWorktree(target, "committed");
145+
146+
await expectRegisteredWorktreePreserved(target, "committed");
147+
},
148+
);
149+
});

‎src/agents/worktrees/service.ts‎

Lines changed: 53 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,43 @@ async function resolveRepository(repoRoot: string): Promise<ResolvedRepository>
212212
return await resolveRepositoryFromRealPath(requested, repoRoot);
213213
}
214214

215+
async function canonicalPathKey(target: string): Promise<string> {
216+
const canonical = await fs.realpath(target);
217+
return process.platform === "win32" ? canonical.toLowerCase() : canonical;
218+
}
219+
220+
async function shouldPreserveOrphanCandidate(
221+
target: string,
222+
managedPaths: ReadonlySet<string>,
223+
): Promise<boolean> {
224+
const targetKey = await canonicalPathKey(target);
225+
if (managedPaths.has(targetKey)) {
226+
return true;
227+
}
228+
const hasOwnGitMarker = await pathExists(path.join(target, ".git"));
229+
if (!hasOwnGitMarker) {
230+
return false;
231+
}
232+
// Query from the checkout itself so registered unborn worktrees do not pass
233+
// through resolveRepository's intentional HEAD commit requirement.
234+
const listed = await listGitWorktrees(target);
235+
for (const entry of listed) {
236+
let listedKey: string;
237+
try {
238+
listedKey = await canonicalPathKey(entry.path);
239+
} catch (error) {
240+
if (isMissingFileError(error)) {
241+
continue;
242+
}
243+
throw error;
244+
}
245+
if (listedKey === targetKey) {
246+
return true;
247+
}
248+
}
249+
return false;
250+
}
251+
215252
async function cleanupFailedCreate(repoRoot: string, worktreePath: string, branch: string) {
216253
const removed = await runGit(repoRoot, ["worktree", "remove", "--force", worktreePath]);
217254
const deletedBranch = await runGit(repoRoot, ["branch", "-D", branch]);
@@ -1236,7 +1273,16 @@ export class ManagedWorktreeService {
12361273
}
12371274

12381275
private async reconcileOrphans(records: ManagedWorktreeRecord[]): Promise<number> {
1239-
const managedPaths = new Set(records.map((record) => path.resolve(record.path)));
1276+
const managedPaths = new Set<string>();
1277+
for (const record of records) {
1278+
try {
1279+
managedPaths.add(await canonicalPathKey(record.path));
1280+
} catch (error) {
1281+
if (!isMissingFileError(error)) {
1282+
throw error;
1283+
}
1284+
}
1285+
}
12401286
const worktreesRoot = path.join(resolveStateDir(this.env), "worktrees");
12411287
const fingerprints = await fs.readdir(worktreesRoot, { withFileTypes: true }).catch(() => []);
12421288
let deleted = 0;
@@ -1245,22 +1291,20 @@ export class ManagedWorktreeService {
12451291
continue;
12461292
}
12471293
const fingerprintPath = path.join(worktreesRoot, fingerprint.name);
1294+
// A root entry can be a checkout, not a fingerprint container; descending
1295+
// before applying the same preservation rule would expose its contents to deletion.
1296+
if (await shouldPreserveOrphanCandidate(fingerprintPath, managedPaths)) {
1297+
continue;
1298+
}
12481299
const names = await fs.readdir(fingerprintPath, { withFileTypes: true }).catch(() => []);
12491300
for (const name of names) {
12501301
if (!name.isDirectory()) {
12511302
continue;
12521303
}
12531304
const candidate = path.join(fingerprintPath, name.name);
1254-
if (managedPaths.has(path.resolve(candidate))) {
1305+
if (await shouldPreserveOrphanCandidate(candidate, managedPaths)) {
12551306
continue;
12561307
}
1257-
const repository = await resolveRepository(candidate).catch(() => undefined);
1258-
if (repository) {
1259-
const listed = await listGitWorktrees(repository.repoRoot).catch(() => []);
1260-
if (listed.some((entry) => path.resolve(entry.path) === path.resolve(candidate))) {
1261-
continue;
1262-
}
1263-
}
12641308
await fs.rm(candidate, { recursive: true, force: true });
12651309
deleted += 1;
12661310
}

0 commit comments

Comments
 (0)