The best way to control Claude Code, Codex and more from any computer or phone
refactor(server): resolve project and worktree folders in one place (#20449)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 23:45 UTC
8e0d5e5e4dafb2e9fb9b35190eda456ffed07a18
21 files changed
+1001
-197
apps/server/src/mcp/WorktreeMcpService.test.ts
+15
-71
@@ -17,7 +17,6 @@ import * as Exit from "effect/Exit";
17
import * as Fiber from "effect/Fiber";
18
import * as Layer from "effect/Layer";
19
import * as Option from "effect/Option";
20
-import * as Path from "effect/Path";
20
import * as Schema from "effect/Schema";
21
22
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -104,7 +103,6 @@ interface HarnessOptions {
103
readonly projectMissing?: boolean;
104
readonly projectReadFails?: boolean;
105
readonly existingBranchWorktreePath?: string | null;
107
- readonly pathSemantics?: "win32" | "posix";
106
readonly createWorktreeFails?: boolean;
107
readonly fetchRemoteFails?: boolean;
108
readonly resolveRemoteFails?: boolean;
@@ -287,22 +285,7 @@ const makeHarness = (options: HarnessOptions = {}) => {
285
}
286
});
287
290
- // Optional deterministic Path semantics: providing this BEFORE the general
291
- // mocks means the service resolves Path here rather than from NodeServices,
292
- // so absolute-path validation is testable independently of the host OS.
293
- const win32IsAbsolute = (value: string) => /^(?:[a-zA-Z]:[\\/]|[\\/])/.test(value);
294
- const posixIsAbsolute = (value: string) => value.startsWith("/");
295
- const layerService =
296
- options.pathSemantics === undefined
297
- ? WorktreeMcpService.layer
298
- : WorktreeMcpService.layer.pipe(
299
- Layer.provide(
300
- Layer.succeed(Path.Path, {
301
- isAbsolute: options.pathSemantics === "win32" ? win32IsAbsolute : posixIsAbsolute,
302
- } as unknown as Path.Path),
303
- ),
304
- );
305
- const layer = layerService.pipe(
288
+ const layer = WorktreeMcpService.layer.pipe(
289
Layer.provide(
290
Layer.mergeAll(
291
Layer.mock(ThreadManagementService.ThreadManagementService)({
@@ -386,6 +369,9 @@ const runStatus = (harness: ReturnType<typeof makeHarness>) =>
369
return yield* service.status(harness.scope);
370
}).pipe(Effect.provide(harness.layer));
371
372
+// Decodes tool arguments the way the MCP tool does before calling the service.
373
+const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
374
+
375
describe("t3_worktree_handoff", () => {
376
it.effect("creates a worktree from the current branch and re-points the thread", () => {
377
const harness = makeHarness();
@@ -501,14 +487,13 @@ describe("t3_worktree_handoff", () => {
487
});
488
});
489
504
- it.effect("starts from origin and honors explicit baseRef and path", () => {
490
+ it.effect("starts from origin and honors an explicit baseRef", () => {
491
const harness = makeHarness();
492
return Effect.gen(function* () {
493
const result = yield* runHandoff(harness, {
494
branch: "feature/from-origin",
495
baseRef: "dev",
496
startFromOrigin: true,
511
- path: "/custom/worktree/location",
497
runSetupScript: false,
498
});
499
@@ -526,11 +511,11 @@ describe("t3_worktree_handoff", () => {
511
refName: "abc123",
512
newRefName: "feature/from-origin",
513
baseRefName: "dev",
529
- path: "/custom/worktree/location",
514
+ path: null,
515
});
516
expect(harness.localStatus).toHaveBeenCalled();
517
expect(harness.runForThread).not.toHaveBeenCalled();
533
- expect(result.worktreePath).toBe("/custom/worktree/location");
518
+ expect(result.worktreePath).toBe("/worktrees/project/feature/from-origin");
519
expect(result.startedFromOrigin).toBe(true);
520
expect(result.setupScript).toEqual({ status: "skipped" });
521
});
@@ -825,28 +810,16 @@ describe("t3_worktree_handoff", () => {
810
});
811
});
812
828
- it.effect("accepts a Windows drive path under win32 path semantics", () => {
829
- const harness = makeHarness({ pathSemantics: "win32" });
813
+ it.effect("creates the worktree in the managed directory even when a call names a path", () => {
814
+ const harness = makeHarness();
815
return Effect.gen(function* () {
831
- const result = yield* runHandoff(harness, {
832
- branch: "feature/windows-path",
833
- path: "C:\\worktrees\\custom",
816
+ const input = yield* decodeHandoffInput({
817
+ branch: "feature/elsewhere",
818
+ path: "/home/user/.ssh/checkout",
819
});
835
- expect(result.worktreePath).toBe("C:\\worktrees\\custom");
836
- expect(harness.createWorktree).toHaveBeenCalledWith(
837
- expect.objectContaining({ path: "C:\\worktrees\\custom" }),
838
- );
839
- });
840
- });
841
-
842
- it.effect("rejects a Windows drive path under posix path semantics", () => {
843
- const harness = makeHarness({ pathSemantics: "posix" });
844
- return Effect.gen(function* () {
845
- const exit = yield* Effect.exit(
846
- runHandoff(harness, { branch: "feature/windows-path", path: "C:\\worktrees\\custom" }),
847
- );
848
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
849
- expect(harness.createWorktree).not.toHaveBeenCalled();
820
+ const result = yield* runHandoff(harness, input);
821
+ expect(harness.createWorktree).toHaveBeenCalledWith(expect.objectContaining({ path: null }));
822
+ expect(result.worktreePath).toBe("/worktrees/project/feature/elsewhere");
823
});
824
});
825
@@ -914,17 +887,6 @@ describe("t3_worktree_handoff", () => {
887
});
888
});
889
917
- it.effect("rejects a relative path", () => {
918
- const harness = makeHarness();
919
- return Effect.gen(function* () {
920
- const exit = yield* Effect.exit(
921
- runHandoff(harness, { branch: "feature/relative-path", path: "worktrees/nested" }),
922
- );
923
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
924
- expect(harness.createWorktree).not.toHaveBeenCalled();
925
- });
926
- });
927
-
890
it.effect("fails when baseRef is omitted and HEAD is detached", () => {
891
const harness = makeHarness({ currentBranch: null });
892
return Effect.gen(function* () {
@@ -1013,24 +975,6 @@ describe("t3_worktree_status", () => {
975
describe("WorktreeMcpHandoffInput schema", () => {
976
const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
977
1016
- it.effect("accepts POSIX, Windows drive, and UNC absolute paths", () =>
1017
- Effect.gen(function* () {
1018
- for (const path of ["/abs/posix", "C:\\abs\\drive", "C:/abs/drive", "\\\\host\\share"]) {
1019
- const decoded = yield* decode({ branch: "feature/x", path });
1020
- expect(decoded.path).toBe(path);
1021
- }
1022
- }),
1023
- );
1024
-
1025
- it.effect("rejects relative paths", () =>
1026
- Effect.gen(function* () {
1027
- for (const path of ["worktrees/nested", "./nested", "../sibling"]) {
1028
- const exit = yield* Effect.exit(decode({ branch: "feature/x", path }));
1029
- expect(Exit.isFailure(exit), `path '${path}' should be rejected`).toBe(true);
1030
- }
1031
- }),
1032
- );
1033
-
978
it.effect("rejects a missing or blank branch", () =>
979
Effect.gen(function* () {
980
expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true);
apps/server/src/mcp/WorktreeMcpService.ts
+1
-11
@@ -15,7 +15,6 @@ import * as Crypto from "effect/Crypto";
15
import * as Effect from "effect/Effect";
16
import * as Layer from "effect/Layer";
17
import * as Option from "effect/Option";
18
-import * as Path from "effect/Path";
18
19
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
20
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
@@ -57,7 +56,6 @@ const asOperationFailed = (prefix: string) =>
56
57
const make = Effect.gen(function* () {
58
const crypto = yield* Crypto.Crypto;
60
- const path = yield* Path.Path;
59
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
60
const projects = yield* ProjectService.ProjectService;
61
const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -165,13 +163,6 @@ const make = Effect.gen(function* () {
163
const project = yield* loadProject(scope, projection.thread.projectId);
164
const projectCwd = project.workspaceRoot;
165
168
- if (input.path !== undefined && !path.isAbsolute(input.path)) {
169
- return yield* failure(
170
- "invalid_request",
171
- `path must be an absolute filesystem path, got '${input.path}'. A relative path would be created relative to the project workspace but stored verbatim as the thread's worktree binding.`,
172
- );
173
- }
174
-
166
const localStatus = yield* gitWorkflow
167
.localStatus({ cwd: projectCwd })
168
.pipe(asOperationFailed("Unable to read git status"));
@@ -252,7 +243,7 @@ const make = Effect.gen(function* () {
243
refName: worktreeBaseRef,
244
newRefName: input.branch,
245
baseRefName: baseRef,
255
- path: input.path ?? null,
246
+ path: null,
247
})
248
.pipe(asOperationFailed("Unable to create the worktree")),
249
);
@@ -464,7 +455,6 @@ export const layer: Layer.Layer<
455
WorktreeMcpService,
456
never,
457
| Crypto.Crypto
467
- | Path.Path
458
| ThreadManagementService.ThreadManagementService
459
| ProjectService.ProjectService
460
| ServerSettings.ServerSettingsService
apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+4
@@ -16,6 +16,8 @@ import * as Layer from "effect/Layer";
16
import * as Option from "effect/Option";
17
import * as Path from "effect/Path";
18
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
19
+import * as ServerConfig from "../config.ts";
20
+import * as ServerSettings from "../serverSettings.ts";
21
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
22
import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
23
import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts";
@@ -105,6 +107,8 @@ it.effect.each([
107
Layer.provide(
108
Layer.mergeAll(
109
NodeServices.layer,
110
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
111
+ ServerSettings.layerTest(),
112
ThreadCommandExecutor.layer,
113
IdAllocator.layer,
114
Layer.mock(GitWorkflowService.GitWorkflowService)({}),
apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
+23
-4
@@ -19,6 +19,8 @@ import * as Option from "effect/Option";
19
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
20
import * as Layer from "effect/Layer";
21
22
+import * as ServerConfig from "../config.ts";
23
+import * as ServerSettings from "../serverSettings.ts";
24
import * as GitWorkflow from "../git/GitWorkflowService.ts";
25
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
26
import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
@@ -43,6 +45,8 @@ const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe(
45
Layer.provide(
46
Layer.mergeAll(
47
NodeServices.layer,
48
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
49
+ ServerSettings.layerTest(),
50
Layer.mock(GitWorkflow.GitWorkflowService)({}),
51
Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(unrelatedProject) }),
52
),
@@ -395,13 +399,20 @@ it.effect.each([
399
{ order: "cleanup-first", restoreFiles: true },
400
{ order: "cleanup-first", restoreFiles: false },
401
{ order: "rollback-first", restoreFiles: true },
398
-])("locks rollback with %s", ({ order, restoreFiles }) =>
402
+ // A path the server would not have made is left missing, not recreated.
403
+ { order: "cleanup-first", restoreFiles: false, unmanaged: true },
404
+])("locks rollback with %s", ({ order, restoreFiles, unmanaged = false }) =>
405
Effect.gen(function* () {
406
const fileSystem = yield* FileSystem.FileSystem;
407
const path = yield* Path.Path;
402
- const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-" });
403
- const worktreePath = path.join(workspaceRoot, "worktree");
404
- yield* fileSystem.makeDirectory(worktreePath);
408
+ const workspaceRoot = yield* fileSystem.realPath(
409
+ yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-" }),
410
+ );
411
+ const worktreesDir = path.join(workspaceRoot, "worktrees");
412
+ const worktreePath = unmanaged
413
+ ? path.join(workspaceRoot, "elsewhere", "feature")
414
+ : path.join(worktreesDir, "repo", "feature");
415
+ yield* fileSystem.makeDirectory(worktreePath, { recursive: true });
416
const threadId = ThreadId.make("rollback-worktree");
417
const projectId = ProjectId.make("rollback-worktree-project");
418
const providerThreadId = ProviderThreadId.make("rollback-worktree-provider-thread");
@@ -438,6 +449,8 @@ it.effect.each([
449
Layer.mergeAll(
450
ThreadCommandExecutor.layer,
451
NodeServices.layer,
452
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never),
453
+ ServerSettings.layerTest(),
454
Layer.mock(ProjectStore.ProjectStoreV2)({
455
get: (id) => {
456
assert.equal(id, projectId);
@@ -536,6 +549,12 @@ it.effect.each([
549
if (order === "rollback-first") assert.isFalse(cleanupEntered);
550
yield* Deferred.succeed(release, undefined);
551
if (cleanup !== undefined) yield* Fiber.join(cleanup);
552
+ if (unmanaged) {
553
+ const error = yield* Fiber.join(rollback).pipe(Effect.flip);
554
+ assert.equal(error._tag, "CheckpointRollbackExecutionError");
555
+ assert.deepEqual(calls, ["cleanup"]);
556
+ return;
557
+ }
558
yield* Fiber.join(rollback);
559
if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup);
560
const rollbackCalls = restoreFiles
apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+13
-1
@@ -16,6 +16,9 @@ import * as Path from "effect/Path";
16
import * as Schema from "effect/Schema";
17
18
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
19
+import type * as ServerConfig from "../config.ts";
20
+import type * as ServerSettings from "../serverSettings.ts";
21
+import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
22
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
23
import {
24
isCheckpointRestoreIsolated,
@@ -96,6 +99,8 @@ export const layer: Layer.Layer<
99
| FileSystem.FileSystem
100
| Path.Path
101
| ProjectStore.ProjectStoreV2
102
+ | ServerConfig.ServerConfig
103
+ | ServerSettings.ServerSettingsService
104
| ThreadCommandExecutor.ThreadCommandExecutor
105
> = Layer.effect(
106
CheckpointRollbackServiceV2,
@@ -111,6 +116,7 @@ export const layer: Layer.Layer<
116
const projects = yield* ProjectStore.ProjectStoreV2;
117
const path = yield* Path.Path;
118
const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
119
+ const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
120
121
const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
122
readonly threadId: ThreadId;
@@ -196,7 +202,13 @@ export const layer: Layer.Layer<
202
});
203
204
const { worktreePath, branch } = projection.thread;
199
- if (worktreePath != null && branch != null && !(yield* fileSystem.exists(worktreePath))) {
205
+ // Recreated only where the server would have made it, as turn start does.
206
+ if (
207
+ worktreePath != null &&
208
+ branch != null &&
209
+ !(yield* fileSystem.exists(worktreePath)) &&
210
+ (yield* isManagedWorktreePath(worktreePath))
211
+ ) {
212
const project = yield* projects.get(projection.thread.projectId);
213
if (Option.isSome(project)) {
214
yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot });
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+132
-20
@@ -26,12 +26,15 @@ import * as Fiber from "effect/Fiber";
26
import * as Layer from "effect/Layer";
27
import * as Option from "effect/Option";
28
import * as Path from "effect/Path";
29
+import * as PlatformError from "effect/PlatformError";
30
import * as Schema from "effect/Schema";
31
32
+import * as ServerConfig from "../config.ts";
33
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
34
import * as GitWorkflow from "../git/GitWorkflowService.ts";
35
import * as ProjectService from "../project/ProjectService.ts";
36
import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
37
+import * as ServerSettings from "../serverSettings.ts";
38
import * as ContextHandoffService from "./ContextHandoffService.ts";
39
import * as EventSink from "./EventSink.ts";
40
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -45,7 +48,31 @@ import * as RuntimePolicy from "./RuntimePolicy.ts";
48
49
const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);
50
48
-it("does not commit running state when inherited background routing cannot be read", async () => {
51
+const managedWorktreesDir = "/tmp/provider-turn-start-worktrees";
52
+// fs.realpath applies `..` and `.` before following symlinks.
53
+const normalize = (target: string) => {
54
+ const parts: Array<string> = [];
55
+ for (const part of target.split("/")) {
56
+ if (part === "..") parts.pop();
57
+ else if (part !== "" && part !== ".") parts.push(part);
58
+ }
59
+ return `/${parts.join("/")}`;
60
+};
61
+const layerWorktreeLocation = (worktreesDir = managedWorktreesDir) =>
62
+ Layer.mergeAll(
63
+ Path.layer,
64
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as ServerConfig.ServerConfig["Service"]),
65
+ ServerSettings.layerTest(),
66
+ );
67
+
68
+/** Starts a run on a thread whose worktree folder is missing, with routing reads failing after. */
69
+function startWithMissingWorktree(
70
+ worktreePath: string,
71
+ realPaths: Record<string, string> = {
72
+ [managedWorktreesDir]: managedWorktreesDir,
73
+ [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`,
74
+ },
75
+) {
76
const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");
77
const runId = RunId.make("run_provider_turn_start_projection_failure");
78
const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure");
@@ -65,7 +92,7 @@ it("does not commit running state when inherited background routing cannot be re
92
id: threadId,
93
projectId: ProjectId.make("project_provider_turn_start_projection_failure"),
94
branch: "feature/restore",
68
- worktreePath: "/tmp/missing-provider-turn-start-worktree",
95
+ worktreePath,
96
},
97
runs: [
98
{
@@ -100,8 +127,22 @@ it("does not commit running state when inherited background routing cannot be re
127
Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
128
Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
129
IdAllocator.layer,
103
- Path.layer,
104
- FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
130
+ Layer.succeed(FileSystem.FileSystem, {
131
+ exists: () => Effect.succeed(false),
132
+ // Paths that exist on the fake disk, mapped to where their symlinks lead.
133
+ realPath: (target: string) =>
134
+ normalize(target) in realPaths
135
+ ? Effect.succeed(realPaths[normalize(target)])
136
+ : Effect.fail(
137
+ PlatformError.systemError({
138
+ _tag: "NotFound",
139
+ module: "FileSystem",
140
+ method: "realPath",
141
+ pathOrDescriptor: target,
142
+ }),
143
+ ),
144
+ } as never),
145
+ layerWorktreeLocation(),
146
Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }),
147
Layer.mock(ProjectService.ProjectService)({
148
getById: () =>
@@ -145,27 +186,97 @@ it("does not commit running state when inherited background routing cannot be re
186
),
187
);
188
148
- await Effect.gen(function* () {
149
- const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
189
+ const start = Effect.gen(function* () {
190
+ return yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
191
.start({ threadId, runId })
192
.pipe(Effect.flip);
152
-
153
- expect(error._tag).toBe("ProviderTurnStartError");
154
- expect(projectionReadCount).toBe(3);
155
- expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
156
- expect(createWorktree).toHaveBeenCalledWith({
157
- cwd: "/tmp/provider-turn-start-project",
158
- refName: "feature/restore",
159
- path: "/tmp/missing-provider-turn-start-worktree",
160
- });
161
- expect(writeIfRunCurrent).not.toHaveBeenCalled();
162
- expect(startRootRun).not.toHaveBeenCalled();
193
}).pipe(Effect.provide(layer), Effect.runPromise);
194
+ return {
195
+ start,
196
+ pruneWorktrees,
197
+ createWorktree,
198
+ writeIfRunCurrent,
199
+ startRootRun,
200
+ projectionReads: () => projectionReadCount,
201
+ };
202
+}
203
+
204
+it("does not commit running state when inherited background routing cannot be read", async () => {
205
+ const worktreePath = `${managedWorktreesDir}/project/feature-restore`;
206
+ const harness = startWithMissingWorktree(worktreePath);
207
+ const error = await harness.start;
208
+
209
+ expect(error._tag).toBe("ProviderTurnStartError");
210
+ expect(harness.projectionReads()).toBe(3);
211
+ expect(harness.pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
212
+ expect(harness.createWorktree).toHaveBeenCalledWith({
213
+ cwd: "/tmp/provider-turn-start-project",
214
+ refName: "feature/restore",
215
+ path: worktreePath,
216
+ });
217
+ expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
218
+ expect(harness.startRootRun).not.toHaveBeenCalled();
219
+});
220
+
221
+it.each([
222
+ {
223
+ label: "<managed>/<repo>/<branch>",
224
+ worktreePath: `${managedWorktreesDir}/project/feature-restore`,
225
+ recreated: true,
226
+ },
227
+ {
228
+ label: "the real path of a symlinked managed folder",
229
+ worktreePath: "/real-worktrees/project/feature-restore",
230
+ realPaths: { [managedWorktreesDir]: "/real-worktrees", "/real-worktrees": "/real-worktrees" },
231
+ recreated: true,
232
+ },
233
+ {
234
+ label: "a path outside the managed folder",
235
+ worktreePath: "/tmp/provider-turn-start-project/.git/hooks",
236
+ recreated: false,
237
+ },
238
+ {
239
+ label: "a symlink inside the managed folder that leads out",
240
+ worktreePath: `${managedWorktreesDir}/project/hooks`,
241
+ realPaths: {
242
+ [managedWorktreesDir]: managedWorktreesDir,
243
+ [`${managedWorktreesDir}/project`]: "/tmp/provider-turn-start-project/.git",
244
+ },
245
+ recreated: false,
246
+ },
247
+ {
248
+ label: "a folder nested below a worktree",
249
+ worktreePath: `${managedWorktreesDir}/project/feature-restore/link/hooks`,
250
+ recreated: false,
251
+ },
252
+ {
253
+ label: "'..' out of the managed folder",
254
+ worktreePath: `${managedWorktreesDir}/project/../../outside`,
255
+ recreated: false,
256
+ },
257
+ {
258
+ // Left raw on purpose: git follows `link` before applying `..`.
259
+ label: "'..' after a symlink inside the managed folder",
260
+ worktreePath: `${managedWorktreesDir}/project/x/link/../../hooks`,
261
+ realPaths: {
262
+ [managedWorktreesDir]: managedWorktreesDir,
263
+ [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`,
264
+ [`${managedWorktreesDir}/project/x`]: `${managedWorktreesDir}/project/x`,
265
+ [`${managedWorktreesDir}/project/x/link`]: "/tmp/provider-turn-start-project/.git/refs/heads",
266
+ },
267
+ recreated: false,
268
+ },
269
+ { label: "a relative path", worktreePath: "project/feature-restore", recreated: false },
270
+])("recreates a missing worktree only at the managed location: $label", async (input) => {
271
+ const harness = startWithMissingWorktree(input.worktreePath, input.realPaths);
272
+ await harness.start;
273
+ expect(harness.createWorktree).toHaveBeenCalledTimes(input.recreated ? 1 : 0);
274
});
275
276
function makeLocalCommandHarness(input: {
277
readonly text: string;
278
readonly worktreePath?: string;
279
+ readonly worktreesDir?: string;
280
readonly fileSystem?: FileSystem.FileSystem;
281
readonly previousNativeSession?: boolean;
282
readonly previousMessages?: ReadonlyArray<string>;
@@ -516,7 +627,7 @@ function makeLocalCommandHarness(input: {
627
}),
628
Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
629
IdAllocator.layer,
519
- Path.layer,
630
+ layerWorktreeLocation(input.worktreesDir),
631
input.fileSystem === undefined
632
? FileSystem.layerNoop({ exists: () => Effect.succeed(true) })
633
: Layer.succeed(FileSystem.FileSystem, input.fileSystem),
@@ -594,13 +705,14 @@ effectIt.effect.each(["cleanup-first", "startup-first"])(
705
const fileSystem = yield* FileSystem.FileSystem;
706
const path = yield* Path.Path;
707
const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" });
597
- const worktreePath = path.join(workspaceRoot, "worktree");
598
- yield* fileSystem.makeDirectory(worktreePath);
708
+ const worktreePath = path.join(workspaceRoot, "project", "worktree");
709
+ yield* fileSystem.makeDirectory(worktreePath, { recursive: true });
710
const release = yield* Deferred.make<void>();
711
const openEntered = yield* Deferred.make<void>();
712
const harness = makeLocalCommandHarness({
713
text: "Continue",
714
worktreePath,
715
+ worktreesDir: workspaceRoot,
716
fileSystem,
717
failReadsAfterRunning: true,
718
});
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+10
-1
@@ -22,11 +22,15 @@ import * as Option from "effect/Option";
22
import * as Path from "effect/Path";
23
import * as Predicate from "effect/Predicate";
24
import * as Schema from "effect/Schema";
25
+import * as HostProcess from "@t3tools/shared/HostProcess";
26
27
+import * as ServerConfig from "../config.ts";
28
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
29
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
30
import * as ProjectService from "../project/ProjectService.ts";
31
import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
32
+import * as ServerSettings from "../serverSettings.ts";
33
+import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
34
import * as EventSink from "./EventSink.ts";
35
import * as ContextHandoffService from "./ContextHandoffService.ts";
36
import {
@@ -88,6 +92,8 @@ export const layer: Layer.Layer<
92
| IdAllocator.IdAllocatorV2
93
| FileSystem.FileSystem
94
| Path.Path
95
+ | ServerConfig.ServerConfig
96
+ | ServerSettings.ServerSettingsService
97
| GitWorkflowService.GitWorkflowService
98
| ProjectService.ProjectService
99
| ProviderAuthService.ProviderAuthService
@@ -103,6 +109,8 @@ export const layer: Layer.Layer<
109
const idAllocator = yield* IdAllocator.IdAllocatorV2;
110
const fileSystem = yield* FileSystem.FileSystem;
111
const path = yield* Path.Path;
112
+ const serverConfig = yield* ServerConfig.ServerConfig;
113
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
114
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
115
const projects = yield* ProjectService.ProjectService;
116
const providerAuth = yield* ProviderAuthService.ProviderAuthService;
@@ -110,6 +118,7 @@ export const layer: Layer.Layer<
118
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
119
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
120
const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
121
+ const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
122
123
// These callbacks outlive startup while a run drains background work. Build
124
// them outside start's scope so they cannot retain its full thread history.
@@ -448,7 +457,7 @@ export const layer: Layer.Layer<
457
const exists = yield* fileSystem
458
.exists(worktreePath)
459
.pipe(Effect.orElseSucceed(() => true));
451
- if (!exists) {
460
+ if (!exists && (yield* isManagedWorktreePath(worktreePath))) {
461
const project = yield* projects.getById(projection.thread.projectId).pipe(
462
Effect.map(Option.getOrUndefined),
463
Effect.orElseSucceed(() => undefined),
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+4
@@ -401,6 +401,8 @@ export function layerWithRegistry<Error>(
401
}),
402
layerRunExecutionServiceProvided,
403
layerRuntime,
404
+ layerServerConfig,
405
+ layerServerSettings,
406
),
407
),
408
);
@@ -420,6 +422,8 @@ export function layerWithRegistry<Error>(
422
layerProviderSessionManagerProvided,
423
ThreadCommandExecutor.layer,
424
layerRuntime,
425
+ layerServerConfig,
426
+ layerServerSettings,
427
),
428
),
429
);
apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs
+31
-14
@@ -16,20 +16,35 @@ const [Effect, Layer, FileSystem, Path] = await Promise.all([
16
const app = (file) => import(NodeURL.pathToFileURL(root + "/apps/server/src/" + file + ".ts"));
17
const providerCore = (file) =>
18
import(NodeURL.pathToFileURL(root + "/packages/provider-core/src/server/" + file + ".ts"));
19
-const [Start, Projection, Run, Sessions, Policy, Id, Sink, Handoff, Git, Project, Auth] =
20
- await Promise.all([
21
- app("orchestration-v2/ProviderTurnStartService"),
22
- app("orchestration-v2/ProjectionStore"),
23
- app("orchestration-v2/RunExecutionService"),
24
- app("orchestration-v2/ProviderSessionManager"),
25
- app("orchestration-v2/RuntimePolicy"),
26
- providerCore("IdAllocator"),
27
- app("orchestration-v2/EventSink"),
28
- app("orchestration-v2/ContextHandoffService"),
29
- app("git/GitWorkflowService"),
30
- app("project/ProjectService"),
31
- app("provider/ProviderAuthService"),
32
- ]);
19
+const [
20
+ Start,
21
+ Projection,
22
+ Run,
23
+ Sessions,
24
+ Policy,
25
+ Id,
26
+ Sink,
27
+ Handoff,
28
+ Git,
29
+ Project,
30
+ Auth,
31
+ Config,
32
+ Settings,
33
+] = await Promise.all([
34
+ app("orchestration-v2/ProviderTurnStartService"),
35
+ app("orchestration-v2/ProjectionStore"),
36
+ app("orchestration-v2/RunExecutionService"),
37
+ app("orchestration-v2/ProviderSessionManager"),
38
+ app("orchestration-v2/RuntimePolicy"),
39
+ providerCore("IdAllocator"),
40
+ app("orchestration-v2/EventSink"),
41
+ app("orchestration-v2/ContextHandoffService"),
42
+ app("git/GitWorkflowService"),
43
+ app("project/ProjectService"),
44
+ app("provider/ProviderAuthService"),
45
+ app("config"),
46
+ app("serverSettings"),
47
+]);
48
let current;
49
let fullReads = 0;
50
let threadReads = 0;
@@ -54,6 +69,8 @@ const dependencies = Layer.mergeAll(
69
Layer.mock(Git.GitWorkflowService)({}),
70
Layer.mock(Project.ProjectService)({}),
71
Layer.mock(Auth.ProviderAuthService)({}),
72
+ Layer.mock(Config.ServerConfig)({ worktreesDir: "/synthetic-worktrees" }),
73
+ Settings.layerTest(),
74
Layer.mock(Projection.ProjectionStoreV2)({
75
getThreadProjection: () =>
76
Effect.sync(() => {
apps/server/src/review/ReviewService.test.ts
+112
-1
@@ -4,13 +4,16 @@ import * as Effect from "effect/Effect";
4
import * as FileSystem from "effect/FileSystem";
5
import * as Layer from "effect/Layer";
6
import * as PlatformError from "effect/PlatformError";
7
+import * as SqlClient from "effect/sql/SqlClient";
8
import { ProjectId } from "@t3tools/contracts";
9
10
import * as ServerConfig from "../config.ts";
11
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
12
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
13
import * as ServerSettings from "../serverSettings.ts";
14
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
15
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
16
+import * as KnownWorkspaces from "../workspace/KnownWorkspaces.ts";
17
import * as ReviewService from "./ReviewService.ts";
18
19
function layer(input: {
@@ -20,9 +23,33 @@ function layer(input: {
23
readonly worktreesDirectory?: string;
24
readonly previousWorktreesDirectories?: ReadonlyArray<string>;
25
readonly projectRoots?: ReadonlyArray<string> | "unavailable";
26
+ readonly threadWorktrees?: ReadonlyArray<{ worktreePath: string; deleted?: boolean }>;
27
+ /** What `git worktree list` reports for every project. */
28
+ readonly gitWorktrees?: ReadonlyArray<string>;
29
}) {
30
const projectRoots = input.projectRoots ?? [];
31
return ReviewService.layer.pipe(
32
+ Layer.provide(KnownWorkspaces.layer),
33
+ Layer.provide(
34
+ Layer.effectDiscard(
35
+ Effect.gen(function* () {
36
+ const sql = yield* SqlClient.SqlClient;
37
+ for (const [index, thread] of (input.threadWorktrees ?? []).entries()) {
38
+ yield* sql`
39
+ INSERT INTO orchestration_v2_projection_threads (
40
+ thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
41
+ created_at, updated_at, deleted_at, payload_json
42
+ ) VALUES (
43
+ ${`thread-${index}`}, 'project-0', 'Thread', 'codex', 'full-access', 'default',
44
+ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z',
45
+ ${thread.deleted ? "2026-01-02T00:00:00.000Z" : null},
46
+ ${JSON.stringify({ worktreePath: thread.worktreePath })}
47
+ )
48
+ `;
49
+ }
50
+ }),
51
+ ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
52
+ ),
53
Layer.provide(
54
Layer.mock(ProjectStore.ProjectStoreV2)({
55
listShells: () =>
@@ -54,7 +81,11 @@ function layer(input: {
81
}),
82
}),
83
),
57
- Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
84
+ Layer.provide(
85
+ Layer.mock(GitVcsDriver.GitVcsDriver)({
86
+ listWorktreePaths: () => Effect.succeed([...(input.gitWorktrees ?? [])]),
87
+ }),
88
+ ),
89
Layer.provide(
90
ServerSettings.ServerSettingsService.layerTest({
91
worktreesDirectory: input.worktreesDirectory ?? "",
@@ -178,6 +209,10 @@ describe("ReviewService", () => {
209
210
assert.strictEqual((yield* review(projectRoot, [projectRoot])).cwd, projectRoot);
211
assert.strictEqual((yield* review(projectChild, [projectRoot])).cwd, projectChild);
212
+ // A child whose name starts with `..` is still inside.
213
+ const dottedChild = `${projectRoot}/..feature`;
214
+ yield* fs.makeDirectory(dottedChild);
215
+ assert.strictEqual((yield* review(dottedChild, [projectRoot])).cwd, dottedChild);
216
for (const [cwd, projectRoots] of [
217
[sibling, [projectRoot]],
218
[projectRoot, []],
@@ -189,6 +224,82 @@ describe("ReviewService", () => {
224
}).pipe(Effect.provide(NodeServices.layer)),
225
);
226
227
+ it.effect("allows the worktree a thread is bound to, and nothing else outside the project", () =>
228
+ Effect.gen(function* () {
229
+ const fs = yield* FileSystem.FileSystem;
230
+ const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
231
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
232
+ const project = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-project-" });
233
+ // Checkouts outside every managed folder, as `git worktree add ../feature` makes.
234
+ const bound = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-bound-" });
235
+ const deleted = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-deleted-" });
236
+ const unbound = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-unbound-" });
237
+ // A client can set a thread's path to any folder; git doesn't list this one.
238
+ const claimed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-claimed-" });
239
+ yield* fs.makeDirectory(`${bound}/sub`);
240
+
241
+ const review = (cwd: string) =>
242
+ Effect.gen(function* () {
243
+ const service = yield* ReviewService.ReviewService;
244
+ return yield* service.getDiffPreview({ cwd });
245
+ }).pipe(
246
+ Effect.provide(
247
+ layer({
248
+ workspaceRoot,
249
+ baseDir,
250
+ projectRoots: [project],
251
+ gitWorktrees: [project, bound, deleted],
252
+ threadWorktrees: [
253
+ { worktreePath: bound },
254
+ { worktreePath: claimed },
255
+ { worktreePath: deleted, deleted: true },
256
+ // A relative path would resolve against the server's own cwd.
257
+ { worktreePath: "t3-review-relative" },
258
+ // A filesystem root would make every folder look bound.
259
+ { worktreePath: "/" },
260
+ ],
261
+ }),
262
+ ),
263
+ );
264
+
265
+ for (const cwd of [bound, `${bound}/sub`]) {
266
+ assert.strictEqual((yield* review(cwd)).cwd, cwd);
267
+ }
268
+ for (const cwd of [deleted, unbound, claimed, `${process.cwd()}/t3-review-relative`]) {
269
+ const error = yield* review(cwd).pipe(Effect.flip);
270
+ assert.strictEqual(error._tag, "VcsRepositoryDetectionError");
271
+ }
272
+ }).pipe(Effect.provide(NodeServices.layer)),
273
+ );
274
+
275
+ it.effect("allows a thread's worktree linked from a managed folder to a checkout elsewhere", () =>
276
+ Effect.gen(function* () {
277
+ const fs = yield* FileSystem.FileSystem;
278
+ const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
279
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
280
+ const managed = yield* fs.realPath(
281
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-worktrees-" }),
282
+ );
283
+ const checkout = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-checkout-" });
284
+ yield* fs.symlink(checkout, `${managed}/feature`);
285
+
286
+ const result = yield* Effect.gen(function* () {
287
+ const review = yield* ReviewService.ReviewService;
288
+ return yield* review.getDiffPreview({ cwd: checkout });
289
+ }).pipe(
290
+ Effect.provide(
291
+ layer({
292
+ workspaceRoot,
293
+ baseDir,
294
+ worktreesDirectory: managed,
295
+ threadWorktrees: [{ worktreePath: `${managed}/feature` }],
296
+ }),
297
+ ),
298
+ );
299
+ assert.strictEqual(result.cwd, checkout);
300
+ }).pipe(Effect.provide(NodeServices.layer)),
301
+ );
302
+
303
it.effect("allows diff preview cwd inside the configured workspace root", () =>
304
Effect.gen(function* () {
305
const fs = yield* FileSystem.FileSystem;
apps/server/src/review/ReviewService.ts
+5
-40
@@ -16,12 +16,9 @@ import {
16
} from "@t3tools/contracts";
17
18
import * as ServerConfig from "../config.ts";
19
-import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
19
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
20
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
22
-import * as ServerSettings from "../serverSettings.ts";
23
-import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
24
-import * as HostProcess from "@t3tools/shared/HostProcess";
21
+import * as KnownWorkspaces from "../workspace/KnownWorkspaces.ts";
22
23
export class ReviewService extends Context.Service<
24
ReviewService,
@@ -42,8 +39,7 @@ export const make = Effect.gen(function* () {
39
const path = yield* Path.Path;
40
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
41
const git = yield* GitVcsDriver.GitVcsDriver;
45
- const settings = yield* ServerSettings.ServerSettingsService;
46
- const projectStore = yield* ProjectStore.ProjectStoreV2;
42
+ const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
43
44
const canonicalizePath = (value: string) => {
45
const resolvedPath = path.resolve(value);
@@ -64,52 +60,21 @@ export const make = Effect.gen(function* () {
60
);
61
};
62
67
- const isWithinRoot = (candidate: string, root: string) => {
68
- const relative = path.relative(root, candidate);
69
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
70
- };
71
-
63
const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* (
64
operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
65
cwd: string,
66
) {
76
- const worktreesDirectories = yield* settings.getSettings.pipe(
77
- Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
78
- );
79
- const home = yield* HostProcess.HomeDirectory;
80
- const [candidate, workspaceRoot, worktreesRoots] = yield* Effect.all([
67
+ const [candidate, workspaceRoot] = yield* Effect.all([
68
canonicalizePath(cwd),
69
canonicalizePath(config.cwd),
83
- Effect.forEach(
84
- managedWorktreesDirectories(worktreesDirectories, config.worktreesDir, path, home),
85
- (directory) => canonicalizePath(directory).pipe(Effect.orElseSucceed(() => null)),
86
- ).pipe(
87
- Effect.map((roots) =>
88
- roots.filter((root): root is string => root !== null && !isFilesystemRoot(root, path)),
89
- ),
90
- ),
70
]);
92
-
71
if (
94
- isWithinRoot(candidate, workspaceRoot) ||
95
- worktreesRoots.some((root) => isWithinRoot(candidate, root))
72
+ KnownWorkspaces.isWithinRoot(path, candidate, workspaceRoot) ||
73
+ (yield* knownWorkspaces.contains(candidate))
74
) {
75
return;
76
}
77
100
- // Registered projects can live outside the server cwd, which is the home
101
- // directory in packaged desktop builds, e.g. a repository on another
102
- // Windows drive. Unreadable or unresolvable project roots grant nothing.
103
- const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => []));
104
- for (const project of projects) {
105
- const root = yield* canonicalizePath(project.workspaceRoot).pipe(
106
- Effect.orElseSucceed(() => null),
107
- );
108
- if (root !== null && isWithinRoot(candidate, root)) {
109
- return;
110
- }
111
- }
112
-
78
return yield* new VcsRepositoryDetectionError({
79
operation,
80
cwd,
apps/server/src/server.ts
+8
-1
@@ -95,6 +95,7 @@ import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
95
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
96
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
97
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
98
+import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts";
99
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
100
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
101
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
@@ -370,8 +371,13 @@ const layerProjectCloneTracker = ProjectCloneTracker.layer.pipe(
371
Layer.provide(layerSourceControlRepositoryService),
372
);
373
373
-const layerReview = ReviewService.layer.pipe(
374
+const layerKnownWorkspaces = KnownWorkspaces.layer.pipe(
375
Layer.provide(ProjectStore.layer),
376
+ Layer.provide(GitVcsDriver.layer),
377
+);
378
+
379
+const layerReview = ReviewService.layer.pipe(
380
+ Layer.provideMerge(layerKnownWorkspaces),
381
Layer.provideMerge(GitVcsDriver.layer),
382
Layer.provideMerge(layerVcsDriverRegistry),
383
);
@@ -423,6 +429,7 @@ const layerWorkspaceEntries = WorkspaceEntries.layer.pipe(Layer.provide(Workspac
429
const layerWorkspaceFileSystem = WorkspaceFileSystem.layer.pipe(
430
Layer.provide(WorkspacePaths.layer),
431
Layer.provide(layerWorkspaceEntries),
432
+ Layer.provide(layerKnownWorkspaces),
433
);
434
435
const layerWorkspace = Layer.mergeAll(
apps/server/src/vcs/GitVcsDriverCore.ts
+2
-1
@@ -3411,7 +3411,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3411
)(function* (input, options) {
3412
const targetBranch = input.newRefName ?? input.refName;
3413
const sanitizedBranch = targetBranch.replace(/\//g, "-");
3414
- const repoName = path.basename(input.cwd);
3414
+ // resolve: a cwd like `<repo>/sub/..` must not name the folder `..`.
3415
+ const repoName = path.basename(path.resolve(input.cwd));
3416
let worktreePath = input.path;
3417
if (worktreePath == null) {
3418
const parentDir = resolveWorktreesDirectory(
apps/server/src/workspace/KnownWorkspaces.ts
new
+156
@@ -0,0 +1,156 @@
1
+/**
2
+ * KnownWorkspaces - the folders a client-named cwd may act in: a T3-managed
3
+ * worktree folder, a registered project, or a thread's worktree. Clients send
4
+ * the thread's worktree, else the project root. A client also sets a thread's
5
+ * worktree path, so one counts only under a managed folder or when git lists
6
+ * it as a worktree of the thread's project.
7
+ *
8
+ * @module KnownWorkspaces
9
+ */
10
+import * as HostProcess from "@t3tools/shared/HostProcess";
11
+import * as Context from "effect/Context";
12
+import * as Effect from "effect/Effect";
13
+import * as FileSystem from "effect/FileSystem";
14
+import * as Layer from "effect/Layer";
15
+import * as Path from "effect/Path";
16
+import * as Schema from "effect/Schema";
17
+import * as SqlClient from "effect/sql/SqlClient";
18
+
19
+import * as ServerConfig from "../config.ts";
20
+import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
21
+import * as ServerSettings from "../serverSettings.ts";
22
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
23
+import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
24
+
25
+export class UnknownWorkspaceError extends Schema.TaggedError<UnknownWorkspaceError>()(
26
+ "UnknownWorkspaceError",
27
+ {
28
+ cwd: Schema.String,
29
+ cause: Schema.optional(Schema.Defect()),
30
+ },
31
+) {
32
+ override get message(): string {
33
+ return `'${this.cwd}' is not a registered project, a managed worktree, or a thread's worktree.`;
34
+ }
35
+}
36
+
37
+/** Whether `candidate` is `root` or inside it. Resolve both the same way first. */
38
+export const isWithinRoot = (path: Path.Path, candidate: string, root: string) => {
39
+ const relative = path.relative(root, candidate);
40
+ return (
41
+ relative === "" ||
42
+ (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
43
+ );
44
+};
45
+
46
+export class KnownWorkspaces extends Context.Service<
47
+ KnownWorkspaces,
48
+ {
49
+ /** Whether a symlink-resolved path is inside a known workspace. */
50
+ readonly contains: (realPath: string) => Effect.Effect<boolean>;
51
+ /** Fails unless `cwd` exists and resolves inside a known workspace. */
52
+ readonly assertContains: (cwd: string) => Effect.Effect<void, UnknownWorkspaceError>;
53
+ }
54
+>()("t3/workspace/KnownWorkspaces") {}
55
+
56
+/** @public Service construction is part of the canonical Effect module API. */
57
+export const make = Effect.gen(function* () {
58
+ const config = yield* ServerConfig.ServerConfig;
59
+ const fileSystem = yield* FileSystem.FileSystem;
60
+ const path = yield* Path.Path;
61
+ const settings = yield* ServerSettings.ServerSettingsService;
62
+ const projectStore = yield* ProjectStore.ProjectStoreV2;
63
+ const sql = yield* SqlClient.SqlClient;
64
+ const git = yield* GitVcsDriver.GitVcsDriver;
65
+
66
+ // A root that does not exist yet keeps its lexical path. One that cannot be
67
+ // resolved for another reason, or resolves to a filesystem root, grants nothing.
68
+ const resolveRoot = (value: string) => {
69
+ const resolvedPath = path.resolve(value);
70
+ return fileSystem.realPath(resolvedPath).pipe(
71
+ Effect.catchTags({
72
+ PlatformError: (cause) =>
73
+ Effect.succeed(cause.reason._tag === "NotFound" ? resolvedPath : null),
74
+ }),
75
+ Effect.map((root) => (root === null || isFilesystemRoot(root, path) ? null : root)),
76
+ );
77
+ };
78
+
79
+ const contains: KnownWorkspaces["Service"]["contains"] = Effect.fn("KnownWorkspaces.contains")(
80
+ function* (realPath) {
81
+ const within = (root: string | null) => root !== null && isWithinRoot(path, realPath, root);
82
+ const worktreeSettings = yield* settings.getSettings.pipe(
83
+ Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
84
+ );
85
+ const home = yield* HostProcess.HomeDirectory;
86
+ const managedDirectories = managedWorktreesDirectories(
87
+ worktreeSettings,
88
+ config.worktreesDir,
89
+ path,
90
+ home,
91
+ );
92
+ const managed = (yield* Effect.forEach(managedDirectories, resolveRoot)).filter(
93
+ (root) => root !== null,
94
+ );
95
+ if (managed.some(within)) return true;
96
+
97
+ const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => []));
98
+ for (const project of projects) {
99
+ if (within(yield* resolveRoot(project.workspaceRoot))) return true;
100
+ }
101
+
102
+ const threads = yield* sql<{ readonly worktreePath: string; readonly projectId: string }>`
103
+ SELECT DISTINCT
104
+ json_extract(payload_json, '$.worktreePath') AS "worktreePath",
105
+ project_id AS "projectId"
106
+ FROM orchestration_v2_projection_threads
107
+ WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
108
+ `.pipe(Effect.orElseSucceed(() => []));
109
+ const projectWorktrees = new Map<string, ReadonlyArray<string>>();
110
+ const isProjectWorktree = Effect.fnUntraced(function* (
111
+ projectId: string,
112
+ worktreePath: string,
113
+ ) {
114
+ const project = projects.find((candidate) => candidate.id === projectId);
115
+ if (project === undefined) return false;
116
+ let listed = projectWorktrees.get(projectId);
117
+ if (listed === undefined) {
118
+ listed = yield* git.listWorktreePaths(project.workspaceRoot).pipe(
119
+ Effect.flatMap((paths) => Effect.forEach(paths, resolveRoot)),
120
+ Effect.map((paths) => paths.filter((listedPath) => listedPath !== null)),
121
+ Effect.orElseSucceed((): ReadonlyArray<string> => []),
122
+ );
123
+ projectWorktrees.set(projectId, listed);
124
+ }
125
+ const real = yield* resolveRoot(worktreePath);
126
+ return real !== null && listed.includes(real);
127
+ });
128
+ for (const { worktreePath, projectId } of threads) {
129
+ // A relative path would resolve against the server's own cwd. One under a
130
+ // managed folder is still resolved: it can be a symlink to a checkout elsewhere.
131
+ if (!path.isAbsolute(worktreePath)) continue;
132
+ if (!within(yield* resolveRoot(worktreePath))) continue;
133
+ const lexical = path.resolve(worktreePath);
134
+ if (managedDirectories.some((directory) => isWithinRoot(path, lexical, directory))) {
135
+ return true;
136
+ }
137
+ if (yield* isProjectWorktree(projectId, worktreePath)) return true;
138
+ }
139
+ return false;
140
+ },
141
+ );
142
+
143
+ const assertContains: KnownWorkspaces["Service"]["assertContains"] = Effect.fn(
144
+ "KnownWorkspaces.assertContains",
145
+ )(function* (cwd) {
146
+ // `..` collapses on the path as named before symlinks resolve, as the write does.
147
+ const realCwd = yield* fileSystem
148
+ .realPath(path.resolve(cwd))
149
+ .pipe(Effect.mapError((cause) => new UnknownWorkspaceError({ cwd, cause })));
150
+ if (!(yield* contains(realCwd))) return yield* new UnknownWorkspaceError({ cwd });
151
+ });
152
+
153
+ return KnownWorkspaces.of({ contains, assertContains });
154
+});
155
+
156
+export const layer = Layer.effect(KnownWorkspaces, make);
apps/server/src/workspace/WorkspaceFileSystem.test.ts
+242
@@ -11,13 +11,24 @@ import * as Path from "effect/Path";
11
import * as ServerConfig from "../config.ts";
12
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
13
import * as VcsProcess from "../vcs/VcsProcess.ts";
14
+import * as KnownWorkspaces from "./KnownWorkspaces.ts";
15
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
16
import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
17
import * as WorkspacePaths from "./WorkspacePaths.ts";
18
import * as HostProcess from "@t3tools/shared/HostProcess";
19
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
20
21
+// Temp folders count as known workspaces unless named as unknown.
22
+const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
23
+const layerKnownWorkspacesTest = Layer.mock(KnownWorkspaces.KnownWorkspaces)({
24
+ assertContains: (cwd) =>
25
+ cwd.includes(UNKNOWN_WORKSPACE_PREFIX)
26
+ ? Effect.fail(new KnownWorkspaces.UnknownWorkspaceError({ cwd }))
27
+ : Effect.void,
28
+});
29
+
30
const layerProject = WorkspaceFileSystem.layer.pipe(
31
+ Layer.provide(layerKnownWorkspacesTest),
32
Layer.provide(WorkspacePaths.layer),
33
Layer.provide(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
34
);
@@ -360,6 +371,23 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
371
}),
372
);
373
374
+ it.effect("rejects writes outside a known workspace", () =>
375
+ Effect.gen(function* () {
376
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
377
+ const fileSystem = yield* FileSystem.FileSystem;
378
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({
379
+ prefix: UNKNOWN_WORKSPACE_PREFIX,
380
+ });
381
+
382
+ const error = yield* workspaceFileSystem
383
+ .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
384
+ .pipe(Effect.flip);
385
+
386
+ expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
387
+ expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
388
+ }),
389
+ );
390
+
391
it.effect("rejects writes by absolute path", () =>
392
Effect.gen(function* () {
393
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -428,5 +456,219 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
456
expect(escapedStat).toBeNull();
457
}),
458
);
459
+
460
+ it.effect.skipIf(!symlinksSupported)(
461
+ "rejects writes through symlinks that resolve outside the workspace root",
462
+ () =>
463
+ Effect.gen(function* () {
464
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
465
+ const fileSystem = yield* FileSystem.FileSystem;
466
+ const path = yield* Path.Path;
467
+ const cwd = yield* makeTempDir;
468
+ const outsideDir = yield* makeTempDir;
469
+ yield* writeTextFile(outsideDir, "existing.md", "outside\n");
470
+ yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
471
+ yield* fileSystem.symlink(
472
+ path.join(outsideDir, "existing.md"),
473
+ path.join(cwd, "linked-file.md"),
474
+ );
475
+ yield* fileSystem.symlink(
476
+ path.join(outsideDir, "missing.md"),
477
+ path.join(cwd, "dangling.md"),
478
+ );
479
+
480
+ for (const relativePath of [
481
+ "linked-dir/new.md",
482
+ "linked-dir/nested/new.md",
483
+ "linked-file.md",
484
+ ]) {
485
+ const error = yield* workspaceFileSystem
486
+ .writeFile({ cwd, relativePath, contents: "# nope\n" })
487
+ .pipe(Effect.flip);
488
+ expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
489
+ }
490
+ const danglingError = yield* workspaceFileSystem
491
+ .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
492
+ .pipe(Effect.flip);
493
+ expect(danglingError).toBeInstanceOf(
494
+ WorkspaceFileSystem.WorkspaceFileSystemOperationError,
495
+ );
496
+ expect(danglingError).toMatchObject({ operation: "realpath-target" });
497
+
498
+ expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
499
+ expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
500
+ "outside\n",
501
+ );
502
+ }),
503
+ );
504
+
505
+ it.effect.skipIf(!symlinksSupported)(
506
+ "writes through symlinks that stay inside the workspace root",
507
+ () =>
508
+ Effect.gen(function* () {
509
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
510
+ const fileSystem = yield* FileSystem.FileSystem;
511
+ const path = yield* Path.Path;
512
+ const parentDir = yield* makeTempDir;
513
+ const cwd = path.join(parentDir, "workspace");
514
+ const cwdAlias = path.join(parentDir, "workspace-alias");
515
+ yield* writeTextFile(cwd, "docs/README.md", "old\n");
516
+ yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
517
+ yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
518
+ yield* fileSystem.symlink(cwd, cwdAlias);
519
+
520
+ yield* workspaceFileSystem.writeFile({
521
+ cwd,
522
+ relativePath: "docs-alias/plans/plan.md",
523
+ contents: "# Plan\n",
524
+ });
525
+ yield* workspaceFileSystem.writeFile({
526
+ cwd,
527
+ relativePath: "README.md",
528
+ contents: "new\n",
529
+ });
530
+ yield* workspaceFileSystem.writeFile({
531
+ cwd: cwdAlias,
532
+ relativePath: "notes.md",
533
+ contents: "notes\n",
534
+ });
535
+ // `..` after a link in cwd is resolved by name, as for the relative path.
536
+ yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
537
+ yield* workspaceFileSystem.writeFile({
538
+ cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
539
+ relativePath: "dotdot.md",
540
+ contents: "dotdot\n",
541
+ });
542
+
543
+ expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
544
+ "# Plan\n",
545
+ );
546
+ expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
547
+ expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
548
+ expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
549
+ expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
550
+ }),
551
+ );
552
+
553
+ // On Windows `\` is a separator, so the name cannot exist there.
554
+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
555
+ "keeps a backslash in a file name as part of the name",
556
+ () =>
557
+ Effect.gen(function* () {
558
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
559
+ const fileSystem = yield* FileSystem.FileSystem;
560
+ const cwd = yield* makeTempDir;
561
+ yield* writeTextFile(cwd, "a\\b.md", "old\n");
562
+
563
+ yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
564
+
565
+ expect(
566
+ (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
567
+ ).toBe("new\n");
568
+ expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
569
+ }),
570
+ );
571
+
572
+ it.effect("refuses writes into git's own folders", () =>
573
+ Effect.gen(function* () {
574
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
575
+ const fileSystem = yield* FileSystem.FileSystem;
576
+ const path = yield* Path.Path;
577
+ const cwd = yield* makeTempDir;
578
+ yield* writeTextFile(cwd, ".git/config", "[core]\n");
579
+ // A bare repository named `.bare`, and a linked worktree's git folder inside it.
580
+ yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
581
+ yield* writeTextFile(cwd, ".bare/objects/info/packs");
582
+ yield* writeTextFile(cwd, ".bare/refs/heads/main");
583
+ yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
584
+ // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
585
+ yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
586
+ yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
587
+ yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
588
+ if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
589
+
590
+ for (const [folder, relativePath] of [
591
+ [cwd, ".git/config"],
592
+ [cwd, ".git/hooks/pre-commit"],
593
+ [cwd, "sub/.git"],
594
+ [cwd, ".GIT/config"],
595
+ [cwd, ".gıt/config"],
596
+ [cwd, ".git. /config"],
597
+ [cwd, ".git::$INDEX_ALLOCATION/config"],
598
+ [cwd, "GIT~1/config"],
599
+ [path.join(cwd, ".git"), "config"],
600
+ [cwd, ".bare/config"],
601
+ [path.join(cwd, ".bare"), "hooks/post-checkout"],
602
+ [path.join(cwd, ".bare/hooks"), "post-checkout"],
603
+ [path.join(cwd, ".bare/worktrees/main"), "commondir"],
604
+ ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
605
+ ] as const) {
606
+ const error = yield* workspaceFileSystem
607
+ .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
608
+ .pipe(Effect.flip);
609
+ expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
610
+ }
611
+
612
+ expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
613
+ expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
614
+ expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
615
+ [".git", "pre-push.sample"],
616
+ );
617
+ expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
618
+ expect(
619
+ yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
620
+ ).toBe("../..\n");
621
+ }),
622
+ );
623
+
624
+ it.effect.skipIf(!symlinksSupported)(
625
+ "refuses writes through a git config that links to a file outside git's folders",
626
+ () =>
627
+ Effect.gen(function* () {
628
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
629
+ const fileSystem = yield* FileSystem.FileSystem;
630
+ const path = yield* Path.Path;
631
+ const cwd = yield* makeTempDir;
632
+ yield* writeTextFile(cwd, "shared/config", "[core]\n");
633
+ yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
634
+ yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
635
+
636
+ const error = yield* workspaceFileSystem
637
+ .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
638
+ .pipe(Effect.flip);
639
+
640
+ expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
641
+ expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
642
+ "[core]\n",
643
+ );
644
+ }),
645
+ );
646
+
647
+ it.effect("writes files that sit beside git's folders", () =>
648
+ Effect.gen(function* () {
649
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
650
+ const fileSystem = yield* FileSystem.FileSystem;
651
+ const path = yield* Path.Path;
652
+ const parentDir = yield* makeTempDir;
653
+ // A bare repository with a worktree checked out inside it.
654
+ const bare = path.join(parentDir, "repo.git");
655
+ yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
656
+ yield* writeTextFile(bare, "objects/info/packs");
657
+ yield* writeTextFile(bare, "refs/heads/main");
658
+ yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
659
+
660
+ for (const [cwd, relativePath] of [
661
+ [path.join(bare, "main"), ".gitignore"],
662
+ [path.join(bare, "main"), ".gitattributes"],
663
+ [path.join(bare, "main"), ".github/workflows/ci.yml"],
664
+ [path.join(bare, "main"), "vendor/lib.git/README.md"],
665
+ [path.join(bare, "main/.github"), "CODEOWNERS"],
666
+ [bare, "main/plan.md"],
667
+ ] as const) {
668
+ yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
669
+ expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
670
+ }
671
+ }),
672
+ );
673
});
674
});
apps/server/src/workspace/WorkspaceFileSystem.ts
+158
-22
@@ -20,12 +20,20 @@ import * as Layer from "effect/Layer";
20
import * as Path from "effect/Path";
21
import * as Schema from "effect/Schema";
22
23
+import * as KnownWorkspaces from "./KnownWorkspaces.ts";
24
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
25
import * as WorkspacePaths from "./WorkspacePaths.ts";
26
import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
27
28
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
29
30
+// Windows also reaches `.git` through trailing dots or spaces, a `:` stream
31
+// suffix, or the 8.3 short name `GIT~1`. Names compare upcased, as NTFS does.
32
+const isGitMetadataName = (segment: string) => {
33
+ const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase();
34
+ return name === ".GIT" || name === "GIT~1";
35
+};
36
+
37
export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
38
"WorkspaceFileSystemOperationError",
39
{
@@ -112,11 +120,14 @@ export class WorkspaceFileSystem extends Context.Service<
120
ProjectReadFileResult,
121
WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
122
>;
123
+ /** Writes inside a known workspace only. */
124
readonly writeFile: (
125
input: ProjectWriteFileInput,
126
) => Effect.Effect<
127
ProjectWriteFileResult,
119
- WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
128
+ | WorkspaceFileSystemError
129
+ | WorkspacePaths.WorkspacePathOutsideRootError
130
+ | KnownWorkspaces.UnknownWorkspaceError
131
>;
132
}
133
>()("t3/workspace/WorkspaceFileSystem") {}
@@ -126,6 +137,7 @@ export const make = Effect.gen(function* () {
137
const fileSystem = yield* FileSystem.FileSystem;
138
const path = yield* Path.Path;
139
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
140
+ const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
141
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
142
143
const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
@@ -171,6 +183,42 @@ export const make = Effect.gen(function* () {
183
return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
184
});
185
186
+ /** Both paths must already be real paths. */
187
+ const isInsideRealRoot = (realWorkspaceRoot: string, realPath: string) => {
188
+ const relative = path.relative(realWorkspaceRoot, realPath);
189
+ return !(
190
+ relative.startsWith(`..${path.sep}`) ||
191
+ relative === ".." ||
192
+ path.isAbsolute(relative)
193
+ );
194
+ };
195
+
196
+ /**
197
+ * Git runs config and hooks from its own folders, so a write never lands in one:
198
+ * a `.git` entry, or a repository folder under another name such as `.bare`.
199
+ * Folders are checked upward to a linked worktree's top, which holds a `.git`
200
+ * file, since worktrees can sit inside a bare repository. `absolutePath` must
201
+ * be normalized.
202
+ */
203
+ const isInGitFolder = async (absolutePath: string) => {
204
+ if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
205
+ for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
206
+ const [head, commondir, objects, refs, dotGit] = await Promise.all(
207
+ ["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
208
+ NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
209
+ // Any other failure leaves the folder unknown, so the write is refused.
210
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
211
+ throw error;
212
+ }),
213
+ ),
214
+ );
215
+ // What git reads as a repository: HEAD, plus objects and refs here or in
216
+ // the folder a `commondir` file names, as in a linked worktree's git folder.
217
+ if (head && (commondir || (objects && refs))) return true;
218
+ if (dotGit?.isFile() || path.dirname(folder) === folder) return false;
219
+ }
220
+ };
221
+
222
/**
223
* Workspace-relative paths must stay inside the root, symlinks included. An
224
* absolute path reads a host file in place, such as a report an agent wrote to a
@@ -202,7 +250,7 @@ export const make = Effect.gen(function* () {
250
});
251
252
const realWorkspaceRoot = yield* Effect.tryPromise({
205
- try: () => NodeFSP.realpath(input.cwd),
253
+ try: () => NodeFSP.realpath(path.resolve(input.cwd)),
254
catch: (cause) =>
255
new WorkspaceFileSystemOperationError({
256
workspaceRoot: input.cwd,
@@ -225,12 +273,7 @@ export const make = Effect.gen(function* () {
273
cause,
274
}),
275
});
228
- const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
229
- if (
230
- relativeRealPath.startsWith(`..${path.sep}`) ||
231
- relativeRealPath === ".." ||
232
- path.isAbsolute(relativeRealPath)
233
- ) {
276
+ if (!isInsideRealRoot(realWorkspaceRoot, realTargetPath)) {
277
return yield* new WorkspaceFilePathEscapeError({
278
workspaceRoot: input.cwd,
279
relativePath: input.relativePath,
@@ -334,40 +377,133 @@ export const make = Effect.gen(function* () {
377
);
378
});
379
337
- const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
338
- "WorkspaceFileSystem.writeFile",
339
- )(function* (input) {
380
+ /**
381
+ * Resolves the file a write targets. The deepest existing ancestor resolves to
382
+ * its real path before the root check, so neither the file nor the directories
383
+ * created for it can follow a symlink out of the root. A dangling symlink is
384
+ * rejected rather than written through.
385
+ */
386
+ const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
387
+ input: ProjectWriteFileInput,
388
+ ) {
389
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
390
workspaceRoot: input.cwd,
391
relativePath: input.relativePath,
392
});
393
+ const realWorkspaceRoot = yield* Effect.tryPromise({
394
+ // Resolve `..` in cwd the way the relative path was resolved, before following links.
395
+ try: () => NodeFSP.realpath(path.resolve(input.cwd)),
396
+ catch: (cause) =>
397
+ new WorkspaceFileSystemOperationError({
398
+ workspaceRoot: input.cwd,
399
+ relativePath: input.relativePath,
400
+ resolvedPath: target.absolutePath,
401
+ operationPath: input.cwd,
402
+ operation: "realpath-workspace-root",
403
+ cause,
404
+ }),
405
+ });
406
345
- yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
346
- Effect.mapError(
347
- (cause) =>
407
+ // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
408
+ const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
409
+ const realTargetPath = yield* Effect.tryPromise({
410
+ try: async () => {
411
+ for (let depth = segments.length; depth > 0; depth--) {
412
+ const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
413
+ try {
414
+ return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
415
+ } catch (error) {
416
+ // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
417
+ const exists = await NodeFSP.lstat(candidate).then(
418
+ () => true,
419
+ () => false,
420
+ );
421
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
422
+ }
423
+ }
424
+ return path.join(realWorkspaceRoot, ...segments);
425
+ },
426
+ catch: (cause) =>
427
+ new WorkspaceFileSystemOperationError({
428
+ workspaceRoot: input.cwd,
429
+ relativePath: input.relativePath,
430
+ resolvedPath: target.absolutePath,
431
+ operationPath: target.absolutePath,
432
+ operation: "realpath-target",
433
+ cause,
434
+ }),
435
+ });
436
+ // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
437
+ const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
438
+ const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
439
+ Effect.tryPromise({
440
+ try: () => isInGitFolder(checkedPath),
441
+ catch: (cause) =>
442
new WorkspaceFileSystemOperationError({
443
workspaceRoot: input.cwd,
444
relativePath: input.relativePath,
351
- resolvedPath: target.absolutePath,
352
- operationPath: path.dirname(target.absolutePath),
353
- operation: "make-directory",
445
+ resolvedPath: realTargetPath,
446
+ operationPath: checkedPath,
447
+ operation: "stat",
448
cause,
449
}),
356
- ),
450
+ }),
451
);
358
- yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
452
+ if (
453
+ !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
454
+ (yield* inGitFolder(realTargetPath)) ||
455
+ (yield* inGitFolder(namedTargetPath))
456
+ ) {
457
+ return yield* new WorkspaceFilePathEscapeError({
458
+ workspaceRoot: input.cwd,
459
+ relativePath: input.relativePath,
460
+ resolvedWorkspaceRoot: realWorkspaceRoot,
461
+ resolvedPath: realTargetPath,
462
+ });
463
+ }
464
+ return { relativePath: target.relativePath, realTargetPath };
465
+ });
466
+
467
+ const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
468
+ "WorkspaceFileSystem.writeFile",
469
+ )(function* (input) {
470
+ yield* knownWorkspaces.assertContains(input.cwd);
471
+ const target = yield* resolveWriteTarget(input);
472
+ const realTargetPath = target.realTargetPath;
473
+
474
+ yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
475
Effect.mapError(
476
(cause) =>
477
new WorkspaceFileSystemOperationError({
478
workspaceRoot: input.cwd,
479
relativePath: input.relativePath,
364
- resolvedPath: target.absolutePath,
365
- operationPath: target.absolutePath,
366
- operation: "write-file",
480
+ resolvedPath: realTargetPath,
481
+ operationPath: path.dirname(realTargetPath),
482
+ operation: "make-directory",
483
cause,
484
}),
485
),
486
);
487
+ yield* Effect.tryPromise({
488
+ // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
489
+ try: () =>
490
+ NodeFSP.writeFile(realTargetPath, input.contents, {
491
+ flag:
492
+ NodeFS.constants.O_WRONLY |
493
+ NodeFS.constants.O_CREAT |
494
+ NodeFS.constants.O_TRUNC |
495
+ (NodeFS.constants.O_NOFOLLOW ?? 0),
496
+ }),
497
+ catch: (cause) =>
498
+ new WorkspaceFileSystemOperationError({
499
+ workspaceRoot: input.cwd,
500
+ relativePath: input.relativePath,
501
+ resolvedPath: realTargetPath,
502
+ operationPath: realTargetPath,
503
+ operation: "write-file",
504
+ cause,
505
+ }),
506
+ });
507
yield* workspaceEntries.refresh(input.cwd);
508
return { relativePath: target.relativePath };
509
});
apps/server/src/worktreesDirectory.ts
+65
-1
@@ -1,7 +1,13 @@
1
-import type * as Path from "effect/Path";
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 { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
7
8
+import * as ServerConfig from "./config.ts";
9
+import * as ServerSettings from "./serverSettings.ts";
10
+
11
/**
12
* Null when the setting is not an absolute path on this machine, such as `D:\worktrees`
13
* configured for a Windows server and synced to a Linux one, or when it is a filesystem root,
@@ -41,3 +47,61 @@ export function managedWorktreesDirectories(
47
}
48
return [...directories];
49
}
50
+
51
+/**
52
+ * A thread's path and branch can come from a client, so a missing worktree is
53
+ * only recreated where the server would have put it:
54
+ * `<managed worktrees folder>/<repo>/<branch>`, compared by real path.
55
+ */
56
+export const makeIsManagedWorktreePath = Effect.gen(function* () {
57
+ const fileSystem = yield* FileSystem.FileSystem;
58
+ const path = yield* Path.Path;
59
+ const serverConfig = yield* ServerConfig.ServerConfig;
60
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
61
+
62
+ // Where git would create `target`: the real path of its nearest existing
63
+ // ancestor plus the missing rest, since git follows symlinks on the way.
64
+ const realLocation = (target: string): Effect.Effect<string> =>
65
+ fileSystem.realPath(target).pipe(
66
+ Effect.catch(() => {
67
+ const parent = path.dirname(target);
68
+ return parent === target
69
+ ? Effect.succeed(target)
70
+ : Effect.map(realLocation(parent), (real) => path.join(real, path.basename(target)));
71
+ }),
72
+ );
73
+
74
+ return Effect.fn("worktreesDirectory.isManagedWorktreePath")(function* (worktreePath: string) {
75
+ // git resolves a relative path against the project, not the server cwd.
76
+ if (!path.isAbsolute(worktreePath)) return false;
77
+ // Server-made paths are normalized. A `..` would be applied after git
78
+ // follows a symlink but before realPath does, so the two disagree.
79
+ if (path.resolve(worktreePath) !== worktreePath) return false;
80
+ const settings = yield* serverSettings.getSettings.pipe(
81
+ Effect.orElseSucceed(() => ({
82
+ worktreesDirectory: "",
83
+ previousWorktreesDirectories: [],
84
+ })),
85
+ );
86
+ const roots = yield* Effect.forEach(
87
+ managedWorktreesDirectories(
88
+ settings,
89
+ serverConfig.worktreesDir,
90
+ path,
91
+ yield* HostProcess.HomeDirectory,
92
+ ),
93
+ realLocation,
94
+ );
95
+ const candidate = yield* realLocation(worktreePath);
96
+ return roots.some((root) => {
97
+ if (isFilesystemRoot(root, path)) return false;
98
+ const relative = path.relative(root, candidate);
99
+ const segments = relative.split(path.sep);
100
+ return (
101
+ !path.isAbsolute(relative) &&
102
+ segments.length === 2 &&
103
+ segments.every((segment) => segment !== "" && segment !== "..")
104
+ );
105
+ });
106
+ });
107
+});
apps/server/src/ws.ts
+4
-1
@@ -196,6 +196,7 @@ import { parseBase64DataUrl } from "./imageMime.ts";
196
import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts";
197
import * as PortScanner from "./preview/PortScanner.ts";
198
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
199
+import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts";
200
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
201
import { readWorkflowScript } from "./orchestration-v2/workflowScriptQuery.ts";
202
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
@@ -505,7 +506,8 @@ function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntries
506
function projectFileFailureContext(
507
error:
508
| WorkspaceFileSystem.WorkspaceFileSystemError
508
- | WorkspacePaths.WorkspacePathOutsideRootError,
509
+ | WorkspacePaths.WorkspacePathOutsideRootError
510
+ | KnownWorkspaces.UnknownWorkspaceError,
511
): {
512
readonly failure: ProjectFileFailure;
513
readonly resolvedPath?: string;
@@ -515,6 +517,7 @@ function projectFileFailureContext(
517
} {
518
switch (error._tag) {
519
case "WorkspacePathOutsideRootError":
520
+ case "UnknownWorkspaceError":
521
return { failure: "workspace_path_outside_root" };
522
case "WorkspaceFileSystemOperationError":
523
return {
packages/contracts/src/rpc.test.ts
+11
-1
@@ -3,7 +3,7 @@ import * as Exit from "effect/Exit";
3
import * as Schema from "effect/Schema";
4
5
import { ORCHESTRATION_V2_WS_METHODS } from "./orchestrationV2.ts";
6
-import { WsRpcGroup, WsSubscribeServerConfigRpc } from "./rpc.ts";
6
+import { WS_METHODS, WsRpcGroup, WsSubscribeServerConfigRpc } from "./rpc.ts";
7
8
describe("subscribeServerConfig payload compatibility", () => {
9
it("is accepted by a server whose schema predates the field", () => {
@@ -61,4 +61,14 @@ describe("WebSocket RPC contracts", () => {
61
),
62
).toBe(true);
63
});
64
+
65
+ it("lets the server pick a new worktree's folder", () => {
66
+ const createWorktree = WsRpcGroup.requests.get(WS_METHODS.vcsCreateWorktree);
67
+ if (createWorktree === undefined) throw new Error("vcs.createWorktree is not registered");
68
+ const decode = Schema.decodeUnknownExit(createWorktree.payloadSchema);
69
+ const request = { cwd: "/repo", refName: "main", newRefName: "feature/x" };
70
+
71
+ expect(Exit.isSuccess(decode({ ...request, path: null }))).toBe(true);
72
+ expect(Exit.isFailure(decode({ ...request, path: "/repo/.git/hooks" }))).toBe(true);
73
+ });
74
});
packages/contracts/src/rpc.ts
+4
-1
@@ -1381,7 +1381,10 @@ const WsVcsListRefsRpc = Rpc.make(WS_METHODS.vcsListRefs, {
1381
});
1382
1383
const WsVcsCreateWorktreeRpc = Rpc.make(WS_METHODS.vcsCreateWorktree, {
1384
- payload: VcsCreateWorktreeInput,
1384
+ // Clients cannot choose the folder: new worktrees go in the server's managed
1385
+ // worktrees folder. `path` stays a required null because older servers
1386
+ // require the key.
1387
+ payload: Schema.Struct({ ...VcsCreateWorktreeInput.fields, path: Schema.Null }),
1388
success: VcsCreateWorktreeResult,
1389
error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),
1390
});
packages/contracts/src/worktreeMcp.ts
+1
-6
@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";
3
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
4
5
/**
6
+ * The server picks the location in its managed worktrees folder.
7
* Changing the thread's workspace detaches the live provider session, so the
8
* current turn ends shortly after the handoff is recorded; the conversation
9
* continues inside the worktree on the thread's next run.
@@ -23,12 +24,6 @@ export const WorktreeMcpHandoffInput = Schema.Struct({
24
"Fetch origin and start the worktree branch from the remote-tracking commit of baseRef instead of the local ref. Defaults to the server's 'new worktrees start from origin' setting.",
25
}),
26
),
26
- path: Schema.optional(
27
- TrimmedNonEmptyString.check(Schema.isPattern(/^(?:[A-Za-z]:[\\/]|[\\/])/)).annotate({
28
- description:
29
- "Absolute filesystem path for the new worktree. Relative paths are rejected. Defaults to the server-managed worktrees directory.",
30
- }),
31
- ),
27
runSetupScript: Schema.optional(
28
Schema.Boolean.annotate({
29
description: