Skip to content

Commit 8e0d5e5

Browse files
refactor(server): resolve project and worktree folders in one place (pingdotgg#20449)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent f4da080 commit 8e0d5e5

21 files changed

Lines changed: 1001 additions & 197 deletions

‎apps/server/src/mcp/WorktreeMcpService.test.ts‎

Lines changed: 15 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import * as Exit from "effect/Exit";
1717
import * as Fiber from "effect/Fiber";
1818
import * as Layer from "effect/Layer";
1919
import * as Option from "effect/Option";
20-
import * as Path from "effect/Path";
2120
import * as Schema from "effect/Schema";
2221

2322
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -104,7 +103,6 @@ interface HarnessOptions {
104103
readonly projectMissing?: boolean;
105104
readonly projectReadFails?: boolean;
106105
readonly existingBranchWorktreePath?: string | null;
107-
readonly pathSemantics?: "win32" | "posix";
108106
readonly createWorktreeFails?: boolean;
109107
readonly fetchRemoteFails?: boolean;
110108
readonly resolveRemoteFails?: boolean;
@@ -287,22 +285,7 @@ const makeHarness = (options: HarnessOptions = {}) => {
287285
}
288286
});
289287

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(
306289
Layer.provide(
307290
Layer.mergeAll(
308291
Layer.mock(ThreadManagementService.ThreadManagementService)({
@@ -386,6 +369,9 @@ const runStatus = (harness: ReturnType<typeof makeHarness>) =>
386369
return yield* service.status(harness.scope);
387370
}).pipe(Effect.provide(harness.layer));
388371

372+
// Decodes tool arguments the way the MCP tool does before calling the service.
373+
const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
374+
389375
describe("t3_worktree_handoff", () => {
390376
it.effect("creates a worktree from the current branch and re-points the thread", () => {
391377
const harness = makeHarness();
@@ -501,14 +487,13 @@ describe("t3_worktree_handoff", () => {
501487
});
502488
});
503489

504-
it.effect("starts from origin and honors explicit baseRef and path", () => {
490+
it.effect("starts from origin and honors an explicit baseRef", () => {
505491
const harness = makeHarness();
506492
return Effect.gen(function* () {
507493
const result = yield* runHandoff(harness, {
508494
branch: "feature/from-origin",
509495
baseRef: "dev",
510496
startFromOrigin: true,
511-
path: "/custom/worktree/location",
512497
runSetupScript: false,
513498
});
514499

@@ -526,11 +511,11 @@ describe("t3_worktree_handoff", () => {
526511
refName: "abc123",
527512
newRefName: "feature/from-origin",
528513
baseRefName: "dev",
529-
path: "/custom/worktree/location",
514+
path: null,
530515
});
531516
expect(harness.localStatus).toHaveBeenCalled();
532517
expect(harness.runForThread).not.toHaveBeenCalled();
533-
expect(result.worktreePath).toBe("/custom/worktree/location");
518+
expect(result.worktreePath).toBe("/worktrees/project/feature/from-origin");
534519
expect(result.startedFromOrigin).toBe(true);
535520
expect(result.setupScript).toEqual({ status: "skipped" });
536521
});
@@ -825,28 +810,16 @@ describe("t3_worktree_handoff", () => {
825810
});
826811
});
827812

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();
830815
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",
834819
});
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");
850823
});
851824
});
852825

@@ -914,17 +887,6 @@ describe("t3_worktree_handoff", () => {
914887
});
915888
});
916889

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-
928890
it.effect("fails when baseRef is omitted and HEAD is detached", () => {
929891
const harness = makeHarness({ currentBranch: null });
930892
return Effect.gen(function* () {
@@ -1013,24 +975,6 @@ describe("t3_worktree_status", () => {
1013975
describe("WorktreeMcpHandoffInput schema", () => {
1014976
const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
1015977

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-
1034978
it.effect("rejects a missing or blank branch", () =>
1035979
Effect.gen(function* () {
1036980
expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true);

‎apps/server/src/mcp/WorktreeMcpService.ts‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import * as Crypto from "effect/Crypto";
1515
import * as Effect from "effect/Effect";
1616
import * as Layer from "effect/Layer";
1717
import * as Option from "effect/Option";
18-
import * as Path from "effect/Path";
1918

2019
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
2120
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
@@ -57,7 +56,6 @@ const asOperationFailed = (prefix: string) =>
5756

5857
const make = Effect.gen(function* () {
5958
const crypto = yield* Crypto.Crypto;
60-
const path = yield* Path.Path;
6159
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
6260
const projects = yield* ProjectService.ProjectService;
6361
const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -165,13 +163,6 @@ const make = Effect.gen(function* () {
165163
const project = yield* loadProject(scope, projection.thread.projectId);
166164
const projectCwd = project.workspaceRoot;
167165

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-
175166
const localStatus = yield* gitWorkflow
176167
.localStatus({ cwd: projectCwd })
177168
.pipe(asOperationFailed("Unable to read git status"));
@@ -252,7 +243,7 @@ const make = Effect.gen(function* () {
252243
refName: worktreeBaseRef,
253244
newRefName: input.branch,
254245
baseRefName: baseRef,
255-
path: input.path ?? null,
246+
path: null,
256247
})
257248
.pipe(asOperationFailed("Unable to create the worktree")),
258249
);
@@ -464,7 +455,6 @@ export const layer: Layer.Layer<
464455
WorktreeMcpService,
465456
never,
466457
| Crypto.Crypto
467-
| Path.Path
468458
| ThreadManagementService.ThreadManagementService
469459
| ProjectService.ProjectService
470460
| ServerSettings.ServerSettingsService

‎apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import * as Layer from "effect/Layer";
1616
import * as Option from "effect/Option";
1717
import * as Path from "effect/Path";
1818
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
19+
import * as ServerConfig from "../config.ts";
20+
import * as ServerSettings from "../serverSettings.ts";
1921
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
2022
import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
2123
import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts";
@@ -105,6 +107,8 @@ it.effect.each([
105107
Layer.provide(
106108
Layer.mergeAll(
107109
NodeServices.layer,
110+
Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
111+
ServerSettings.layerTest(),
108112
ThreadCommandExecutor.layer,
109113
IdAllocator.layer,
110114
Layer.mock(GitWorkflowService.GitWorkflowService)({}),

‎apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import * as Option from "effect/Option";
1919
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
2020
import * as Layer from "effect/Layer";
2121

22+
import * as ServerConfig from "../config.ts";
23+
import * as ServerSettings from "../serverSettings.ts";
2224
import * as GitWorkflow from "../git/GitWorkflowService.ts";
2325
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
2426
import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
@@ -43,6 +45,8 @@ const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe(
4345
Layer.provide(
4446
Layer.mergeAll(
4547
NodeServices.layer,
48+
Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
49+
ServerSettings.layerTest(),
4650
Layer.mock(GitWorkflow.GitWorkflowService)({}),
4751
Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(unrelatedProject) }),
4852
),
@@ -395,13 +399,20 @@ it.effect.each([
395399
{ order: "cleanup-first", restoreFiles: true },
396400
{ order: "cleanup-first", restoreFiles: false },
397401
{ 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 }) =>
399405
Effect.gen(function* () {
400406
const fileSystem = yield* FileSystem.FileSystem;
401407
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 });
405416
const threadId = ThreadId.make("rollback-worktree");
406417
const projectId = ProjectId.make("rollback-worktree-project");
407418
const providerThreadId = ProviderThreadId.make("rollback-worktree-provider-thread");
@@ -438,6 +449,8 @@ it.effect.each([
438449
Layer.mergeAll(
439450
ThreadCommandExecutor.layer,
440451
NodeServices.layer,
452+
Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never),
453+
ServerSettings.layerTest(),
441454
Layer.mock(ProjectStore.ProjectStoreV2)({
442455
get: (id) => {
443456
assert.equal(id, projectId);
@@ -536,6 +549,12 @@ it.effect.each([
536549
if (order === "rollback-first") assert.isFalse(cleanupEntered);
537550
yield* Deferred.succeed(release, undefined);
538551
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+
}
539558
yield* Fiber.join(rollback);
540559
if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup);
541560
const rollbackCalls = restoreFiles

‎apps/server/src/orchestration-v2/CheckpointRollbackService.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ import * as Path from "effect/Path";
1616
import * as Schema from "effect/Schema";
1717

1818
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";
1922
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
2023
import {
2124
isCheckpointRestoreIsolated,
@@ -96,6 +99,8 @@ export const layer: Layer.Layer<
9699
| FileSystem.FileSystem
97100
| Path.Path
98101
| ProjectStore.ProjectStoreV2
102+
| ServerConfig.ServerConfig
103+
| ServerSettings.ServerSettingsService
99104
| ThreadCommandExecutor.ThreadCommandExecutor
100105
> = Layer.effect(
101106
CheckpointRollbackServiceV2,
@@ -111,6 +116,7 @@ export const layer: Layer.Layer<
111116
const projects = yield* ProjectStore.ProjectStoreV2;
112117
const path = yield* Path.Path;
113118
const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
119+
const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
114120

115121
const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
116122
readonly threadId: ThreadId;
@@ -196,7 +202,13 @@ export const layer: Layer.Layer<
196202
});
197203

198204
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+
) {
200212
const project = yield* projects.get(projection.thread.projectId);
201213
if (Option.isSome(project)) {
202214
yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot });

0 commit comments

Comments
 (0)