The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 17:15 UTC
fix(server): a folder that only holds a repository's worktrees is refused as a project (#36366)
Julius Marminge committed
Nov 13, 2026 at 12:41 UTC
41156481b1c2a9ea8f8b97680b76f17685387d38
7 files changed
+319
-24
apps/server/src/project/ProjectService.test.ts
+64
@@ -31,6 +31,7 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
31
import * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
32
import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
33
import * as SqlitePersistence from "../persistence/Sqlite.ts";
34
+import * as ProcessRunner from "../processRunner.ts";
35
import * as ServerSettings from "../serverSettings.ts";
36
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
37
import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts";
@@ -783,6 +784,69 @@ it.effect("resolves a restored icon immediately after reselecting its saved path
784
}).pipe(Effect.provide(NodeServices.layer)),
785
);
786
787
+it.effect("refuses a worktree container as a new project and as a new workspace root", () =>
788
+ Effect.gen(function* () {
789
+ const fileSystem = yield* FileSystem.FileSystem;
790
+ const processRunner = yield* ProcessRunner.ProcessRunner;
791
+ const fixture = yield* fileSystem.makeTempDirectoryScoped({ prefix: "project-container-" });
792
+ const git = (cwd: string, ...args: ReadonlyArray<string>) =>
793
+ processRunner.run({
794
+ command: "git",
795
+ args: ["-C", cwd, "-c", "user.email=t@t", "-c", "user.name=t", ...args],
796
+ });
797
+ const source = `${fixture}/source`;
798
+ const container = `${fixture}/container`;
799
+ yield* fileSystem.makeDirectory(source);
800
+ yield* fileSystem.makeDirectory(container);
801
+ yield* git(source, "init", "-b", "develop");
802
+ yield* fileSystem.writeFileString(`${source}/README.md`, "readme\n");
803
+ yield* git(source, "add", "README.md");
804
+ yield* git(source, "commit", "-m", "init");
805
+ yield* git(fixture, "clone", "--bare", source, `${container}/.bare`);
806
+ yield* fileSystem.writeFileString(`${container}/.git`, "gitdir: ./.bare\n");
807
+ yield* git(container, "worktree", "add", "develop", "develop");
808
+
809
+ yield* Effect.gen(function* () {
810
+ const service = yield* ProjectService.ProjectService;
811
+ // As cloned the container is bare; Initialize Git or a config edit clears core.bare.
812
+ for (const coreBare of ["true", "false"]) {
813
+ yield* git(container, "config", "core.bare", coreBare);
814
+ const rejected = yield* service
815
+ .create({
816
+ commandId: CommandId.make(`command:container:create:${coreBare}`),
817
+ projectId: ProjectId.make(`project:container:${coreBare}`),
818
+ title: "Container",
819
+ workspaceRoot: container,
820
+ })
821
+ .pipe(Effect.flip);
822
+ assert.equal(rejected._tag, "ProjectInvalidError", `core.bare=${coreBare}`);
823
+ assert.include(rejected.message, "Add one of its worktrees");
824
+ assert.isTrue(Option.isNone(yield* service.getByWorkspaceRoot(container)));
825
+ }
826
+
827
+ const projectId = ProjectId.make("project:container:worktree");
828
+ const worktree = yield* service.create({
829
+ commandId: CommandId.make("command:container:worktree"),
830
+ projectId,
831
+ title: "Worktree",
832
+ workspaceRoot: `${container}/develop`,
833
+ });
834
+ const moved = yield* service
835
+ .update({
836
+ commandId: CommandId.make("command:container:move"),
837
+ projectId,
838
+ workspaceRoot: container,
839
+ })
840
+ .pipe(Effect.flip);
841
+ assert.equal(moved._tag, "ProjectInvalidError");
842
+ assert.equal(
843
+ Option.getOrThrow(yield* service.getById(projectId)).workspaceRoot,
844
+ worktree.workspaceRoot,
845
+ );
846
+ }).pipe(Effect.provide(layerTest));
847
+ }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),
848
+);
849
+
850
it.effect("serializes two projects claiming the same workspace root", () =>
851
Effect.gen(function* () {
852
const eventSink = yield* EventSink.EventSinkV2;
apps/server/src/project/ProjectService.ts
+20
@@ -34,7 +34,9 @@ import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecuto
34
import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts";
35
import * as ServerSettings from "../serverSettings.ts";
36
import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
37
+import * as ProcessRunner from "../processRunner.ts";
38
import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts";
39
+import { makeIsWorktreeContainer } from "./worktreeContainer.ts";
40
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
41
42
export interface ProjectCreateInput extends ProjectCreatePayload {
@@ -182,6 +184,9 @@ export const make = Effect.gen(function* () {
184
const serverSettings = yield* ServerSettings.ServerSettingsService;
185
const fileSystem = yield* FileSystem.FileSystem;
186
const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
187
+ const isWorktreeContainer = yield* makeIsWorktreeContainer.pipe(
188
+ Effect.provide(ProcessRunner.layer),
189
+ );
190
const projectLocks = yield* KeyedLock.make<ProjectId>();
191
const workspaceLocks = yield* KeyedLock.make<string>();
192
@@ -244,6 +249,17 @@ export const make = Effect.gen(function* () {
249
),
250
);
251
252
+ const rejectWorktreeContainer = Effect.fn("ProjectService.rejectWorktreeContainer")(function* (
253
+ projectId: ProjectId,
254
+ workspaceRoot: string,
255
+ ) {
256
+ if (!(yield* isWorktreeContainer(workspaceRoot))) return;
257
+ return yield* new ProjectInvalidError({
258
+ projectId,
259
+ detail: `${workspaceRoot} holds a repository's worktrees but is not a checkout itself. Add one of its worktrees as the project instead.`,
260
+ });
261
+ });
262
+
263
const commit = Effect.fn("ProjectService.commit")(function* (command: ProjectCommand) {
264
const { projectId } = command;
265
const dispatchError = (cause: unknown) =>
@@ -383,6 +399,7 @@ export const make = Effect.gen(function* () {
399
workspaceRoot: input.workspaceRoot,
400
createIfMissing: input.createWorkspaceRootIfMissing ?? false,
401
});
402
+ yield* rejectWorktreeContainer(input.projectId, workspaceRoot);
403
yield* commit({
404
type: "project.create",
405
commandId: input.commandId,
@@ -410,6 +427,9 @@ export const make = Effect.gen(function* () {
427
projectId: input.projectId,
428
workspaceRoot: input.workspaceRoot,
429
});
430
+ if (workspaceRoot !== previousRoot) {
431
+ yield* rejectWorktreeContainer(input.projectId, workspaceRoot);
432
+ }
433
yield* commit({
434
type: "project.meta.update",
435
commandId: input.commandId,
apps/server/src/project/worktreeContainer.test.ts
new
+94
@@ -0,0 +1,94 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { assert, it } from "@effect/vitest";
3
+import * as Effect from "effect/Effect";
4
+import * as FileSystem from "effect/FileSystem";
5
+import * as Layer from "effect/Layer";
6
+import * as Path from "effect/Path";
7
+
8
+import * as ProcessRunner from "../processRunner.ts";
9
+import { makeIsWorktreeContainer } from "./worktreeContainer.ts";
10
+
11
+const git = Effect.fn("worktreeContainerTest.git")(function* (
12
+ cwd: string,
13
+ ...args: ReadonlyArray<string>
14
+) {
15
+ const processRunner = yield* ProcessRunner.ProcessRunner;
16
+ return yield* processRunner.run({
17
+ command: "git",
18
+ args: ["-C", cwd, "-c", "user.email=t@t", "-c", "user.name=t", ...args],
19
+ });
20
+});
21
+
22
+it.layer(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))(
23
+ "isWorktreeContainer",
24
+ (it) => {
25
+ it.effect("is true only for a folder of worktrees around metadata that is no checkout", () =>
26
+ Effect.gen(function* () {
27
+ const fileSystem = yield* FileSystem.FileSystem;
28
+ const path = yield* Path.Path;
29
+ const isWorktreeContainer = yield* makeIsWorktreeContainer;
30
+ const fixture = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-container-test-" });
31
+
32
+ const source = path.join(fixture, "source");
33
+ yield* fileSystem.makeDirectory(source);
34
+ yield* git(source, "init", "-b", "develop");
35
+ yield* fileSystem.writeFileString(path.join(source, "README.md"), "readme\n");
36
+ yield* git(source, "add", "README.md");
37
+ yield* git(source, "commit", "-m", "init");
38
+
39
+ const makeContainer = Effect.fn(function* (name: string, coreBare: boolean) {
40
+ const root = path.join(fixture, name);
41
+ yield* fileSystem.makeDirectory(root);
42
+ yield* git(fixture, "clone", "--bare", source, path.join(root, ".bare"));
43
+ yield* fileSystem.writeFileString(path.join(root, ".git"), "gitdir: ./.bare\n");
44
+ yield* git(root, "worktree", "add", "develop", "develop");
45
+ yield* git(root, "config", "core.bare", String(coreBare));
46
+ return root;
47
+ });
48
+ const makeSeparateGitDirCheckout = Effect.fn(function* (name: string) {
49
+ const root = path.join(fixture, name);
50
+ yield* fileSystem.makeDirectory(root);
51
+ yield* git(root, "init", "-b", "develop", "--separate-git-dir", ".metadata", ".");
52
+ return root;
53
+ });
54
+
55
+ const container = yield* makeContainer("container", false);
56
+ assert.isTrue(yield* isWorktreeContainer(container), "container");
57
+ assert.isFalse(yield* isWorktreeContainer(path.join(container, "develop")), "its worktree");
58
+
59
+ const linked = path.join(fixture, "link");
60
+ yield* fileSystem.symlink(container, linked);
61
+ assert.isTrue(yield* isWorktreeContainer(linked), "container through a symlink");
62
+
63
+ // The issue's steps leave core.bare set; Initialize Git would clear it later.
64
+ const bare = yield* makeContainer("bare", true);
65
+ assert.isTrue(yield* isWorktreeContainer(bare), "core.bare container");
66
+
67
+ // Git allows an orphan worktree before the first commit: no index, yet a valid checkout.
68
+ const fresh = yield* makeSeparateGitDirCheckout("fresh");
69
+ yield* git(fresh, "worktree", "add", "--orphan", "-b", "feature", "../fresh-feature");
70
+ assert.isFalse(yield* isWorktreeContainer(fresh), "fresh checkout with an orphan worktree");
71
+
72
+ const checkout = yield* makeSeparateGitDirCheckout("checkout");
73
+ yield* fileSystem.writeFileString(path.join(checkout, "README.md"), "readme\n");
74
+ yield* git(checkout, "add", "README.md");
75
+ yield* git(checkout, "commit", "-m", "init");
76
+ yield* git(checkout, "worktree", "add", "worktrees/feature", "-b", "feature");
77
+ assert.isFalse(yield* isWorktreeContainer(checkout), "checkout with a nested worktree");
78
+
79
+ const outside = path.join(fixture, "outside");
80
+ yield* git(
81
+ fixture,
82
+ "clone",
83
+ "--no-checkout",
84
+ "--separate-git-dir",
85
+ path.join(outside, ".metadata"),
86
+ source,
87
+ outside,
88
+ );
89
+ yield* git(outside, "worktree", "add", "../outside-feature", "-b", "feature");
90
+ assert.isFalse(yield* isWorktreeContainer(outside), "worktrees outside the folder");
91
+ }),
92
+ );
93
+ },
94
+);
apps/server/src/project/worktreeContainer.ts
new
+95
@@ -0,0 +1,95 @@
1
+import * as HostProcess from "@t3tools/shared/HostProcess";
2
+import * as Effect from "effect/Effect";
3
+import * as FileSystem from "effect/FileSystem";
4
+import * as Path from "effect/Path";
5
+
6
+import * as ProcessRunner from "../processRunner.ts";
7
+import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts";
8
+
9
+const parseGitfileTarget = (contents: string): string | undefined => {
10
+ const firstLine = contents.split(/\r?\n/u, 1)[0] ?? "";
11
+ if (!firstLine.startsWith("gitdir:")) return undefined;
12
+ const target = firstLine.slice("gitdir:".length).trim();
13
+ return target === "" ? undefined : target;
14
+};
15
+
16
+const splitNul = (stdout: string) => stdout.split("\0").filter((entry) => entry !== "");
17
+
18
+/**
19
+ * Whether a folder only holds a repository's metadata and worktrees: its `.git` file points at
20
+ * metadata inside it, a linked worktree lives inside it, and either the repository is bare or it
21
+ * has commits but no index. A checkout whose tracked files are all deleted keeps its index, and a
22
+ * fresh one has no commit. Anything this cannot establish answers false.
23
+ */
24
+export const makeIsWorktreeContainer = Effect.gen(function* () {
25
+ const fileSystem = yield* FileSystem.FileSystem;
26
+ const path = yield* Path.Path;
27
+ const processRunner = yield* ProcessRunner.ProcessRunner;
28
+ const platform = yield* HostProcess.Platform;
29
+ const env = {
30
+ ...unsetInheritedRepositoryEnv(process.env, platform),
31
+ ...explicitBareRepositoryEnv(process.env, platform),
32
+ };
33
+
34
+ const realPath = (target: string) => fileSystem.realPath(target).pipe(Effect.option);
35
+ const isInside = (parent: string, child: string) => {
36
+ const relative = path.relative(parent, child);
37
+ return (
38
+ relative !== "" &&
39
+ relative !== ".." &&
40
+ !relative.startsWith(`..${path.sep}`) &&
41
+ !path.isAbsolute(relative)
42
+ );
43
+ };
44
+
45
+ return Effect.fn("ProjectService.isWorktreeContainer")(function* (workspaceRoot: string) {
46
+ // A `.git` directory is an ordinary checkout, so only a gitfile costs any Git process.
47
+ const gitfileTarget = yield* fileSystem.readFileString(path.join(workspaceRoot, ".git")).pipe(
48
+ Effect.map(parseGitfileTarget),
49
+ Effect.orElseSucceed(() => undefined),
50
+ );
51
+ if (gitfileTarget === undefined) return false;
52
+ const root = yield* realPath(workspaceRoot);
53
+ const gitDir = yield* realPath(path.resolve(workspaceRoot, gitfileTarget));
54
+ if (root._tag === "None" || gitDir._tag === "None") return false;
55
+ if (!isInside(root.value, gitDir.value)) return false;
56
+
57
+ const git = (args: ReadonlyArray<string>) =>
58
+ processRunner
59
+ .run({
60
+ command: "git",
61
+ args: ["-C", workspaceRoot, ...args],
62
+ env,
63
+ timeoutBehavior: "timedOutResult",
64
+ })
65
+ .pipe(
66
+ Effect.map((result) => (result.code === 0 && !result.timedOut ? result.stdout : null)),
67
+ Effect.orElseSucceed(() => null),
68
+ );
69
+
70
+ // Initializing Git in a bare container clears core.bare, so it is refused while still bare.
71
+ const isBare = yield* git(["rev-parse", "--is-bare-repository"]);
72
+ if (isBare === null) return false;
73
+ if (isBare.trim() !== "true") {
74
+ const hasCommit = yield* git(["rev-parse", "--quiet", "--verify", "HEAD^{commit}"]);
75
+ if (hasCommit === null) return false;
76
+ const hasIndex = yield* fileSystem
77
+ .exists(path.join(gitDir.value, "index"))
78
+ .pipe(Effect.orElseSucceed(() => true));
79
+ if (hasIndex) return false;
80
+ }
81
+
82
+ const worktrees = yield* git(["worktree", "list", "--porcelain", "-z"]);
83
+ if (worktrees === null) return false;
84
+ // The first entry is the main worktree, which Git reports as the metadata directory here.
85
+ const linkedWorktreePaths = splitNul(worktrees)
86
+ .filter((field) => field.startsWith("worktree "))
87
+ .slice(1)
88
+ .map((field) => field.slice("worktree ".length));
89
+ for (const worktreePath of linkedWorktreePaths) {
90
+ const worktree = yield* realPath(worktreePath);
91
+ if (worktree._tag === "Some" && isInside(root.value, worktree.value)) return true;
92
+ }
93
+ return false;
94
+ });
95
+});
apps/server/src/serverRuntimeStartup.test.ts
+27
-17
@@ -52,6 +52,7 @@ it.effect.each([
52
"disabled-default",
53
"launch-failure",
54
"project-failure",
55
+ "project-refused",
56
] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) =>
57
Effect.gen(function* () {
58
const projectId = ProjectId.make("bootstrap-project");
@@ -155,22 +156,28 @@ it.effect.each([
156
bootstrap: () =>
157
scenario === "project-failure"
158
? Effect.die("project bootstrap failed")
158
- : Effect.succeed({
159
- created: true,
160
- project: {
161
- id: projectId,
162
- title: "Project",
163
- workspaceRoot: "/bootstrap-project",
164
- repositoryIdentity: null,
165
- faviconPath: null,
166
- scripts: [],
167
- createdAt: "2026-01-01T00:00:00Z",
168
- updatedAt: "2026-01-01T00:00:00Z",
169
- deletedAt: null,
170
- defaultModelSelection:
171
- scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null,
172
- },
173
- }),
159
+ : scenario === "project-refused"
160
+ ? Effect.fail(
161
+ new ProjectService.ProjectInvalidError({ projectId, detail: "refused folder" }),
162
+ )
163
+ : Effect.succeed({
164
+ created: true,
165
+ project: {
166
+ id: projectId,
167
+ title: "Project",
168
+ workspaceRoot: "/bootstrap-project",
169
+ repositoryIdentity: null,
170
+ faviconPath: null,
171
+ scripts: [],
172
+ createdAt: "2026-01-01T00:00:00Z",
173
+ updatedAt: "2026-01-01T00:00:00Z",
174
+ deletedAt: null,
175
+ defaultModelSelection:
176
+ scenario === "disabled-default"
177
+ ? { instanceId, model: "custom-model" }
178
+ : null,
179
+ },
180
+ }),
181
}),
182
Layer.mock(ThreadManagement.ThreadManagementService)({
183
countThreads: () => Effect.succeed(0),
@@ -223,7 +230,10 @@ it.effect.each([
230
} else {
231
assert.isDefined(welcome);
232
if (welcome?.type === "welcome") {
226
- assert.equal(welcome.payload.bootstrapProjectId, projectId);
233
+ assert.equal(
234
+ welcome.payload.bootstrapProjectId,
235
+ scenario === "project-refused" ? undefined : projectId,
236
+ );
237
assert.isUndefined(welcome.payload.bootstrapThreadId);
238
}
239
}
apps/server/src/serverRuntimeStartup.ts
+18
-6
@@ -270,12 +270,24 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
270
271
if (serverConfig.autoBootstrapProjectFromCwd) {
272
const threadModelSelection = getAutoBootstrapThreadModelSelection();
273
- const { project } = yield* projects.bootstrap({
274
- commandId: CommandId.make(yield* randomUUID),
275
- projectId: ProjectId.make(yield* randomUUID),
276
- title: path.basename(serverConfig.cwd) || "project",
277
- workspaceRoot: serverConfig.cwd,
278
- });
273
+ const bootstrapped = yield* projects
274
+ .bootstrap({
275
+ commandId: CommandId.make(yield* randomUUID),
276
+ projectId: ProjectId.make(yield* randomUUID),
277
+ title: path.basename(serverConfig.cwd) || "project",
278
+ workspaceRoot: serverConfig.cwd,
279
+ })
280
+ .pipe(
281
+ // A folder the project rules refuse must not stop the server from starting there.
282
+ Effect.catchTags({
283
+ ProjectInvalidError: (error) =>
284
+ Effect.logWarning("Skipped bootstrap project", { detail: error.detail }).pipe(
285
+ Effect.as(undefined),
286
+ ),
287
+ }),
288
+ );
289
+ if (bootstrapped === undefined) return {} satisfies AutoBootstrapWelcomeTargets;
290
+ const { project } = bootstrapped;
291
const existingThread = (yield* threads.listActiveShellIndex()).find(
292
(thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),
293
);
apps/server/src/ws.ts
+1
-1
@@ -2979,7 +2979,7 @@ export const layerWsRpc = (
2979
new ProjectMutationError({
2980
commandId: mutation.commandId,
2981
message:
2982
- cause._tag === "ProjectNotEmptyError"
2982
+ cause._tag === "ProjectNotEmptyError" || cause._tag === "ProjectInvalidError"
2983
? cause.message
2984
: "Failed to mutate project.",
2985
cause,