Skip to content

Commit 896ed9a

Browse files
Nurozenclaude
andcommitted
fix(server): refuse worktree removal while another thread references it
Worktree removal and shared-worktree detection only consulted the active shell, so archived threads sharing a worktree were treated as gone: deleting a sibling could remove a worktree an archived thread still points at, and checkpoint branch-drift adoption ignored archived co-owners. Removal now refuses while any non-deleted thread references the path — resolved by a single atomic query so a thread can never fall between separate active and archived reads — drift adoption counts archived siblings, and the legacy sidebar's bulk delete no longer pre-seeds its deleted-set with the whole batch (which made the first deletion treat still-alive batch mates as gone). Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 827345a commit 896ed9a

12 files changed

Lines changed: 196 additions & 22 deletions

‎apps/server/src/checkpointing/CheckpointDiffQuery.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ describe("CheckpointDiffQuery.layer", () => {
109109
getThreadShellById: () => Effect.succeed(Option.none()),
110110
getThreadDetailById: () => Effect.succeed(Option.none()),
111111
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
112+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
112113
searchThreads: () => Effect.succeed({ matches: [] }),
113114
}),
114115
),
@@ -204,6 +205,7 @@ describe("CheckpointDiffQuery.layer", () => {
204205
getThreadShellById: () => Effect.succeed(Option.none()),
205206
getThreadDetailById: () => Effect.succeed(Option.none()),
206207
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
208+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
207209
searchThreads: () => Effect.succeed({ matches: [] }),
208210
}),
209211
),
@@ -289,6 +291,7 @@ describe("CheckpointDiffQuery.layer", () => {
289291
getThreadShellById: () => Effect.succeed(Option.none()),
290292
getThreadDetailById: () => Effect.succeed(Option.none()),
291293
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
294+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
292295
searchThreads: () => Effect.succeed({ matches: [] }),
293296
}),
294297
),
@@ -359,6 +362,7 @@ describe("CheckpointDiffQuery.layer", () => {
359362
getThreadShellById: () => Effect.succeed(Option.none()),
360363
getThreadDetailById: () => Effect.succeed(Option.none()),
361364
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
365+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
362366
searchThreads: () => Effect.succeed({ matches: [] }),
363367
}),
364368
),
@@ -414,6 +418,7 @@ describe("CheckpointDiffQuery.layer", () => {
414418
getThreadShellById: () => Effect.succeed(Option.none()),
415419
getThreadDetailById: () => Effect.succeed(Option.none()),
416420
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
421+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
417422
searchThreads: () => Effect.succeed({ matches: [] }),
418423
}),
419424
),

‎apps/server/src/orchestration/Layers/CheckpointReactor.test.ts‎

Lines changed: 55 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,7 @@ describe("CheckpointReactor", () => {
282282
readonly threadWorktreePath?: string | null;
283283
readonly threadBranch?: string | null;
284284
readonly secondThreadSharingWorktree?: boolean;
285+
readonly secondThreadArchived?: boolean;
285286
readonly localStatusRefName?: string | null;
286287
readonly providerSessionCwd?: string;
287288
readonly providerName?: ProviderDriverKind;
@@ -401,22 +402,34 @@ describe("CheckpointReactor", () => {
401402
.pipe(
402403
options?.secondThreadSharingWorktree
403404
? Effect.andThen(
404-
engine.dispatch({
405-
type: "thread.create",
406-
commandId: CommandId.make("cmd-thread-create-2"),
407-
threadId: ThreadId.make("thread-2"),
408-
projectId: asProjectId("project-1"),
409-
title: "Thread 2",
410-
modelSelection: {
411-
instanceId: ProviderInstanceId.make("codex"),
412-
model: "gpt-5-codex",
413-
},
414-
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
415-
runtimeMode: "approval-required",
416-
branch: null,
417-
worktreePath: options?.threadWorktreePath ?? cwd,
418-
createdAt,
419-
}),
405+
engine
406+
.dispatch({
407+
type: "thread.create",
408+
commandId: CommandId.make("cmd-thread-create-2"),
409+
threadId: ThreadId.make("thread-2"),
410+
projectId: asProjectId("project-1"),
411+
title: "Thread 2",
412+
modelSelection: {
413+
instanceId: ProviderInstanceId.make("codex"),
414+
model: "gpt-5-codex",
415+
},
416+
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
417+
runtimeMode: "approval-required",
418+
branch: null,
419+
worktreePath: options?.threadWorktreePath ?? cwd,
420+
createdAt,
421+
})
422+
.pipe(
423+
options?.secondThreadArchived
424+
? Effect.andThen(
425+
engine.dispatch({
426+
type: "thread.archive",
427+
commandId: CommandId.make("cmd-thread-archive-2"),
428+
threadId: ThreadId.make("thread-2"),
429+
}),
430+
)
431+
: Effect.asVoid,
432+
),
420433
)
421434
: Effect.asVoid,
422435
),
@@ -608,6 +621,32 @@ describe("CheckpointReactor", () => {
608621
expect(thread?.branch).toBe("t3code/original-branch");
609622
});
610623

624+
it("does not adopt a drifted checkout when the worktree is shared by an archived thread", async () => {
625+
const harness = await createHarness({
626+
seedFilesystemCheckpoints: false,
627+
threadBranch: "t3code/original-branch",
628+
localStatusRefName: "t3code/renamed-by-agent",
629+
secondThreadSharingWorktree: true,
630+
secondThreadArchived: true,
631+
});
632+
633+
harness.provider.emit({
634+
type: "turn.completed",
635+
eventId: EventId.make("evt-turn-completed-branch-drift-archived"),
636+
provider: ProviderDriverKind.make("codex"),
637+
createdAt: "2026-01-01T00:00:00.000Z",
638+
threadId: ThreadId.make("thread-1"),
639+
turnId: asTurnId("turn-branch-drift-archived"),
640+
payload: { state: "completed" },
641+
});
642+
643+
await harness.drain();
644+
645+
const snapshot = await harness.readModel();
646+
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
647+
expect(thread?.branch).toBe("t3code/original-branch");
648+
});
649+
611650
it("does not adopt a temporary placeholder checkout as the thread branch", async () => {
612651
const harness = await createHarness({
613652
seedFilesystemCheckpoints: false,

‎apps/server/src/orchestration/Layers/CheckpointReactor.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -590,10 +590,13 @@ const make = Effect.gen(function* () {
590590
return;
591591
}
592592

593-
const shell = yield* projectionSnapshotQuery.getShellSnapshot();
594-
const worktreeIsShared = shell.threads.some(
595-
(other) => other.id !== thread.id && other.worktreePath === thread.worktreePath,
593+
// Archived threads keep their worktree reference, so the check reads
594+
// every non-deleted thread — the shell snapshot would miss an archived
595+
// sibling sharing the path.
596+
const worktreeThreadIds = yield* projectionSnapshotQuery.listThreadIdsByWorktreePath(
597+
thread.worktreePath,
596598
);
599+
const worktreeIsShared = worktreeThreadIds.some((id) => id !== thread.id);
597600
if (worktreeIsShared) {
598601
return;
599602
}

‎apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ describe("OrchestrationEngine", () => {
215215
getThreadShellById: () => Effect.succeed(Option.none()),
216216
getThreadDetailById: () => Effect.succeed(Option.none()),
217217
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
218+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
218219
searchThreads: () => Effect.succeed({ matches: [] }),
219220
}),
220221
),

‎apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
114114
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
115115
}),
116116
);
117+
const WorktreePathLookupInput = Schema.Struct({
118+
worktreePath: Schema.String,
119+
});
117120
const ProjectionLatestTurnDbRowSchema = Schema.Struct({
118121
threadId: ProjectionThread.fields.threadId,
119122
turnId: TurnId,
@@ -1255,6 +1258,21 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
12551258
`,
12561259
});
12571260

1261+
// Includes archived threads: any non-deleted row keeps its worktree alive.
1262+
const listThreadIdRowsByWorktreePath = SqlSchema.findAll({
1263+
Request: WorktreePathLookupInput,
1264+
Result: ProjectionThreadIdLookupRowSchema,
1265+
execute: ({ worktreePath }) =>
1266+
sql`
1267+
SELECT
1268+
thread_id AS "threadId"
1269+
FROM projection_threads
1270+
WHERE worktree_path = ${worktreePath}
1271+
AND deleted_at IS NULL
1272+
ORDER BY created_at ASC, thread_id ASC
1273+
`,
1274+
});
1275+
12581276
// Resolves a page of recent turns for a windowed thread detail read. Walks
12591277
// back from the exclusive (beforeAnchorAt, beforeTurnKey) keyset boundary
12601278
// (sentinels "~"/"" mean unbounded, i.e. the first page) until it has seen
@@ -3140,6 +3158,19 @@ pending_approval_requests AS (
31403158
),
31413159
);
31423160

3161+
const listThreadIdsByWorktreePath: ProjectionSnapshotQueryShape["listThreadIdsByWorktreePath"] = (
3162+
worktreePath,
3163+
) =>
3164+
listThreadIdRowsByWorktreePath({ worktreePath }).pipe(
3165+
Effect.mapError(
3166+
toPersistenceSqlOrDecodeError(
3167+
"ProjectionSnapshotQuery.listThreadIdsByWorktreePath:query",
3168+
"ProjectionSnapshotQuery.listThreadIdsByWorktreePath:decodeRows",
3169+
),
3170+
),
3171+
Effect.map((rows) => rows.map((row) => row.threadId)),
3172+
);
3173+
31433174
return {
31443175
getCommandReadModel,
31453176
getSnapshot,
@@ -3157,6 +3188,7 @@ pending_approval_requests AS (
31573188
getThreadShellById,
31583189
getThreadDetailById,
31593190
getThreadDetailSnapshot,
3191+
listThreadIdsByWorktreePath,
31603192
} satisfies ProjectionSnapshotQueryShape;
31613193
});
31623194

‎apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,15 @@ export interface ProjectionSnapshotQueryShape {
213213
threadId: ThreadId,
214214
window?: OrchestrationThreadDetailWindow,
215215
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
216+
217+
/**
218+
* Read the ids of all non-deleted threads (archived included) whose
219+
* worktree path matches exactly. Guards worktree removal while any thread
220+
* still references the path.
221+
*/
222+
readonly listThreadIdsByWorktreePath: (
223+
worktreePath: string,
224+
) => Effect.Effect<ReadonlyArray<ThreadId>, ProjectionRepositoryError>;
216225
}
217226

218227
/**

‎apps/server/src/project/ProjectSetupScriptRunner.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
4545
getThreadShellById: () => Effect.die("unused"),
4646
getThreadDetailById: () => Effect.die("unused"),
4747
getThreadDetailSnapshot: () => Effect.die("unused"),
48+
listThreadIdsByWorktreePath: () => Effect.die("unused"),
4849
searchThreads: () => Effect.succeed({ matches: [] }),
4950
});
5051

‎apps/server/src/provider/Layers/ProviderSessionReaper.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ describe("ProviderSessionReaper", () => {
224224
),
225225
getThreadDetailById: () => Effect.die("unused"),
226226
getThreadDetailSnapshot: () => Effect.die("unused"),
227+
listThreadIdsByWorktreePath: () => Effect.die("unused"),
227228
searchThreads: () => Effect.succeed({ matches: [] }),
228229
}),
229230
),

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -884,6 +884,7 @@ const buildAppUnderTest = (options?: {
884884
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
885885
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
886886
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
887+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
887888
...options?.layers?.projectionSnapshotQuery,
888889
}),
889890
),
@@ -6258,6 +6259,49 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
62586259
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
62596260
);
62606261

6262+
it.effect("refuses vcs.removeWorktree while a thread still references the worktree", () =>
6263+
Effect.gen(function* () {
6264+
let removeCalls = 0;
6265+
yield* buildAppUnderTest({
6266+
config: {
6267+
cwd: "/tmp/repo",
6268+
},
6269+
layers: {
6270+
gitVcsDriver: {
6271+
removeWorktree: () =>
6272+
Effect.sync(() => {
6273+
removeCalls += 1;
6274+
}),
6275+
},
6276+
projectionSnapshotQuery: {
6277+
// An archived thread still counts: any non-deleted thread at the
6278+
// path keeps the worktree alive.
6279+
listThreadIdsByWorktreePath: () =>
6280+
Effect.succeed([ThreadId.make("thread-archived-owner")]),
6281+
},
6282+
},
6283+
});
6284+
6285+
const wsUrl = yield* getWsServerUrl("/ws");
6286+
const result = yield* Effect.scoped(
6287+
withWsRpcClient(wsUrl, (client) =>
6288+
client[WS_METHODS.vcsRemoveWorktree]({ cwd: "/tmp/repo", path: "/tmp/wt" }),
6289+
).pipe(Effect.result),
6290+
);
6291+
6292+
assertFailure(
6293+
result,
6294+
new GitCommandError({
6295+
operation: "ws.vcsRemoveWorktree",
6296+
command: "git",
6297+
cwd: "/tmp/repo",
6298+
detail: "refused to remove worktree /tmp/wt: 1 thread(s) still reference it",
6299+
}),
6300+
);
6301+
assert.equal(removeCalls, 0);
6302+
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
6303+
);
6304+
62616305
it.effect("routes websocket rpc git.pull errors", () =>
62626306
Effect.gen(function* () {
62636307
const gitError = new GitCommandError({

‎apps/server/src/serverRuntimeStartup.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
100100
getThreadShellById: () => Effect.succeed(Option.none()),
101101
getThreadDetailById: () => Effect.succeed(Option.none()),
102102
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
103+
listThreadIdsByWorktreePath: () => Effect.succeed([]),
103104
searchThreads: () => Effect.succeed({ matches: [] }),
104105
}),
105106
Effect.provideService(AnalyticsService.AnalyticsService, {
@@ -172,6 +173,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
172173
getThreadShellById: () => Effect.die("unused"),
173174
getThreadDetailById: () => Effect.die("unused"),
174175
getThreadDetailSnapshot: () => Effect.die("unused"),
176+
listThreadIdsByWorktreePath: () => Effect.die("unused"),
175177
searchThreads: () => Effect.succeed({ matches: [] }),
176178
}),
177179
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
@@ -225,6 +227,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
225227
getThreadShellById: () => Effect.die("unused"),
226228
getThreadDetailById: () => Effect.die("unused"),
227229
getThreadDetailSnapshot: () => Effect.die("unused"),
230+
listThreadIdsByWorktreePath: () => Effect.die("unused"),
228231
searchThreads: () => Effect.succeed({ matches: [] }),
229232
}),
230233
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
@@ -287,6 +290,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
287290
getThreadShellById: () => Effect.die("unused"),
288291
getThreadDetailById: () => Effect.die("unused"),
289292
getThreadDetailSnapshot: () => Effect.die("unused"),
293+
listThreadIdsByWorktreePath: () => Effect.die("unused"),
290294
searchThreads: () => Effect.succeed({ matches: [] }),
291295
}),
292296
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {

0 commit comments

Comments
 (0)