@devries-cameron20 / t3code-1 / commits / 171f8d880f
Fork 0

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

fix(server): clean up deleted threads worktrees with subagents (#23900)

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

Julius Marminge committed Oct 23, 2026 at 10:56 UTC 171f8d880f2874f968ba1facc818f2d8b2074f6f
2 files changed +153 -38
apps/server/src/storageCleanup.test.ts
+106 -6
@@ -262,6 +262,7 @@ const cleanupFixture = (
262 storageCleanup,
263 };
264 let threads = [shell({ branch: "feature", worktreePath: worktree })];
265 + let deletedThreads: OrchestrationV2ThreadShell[] = [];
266 let storedWorktreePaths: string[] = [worktree];
267 let projectRoots = [repo];
268 let editBeforeRemoval = false;
@@ -358,12 +359,17 @@ const cleanupFixture = (
359 }),
360 },
361 ]
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 + : [],
373 )) as unknown as SqlClient.SqlClient),
374 Effect.provideService(GitManager.GitManager, {
375 invalidateStatus: () => Effect.void,
@@ -415,6 +421,9 @@ const cleanupFixture = (
421 setThreads: (next: typeof threads) => {
422 threads = next;
423 },
424 + setDeletedThreads: (next: OrchestrationV2ThreadShell[]) => {
425 + deletedThreads = next;
426 + },
427 setStoredWorktreePaths: (paths: string[]) => {
428 storedWorktreePaths = paths;
429 },
@@ -848,6 +857,97 @@ describe("subagent worktree ownership", () => {
857 );
858 });
859
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 +
951 describe("orphan worktree reports", () => {
952 it.live("keeps orphan results visible when thread results fill the report", () =>
953 runCleanupTest(
apps/server/src/storageCleanup.ts
+47 -32
@@ -146,7 +146,9 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu
146 }
147
148 /** 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 +) {
152 if (threads.length === 1) return threads[0];
153 const byId = new Map(threads.map((thread) => [thread.id, thread]));
154 const tops = threads.filter((thread) => !byId.has(thread.lineage.parentThreadId!));
@@ -750,8 +752,24 @@ const make = Effect.gen(function* () {
752 snapshot.threads.filter((thread) => thread.worktreePath !== null),
753 (thread) => path.resolve(thread.worktreePath!),
754 );
755 + const deletedByPath = Map.groupBy(deletedThreads, (thread) =>
756 + path.resolve(thread.worktreePath!),
757 + );
758 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 + ),
773 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
774 ];
775 for (const thread of candidates) {
@@ -761,6 +779,7 @@ const make = Effect.gen(function* () {
779 const group = groups.get(worktreePath) ?? [];
780 const activityAt = Math.max(...group.map(storageCleanupActivityAt));
781 const deleted = "workspaceRoot" in thread;
782 + const members = deleted ? [thread, ...group] : group;
783 const project = deleted
784 ? { workspaceRoot: thread.workspaceRoot }
785 : snapshot.projects.find((entry) => entry.id === thread.projectId);
@@ -779,12 +798,12 @@ const make = Effect.gen(function* () {
798 yield* Effect.gen(function* () {
799 if (!(yield* fs.exists(worktreePath))) return;
800 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`);
803 if (project === undefined) return keep("project is unavailable");
804 if (
805 thread.branch === null ||
787 - (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
806 + !group.every((member) => storageCleanupThreadIdle(member, now))
807 )
808 return keep("thread is running or has pending work");
809 if (group.some((member) => member.branch !== thread.branch))
@@ -807,7 +826,6 @@ const make = Effect.gen(function* () {
826 const changes = yield* localChangesReason(worktreePath, settings);
827 if (changes !== null) return keep(changes);
828 if (
810 - !deleted &&
829 group.some(
830 (member) =>
831 member.settledAt !== null &&
@@ -928,7 +946,6 @@ const make = Effect.gen(function* () {
946 if (hasTerminal(worktreePath)) return "open terminal";
947 if (deleted) {
948 if (
931 - latest.length > 0 ||
949 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
950 .worktreeOnDelete
951 )
@@ -940,32 +957,30 @@ const make = Effect.gen(function* () {
957 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
958 `.pipe(NodeSqliteClient.readOnly);
959 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";
960 }
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";
984 // Sessions can outlive their run and can be shared across app threads.
985 const sessionRows = yield* sql<{ payload_json: string }>`
986 SELECT payload_json FROM orchestration_v2_projection_provider_sessions