Skip to content
TypeScript

refactor(server): resolve project and worktree folders in one place (#20449)

Julius Marminge8e0d5e5e4daf
diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts
index 513471134e4..eea8d4bbd8a 100644
--- a/apps/server/src/mcp/WorktreeMcpService.test.ts
+++ b/apps/server/src/mcp/WorktreeMcpService.test.ts
@@ -17,7 +17,6 @@ import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
-import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -104,7 +103,6 @@ interface HarnessOptions {
readonly projectMissing?: boolean;
readonly projectReadFails?: boolean;
readonly existingBranchWorktreePath?: string | null;
- readonly pathSemantics?: "win32" | "posix";
readonly createWorktreeFails?: boolean;
readonly fetchRemoteFails?: boolean;
readonly resolveRemoteFails?: boolean;
@@ -287,22 +285,7 @@ const makeHarness = (options: HarnessOptions = {}) => {
}
});
- // Optional deterministic Path semantics: providing this BEFORE the general
- // mocks means the service resolves Path here rather than from NodeServices,
- // so absolute-path validation is testable independently of the host OS.
- const win32IsAbsolute = (value: string) => /^(?:[a-zA-Z]:[\\/]|[\\/])/.test(value);
- const posixIsAbsolute = (value: string) => value.startsWith("/");
- const layerService =
- options.pathSemantics === undefined
- ? WorktreeMcpService.layer
- : WorktreeMcpService.layer.pipe(
- Layer.provide(
- Layer.succeed(Path.Path, {
- isAbsolute: options.pathSemantics === "win32" ? win32IsAbsolute : posixIsAbsolute,
- } as unknown as Path.Path),
- ),
- );
- const layer = layerService.pipe(
+ const layer = WorktreeMcpService.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ThreadManagementService.ThreadManagementService)({
@@ -386,6 +369,9 @@ const runStatus = (harness: ReturnType<typeof makeHarness>) =>
return yield* service.status(harness.scope);
}).pipe(Effect.provide(harness.layer));
+// Decodes tool arguments the way the MCP tool does before calling the service.
+const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
+
describe("t3_worktree_handoff", () => {
it.effect("creates a worktree from the current branch and re-points the thread", () => {
const harness = makeHarness();
@@ -501,14 +487,13 @@ describe("t3_worktree_handoff", () => {
});
});
- it.effect("starts from origin and honors explicit baseRef and path", () => {
+ it.effect("starts from origin and honors an explicit baseRef", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const result = yield* runHandoff(harness, {
branch: "feature/from-origin",
baseRef: "dev",
startFromOrigin: true,
- path: "/custom/worktree/location",
runSetupScript: false,
});
@@ -526,11 +511,11 @@ describe("t3_worktree_handoff", () => {
refName: "abc123",
newRefName: "feature/from-origin",
baseRefName: "dev",
- path: "/custom/worktree/location",
+ path: null,
});
expect(harness.localStatus).toHaveBeenCalled();
expect(harness.runForThread).not.toHaveBeenCalled();
- expect(result.worktreePath).toBe("/custom/worktree/location");
+ expect(result.worktreePath).toBe("/worktrees/project/feature/from-origin");
expect(result.startedFromOrigin).toBe(true);
expect(result.setupScript).toEqual({ status: "skipped" });
});
@@ -825,28 +810,16 @@ describe("t3_worktree_handoff", () => {
});
});
- it.effect("accepts a Windows drive path under win32 path semantics", () => {
- const harness = makeHarness({ pathSemantics: "win32" });
+ it.effect("creates the worktree in the managed directory even when a call names a path", () => {
+ const harness = makeHarness();
return Effect.gen(function* () {
- const result = yield* runHandoff(harness, {
- branch: "feature/windows-path",
- path: "C:\\worktrees\\custom",
+ const input = yield* decodeHandoffInput({
+ branch: "feature/elsewhere",
+ path: "/home/user/.ssh/checkout",
});
- expect(result.worktreePath).toBe("C:\\worktrees\\custom");
- expect(harness.createWorktree).toHaveBeenCalledWith(
- expect.objectContaining({ path: "C:\\worktrees\\custom" }),
- );
- });
- });
-
- it.effect("rejects a Windows drive path under posix path semantics", () => {
- const harness = makeHarness({ pathSemantics: "posix" });
- return Effect.gen(function* () {
- const exit = yield* Effect.exit(
- runHandoff(harness, { branch: "feature/windows-path", path: "C:\\worktrees\\custom" }),
- );
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
- expect(harness.createWorktree).not.toHaveBeenCalled();
+ const result = yield* runHandoff(harness, input);
+ expect(harness.createWorktree).toHaveBeenCalledWith(expect.objectContaining({ path: null }));
+ expect(result.worktreePath).toBe("/worktrees/project/feature/elsewhere");
});
});
@@ -914,17 +887,6 @@ describe("t3_worktree_handoff", () => {
});
});
- it.effect("rejects a relative path", () => {
- const harness = makeHarness();
- return Effect.gen(function* () {
- const exit = yield* Effect.exit(
- runHandoff(harness, { branch: "feature/relative-path", path: "worktrees/nested" }),
- );
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
- expect(harness.createWorktree).not.toHaveBeenCalled();
- });
- });
-
it.effect("fails when baseRef is omitted and HEAD is detached", () => {
const harness = makeHarness({ currentBranch: null });
return Effect.gen(function* () {
@@ -1013,24 +975,6 @@ describe("t3_worktree_status", () => {
describe("WorktreeMcpHandoffInput schema", () => {
const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
- it.effect("accepts POSIX, Windows drive, and UNC absolute paths", () =>
- Effect.gen(function* () {
- for (const path of ["/abs/posix", "C:\\abs\\drive", "C:/abs/drive", "\\\\host\\share"]) {
- const decoded = yield* decode({ branch: "feature/x", path });
- expect(decoded.path).toBe(path);
- }
- }),
- );
-
- it.effect("rejects relative paths", () =>
- Effect.gen(function* () {
- for (const path of ["worktrees/nested", "./nested", "../sibling"]) {
- const exit = yield* Effect.exit(decode({ branch: "feature/x", path }));
- expect(Exit.isFailure(exit), `path '${path}' should be rejected`).toBe(true);
- }
- }),
- );
-
it.effect("rejects a missing or blank branch", () =>
Effect.gen(function* () {
expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true);
diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts
index 15cf334d6fa..b738aaac12f 100644
--- a/apps/server/src/mcp/WorktreeMcpService.ts
+++ b/apps/server/src/mcp/WorktreeMcpService.ts
@@ -15,7 +15,6 @@ import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
-import * as Path from "effect/Path";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
@@ -57,7 +56,6 @@ const asOperationFailed = (prefix: string) =>
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
- const path = yield* Path.Path;
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
const projects = yield* ProjectService.ProjectService;
const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -165,13 +163,6 @@ const make = Effect.gen(function* () {
const project = yield* loadProject(scope, projection.thread.projectId);
const projectCwd = project.workspaceRoot;
- if (input.path !== undefined && !path.isAbsolute(input.path)) {
- return yield* failure(
- "invalid_request",
- `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.`,
- );
- }
-
const localStatus = yield* gitWorkflow
.localStatus({ cwd: projectCwd })
.pipe(asOperationFailed("Unable to read git status"));
@@ -252,7 +243,7 @@ const make = Effect.gen(function* () {
refName: worktreeBaseRef,
newRefName: input.branch,
baseRefName: baseRef,
- path: input.path ?? null,
+ path: null,
})
.pipe(asOperationFailed("Unable to create the worktree")),
);
@@ -464,7 +455,6 @@ export const layer: Layer.Layer<
WorktreeMcpService,
never,
| Crypto.Crypto
- | Path.Path
| ThreadManagementService.ThreadManagementService
| ProjectService.ProjectService
| ServerSettings.ServerSettingsService
diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
index 838f0d4372b..c6213056322 100644
--- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
@@ -16,6 +16,8 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
+import * as ServerConfig from "../config.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts";
@@ -105,6 +107,8 @@ it.effect.each([
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
+ ServerSettings.layerTest(),
ThreadCommandExecutor.layer,
IdAllocator.layer,
Layer.mock(GitWorkflowService.GitWorkflowService)({}),
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
index 8ca3af22443..abb9f72f9ff 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
@@ -19,6 +19,8 @@ import * as Option from "effect/Option";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
import * as Layer from "effect/Layer";
+import * as ServerConfig from "../config.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as GitWorkflow from "../git/GitWorkflowService.ts";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
@@ -43,6 +45,8 @@ const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
+ ServerSettings.layerTest(),
Layer.mock(GitWorkflow.GitWorkflowService)({}),
Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(unrelatedProject) }),
),
@@ -395,13 +399,20 @@ it.effect.each([
{ order: "cleanup-first", restoreFiles: true },
{ order: "cleanup-first", restoreFiles: false },
{ order: "rollback-first", restoreFiles: true },
-])("locks rollback with %s", ({ order, restoreFiles }) =>
+ // A path the server would not have made is left missing, not recreated.
+ { order: "cleanup-first", restoreFiles: false, unmanaged: true },
+])("locks rollback with %s", ({ order, restoreFiles, unmanaged = false }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
- const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-" });
- const worktreePath = path.join(workspaceRoot, "worktree");
- yield* fileSystem.makeDirectory(worktreePath);
+ const workspaceRoot = yield* fileSystem.realPath(
+ yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-" }),
+ );
+ const worktreesDir = path.join(workspaceRoot, "worktrees");
+ const worktreePath = unmanaged
+ ? path.join(workspaceRoot, "elsewhere", "feature")
+ : path.join(worktreesDir, "repo", "feature");
+ yield* fileSystem.makeDirectory(worktreePath, { recursive: true });
const threadId = ThreadId.make("rollback-worktree");
const projectId = ProjectId.make("rollback-worktree-project");
const providerThreadId = ProviderThreadId.make("rollback-worktree-provider-thread");
@@ -438,6 +449,8 @@ it.effect.each([
Layer.mergeAll(
ThreadCommandExecutor.layer,
NodeServices.layer,
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as never),
+ ServerSettings.layerTest(),
Layer.mock(ProjectStore.ProjectStoreV2)({
get: (id) => {
assert.equal(id, projectId);
@@ -536,6 +549,12 @@ it.effect.each([
if (order === "rollback-first") assert.isFalse(cleanupEntered);
yield* Deferred.succeed(release, undefined);
if (cleanup !== undefined) yield* Fiber.join(cleanup);
+ if (unmanaged) {
+ const error = yield* Fiber.join(rollback).pipe(Effect.flip);
+ assert.equal(error._tag, "CheckpointRollbackExecutionError");
+ assert.deepEqual(calls, ["cleanup"]);
+ return;
+ }
yield* Fiber.join(rollback);
if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup);
const rollbackCalls = restoreFiles
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
index 89726eee19f..abacb6d666a 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
@@ -16,6 +16,9 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
+import type * as ServerConfig from "../config.ts";
+import type * as ServerSettings from "../serverSettings.ts";
+import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import {
isCheckpointRestoreIsolated,
@@ -96,6 +99,8 @@ export const layer: Layer.Layer<
| FileSystem.FileSystem
| Path.Path
| ProjectStore.ProjectStoreV2
+ | ServerConfig.ServerConfig
+ | ServerSettings.ServerSettingsService
| ThreadCommandExecutor.ThreadCommandExecutor
> = Layer.effect(
CheckpointRollbackServiceV2,
@@ -111,6 +116,7 @@ export const layer: Layer.Layer<
const projects = yield* ProjectStore.ProjectStoreV2;
const path = yield* Path.Path;
const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
+ const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
readonly threadId: ThreadId;
@@ -196,7 +202,13 @@ export const layer: Layer.Layer<
});
const { worktreePath, branch } = projection.thread;
- if (worktreePath != null && branch != null && !(yield* fileSystem.exists(worktreePath))) {
+ // Recreated only where the server would have made it, as turn start does.
+ if (
+ worktreePath != null &&
+ branch != null &&
+ !(yield* fileSystem.exists(worktreePath)) &&
+ (yield* isManagedWorktreePath(worktreePath))
+ ) {
const project = yield* projects.get(projection.thread.projectId);
if (Option.isSome(project)) {
yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot });
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
index f1de494ae19..d8ae628e6f4 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
@@ -26,12 +26,15 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
+import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
+import * as ServerConfig from "../config.ts";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import * as GitWorkflow from "../git/GitWorkflowService.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as ContextHandoffService from "./ContextHandoffService.ts";
import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -45,7 +48,31 @@ import * as RuntimePolicy from "./RuntimePolicy.ts";
const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);
-it("does not commit running state when inherited background routing cannot be read", async () => {
+const managedWorktreesDir = "/tmp/provider-turn-start-worktrees";
+// fs.realpath applies `..` and `.` before following symlinks.
+const normalize = (target: string) => {
+ const parts: Array<string> = [];
+ for (const part of target.split("/")) {
+ if (part === "..") parts.pop();
+ else if (part !== "" && part !== ".") parts.push(part);
+ }
+ return `/${parts.join("/")}`;
+};
+const layerWorktreeLocation = (worktreesDir = managedWorktreesDir) =>
+ Layer.mergeAll(
+ Path.layer,
+ Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as ServerConfig.ServerConfig["Service"]),
+ ServerSettings.layerTest(),
+ );
+
+/** Starts a run on a thread whose worktree folder is missing, with routing reads failing after. */
+function startWithMissingWorktree(
+ worktreePath: string,
+ realPaths: Record<string, string> = {
+ [managedWorktreesDir]: managedWorktreesDir,
+ [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`,
+ },
+) {
const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");
const runId = RunId.make("run_provider_turn_start_projection_failure");
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
id: threadId,
projectId: ProjectId.make("project_provider_turn_start_projection_failure"),
branch: "feature/restore",
- worktreePath: "/tmp/missing-provider-turn-start-worktree",
+ worktreePath,
},
runs: [
{
@@ -100,8 +127,22 @@ it("does not commit running state when inherited background routing cannot be re
Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
IdAllocator.layer,
- Path.layer,
- FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
+ Layer.succeed(FileSystem.FileSystem, {
+ exists: () => Effect.succeed(false),
+ // Paths that exist on the fake disk, mapped to where their symlinks lead.
+ realPath: (target: string) =>
+ normalize(target) in realPaths
+ ? Effect.succeed(realPaths[normalize(target)])
+ : Effect.fail(
+ PlatformError.systemError({
+ _tag: "NotFound",
+ module: "FileSystem",
+ method: "realPath",
+ pathOrDescriptor: target,
+ }),
+ ),
+ } as never),
+ layerWorktreeLocation(),
Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }),
Layer.mock(ProjectService.ProjectService)({
getById: () =>
@@ -145,27 +186,97 @@ it("does not commit running state when inherited background routing cannot be re
),
);
- await Effect.gen(function* () {
- const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
+ const start = Effect.gen(function* () {
+ return yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
.start({ threadId, runId })
.pipe(Effect.flip);
-
- expect(error._tag).toBe("ProviderTurnStartError");
- expect(projectionReadCount).toBe(3);
- expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
- expect(createWorktree).toHaveBeenCalledWith({
- cwd: "/tmp/provider-turn-start-project",
- refName: "feature/restore",
- path: "/tmp/missing-provider-turn-start-worktree",
- });
- expect(writeIfRunCurrent).not.toHaveBeenCalled();
- expect(startRootRun).not.toHaveBeenCalled();
}).pipe(Effect.provide(layer), Effect.runPromise);
+ return {
+ start,
+ pruneWorktrees,
+ createWorktree,
+ writeIfRunCurrent,
+ startRootRun,
+ projectionReads: () => projectionReadCount,
+ };
+}
+
+it("does not commit running state when inherited background routing cannot be read", async () => {
+ const worktreePath = `${managedWorktreesDir}/project/feature-restore`;
+ const harness = startWithMissingWorktree(worktreePath);
+ const error = await harness.start;
+
+ expect(error._tag).toBe("ProviderTurnStartError");
+ expect(harness.projectionReads()).toBe(3);
+ expect(harness.pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
+ expect(harness.createWorktree).toHaveBeenCalledWith({
+ cwd: "/tmp/provider-turn-start-project",
+ refName: "feature/restore",
+ path: worktreePath,
+ });
+ expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
+ expect(harness.startRootRun).not.toHaveBeenCalled();
+});
+
+it.each([
+ {
+ label: "<managed>/<repo>/<branch>",
+ worktreePath: `${managedWorktreesDir}/project/feature-restore`,
+ recreated: true,
+ },
+ {
+ label: "the real path of a symlinked managed folder",
+ worktreePath: "/real-worktrees/project/feature-restore",
+ realPaths: { [managedWorktreesDir]: "/real-worktrees", "/real-worktrees": "/real-worktrees" },
+ recreated: true,
+ },
+ {
+ label: "a path outside the managed folder",
+ worktreePath: "/tmp/provider-turn-start-project/.git/hooks",
+ recreated: false,
+ },
+ {
+ label: "a symlink inside the managed folder that leads out",
+ worktreePath: `${managedWorktreesDir}/project/hooks`,
+ realPaths: {
+ [managedWorktreesDir]: managedWorktreesDir,
+ [`${managedWorktreesDir}/project`]: "/tmp/provider-turn-start-project/.git",
+ },
+ recreated: false,
+ },
+ {
+ label: "a folder nested below a worktree",
+ worktreePath: `${managedWorktreesDir}/project/feature-restore/link/hooks`,
+ recreated: false,
+ },
+ {
+ label: "'..' out of the managed folder",
+ worktreePath: `${managedWorktreesDir}/project/../../outside`,
+ recreated: false,
+ },
+ {
+ // Left raw on purpose: git follows `link` before applying `..`.
+ label: "'..' after a symlink inside the managed folder",
+ worktreePath: `${managedWorktreesDir}/project/x/link/../../hooks`,
+ realPaths: {
+ [managedWorktreesDir]: managedWorktreesDir,
+ [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`,
+ [`${managedWorktreesDir}/project/x`]: `${managedWorktreesDir}/project/x`,
+ [`${managedWorktreesDir}/project/x/link`]: "/tmp/provider-turn-start-project/.git/refs/heads",
+ },
+ recreated: false,
+ },
+ { label: "a relative path", worktreePath: "project/feature-restore", recreated: false },
+])("recreates a missing worktree only at the managed location: $label", async (input) => {
+ const harness = startWithMissingWorktree(input.worktreePath, input.realPaths);
+ await harness.start;
+ expect(harness.createWorktree).toHaveBeenCalledTimes(input.recreated ? 1 : 0);
});
function makeLocalCommandHarness(input: {
readonly text: string;
readonly worktreePath?: string;
+ readonly worktreesDir?: string;
readonly fileSystem?: FileSystem.FileSystem;
readonly previousNativeSession?: boolean;
readonly previousMessages?: ReadonlyArray<string>;
@@ -516,7 +627,7 @@ function makeLocalCommandHarness(input: {
}),
Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
IdAllocator.layer,
- Path.layer,
+ layerWorktreeLocation(input.worktreesDir),
input.fileSystem === undefined
? FileSystem.layerNoop({ exists: () => Effect.succeed(true) })
: Layer.succeed(FileSystem.FileSystem, input.fileSystem),
@@ -594,13 +705,14 @@ effectIt.effect.each(["cleanup-first", "startup-first"])(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" });
- const worktreePath = path.join(workspaceRoot, "worktree");
- yield* fileSystem.makeDirectory(worktreePath);
+ const worktreePath = path.join(workspaceRoot, "project", "worktree");
+ yield* fileSystem.makeDirectory(worktreePath, { recursive: true });
const release = yield* Deferred.make<void>();
const openEntered = yield* Deferred.make<void>();
const harness = makeLocalCommandHarness({
text: "Continue",
worktreePath,
+ worktreesDir: workspaceRoot,
fileSystem,
failReadsAfterRunning: true,
});
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index 36354f8c1f4..5c1a27cb473 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -22,11 +22,15 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Predicate from "effect/Predicate";
import * as Schema from "effect/Schema";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as ServerConfig from "../config.ts";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
import * as EventSink from "./EventSink.ts";
import * as ContextHandoffService from "./ContextHandoffService.ts";
import {
@@ -88,6 +92,8 @@ export const layer: Layer.Layer<
| IdAllocator.IdAllocatorV2
| FileSystem.FileSystem
| Path.Path
+ | ServerConfig.ServerConfig
+ | ServerSettings.ServerSettingsService
| GitWorkflowService.GitWorkflowService
| ProjectService.ProjectService
| ProviderAuthService.ProviderAuthService
@@ -103,6 +109,8 @@ export const layer: Layer.Layer<
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
const projects = yield* ProjectService.ProjectService;
const providerAuth = yield* ProviderAuthService.ProviderAuthService;
@@ -110,6 +118,7 @@ export const layer: Layer.Layer<
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
+ const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
// These callbacks outlive startup while a run drains background work. Build
// them outside start's scope so they cannot retain its full thread history.
@@ -448,7 +457,7 @@ export const layer: Layer.Layer<
const exists = yield* fileSystem
.exists(worktreePath)
.pipe(Effect.orElseSucceed(() => true));
- if (!exists) {
+ if (!exists && (yield* isManagedWorktreePath(worktreePath))) {
const project = yield* projects.getById(projection.thread.projectId).pipe(
Effect.map(Option.getOrUndefined),
Effect.orElseSucceed(() => undefined),
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
index 14c08d49221..b6327f3a069 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
@@ -401,6 +401,8 @@ export function layerWithRegistry<Error>(
}),
layerRunExecutionServiceProvided,
layerRuntime,
+ layerServerConfig,
+ layerServerSettings,
),
),
);
@@ -420,6 +422,8 @@ export function layerWithRegistry<Error>(
layerProviderSessionManagerProvided,
ThreadCommandExecutor.layer,
layerRuntime,
+ layerServerConfig,
+ layerServerSettings,
),
),
);
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs b/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs
index 0fafaf06376..840da274232 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs
+++ b/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs
@@ -16,20 +16,35 @@ const [Effect, Layer, FileSystem, Path] = await Promise.all([
const app = (file) => import(NodeURL.pathToFileURL(root + "/apps/server/src/" + file + ".ts"));
const providerCore = (file) =>
import(NodeURL.pathToFileURL(root + "/packages/provider-core/src/server/" + file + ".ts"));
-const [Start, Projection, Run, Sessions, Policy, Id, Sink, Handoff, Git, Project, Auth] =
- await Promise.all([
- app("orchestration-v2/ProviderTurnStartService"),
- app("orchestration-v2/ProjectionStore"),
- app("orchestration-v2/RunExecutionService"),
- app("orchestration-v2/ProviderSessionManager"),
- app("orchestration-v2/RuntimePolicy"),
- providerCore("IdAllocator"),
- app("orchestration-v2/EventSink"),
- app("orchestration-v2/ContextHandoffService"),
- app("git/GitWorkflowService"),
- app("project/ProjectService"),
- app("provider/ProviderAuthService"),
- ]);
+const [
+ Start,
+ Projection,
+ Run,
+ Sessions,
+ Policy,
+ Id,
+ Sink,
+ Handoff,
+ Git,
+ Project,
+ Auth,
+ Config,
+ Settings,
+] = await Promise.all([
+ app("orchestration-v2/ProviderTurnStartService"),
+ app("orchestration-v2/ProjectionStore"),
+ app("orchestration-v2/RunExecutionService"),
+ app("orchestration-v2/ProviderSessionManager"),
+ app("orchestration-v2/RuntimePolicy"),
+ providerCore("IdAllocator"),
+ app("orchestration-v2/EventSink"),
+ app("orchestration-v2/ContextHandoffService"),
+ app("git/GitWorkflowService"),
+ app("project/ProjectService"),
+ app("provider/ProviderAuthService"),
+ app("config"),
+ app("serverSettings"),
+]);
let current;
let fullReads = 0;
let threadReads = 0;
@@ -54,6 +69,8 @@ const dependencies = Layer.mergeAll(
Layer.mock(Git.GitWorkflowService)({}),
Layer.mock(Project.ProjectService)({}),
Layer.mock(Auth.ProviderAuthService)({}),
+ Layer.mock(Config.ServerConfig)({ worktreesDir: "/synthetic-worktrees" }),
+ Settings.layerTest(),
Layer.mock(Projection.ProjectionStoreV2)({
getThreadProjection: () =>
Effect.sync(() => {
diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts
index a19f046a280..74602efb62a 100644
--- a/apps/server/src/review/ReviewService.test.ts
+++ b/apps/server/src/review/ReviewService.test.ts
@@ -4,13 +4,16 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
+import * as SqlClient from "effect/sql/SqlClient";
import { ProjectId } from "@t3tools/contracts";
import * as ServerConfig from "../config.ts";
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
+import * as KnownWorkspaces from "../workspace/KnownWorkspaces.ts";
import * as ReviewService from "./ReviewService.ts";
function layer(input: {
@@ -20,9 +23,33 @@ function layer(input: {
readonly worktreesDirectory?: string;
readonly previousWorktreesDirectories?: ReadonlyArray<string>;
readonly projectRoots?: ReadonlyArray<string> | "unavailable";
+ readonly threadWorktrees?: ReadonlyArray<{ worktreePath: string; deleted?: boolean }>;
+ /** What `git worktree list` reports for every project. */
+ readonly gitWorktrees?: ReadonlyArray<string>;
}) {
const projectRoots = input.projectRoots ?? [];
return ReviewService.layer.pipe(
+ Layer.provide(KnownWorkspaces.layer),
+ Layer.provide(
+ Layer.effectDiscard(
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ for (const [index, thread] of (input.threadWorktrees ?? []).entries()) {
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_threads (
+ thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
+ created_at, updated_at, deleted_at, payload_json
+ ) VALUES (
+ ${`thread-${index}`}, 'project-0', 'Thread', 'codex', 'full-access', 'default',
+ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z',
+ ${thread.deleted ? "2026-01-02T00:00:00.000Z" : null},
+ ${JSON.stringify({ worktreePath: thread.worktreePath })}
+ )
+ `;
+ }
+ }),
+ ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
+ ),
Layer.provide(
Layer.mock(ProjectStore.ProjectStoreV2)({
listShells: () =>
@@ -54,7 +81,11 @@ function layer(input: {
}),
}),
),
- Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
+ Layer.provide(
+ Layer.mock(GitVcsDriver.GitVcsDriver)({
+ listWorktreePaths: () => Effect.succeed([...(input.gitWorktrees ?? [])]),
+ }),
+ ),
Layer.provide(
ServerSettings.ServerSettingsService.layerTest({
worktreesDirectory: input.worktreesDirectory ?? "",
@@ -178,6 +209,10 @@ describe("ReviewService", () => {
assert.strictEqual((yield* review(projectRoot, [projectRoot])).cwd, projectRoot);
assert.strictEqual((yield* review(projectChild, [projectRoot])).cwd, projectChild);
+ // A child whose name starts with `..` is still inside.
+ const dottedChild = `${projectRoot}/..feature`;
+ yield* fs.makeDirectory(dottedChild);
+ assert.strictEqual((yield* review(dottedChild, [projectRoot])).cwd, dottedChild);
for (const [cwd, projectRoots] of [
[sibling, [projectRoot]],
[projectRoot, []],
@@ -189,6 +224,82 @@ describe("ReviewService", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
+ it.effect("allows the worktree a thread is bound to, and nothing else outside the project", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
+ const project = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-project-" });
+ // Checkouts outside every managed folder, as `git worktree add ../feature` makes.
+ const bound = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-bound-" });
+ const deleted = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-deleted-" });
+ const unbound = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-unbound-" });
+ // A client can set a thread's path to any folder; git doesn't list this one.
+ const claimed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-claimed-" });
+ yield* fs.makeDirectory(`${bound}/sub`);
+
+ const review = (cwd: string) =>
+ Effect.gen(function* () {
+ const service = yield* ReviewService.ReviewService;
+ return yield* service.getDiffPreview({ cwd });
+ }).pipe(
+ Effect.provide(
+ layer({
+ workspaceRoot,
+ baseDir,
+ projectRoots: [project],
+ gitWorktrees: [project, bound, deleted],
+ threadWorktrees: [
+ { worktreePath: bound },
+ { worktreePath: claimed },
+ { worktreePath: deleted, deleted: true },
+ // A relative path would resolve against the server's own cwd.
+ { worktreePath: "t3-review-relative" },
+ // A filesystem root would make every folder look bound.
+ { worktreePath: "/" },
+ ],
+ }),
+ ),
+ );
+
+ for (const cwd of [bound, `${bound}/sub`]) {
+ assert.strictEqual((yield* review(cwd)).cwd, cwd);
+ }
+ for (const cwd of [deleted, unbound, claimed, `${process.cwd()}/t3-review-relative`]) {
+ const error = yield* review(cwd).pipe(Effect.flip);
+ assert.strictEqual(error._tag, "VcsRepositoryDetectionError");
+ }
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("allows a thread's worktree linked from a managed folder to a checkout elsewhere", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
+ const managed = yield* fs.realPath(
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-worktrees-" }),
+ );
+ const checkout = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-checkout-" });
+ yield* fs.symlink(checkout, `${managed}/feature`);
+
+ const result = yield* Effect.gen(function* () {
+ const review = yield* ReviewService.ReviewService;
+ return yield* review.getDiffPreview({ cwd: checkout });
+ }).pipe(
+ Effect.provide(
+ layer({
+ workspaceRoot,
+ baseDir,
+ worktreesDirectory: managed,
+ threadWorktrees: [{ worktreePath: `${managed}/feature` }],
+ }),
+ ),
+ );
+ assert.strictEqual(result.cwd, checkout);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
it.effect("allows diff preview cwd inside the configured workspace root", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/review/ReviewService.ts b/apps/server/src/review/ReviewService.ts
index dc372ff8ae0..488cc84be0a 100644
--- a/apps/server/src/review/ReviewService.ts
+++ b/apps/server/src/review/ReviewService.ts
@@ -16,12 +16,9 @@ import {
} from "@t3tools/contracts";
import * as ServerConfig from "../config.ts";
-import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
-import * as ServerSettings from "../serverSettings.ts";
-import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
-import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as KnownWorkspaces from "../workspace/KnownWorkspaces.ts";
export class ReviewService extends Context.Service<
ReviewService,
@@ -42,8 +39,7 @@ export const make = Effect.gen(function* () {
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
const git = yield* GitVcsDriver.GitVcsDriver;
- const settings = yield* ServerSettings.ServerSettingsService;
- const projectStore = yield* ProjectStore.ProjectStoreV2;
+ const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
const canonicalizePath = (value: string) => {
const resolvedPath = path.resolve(value);
@@ -64,52 +60,21 @@ export const make = Effect.gen(function* () {
);
};
- const isWithinRoot = (candidate: string, root: string) => {
- const relative = path.relative(root, candidate);
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
- };
-
const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* (
operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
cwd: string,
) {
- const worktreesDirectories = yield* settings.getSettings.pipe(
- Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
- );
- const home = yield* HostProcess.HomeDirectory;
- const [candidate, workspaceRoot, worktreesRoots] = yield* Effect.all([
+ const [candidate, workspaceRoot] = yield* Effect.all([
canonicalizePath(cwd),
canonicalizePath(config.cwd),
- Effect.forEach(
- managedWorktreesDirectories(worktreesDirectories, config.worktreesDir, path, home),
- (directory) => canonicalizePath(directory).pipe(Effect.orElseSucceed(() => null)),
- ).pipe(
- Effect.map((roots) =>
- roots.filter((root): root is string => root !== null && !isFilesystemRoot(root, path)),
- ),
- ),
]);
-
if (
- isWithinRoot(candidate, workspaceRoot) ||
- worktreesRoots.some((root) => isWithinRoot(candidate, root))
+ KnownWorkspaces.isWithinRoot(path, candidate, workspaceRoot) ||
+ (yield* knownWorkspaces.contains(candidate))
) {
return;
}
- // Registered projects can live outside the server cwd, which is the home
- // directory in packaged desktop builds, e.g. a repository on another
- // Windows drive. Unreadable or unresolvable project roots grant nothing.
- const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => []));
- for (const project of projects) {
- const root = yield* canonicalizePath(project.workspaceRoot).pipe(
- Effect.orElseSucceed(() => null),
- );
- if (root !== null && isWithinRoot(candidate, root)) {
- return;
- }
- }
-
return yield* new VcsRepositoryDetectionError({
operation,
cwd,
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 104541ea418..2d35647f094 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -95,6 +95,7 @@ import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
+import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
@@ -370,8 +371,13 @@ const layerProjectCloneTracker = ProjectCloneTracker.layer.pipe(
Layer.provide(layerSourceControlRepositoryService),
);
-const layerReview = ReviewService.layer.pipe(
+const layerKnownWorkspaces = KnownWorkspaces.layer.pipe(
Layer.provide(ProjectStore.layer),
+ Layer.provide(GitVcsDriver.layer),
+);
+
+const layerReview = ReviewService.layer.pipe(
+ Layer.provideMerge(layerKnownWorkspaces),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(layerVcsDriverRegistry),
);
@@ -423,6 +429,7 @@ const layerWorkspaceEntries = WorkspaceEntries.layer.pipe(Layer.provide(Workspac
const layerWorkspaceFileSystem = WorkspaceFileSystem.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(layerWorkspaceEntries),
+ Layer.provide(layerKnownWorkspaces),
);
const layerWorkspace = Layer.mergeAll(
diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts
index db56c68b48e..3698c77d16a 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.ts
@@ -3411,7 +3411,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
)(function* (input, options) {
const targetBranch = input.newRefName ?? input.refName;
const sanitizedBranch = targetBranch.replace(/\//g, "-");
- const repoName = path.basename(input.cwd);
+ // resolve: a cwd like `<repo>/sub/..` must not name the folder `..`.
+ const repoName = path.basename(path.resolve(input.cwd));
let worktreePath = input.path;
if (worktreePath == null) {
const parentDir = resolveWorktreesDirectory(
diff --git a/apps/server/src/workspace/KnownWorkspaces.ts b/apps/server/src/workspace/KnownWorkspaces.ts
new file mode 100644
index 00000000000..d98939415d9
--- /dev/null
+++ b/apps/server/src/workspace/KnownWorkspaces.ts
@@ -0,0 +1,156 @@
+/**
+ * KnownWorkspaces - the folders a client-named cwd may act in: a T3-managed
+ * worktree folder, a registered project, or a thread's worktree. Clients send
+ * the thread's worktree, else the project root. A client also sets a thread's
+ * worktree path, so one counts only under a managed folder or when git lists
+ * it as a worktree of the thread's project.
+ *
+ * @module KnownWorkspaces
+ */
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
+
+import * as ServerConfig from "../config.ts";
+import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
+import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
+
+export class UnknownWorkspaceError extends Schema.TaggedError<UnknownWorkspaceError>()(
+ "UnknownWorkspaceError",
+ {
+ cwd: Schema.String,
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return `'${this.cwd}' is not a registered project, a managed worktree, or a thread's worktree.`;
+ }
+}
+
+/** Whether `candidate` is `root` or inside it. Resolve both the same way first. */
+export const isWithinRoot = (path: Path.Path, candidate: string, root: string) => {
+ const relative = path.relative(root, candidate);
+ return (
+ relative === "" ||
+ (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+ );
+};
+
+export class KnownWorkspaces extends Context.Service<
+ KnownWorkspaces,
+ {
+ /** Whether a symlink-resolved path is inside a known workspace. */
+ readonly contains: (realPath: string) => Effect.Effect<boolean>;
+ /** Fails unless `cwd` exists and resolves inside a known workspace. */
+ readonly assertContains: (cwd: string) => Effect.Effect<void, UnknownWorkspaceError>;
+ }
+>()("t3/workspace/KnownWorkspaces") {}
+
+/** @public Service construction is part of the canonical Effect module API. */
+export const make = Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const settings = yield* ServerSettings.ServerSettingsService;
+ const projectStore = yield* ProjectStore.ProjectStoreV2;
+ const sql = yield* SqlClient.SqlClient;
+ const git = yield* GitVcsDriver.GitVcsDriver;
+
+ // A root that does not exist yet keeps its lexical path. One that cannot be
+ // resolved for another reason, or resolves to a filesystem root, grants nothing.
+ const resolveRoot = (value: string) => {
+ const resolvedPath = path.resolve(value);
+ return fileSystem.realPath(resolvedPath).pipe(
+ Effect.catchTags({
+ PlatformError: (cause) =>
+ Effect.succeed(cause.reason._tag === "NotFound" ? resolvedPath : null),
+ }),
+ Effect.map((root) => (root === null || isFilesystemRoot(root, path) ? null : root)),
+ );
+ };
+
+ const contains: KnownWorkspaces["Service"]["contains"] = Effect.fn("KnownWorkspaces.contains")(
+ function* (realPath) {
+ const within = (root: string | null) => root !== null && isWithinRoot(path, realPath, root);
+ const worktreeSettings = yield* settings.getSettings.pipe(
+ Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
+ );
+ const home = yield* HostProcess.HomeDirectory;
+ const managedDirectories = managedWorktreesDirectories(
+ worktreeSettings,
+ config.worktreesDir,
+ path,
+ home,
+ );
+ const managed = (yield* Effect.forEach(managedDirectories, resolveRoot)).filter(
+ (root) => root !== null,
+ );
+ if (managed.some(within)) return true;
+
+ const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => []));
+ for (const project of projects) {
+ if (within(yield* resolveRoot(project.workspaceRoot))) return true;
+ }
+
+ const threads = yield* sql<{ readonly worktreePath: string; readonly projectId: string }>`
+ SELECT DISTINCT
+ json_extract(payload_json, '$.worktreePath') AS "worktreePath",
+ project_id AS "projectId"
+ FROM orchestration_v2_projection_threads
+ WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
+ `.pipe(Effect.orElseSucceed(() => []));
+ const projectWorktrees = new Map<string, ReadonlyArray<string>>();
+ const isProjectWorktree = Effect.fnUntraced(function* (
+ projectId: string,
+ worktreePath: string,
+ ) {
+ const project = projects.find((candidate) => candidate.id === projectId);
+ if (project === undefined) return false;
+ let listed = projectWorktrees.get(projectId);
+ if (listed === undefined) {
+ listed = yield* git.listWorktreePaths(project.workspaceRoot).pipe(
+ Effect.flatMap((paths) => Effect.forEach(paths, resolveRoot)),
+ Effect.map((paths) => paths.filter((listedPath) => listedPath !== null)),
+ Effect.orElseSucceed((): ReadonlyArray<string> => []),
+ );
+ projectWorktrees.set(projectId, listed);
+ }
+ const real = yield* resolveRoot(worktreePath);
+ return real !== null && listed.includes(real);
+ });
+ for (const { worktreePath, projectId } of threads) {
+ // A relative path would resolve against the server's own cwd. One under a
+ // managed folder is still resolved: it can be a symlink to a checkout elsewhere.
+ if (!path.isAbsolute(worktreePath)) continue;
+ if (!within(yield* resolveRoot(worktreePath))) continue;
+ const lexical = path.resolve(worktreePath);
+ if (managedDirectories.some((directory) => isWithinRoot(path, lexical, directory))) {
+ return true;
+ }
+ if (yield* isProjectWorktree(projectId, worktreePath)) return true;
+ }
+ return false;
+ },
+ );
+
+ const assertContains: KnownWorkspaces["Service"]["assertContains"] = Effect.fn(
+ "KnownWorkspaces.assertContains",
+ )(function* (cwd) {
+ // `..` collapses on the path as named before symlinks resolve, as the write does.
+ const realCwd = yield* fileSystem
+ .realPath(path.resolve(cwd))
+ .pipe(Effect.mapError((cause) => new UnknownWorkspaceError({ cwd, cause })));
+ if (!(yield* contains(realCwd))) return yield* new UnknownWorkspaceError({ cwd });
+ });
+
+ return KnownWorkspaces.of({ contains, assertContains });
+});
+
+export const layer = Layer.effect(KnownWorkspaces, make);
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
index de5147fa850..ae956e69d0c 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
@@ -11,13 +11,24 @@ import * as Path from "effect/Path";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
+import * as KnownWorkspaces from "./KnownWorkspaces.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
+// Temp folders count as known workspaces unless named as unknown.
+const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
+const layerKnownWorkspacesTest = Layer.mock(KnownWorkspaces.KnownWorkspaces)({
+ assertContains: (cwd) =>
+ cwd.includes(UNKNOWN_WORKSPACE_PREFIX)
+ ? Effect.fail(new KnownWorkspaces.UnknownWorkspaceError({ cwd }))
+ : Effect.void,
+});
+
const layerProject = WorkspaceFileSystem.layer.pipe(
+ Layer.provide(layerKnownWorkspacesTest),
Layer.provide(WorkspacePaths.layer),
Layer.provide(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
);
@@ -360,6 +371,23 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
+ it.effect("rejects writes outside a known workspace", () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: UNKNOWN_WORKSPACE_PREFIX,
+ });
+
+ const error = yield* workspaceFileSystem
+ .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
+ .pipe(Effect.flip);
+
+ expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
+ expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
+ }),
+ );
+
it.effect("rejects writes by absolute path", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -428,5 +456,219 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
expect(escapedStat).toBeNull();
}),
);
+
+ it.effect.skipIf(!symlinksSupported)(
+ "rejects writes through symlinks that resolve outside the workspace root",
+ () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const cwd = yield* makeTempDir;
+ const outsideDir = yield* makeTempDir;
+ yield* writeTextFile(outsideDir, "existing.md", "outside\n");
+ yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
+ yield* fileSystem.symlink(
+ path.join(outsideDir, "existing.md"),
+ path.join(cwd, "linked-file.md"),
+ );
+ yield* fileSystem.symlink(
+ path.join(outsideDir, "missing.md"),
+ path.join(cwd, "dangling.md"),
+ );
+
+ for (const relativePath of [
+ "linked-dir/new.md",
+ "linked-dir/nested/new.md",
+ "linked-file.md",
+ ]) {
+ const error = yield* workspaceFileSystem
+ .writeFile({ cwd, relativePath, contents: "# nope\n" })
+ .pipe(Effect.flip);
+ expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
+ }
+ const danglingError = yield* workspaceFileSystem
+ .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
+ .pipe(Effect.flip);
+ expect(danglingError).toBeInstanceOf(
+ WorkspaceFileSystem.WorkspaceFileSystemOperationError,
+ );
+ expect(danglingError).toMatchObject({ operation: "realpath-target" });
+
+ expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
+ expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
+ "outside\n",
+ );
+ }),
+ );
+
+ it.effect.skipIf(!symlinksSupported)(
+ "writes through symlinks that stay inside the workspace root",
+ () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const parentDir = yield* makeTempDir;
+ const cwd = path.join(parentDir, "workspace");
+ const cwdAlias = path.join(parentDir, "workspace-alias");
+ yield* writeTextFile(cwd, "docs/README.md", "old\n");
+ yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
+ yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
+ yield* fileSystem.symlink(cwd, cwdAlias);
+
+ yield* workspaceFileSystem.writeFile({
+ cwd,
+ relativePath: "docs-alias/plans/plan.md",
+ contents: "# Plan\n",
+ });
+ yield* workspaceFileSystem.writeFile({
+ cwd,
+ relativePath: "README.md",
+ contents: "new\n",
+ });
+ yield* workspaceFileSystem.writeFile({
+ cwd: cwdAlias,
+ relativePath: "notes.md",
+ contents: "notes\n",
+ });
+ // `..` after a link in cwd is resolved by name, as for the relative path.
+ yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
+ yield* workspaceFileSystem.writeFile({
+ cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
+ relativePath: "dotdot.md",
+ contents: "dotdot\n",
+ });
+
+ expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
+ "# Plan\n",
+ );
+ expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
+ expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
+ expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
+ expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
+ }),
+ );
+
+ // On Windows `\` is a separator, so the name cannot exist there.
+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
+ "keeps a backslash in a file name as part of the name",
+ () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const cwd = yield* makeTempDir;
+ yield* writeTextFile(cwd, "a\\b.md", "old\n");
+
+ yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
+
+ expect(
+ (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
+ ).toBe("new\n");
+ expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
+ }),
+ );
+
+ it.effect("refuses writes into git's own folders", () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const cwd = yield* makeTempDir;
+ yield* writeTextFile(cwd, ".git/config", "[core]\n");
+ // A bare repository named `.bare`, and a linked worktree's git folder inside it.
+ yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
+ yield* writeTextFile(cwd, ".bare/objects/info/packs");
+ yield* writeTextFile(cwd, ".bare/refs/heads/main");
+ yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
+ // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
+ yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
+ yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
+ yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
+ if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
+
+ for (const [folder, relativePath] of [
+ [cwd, ".git/config"],
+ [cwd, ".git/hooks/pre-commit"],
+ [cwd, "sub/.git"],
+ [cwd, ".GIT/config"],
+ [cwd, ".gıt/config"],
+ [cwd, ".git. /config"],
+ [cwd, ".git::$INDEX_ALLOCATION/config"],
+ [cwd, "GIT~1/config"],
+ [path.join(cwd, ".git"), "config"],
+ [cwd, ".bare/config"],
+ [path.join(cwd, ".bare"), "hooks/post-checkout"],
+ [path.join(cwd, ".bare/hooks"), "post-checkout"],
+ [path.join(cwd, ".bare/worktrees/main"), "commondir"],
+ ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
+ ] as const) {
+ const error = yield* workspaceFileSystem
+ .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
+ .pipe(Effect.flip);
+ expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
+ }
+
+ expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
+ expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
+ expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
+ [".git", "pre-push.sample"],
+ );
+ expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
+ expect(
+ yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
+ ).toBe("../..\n");
+ }),
+ );
+
+ it.effect.skipIf(!symlinksSupported)(
+ "refuses writes through a git config that links to a file outside git's folders",
+ () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const cwd = yield* makeTempDir;
+ yield* writeTextFile(cwd, "shared/config", "[core]\n");
+ yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
+ yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
+
+ const error = yield* workspaceFileSystem
+ .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
+ .pipe(Effect.flip);
+
+ expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
+ expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
+ "[core]\n",
+ );
+ }),
+ );
+
+ it.effect("writes files that sit beside git's folders", () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const parentDir = yield* makeTempDir;
+ // A bare repository with a worktree checked out inside it.
+ const bare = path.join(parentDir, "repo.git");
+ yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
+ yield* writeTextFile(bare, "objects/info/packs");
+ yield* writeTextFile(bare, "refs/heads/main");
+ yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
+
+ for (const [cwd, relativePath] of [
+ [path.join(bare, "main"), ".gitignore"],
+ [path.join(bare, "main"), ".gitattributes"],
+ [path.join(bare, "main"), ".github/workflows/ci.yml"],
+ [path.join(bare, "main"), "vendor/lib.git/README.md"],
+ [path.join(bare, "main/.github"), "CODEOWNERS"],
+ [bare, "main/plan.md"],
+ ] as const) {
+ yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
+ expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
+ }
+ }),
+ );
});
});
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts
index 3966761d244..96fe5a0d234 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.ts
@@ -20,12 +20,20 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import * as KnownWorkspaces from "./KnownWorkspaces.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
+// Windows also reaches `.git` through trailing dots or spaces, a `:` stream
+// suffix, or the 8.3 short name `GIT~1`. Names compare upcased, as NTFS does.
+const isGitMetadataName = (segment: string) => {
+ const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase();
+ return name === ".GIT" || name === "GIT~1";
+};
+
export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
"WorkspaceFileSystemOperationError",
{
@@ -112,11 +120,14 @@ export class WorkspaceFileSystem extends Context.Service<
ProjectReadFileResult,
WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
>;
+ /** Writes inside a known workspace only. */
readonly writeFile: (
input: ProjectWriteFileInput,
) => Effect.Effect<
ProjectWriteFileResult,
- WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
+ | WorkspaceFileSystemError
+ | WorkspacePaths.WorkspacePathOutsideRootError
+ | KnownWorkspaces.UnknownWorkspaceError
>;
}
>()("t3/workspace/WorkspaceFileSystem") {}
@@ -126,6 +137,7 @@ export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
+ const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
@@ -171,6 +183,42 @@ export const make = Effect.gen(function* () {
return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
});
+ /** Both paths must already be real paths. */
+ const isInsideRealRoot = (realWorkspaceRoot: string, realPath: string) => {
+ const relative = path.relative(realWorkspaceRoot, realPath);
+ return !(
+ relative.startsWith(`..${path.sep}`) ||
+ relative === ".." ||
+ path.isAbsolute(relative)
+ );
+ };
+
+ /**
+ * Git runs config and hooks from its own folders, so a write never lands in one:
+ * a `.git` entry, or a repository folder under another name such as `.bare`.
+ * Folders are checked upward to a linked worktree's top, which holds a `.git`
+ * file, since worktrees can sit inside a bare repository. `absolutePath` must
+ * be normalized.
+ */
+ const isInGitFolder = async (absolutePath: string) => {
+ if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
+ for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
+ const [head, commondir, objects, refs, dotGit] = await Promise.all(
+ ["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
+ NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
+ // Any other failure leaves the folder unknown, so the write is refused.
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
+ throw error;
+ }),
+ ),
+ );
+ // What git reads as a repository: HEAD, plus objects and refs here or in
+ // the folder a `commondir` file names, as in a linked worktree's git folder.
+ if (head && (commondir || (objects && refs))) return true;
+ if (dotGit?.isFile() || path.dirname(folder) === folder) return false;
+ }
+ };
+
/**
* Workspace-relative paths must stay inside the root, symlinks included. An
* 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* () {
});
const realWorkspaceRoot = yield* Effect.tryPromise({
- try: () => NodeFSP.realpath(input.cwd),
+ try: () => NodeFSP.realpath(path.resolve(input.cwd)),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
@@ -225,12 +273,7 @@ export const make = Effect.gen(function* () {
cause,
}),
});
- const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
- if (
- relativeRealPath.startsWith(`..${path.sep}`) ||
- relativeRealPath === ".." ||
- path.isAbsolute(relativeRealPath)
- ) {
+ if (!isInsideRealRoot(realWorkspaceRoot, realTargetPath)) {
return yield* new WorkspaceFilePathEscapeError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -334,40 +377,133 @@ export const make = Effect.gen(function* () {
);
});
- const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
- "WorkspaceFileSystem.writeFile",
- )(function* (input) {
+ /**
+ * Resolves the file a write targets. The deepest existing ancestor resolves to
+ * its real path before the root check, so neither the file nor the directories
+ * created for it can follow a symlink out of the root. A dangling symlink is
+ * rejected rather than written through.
+ */
+ const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
+ input: ProjectWriteFileInput,
+ ) {
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
});
+ const realWorkspaceRoot = yield* Effect.tryPromise({
+ // Resolve `..` in cwd the way the relative path was resolved, before following links.
+ try: () => NodeFSP.realpath(path.resolve(input.cwd)),
+ catch: (cause) =>
+ new WorkspaceFileSystemOperationError({
+ workspaceRoot: input.cwd,
+ relativePath: input.relativePath,
+ resolvedPath: target.absolutePath,
+ operationPath: input.cwd,
+ operation: "realpath-workspace-root",
+ cause,
+ }),
+ });
- yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
- Effect.mapError(
- (cause) =>
+ // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
+ const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
+ const realTargetPath = yield* Effect.tryPromise({
+ try: async () => {
+ for (let depth = segments.length; depth > 0; depth--) {
+ const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
+ try {
+ return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
+ } catch (error) {
+ // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
+ const exists = await NodeFSP.lstat(candidate).then(
+ () => true,
+ () => false,
+ );
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
+ }
+ }
+ return path.join(realWorkspaceRoot, ...segments);
+ },
+ catch: (cause) =>
+ new WorkspaceFileSystemOperationError({
+ workspaceRoot: input.cwd,
+ relativePath: input.relativePath,
+ resolvedPath: target.absolutePath,
+ operationPath: target.absolutePath,
+ operation: "realpath-target",
+ cause,
+ }),
+ });
+ // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
+ const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
+ const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
+ Effect.tryPromise({
+ try: () => isInGitFolder(checkedPath),
+ catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
- resolvedPath: target.absolutePath,
- operationPath: path.dirname(target.absolutePath),
- operation: "make-directory",
+ resolvedPath: realTargetPath,
+ operationPath: checkedPath,
+ operation: "stat",
cause,
}),
- ),
+ }),
);
- yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
+ if (
+ !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
+ (yield* inGitFolder(realTargetPath)) ||
+ (yield* inGitFolder(namedTargetPath))
+ ) {
+ return yield* new WorkspaceFilePathEscapeError({
+ workspaceRoot: input.cwd,
+ relativePath: input.relativePath,
+ resolvedWorkspaceRoot: realWorkspaceRoot,
+ resolvedPath: realTargetPath,
+ });
+ }
+ return { relativePath: target.relativePath, realTargetPath };
+ });
+
+ const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
+ "WorkspaceFileSystem.writeFile",
+ )(function* (input) {
+ yield* knownWorkspaces.assertContains(input.cwd);
+ const target = yield* resolveWriteTarget(input);
+ const realTargetPath = target.realTargetPath;
+
+ yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
- resolvedPath: target.absolutePath,
- operationPath: target.absolutePath,
- operation: "write-file",
+ resolvedPath: realTargetPath,
+ operationPath: path.dirname(realTargetPath),
+ operation: "make-directory",
cause,
}),
),
);
+ yield* Effect.tryPromise({
+ // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
+ try: () =>
+ NodeFSP.writeFile(realTargetPath, input.contents, {
+ flag:
+ NodeFS.constants.O_WRONLY |
+ NodeFS.constants.O_CREAT |
+ NodeFS.constants.O_TRUNC |
+ (NodeFS.constants.O_NOFOLLOW ?? 0),
+ }),
+ catch: (cause) =>
+ new WorkspaceFileSystemOperationError({
+ workspaceRoot: input.cwd,
+ relativePath: input.relativePath,
+ resolvedPath: realTargetPath,
+ operationPath: realTargetPath,
+ operation: "write-file",
+ cause,
+ }),
+ });
yield* workspaceEntries.refresh(input.cwd);
return { relativePath: target.relativePath };
});
diff --git a/apps/server/src/worktreesDirectory.ts b/apps/server/src/worktreesDirectory.ts
index 384ab6711fd..aef9b8c031c 100644
--- a/apps/server/src/worktreesDirectory.ts
+++ b/apps/server/src/worktreesDirectory.ts
@@ -1,7 +1,13 @@
-import type * as Path from "effect/Path";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
+import * as ServerConfig from "./config.ts";
+import * as ServerSettings from "./serverSettings.ts";
+
/**
* Null when the setting is not an absolute path on this machine, such as `D:\worktrees`
* 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(
}
return [...directories];
}
+
+/**
+ * A thread's path and branch can come from a client, so a missing worktree is
+ * only recreated where the server would have put it:
+ * `<managed worktrees folder>/<repo>/<branch>`, compared by real path.
+ */
+export const makeIsManagedWorktreePath = Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
+
+ // Where git would create `target`: the real path of its nearest existing
+ // ancestor plus the missing rest, since git follows symlinks on the way.
+ const realLocation = (target: string): Effect.Effect<string> =>
+ fileSystem.realPath(target).pipe(
+ Effect.catch(() => {
+ const parent = path.dirname(target);
+ return parent === target
+ ? Effect.succeed(target)
+ : Effect.map(realLocation(parent), (real) => path.join(real, path.basename(target)));
+ }),
+ );
+
+ return Effect.fn("worktreesDirectory.isManagedWorktreePath")(function* (worktreePath: string) {
+ // git resolves a relative path against the project, not the server cwd.
+ if (!path.isAbsolute(worktreePath)) return false;
+ // Server-made paths are normalized. A `..` would be applied after git
+ // follows a symlink but before realPath does, so the two disagree.
+ if (path.resolve(worktreePath) !== worktreePath) return false;
+ const settings = yield* serverSettings.getSettings.pipe(
+ Effect.orElseSucceed(() => ({
+ worktreesDirectory: "",
+ previousWorktreesDirectories: [],
+ })),
+ );
+ const roots = yield* Effect.forEach(
+ managedWorktreesDirectories(
+ settings,
+ serverConfig.worktreesDir,
+ path,
+ yield* HostProcess.HomeDirectory,
+ ),
+ realLocation,
+ );
+ const candidate = yield* realLocation(worktreePath);
+ return roots.some((root) => {
+ if (isFilesystemRoot(root, path)) return false;
+ const relative = path.relative(root, candidate);
+ const segments = relative.split(path.sep);
+ return (
+ !path.isAbsolute(relative) &&
+ segments.length === 2 &&
+ segments.every((segment) => segment !== "" && segment !== "..")
+ );
+ });
+ });
+});
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 84cfb8430fb..7e9181cb722 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -196,6 +196,7 @@ import { parseBase64DataUrl } from "./imageMime.ts";
import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
+import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
import { readWorkflowScript } from "./orchestration-v2/workflowScriptQuery.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
@@ -505,7 +506,8 @@ function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntries
function projectFileFailureContext(
error:
| WorkspaceFileSystem.WorkspaceFileSystemError
- | WorkspacePaths.WorkspacePathOutsideRootError,
+ | WorkspacePaths.WorkspacePathOutsideRootError
+ | KnownWorkspaces.UnknownWorkspaceError,
): {
readonly failure: ProjectFileFailure;
readonly resolvedPath?: string;
@@ -515,6 +517,7 @@ function projectFileFailureContext(
} {
switch (error._tag) {
case "WorkspacePathOutsideRootError":
+ case "UnknownWorkspaceError":
return { failure: "workspace_path_outside_root" };
case "WorkspaceFileSystemOperationError":
return {
diff --git a/packages/contracts/src/rpc.test.ts b/packages/contracts/src/rpc.test.ts
index 72b726a94fe..f0c15f65094 100644
--- a/packages/contracts/src/rpc.test.ts
+++ b/packages/contracts/src/rpc.test.ts
@@ -3,7 +3,7 @@ import * as Exit from "effect/Exit";
import * as Schema from "effect/Schema";
import { ORCHESTRATION_V2_WS_METHODS } from "./orchestrationV2.ts";
-import { WsRpcGroup, WsSubscribeServerConfigRpc } from "./rpc.ts";
+import { WS_METHODS, WsRpcGroup, WsSubscribeServerConfigRpc } from "./rpc.ts";
describe("subscribeServerConfig payload compatibility", () => {
it("is accepted by a server whose schema predates the field", () => {
@@ -61,4 +61,14 @@ describe("WebSocket RPC contracts", () => {
),
).toBe(true);
});
+
+ it("lets the server pick a new worktree's folder", () => {
+ const createWorktree = WsRpcGroup.requests.get(WS_METHODS.vcsCreateWorktree);
+ if (createWorktree === undefined) throw new Error("vcs.createWorktree is not registered");
+ const decode = Schema.decodeUnknownExit(createWorktree.payloadSchema);
+ const request = { cwd: "/repo", refName: "main", newRefName: "feature/x" };
+
+ expect(Exit.isSuccess(decode({ ...request, path: null }))).toBe(true);
+ expect(Exit.isFailure(decode({ ...request, path: "/repo/.git/hooks" }))).toBe(true);
+ });
});
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 9536aa93a7e..b74175d23c6 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -1381,7 +1381,10 @@ const WsVcsListRefsRpc = Rpc.make(WS_METHODS.vcsListRefs, {
});
const WsVcsCreateWorktreeRpc = Rpc.make(WS_METHODS.vcsCreateWorktree, {
- payload: VcsCreateWorktreeInput,
+ // Clients cannot choose the folder: new worktrees go in the server's managed
+ // worktrees folder. `path` stays a required null because older servers
+ // require the key.
+ payload: Schema.Struct({ ...VcsCreateWorktreeInput.fields, path: Schema.Null }),
success: VcsCreateWorktreeResult,
error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),
});
diff --git a/packages/contracts/src/worktreeMcp.ts b/packages/contracts/src/worktreeMcp.ts
index eff57bcb97c..c894b7de65a 100644
--- a/packages/contracts/src/worktreeMcp.ts
+++ b/packages/contracts/src/worktreeMcp.ts
@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
/**
+ * The server picks the location in its managed worktrees folder.
* Changing the thread's workspace detaches the live provider session, so the
* current turn ends shortly after the handoff is recorded; the conversation
* continues inside the worktree on the thread's next run.
@@ -23,12 +24,6 @@ export const WorktreeMcpHandoffInput = Schema.Struct({
"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.",
}),
),
- path: Schema.optional(
- TrimmedNonEmptyString.check(Schema.isPattern(/^(?:[A-Za-z]:[\\/]|[\\/])/)).annotate({
- description:
- "Absolute filesystem path for the new worktree. Relative paths are rejected. Defaults to the server-managed worktrees directory.",
- }),
- ),
runSetupScript: Schema.optional(
Schema.Boolean.annotate({
description: