The best way to control Claude Code, Codex and more from any computer or phone
fix(server): worktrees of git-annex repositories can be removed (#34065)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Nei Cardoso de Oliveira Neto committed
Nov 15, 2026 at 01:47 UTC
808dae1584351f6884439424f64114cf568f9a19
4 files changed
+141
-21
apps/server/src/storageCleanup.test.ts
+28
-3
@@ -649,6 +649,15 @@ const cleanupTestLayer = GitVcsDriver.layer.pipe(
649
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "storage-cleanup-" })),
650
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
651
);
652
+const annexWorktree = Effect.fnUntraced(function* (
653
+ fixture: Effect.Success<ReturnType<typeof cleanupFixture>>,
654
+ worktree: string,
655
+) {
656
+ const adminDir = (yield* fixture.command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout;
657
+ yield* fixture.fs.remove(`${worktree}/.git`);
658
+ yield* fixture.fs.symlink(adminDir.trim(), `${worktree}/.git`);
659
+});
660
+
661
const runCleanupTest = <A, E>(
662
effect: Effect.Effect<
663
A,
@@ -2099,7 +2108,7 @@ describe("orphan worktree reports", () => {
2108
),
2109
);
2110
2102
- it.live.each(["nested", "direct"] as const)(
2111
+ it.live.each(["nested", "direct", "annexed"] as const)(
2112
"reports a linked orphan's size without removing its files (%s)",
2113
(location) =>
2114
runCleanupTest(
@@ -2108,8 +2117,13 @@ describe("orphan worktree reports", () => {
2117
fixture.setThreads([]);
2118
const orphan = `${fixture.config.worktreesDir}/${location === "nested" ? "repository/" : ""}orphan`;
2119
yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]);
2111
- const sizes = yield* Effect.forEach(yield* fixture.fs.readDirectory(orphan), (name) =>
2112
- allocatedBytes(fixture.fs, `${orphan}/${name}`),
2120
+ if (location === "annexed") yield* annexWorktree(fixture, orphan);
2121
+ const sizes = yield* Effect.forEach(
2122
+ // Links are not measured, and the annexed `.git` is one.
2123
+ (yield* fixture.fs.readDirectory(orphan)).filter(
2124
+ (name) => location !== "annexed" || name !== ".git",
2125
+ ),
2126
+ (name) => allocatedBytes(fixture.fs, `${orphan}/${name}`),
2127
);
2128
const outside = yield* fixture.fs.makeTempDirectoryScoped();
2129
yield* fixture.fs.writeFileString(`${outside}/external`, "outside data");
@@ -2963,6 +2977,17 @@ describe("storage cleanup reports and local file policies", () => {
2977
}),
2978
),
2979
);
2980
+ it.live("removes a worktree whose .git file git-annex replaced with a symlink", () =>
2981
+ runCleanupTest(
2982
+ Effect.gen(function* () {
2983
+ const fixture = yield* cleanupFixture();
2984
+ const { service, worktree, fs } = fixture;
2985
+ yield* annexWorktree(fixture, worktree);
2986
+ expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" });
2987
+ expect(yield* fs.exists(worktree)).toBe(false);
2988
+ }),
2989
+ ),
2990
+ );
2991
it.live("keeps a worktree when the inspection cannot read its directories", () =>
2992
runCleanupTest(
2993
Effect.gen(function* () {
apps/server/src/storageCleanup.ts
+8
-8
@@ -58,7 +58,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
58
import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";
59
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
60
import { isNonRepositoryGitStderr } from "./vcs/GitVcsDriverCore.ts";
61
-import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";
61
+import { isLinkedWorktree, removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";
62
import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
63
import * as HostProcess from "@t3tools/shared/HostProcess";
64
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
@@ -591,7 +591,7 @@ const make = Effect.gen(function* () {
591
const modified = Option.getOrNull((yield* fs.stat(worktreePath)).mtime);
592
if (modified !== null && modified.getTime() > now - ORPHAN_WORKTREE_GRACE_MS) return;
593
const gitPath = path.join(worktreePath, ".git");
594
- const linked = (yield* fs.exists(gitPath)) && (yield* fs.stat(gitPath)).type === "File";
594
+ const linked = (yield* fs.exists(gitPath)) && (yield* isLinkedWorktree(worktreePath));
595
reported.add(key);
596
const remaining = measurementDeadline - (yield* Clock.currentTimeMillis);
597
if (!orphanSizes.has(key) && (firstMeasurement || remaining > 0)) {
@@ -636,7 +636,7 @@ const make = Effect.gen(function* () {
636
(worktree) =>
637
Effect.gen(function* () {
638
if (pathKey(yield* fs.realPath(worktree)) !== pathKey(worktree)) return false;
639
- return (yield* fs.stat(path.join(worktree, ".git"))).type === "File";
639
+ return yield* isLinkedWorktree(worktree);
640
}).pipe(Effect.orElseSucceed(() => false)),
641
);
642
});
@@ -647,7 +647,7 @@ const make = Effect.gen(function* () {
647
if (referenced.has(pathKey(projectDirectory))) return;
648
const gitPath = path.join(projectDirectory, ".git");
649
if (yield* fs.exists(gitPath)) {
650
- if ((yield* fs.stat(gitPath)).type === "File") yield* report(projectDirectory);
650
+ if (yield* isLinkedWorktree(projectDirectory)) yield* report(projectDirectory);
651
return;
652
}
653
for (const worktreePath of yield* directories(projectDirectory, root)) {
@@ -1084,10 +1084,10 @@ const make = Effect.gen(function* () {
1084
return "worktree is a symbolic link";
1085
if (!roots.some((root) => inside(root, realPath)))
1086
return "outside the managed worktree folder";
1087
- const gitLink = yield* fs
1088
- .stat(path.join(worktreePath, ".git"))
1089
- .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined));
1090
- if (gitLink?.type !== "File") return "not a linked worktree";
1087
+ const linked = yield* isLinkedWorktree(worktreePath).pipe(
1088
+ Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
1089
+ );
1090
+ if (!linked) return "not a linked worktree";
1091
return null;
1092
});
1093
const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
apps/server/src/vcs/GitVcsDriverCore.test.ts
+35
@@ -7262,6 +7262,41 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
7262
}),
7263
);
7264
7265
+ it.effect.skipIf(!symlinksSupported)(
7266
+ "removes a worktree whose .git file git-annex replaced with a symlink, keeping the symlink when refused",
7267
+ () =>
7268
+ Effect.gen(function* () {
7269
+ const cwd = yield* makeTmpDir();
7270
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
7271
+ const pathService = yield* Path.Path;
7272
+ const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "annexed");
7273
+ const driver = yield* GitVcsDriver.GitVcsDriver;
7274
+ yield* driver.createWorktree({
7275
+ cwd,
7276
+ path: worktreePath,
7277
+ refName: initialBranch,
7278
+ newRefName: "feature/annexed",
7279
+ });
7280
+ const gitFile = pathService.join(worktreePath, ".git");
7281
+ const adminDir = (yield* git(worktreePath, ["rev-parse", "--absolute-git-dir"])).trim();
7282
+ NodeFS.rmSync(gitFile);
7283
+ NodeFS.symlinkSync(adminDir, gitFile);
7284
+ yield* writeTextFile(worktreePath, "notes.txt", "draft\n");
7285
+
7286
+ const refused = yield* Effect.result(driver.removeWorktree({ cwd, path: worktreePath }));
7287
+
7288
+ assert.isTrue(Result.isFailure(refused));
7289
+ assert.isTrue(NodeFS.lstatSync(gitFile).isSymbolicLink());
7290
+ assert.equal(NodeFS.realpathSync(gitFile), NodeFS.realpathSync(adminDir));
7291
+ NodeFS.rmSync(pathService.join(worktreePath, "notes.txt"));
7292
+
7293
+ yield* driver.removeWorktree({ cwd, path: worktreePath });
7294
+
7295
+ assert.isFalse(NodeFS.existsSync(worktreePath));
7296
+ assert.isFalse(NodeFS.existsSync(adminDir));
7297
+ }),
7298
+ );
7299
+
7300
it.effect("leaves a folder alone that only shares the worktree's short name", () =>
7301
Effect.gen(function* () {
7302
const cwd = yield* makeTmpDir();
apps/server/src/vcs/worktreeRemoval.ts
+70
-10
@@ -9,6 +9,42 @@ import type * as GitVcsDriver from "./GitVcsDriver.ts";
9
10
const INDEX_LIST_MAX_BYTES = 64 * 1024 * 1024;
11
12
+/**
13
+ * git-annex replaces a linked worktree's `.git` file with a symlink to its admin
14
+ * directory, so its symlinks into `.git/annex` resolve. Git then refuses to remove it.
15
+ */
16
+const annexedAdminDir = Effect.fn("WorktreeRemoval.annexedAdminDir")(
17
+ function* (worktreePath: string) {
18
+ const fileSystem = yield* FileSystem.FileSystem;
19
+ const path = yield* Path.Path;
20
+ const adminDir = path.resolve(
21
+ worktreePath,
22
+ yield* fileSystem.readLink(path.join(worktreePath, ".git")),
23
+ );
24
+ const pointsBackTo = path.dirname(
25
+ path.resolve(
26
+ adminDir,
27
+ (yield* fileSystem.readFileString(path.join(adminDir, "gitdir"))).trim(),
28
+ ),
29
+ );
30
+ return (yield* fileSystem.realPath(pointsBackTo)) === (yield* fileSystem.realPath(worktreePath))
31
+ ? Option.some(adminDir)
32
+ : Option.none();
33
+ },
34
+ Effect.orElseSucceed(() => Option.none<string>()),
35
+);
36
+
37
+export const isLinkedWorktree = Effect.fn("WorktreeRemoval.isLinkedWorktree")(function* (
38
+ worktreePath: string,
39
+) {
40
+ const fileSystem = yield* FileSystem.FileSystem;
41
+ const path = yield* Path.Path;
42
+ return (
43
+ (yield* fileSystem.stat(path.join(worktreePath, ".git"))).type === "File" ||
44
+ Option.isSome(yield* annexedAdminDir(worktreePath))
45
+ );
46
+});
47
+
48
/**
49
* Git for Windows before 2.54 follows NTFS junctions; newer Git leaves them behind.
50
* On Windows, mirror Git's removal checks, then delete with Node's `rm`, which
@@ -33,6 +69,39 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt
69
// Git refuses to remove a worktree with untracked files unless forced, but
70
// its check honors `status.showUntrackedFiles=no` and would delete them.
71
const statusConfig = ["-c", "status.showUntrackedFiles=normal"];
72
+ // Git's own refusals, worded the way it prints them.
73
+ const refuse = (message: string, cause?: unknown) =>
74
+ new GitCommandError({
75
+ operation: input.operation,
76
+ command: "git worktree remove",
77
+ cwd: input.cwd,
78
+ detail: `fatal: ${message}`,
79
+ ...(cause === undefined ? {} : { cause }),
80
+ });
81
+ const annexed = yield* annexedAdminDir(worktreePath);
82
+ if (Option.isSome(annexed)) {
83
+ const adminDir = annexed.value;
84
+ const writeGitFile = fileSystem.writeFileString(gitFile, `gitdir: ${adminDir}\n`);
85
+ // A kept worktree's annexed files resolve only through the symlink; a gitdir
86
+ // file is the fallback when it cannot be recreated.
87
+ yield* Effect.addFinalizer(() =>
88
+ fileSystem.exists(worktreePath).pipe(
89
+ Effect.flatMap((kept) =>
90
+ kept
91
+ ? fileSystem.remove(gitFile, { force: true }).pipe(
92
+ Effect.andThen(fileSystem.symlink(adminDir, gitFile)),
93
+ Effect.catch(() => writeGitFile),
94
+ )
95
+ : Effect.void,
96
+ ),
97
+ Effect.ignore,
98
+ ),
99
+ );
100
+ yield* fileSystem.remove(gitFile).pipe(
101
+ Effect.andThen(writeGitFile),
102
+ Effect.mapError((cause) => refuse(`failed to replace '${gitFile}'`, cause)),
103
+ );
104
+ }
105
const linked =
106
(yield* HostProcess.isWindows) &&
107
(yield* fileSystem.stat(gitFile).pipe(
@@ -50,15 +119,6 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt
119
]);
120
}
121
53
- // Git's own refusals, worded the way it prints them.
54
- const refuse = (message: string, cause?: unknown) =>
55
- new GitCommandError({
56
- operation: input.operation,
57
- command: "git worktree remove",
58
- cwd: input.cwd,
59
- detail: `fatal: ${message}`,
60
- ...(cause === undefined ? {} : { cause }),
61
- });
122
const gitOutput = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
123
input
124
.execute({
@@ -153,4 +213,4 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt
213
);
214
// The folder is gone, so Git only drops the worktree's metadata.
215
return yield* input.run(["worktree", "remove", "--force", "--force", "--", worktreePath]);
156
-});
216
+}, Effect.scoped);