Skip to content

Commit 171f8d8

Browse files
fix(server): clean up deleted threads worktrees with subagents (#23900)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 4dcc244 commit 171f8d8

2 files changed

Lines changed: 153 additions & 38 deletions

File tree

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

Lines changed: 106 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ const cleanupFixture = (
262262
storageCleanup,
263263
};
264264
let threads = [shell({ branch: "feature", worktreePath: worktree })];
265+
let deletedThreads: OrchestrationV2ThreadShell[] = [];
265266
let storedWorktreePaths: string[] = [worktree];
266267
let projectRoots = [repo];
267268
let editBeforeRemoval = false;
@@ -358,12 +359,17 @@ const cleanupFixture = (
358359
}),
359360
},
360361
]
361-
: strings.join("").includes('AS "worktreePath"')
362-
? [
363-
...threads.flatMap((thread) => thread.worktreePath ?? []),
364-
...storedWorktreePaths,
365-
].map((worktreePath) => ({ worktreePath }))
366-
: [],
362+
: strings.join("").includes("deleted_at IS NOT NULL")
363+
? deletedThreads.map((thread) => ({
364+
payload_json: JSON.stringify(thread),
365+
workspaceRoot: repo,
366+
}))
367+
: strings.join("").includes('AS "worktreePath"')
368+
? [
369+
...threads.flatMap((thread) => thread.worktreePath ?? []),
370+
...storedWorktreePaths,
371+
].map((worktreePath) => ({ worktreePath }))
372+
: [],
367373
)) as unknown as SqlClient.SqlClient),
368374
Effect.provideService(GitManager.GitManager, {
369375
invalidateStatus: () => Effect.void,
@@ -415,6 +421,9 @@ const cleanupFixture = (
415421
setThreads: (next: typeof threads) => {
416422
threads = next;
417423
},
424+
setDeletedThreads: (next: OrchestrationV2ThreadShell[]) => {
425+
deletedThreads = next;
426+
},
418427
setStoredWorktreePaths: (paths: string[]) => {
419428
storedWorktreePaths = paths;
420429
},
@@ -848,6 +857,97 @@ describe("subagent worktree ownership", () => {
848857
);
849858
});
850859

860+
describe("deleted thread worktrees", () => {
861+
const parent = (worktreePath: string) =>
862+
shell({ branch: "feature", worktreePath, deletedAt: at(-DAY_MS) });
863+
// Deleting the parent leaves its native subagent thread in the projection.
864+
const subagent = (
865+
owner: OrchestrationV2ThreadShell,
866+
overrides: Partial<OrchestrationV2ThreadShell> = {},
867+
) =>
868+
shell({
869+
id: ThreadId.make("child"),
870+
title: "Subagent",
871+
branch: "feature",
872+
worktreePath: owner.worktreePath,
873+
status: "completed",
874+
createdBy: "agent",
875+
creationSource: "provider",
876+
lineage: {
877+
rootThreadId: owner.id,
878+
parentThreadId: owner.id,
879+
relationshipToParent: "subagent",
880+
},
881+
...overrides,
882+
});
883+
884+
it.effect.each(["no subagents", "native subagent"] as const)(
885+
"removes a deleted thread's worktree with %s",
886+
(scenario) =>
887+
Effect.gen(function* () {
888+
yield* TestClock.setTime(NOW_MS);
889+
const fixture = yield* cleanupFixture({
890+
...DEFAULT_SERVER_SETTINGS.storageCleanup,
891+
worktreeAfterDays: null,
892+
worktreeOnDelete: true,
893+
});
894+
const owner = parent(fixture.worktree);
895+
fixture.setDeletedThreads([owner]);
896+
fixture.setThreads(scenario === "native subagent" ? [subagent(owner)] : []);
897+
const report = yield* fixture.service.runNow;
898+
expect(report.entries[0]).toMatchObject({
899+
threadId: owner.id,
900+
outcome: "removed",
901+
reason: "Thread was deleted",
902+
});
903+
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
904+
}).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
905+
);
906+
907+
it.effect("applies the remaining subagent's rules when deletion cleanup is off", () =>
908+
Effect.gen(function* () {
909+
yield* TestClock.setTime(NOW_MS);
910+
const fixture = yield* cleanupFixture({
911+
...DEFAULT_SERVER_SETTINGS.storageCleanup,
912+
worktreeAfterDays: 8,
913+
worktreeOnDelete: false,
914+
});
915+
const owner = parent(fixture.worktree);
916+
const child = subagent(owner);
917+
fixture.setDeletedThreads([owner]);
918+
fixture.setThreads([child]);
919+
const report = yield* fixture.service.runNow;
920+
expect(report.entries[0]).toMatchObject({
921+
threadId: child.id,
922+
outcome: "removed",
923+
reason: "Inactive for 30 days",
924+
});
925+
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
926+
}).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
927+
);
928+
929+
it.effect("waits out the settle grace of a subagent that just settled", () =>
930+
Effect.gen(function* () {
931+
yield* TestClock.setTime(NOW_MS);
932+
const fixture = yield* cleanupFixture({
933+
...DEFAULT_SERVER_SETTINGS.storageCleanup,
934+
worktreeAfterDays: null,
935+
worktreeOnDelete: true,
936+
});
937+
const owner = parent(fixture.worktree);
938+
fixture.setDeletedThreads([owner]);
939+
fixture.setThreads([subagent(owner, { settledAt: at(0), updatedAt: at(0) })]);
940+
const report = yield* fixture.service.runNow;
941+
expect(report.entries[0]).toMatchObject({
942+
threadId: owner.id,
943+
outcome: "kept",
944+
reason: "Settled moments ago",
945+
});
946+
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
947+
}).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
948+
);
949+
});
950+
851951
describe("orphan worktree reports", () => {
852952
it.live("keeps orphan results visible when thread results fill the report", () =>
853953
runCleanupTest(

‎apps/server/src/storageCleanup.ts‎

Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,9 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu
146146
}
147147

148148
/** Only a complete subagent chain within this worktree shares ownership. */
149-
function worktreeOwner(threads: ReadonlyArray<OrchestrationV2ThreadShell>) {
149+
function worktreeOwner<T extends Pick<OrchestrationV2ThreadShell, "id" | "lineage">>(
150+
threads: ReadonlyArray<T>,
151+
) {
150152
if (threads.length === 1) return threads[0];
151153
const byId = new Map(threads.map((thread) => [thread.id, thread]));
152154
const tops = threads.filter((thread) => !byId.has(thread.lineage.parentThreadId!));
@@ -750,8 +752,24 @@ const make = Effect.gen(function* () {
750752
snapshot.threads.filter((thread) => thread.worktreePath !== null),
751753
(thread) => path.resolve(thread.worktreePath!),
752754
);
755+
const deletedByPath = Map.groupBy(deletedThreads, (thread) =>
756+
path.resolve(thread.worktreePath!),
757+
);
753758
const candidates = [
754-
...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!),
759+
...[...groups].map(
760+
([worktreePath, group]) =>
761+
// A deleted thread still owns the worktree its remaining subagents share,
762+
// but only deletion cleanup acts on it; otherwise the live rules apply.
763+
deletedByPath
764+
.get(worktreePath)
765+
?.find(
766+
(deleted) =>
767+
resolveWorktreeCleanup(serverSettings, deleted.projectId).worktreeOnDelete &&
768+
worktreeOwner([deleted, ...group]) === deleted,
769+
) ??
770+
worktreeOwner(group) ??
771+
group[0]!,
772+
),
755773
...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
756774
];
757775
for (const thread of candidates) {
@@ -761,6 +779,7 @@ const make = Effect.gen(function* () {
761779
const group = groups.get(worktreePath) ?? [];
762780
const activityAt = Math.max(...group.map(storageCleanupActivityAt));
763781
const deleted = "workspaceRoot" in thread;
782+
const members = deleted ? [thread, ...group] : group;
764783
const project = deleted
765784
? { workspaceRoot: thread.workspaceRoot }
766785
: snapshot.projects.find((entry) => entry.id === thread.projectId);
@@ -779,12 +798,12 @@ const make = Effect.gen(function* () {
779798
yield* Effect.gen(function* () {
780799
if (!(yield* fs.exists(worktreePath))) return;
781800
if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
782-
if (group.length > 1 && worktreeOwner(group) === undefined)
783-
return keep(`shared by ${group.length} threads`);
801+
if (members.length > 1 && worktreeOwner(members) === undefined)
802+
return keep(`shared by ${members.length} threads`);
784803
if (project === undefined) return keep("project is unavailable");
785804
if (
786805
thread.branch === null ||
787-
(!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
806+
!group.every((member) => storageCleanupThreadIdle(member, now))
788807
)
789808
return keep("thread is running or has pending work");
790809
if (group.some((member) => member.branch !== thread.branch))
@@ -807,7 +826,6 @@ const make = Effect.gen(function* () {
807826
const changes = yield* localChangesReason(worktreePath, settings);
808827
if (changes !== null) return keep(changes);
809828
if (
810-
!deleted &&
811829
group.some(
812830
(member) =>
813831
member.settledAt !== null &&
@@ -928,7 +946,6 @@ const make = Effect.gen(function* () {
928946
if (hasTerminal(worktreePath)) return "open terminal";
929947
if (deleted) {
930948
if (
931-
latest.length > 0 ||
932949
!resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
933950
.worktreeOnDelete
934951
)
@@ -940,32 +957,30 @@ const make = Effect.gen(function* () {
940957
WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
941958
`.pipe(NodeSqliteClient.readOnly);
942959
if (pendingCleanup.length > 0) return "thread deletion is still pending";
943-
} else {
944-
const latestShells = yield* Effect.forEach(latest, (entry) =>
945-
projections.getThreadShell(entry.threadId),
946-
);
947-
const latestGroup = latestShells.filter((shell) => shell !== null);
948-
const latestOwner = worktreeOwner(latestGroup);
949-
if (
950-
latestGroup.length !== group.length ||
951-
latestOwner?.id !== thread.id ||
952-
latestOwner?.branch !== thread.branch ||
953-
latestGroup.some((shell) => {
954-
const previous = group.find((member) => member.id === shell.id);
955-
return (
956-
previous === undefined ||
957-
shell.branch !== thread.branch ||
958-
!Equal.equals(shell.settledAt, previous.settledAt) ||
959-
(shell.settledAt !== null &&
960-
!Equal.equals(shell.updatedAt, previous.updatedAt)) ||
961-
!storageCleanupThreadIdle(shell, now) ||
962-
path.resolve(shell.worktreePath!) !== worktreePath ||
963-
storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
964-
);
965-
})
966-
)
967-
return "thread activity or shared worktree changed since check";
968960
}
961+
const latestShells = yield* Effect.forEach(latest, (entry) =>
962+
projections.getThreadShell(entry.threadId),
963+
);
964+
const latestGroup = latestShells.filter((shell) => shell !== null);
965+
const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup);
966+
if (
967+
latestGroup.length !== group.length ||
968+
latestOwner?.id !== thread.id ||
969+
latestOwner?.branch !== thread.branch ||
970+
latestGroup.some((shell) => {
971+
const previous = group.find((member) => member.id === shell.id);
972+
return (
973+
previous === undefined ||
974+
shell.branch !== thread.branch ||
975+
!Equal.equals(shell.settledAt, previous.settledAt) ||
976+
(shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
977+
!storageCleanupThreadIdle(shell, now) ||
978+
path.resolve(shell.worktreePath!) !== worktreePath ||
979+
storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
980+
);
981+
})
982+
)
983+
return "thread activity or shared worktree changed since check";
969984
// Sessions can outlive their run and can be shared across app threads.
970985
const sessionRows = yield* sql<{ payload_json: string }>`
971986
SELECT payload_json FROM orchestration_v2_projection_provider_sessions

0 commit comments

Comments
 (0)