@devries-cameron20 / t3code-1 / commits / d3d7f03e65
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): stop PR lookups in emptied worktree folders (#24803)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 2, 2026 at 18:31 UTC d3d7f03e65cfddf6f034033d03ecde964d4eb158
4 files changed +268 -8
apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts
+126
@@ -16,6 +16,8 @@ import * as Effect from "effect/Effect";
16 import * as FileSystem from "effect/FileSystem";
17 import * as Layer from "effect/Layer";
18 import * as Option from "effect/Option";
19 +import * as Path from "effect/Path";
20 +import * as PlatformError from "effect/PlatformError";
21 import * as Queue from "effect/Queue";
22 import * as Stream from "effect/Stream";
23 import * as TestClock from "effect/testing/TestClock";
@@ -152,6 +154,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
154 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
155 ),
156 FileSystem.layerNoop({}),
157 + Path.layer,
158 );
159 yield* Effect.gen(function* () {
160 const service = yield* ThreadPullRequestService.make;
@@ -176,6 +179,127 @@ describe("ThreadPullRequestServiceV2 reads", () => {
179 ),
180 );
181
182 + it.effect.each([
183 + {
184 + worktree: "a linked worktree",
185 + existingPaths: ["/workspace/worktree", "/workspace/worktree/.git"],
186 + unreadablePaths: [],
187 + cwd: "/workspace/worktree",
188 + },
189 + // A folder that outlived its .git makes git fail with not_a_repository.
190 + {
191 + worktree: "a folder without .git",
192 + existingPaths: ["/workspace/worktree"],
193 + unreadablePaths: [],
194 + cwd: "/workspace/project",
195 + },
196 + {
197 + worktree: "a folder whose .git cannot be checked",
198 + existingPaths: ["/workspace/worktree"],
199 + unreadablePaths: ["/workspace/worktree/.git"],
200 + cwd: "/workspace/worktree",
201 + },
202 + {
203 + worktree: "a missing folder",
204 + existingPaths: [],
205 + unreadablePaths: [],
206 + cwd: "/workspace/project",
207 + },
208 + ] as const)(
209 + "looks up a branch whose worktree is $worktree in $cwd",
210 + ({ existingPaths, unreadablePaths, cwd }) =>
211 + Effect.scoped(
212 + Effect.gen(function* () {
213 + const thread = {
214 + ...threadShell("worktree-thread"),
215 + branch: "feature/worktree",
216 + worktreePath: "/workspace/worktree",
217 + };
218 + const project: OrchestrationProjectShell = {
219 + id: thread.projectId,
220 + title: "Project",
221 + workspaceRoot: "/workspace/project",
222 + defaultModelSelection: null,
223 + scripts: [],
224 + createdAt: "2026-08-01T00:00:00.000Z",
225 + updatedAt: "2026-08-01T00:00:00.000Z",
226 + };
227 + const activation = yield* Deferred.make<void>();
228 + const sweepStarted = yield* Deferred.make<void>();
229 + const lookupCwds: Array<string> = [];
230 + const dependencies = Layer.mergeAll(
231 + Layer.mock(Orchestrator.OrchestratorV2)({
232 + streamDomainEvents: Stream.never,
233 + getShellSnapshot: () =>
234 + Deferred.succeed(sweepStarted, undefined).pipe(
235 + Effect.as({
236 + schemaVersion: 2,
237 + snapshotSequence: 1,
238 + threads: [thread],
239 + archivedThreads: [],
240 + }),
241 + ),
242 + }),
243 + Layer.mock(ProjectStore.ProjectStoreV2)({
244 + listShells: () => Effect.succeed([project]),
245 + getShell: () => Effect.succeedSome(project),
246 + }),
247 + Layer.mock(GitManager.GitManager)({
248 + branchPullRequest: (input) =>
249 + Effect.sync(() => {
250 + lookupCwds.push(input.cwd);
251 + return null;
252 + }),
253 + }),
254 + Layer.mock(PullRequestService.PullRequestService)({}),
255 + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
256 + resolve: () =>
257 + Effect.succeed({
258 + canonicalKey: "github.com/acme/project",
259 + locator: {
260 + source: "git-remote" as const,
261 + remoteName: "origin",
262 + remoteUrl: "git@github.com:acme/project.git",
263 + },
264 + provider: SourceControlProviderKind.make("github"),
265 + owner: "acme",
266 + name: "project",
267 + }),
268 + }),
269 + Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
270 + Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
271 + Layer.succeed(
272 + SecureRandom.SecureRandom,
273 + SecureRandom.make((size) => new Uint8Array(size).fill(1)),
274 + ),
275 + FileSystem.layerNoop({
276 + exists: (path) =>
277 + unreadablePaths.some((entry) => entry === path)
278 + ? Effect.fail(
279 + PlatformError.systemError({
280 + _tag: "PermissionDenied",
281 + module: "FileSystem",
282 + method: "exists",
283 + pathOrDescriptor: path,
284 + }),
285 + )
286 + : Effect.succeed(existingPaths.some((entry) => entry === path)),
287 + }),
288 + Path.layer,
289 + );
290 + yield* Effect.gen(function* () {
291 + const service = yield* ThreadPullRequestService.make;
292 + yield* service.start();
293 + yield* Deferred.succeed(activation, undefined);
294 + yield* Deferred.await(sweepStarted);
295 + yield* service.drain;
296 + }).pipe(Effect.provide(dependencies));
297 +
298 + expect(lookupCwds).toEqual([cwd]);
299 + }),
300 + ),
301 + );
302 +
303 it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
304 Effect.scoped(
305 Effect.gen(function* () {
@@ -264,6 +388,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
388 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
389 ),
390 FileSystem.layerNoop({}),
391 + Path.layer,
392 );
393 yield* Effect.gen(function* () {
394 const service = yield* ThreadPullRequestService.make;
@@ -387,6 +512,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
512 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
513 ),
514 FileSystem.layerNoop({}),
515 + Path.layer,
516 );
517 yield* Effect.gen(function* () {
518 const service = yield* ThreadPullRequestService.make;
apps/server/src/orchestration-v2/ThreadPullRequestService.ts
+8 -3
@@ -14,6 +14,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom";
14 import * as Effect from "effect/Effect";
15 import * as FileSystem from "effect/FileSystem";
16 import * as Option from "effect/Option";
17 +import * as Path from "effect/Path";
18 import * as Schedule from "effect/Schedule";
19 import type * as Scope from "effect/Scope";
20 import * as Stream from "effect/Stream";
@@ -102,6 +103,7 @@ export const make = Effect.gen(function* () {
103 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
104 const random = yield* SecureRandom.SecureRandom;
105 const fileSystem = yield* FileSystem.FileSystem;
106 + const path = yield* Path.Path;
107 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
108 const pendingBackfill = new Map<ThreadId, number>();
109
@@ -188,10 +190,13 @@ export const make = Effect.gen(function* () {
190 refresh: request.refresh,
191 });
192 if (first.branch !== null && repository === null) return finishBackfill(group);
191 - const worktreeExists =
192 - first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
193 + // A worktree folder can outlive its .git, and git there fails with not_a_repository.
194 + // An unreadable .git keeps the worktree rather than failing the whole group.
195 const cwd =
194 - worktreeExists && first.worktreePath !== null
196 + first.worktreePath !== null &&
197 + (yield* fileSystem
198 + .exists(path.join(first.worktreePath, ".git"))
199 + .pipe(Effect.orElseSucceed(() => true)))
200 ? first.worktreePath
201 : project.workspaceRoot;
202 const detected =
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+126 -1
@@ -25,6 +25,8 @@ import * as Deferred from "effect/Deferred";
25 import * as Effect from "effect/Effect";
26 import * as FileSystem from "effect/FileSystem";
27 import * as Layer from "effect/Layer";
28 +import * as Path from "effect/Path";
29 +import * as PlatformError from "effect/PlatformError";
30 import * as PubSub from "effect/PubSub";
31 import * as Queue from "effect/Queue";
32 import * as Ref from "effect/Ref";
@@ -553,6 +555,7 @@ interface HarnessOptions {
555 readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"];
556 readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"];
557 readonly existingWorktreePaths?: ReadonlyArray<string>;
558 + readonly unreadablePaths?: ReadonlyArray<string>;
559 readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect<void>;
560 readonly onScriptRun?: (
561 input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput,
@@ -702,8 +705,19 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
705 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
706 Layer.succeed(SecureRandom.SecureRandom, testCrypto),
707 FileSystem.layerNoop({
705 - exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
708 + exists: (path) =>
709 + options.unreadablePaths?.includes(path)
710 + ? Effect.fail(
711 + PlatformError.systemError({
712 + _tag: "PermissionDenied",
713 + module: "FileSystem",
714 + method: "exists",
715 + pathOrDescriptor: path,
716 + }),
717 + )
718 + : Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
719 }),
720 + Path.layer,
721 );
722
723 return {
@@ -897,6 +911,117 @@ describe("ThreadSettlementServiceV2 worker", () => {
911 ),
912 );
913
914 + it.effect("looks up a branch in its worktree only while the worktree has .git", () =>
915 + Effect.scoped(
916 + Effect.gen(function* () {
917 + yield* TestClock.setTime(Date.parse(NOW));
918 + const fixture = yield* makeHarness({
919 + snapshot: makeSnapshot([
920 + makeThread("linked-worktree", {
921 + branch: "linked",
922 + worktreePath: "/worktrees/linked",
923 + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
924 + }),
925 + // A folder that outlived its .git makes git fail with not_a_repository.
926 + makeThread("emptied-worktree", {
927 + branch: "emptied",
928 + worktreePath: "/worktrees/emptied",
929 + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
930 + }),
931 + ]),
932 + existingWorktreePaths: [
933 + "/worktrees/linked",
934 + "/worktrees/linked/.git",
935 + "/worktrees/emptied",
936 + ],
937 + });
938 +
939 + yield* Effect.gen(function* () {
940 + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
941 + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
942 + const cwdByBranch = Object.fromEntries(
943 + (yield* Ref.get(fixture.branchCalls)).map((call) => [call.branch, call.cwd]),
944 + );
945 + expect(cwdByBranch).toEqual({
946 + linked: "/worktrees/linked",
947 + emptied: "/workspace/project",
948 + });
949 + }).pipe(Effect.provide(fixture.layer));
950 + }),
951 + ),
952 + );
953 +
954 + it.effect("does not settle a thread whose worktree cannot be checked", () =>
955 + Effect.scoped(
956 + Effect.gen(function* () {
957 + yield* TestClock.setTime(Date.parse(NOW));
958 + const fixture = yield* makeHarness({
959 + snapshot: makeSnapshot(
960 + [
961 + makeThread("unreadable-worktree", {
962 + branch: "unreadable",
963 + worktreePath: "/worktrees/unreadable",
964 + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
965 + }),
966 + // A merged linked pull request still needs the branch recheck before settling.
967 + makeThread("unreadable-linked-worktree", {
968 + branch: "feature",
969 + worktreePath: "/worktrees/unreadable-linked",
970 + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
971 + linkedPullRequest: {
972 + projectId: PROJECT_ID,
973 + repository: "owner/repository",
974 + number: 41,
975 + url: "https://example.test/owner/repository/pull/41",
976 + },
977 + }),
978 + makeThread("readable-worktree", {
979 + branch: "readable",
980 + worktreePath: "/worktrees/readable",
981 + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
982 + }),
983 + ],
984 + [
985 + {
986 + ...makeProject(),
987 + repositoryIdentity: {
988 + canonicalKey: "example.test/owner/repository",
989 + locator: {
990 + source: "git-remote",
991 + remoteName: "origin",
992 + remoteUrl: "https://example.test/owner/repository.git",
993 + },
994 + provider: SourceControlProviderKind.make("github"),
995 + owner: "owner",
996 + name: "repository",
997 + },
998 + },
999 + ],
1000 + ),
1001 + existingWorktreePaths: ["/worktrees/readable", "/worktrees/readable/.git"],
1002 + unreadablePaths: ["/worktrees/unreadable/.git", "/worktrees/unreadable-linked/.git"],
1003 + pullRequestSummary: (input) =>
1004 + Effect.succeed({
1005 + ...makePullRequestSummary({ ...input, state: "merged" }),
1006 + mergedAt: NOW,
1007 + }),
1008 + branchPullRequest: (input) =>
1009 + input.cwd.startsWith("/worktrees/unreadable")
1010 + ? Effect.die(new Error("git: permission denied"))
1011 + : Effect.succeed(makeBranchPullRequest("merged")),
1012 + });
1013 +
1014 + yield* Effect.gen(function* () {
1015 + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1016 + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1017 + expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1018 + ThreadId.make("readable-worktree"),
1019 + ]);
1020 + }).pipe(Effect.provide(fixture.layer));
1021 + }),
1022 + ),
1023 + );
1024 +
1025 it.effect("reevaluates immediately after a pull request merge", () =>
1026 Effect.scoped(
1027 Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+8 -4
@@ -19,6 +19,7 @@ import * as DateTime from "effect/DateTime";
19 import * as Effect from "effect/Effect";
20 import * as FiberSet from "effect/FiberSet";
21 import * as FileSystem from "effect/FileSystem";
22 +import * as Path from "effect/Path";
23 import * as Schedule from "effect/Schedule";
24 import * as Semaphore from "effect/Semaphore";
25 import type * as Scope from "effect/Scope";
@@ -297,6 +298,7 @@ export const make = Effect.gen(function* () {
298 const pullRequests = yield* PullRequestService.PullRequestService;
299 const random = yield* SecureRandom.SecureRandom;
300 const fileSystem = yield* FileSystem.FileSystem;
301 + const path = yield* Path.Path;
302 // A shell merge or close sends no event, and the branch lookup caches an open pull request for
303 // a minute, so these threads' next lookup reads the host fresh.
304 const shellClosedThreads = new Set<ThreadId>();
@@ -394,12 +396,14 @@ export const make = Effect.gen(function* () {
396 Effect.gen(function* () {
397 const project = projects.get(thread.projectId);
398 if (project === undefined || thread.branch === null) return;
397 - const worktreeExists =
398 - thread.worktreePath !== null &&
399 - (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
399 + // A worktree folder can outlive its .git, and git there fails with not_a_repository.
400 + // An unreadable .git keeps the worktree, so git fails there and the thread is skipped.
401 lookupCwdByThreadId.set(
402 thread.id,
402 - worktreeExists && thread.worktreePath !== null
403 + thread.worktreePath !== null &&
404 + (yield* fileSystem
405 + .exists(path.join(thread.worktreePath, ".git"))
406 + .pipe(Effect.orElseSucceed(() => true)))
407 ? thread.worktreePath
408 : project.workspaceRoot,
409 );