@devries-cameron20 / t3code Mirror · read-only / commits / e733a40295
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 09:15 UTC

fix(server): clean up worktrees shared by subagents (#19748)

maria committed Oct 15, 2026 at 23:42 UTC e733a40295f3c961260f64f8eb850b561a04937b
2 files changed +270 -20
apps/server/src/storageCleanup.test.ts
+201
@@ -463,6 +463,199 @@ const runCleanupTest = <A, E>(
463 >,
464 ) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped);
465
466 +describe("subagent worktree ownership", () => {
467 + it.effect.each([
468 + "idle",
469 + "grandchild",
470 + "null-branch",
471 + "stale-branch",
472 + "isolated-owner",
473 + "fork-owner",
474 + "missing-parent",
475 + "cycle",
476 + "two-tops",
477 + "wrong-root",
478 + "running",
479 + "pending",
480 + "unrelated",
481 + "fork",
482 + "recent-activity",
483 + "recent-inactive",
484 + "recent-grace",
485 + "recent-settle",
486 + "child-settled-now",
487 + "child-settled-only",
488 + ] as const)("checks the whole owner group (%s)", (scenario) =>
489 + Effect.gen(function* () {
490 + yield* TestClock.setTime(NOW_MS);
491 + const fixture = yield* cleanupFixture();
492 + fixture.setSettings({
493 + storageCleanup: {
494 + ...DEFAULT_SERVER_SETTINGS.storageCleanup,
495 + worktreeSettledAfterDays: scenario === "recent-inactive" ? null : 8,
496 + worktreeAfterDays: scenario === "recent-inactive" ? 8 : null,
497 + },
498 + });
499 + const root = shell({
500 + branch: "feature",
501 + worktreePath: fixture.worktree,
502 + settledAt: scenario === "child-settled-only" ? null : at(-20 * DAY_MS),
503 + ...(scenario === "isolated-owner" || scenario === "fork-owner"
504 + ? {
505 + lineage: {
506 + parentThreadId: ThreadId.make("ancestor"),
507 + rootThreadId: ThreadId.make("ancestor"),
508 + relationshipToParent:
509 + scenario === "fork-owner" ? ("fork" as const) : ("subagent" as const),
510 + },
511 + }
512 + : {}),
513 + });
514 + const child = shell({
515 + id: ThreadId.make("child"),
516 + branch:
517 + scenario === "null-branch"
518 + ? null
519 + : scenario === "stale-branch"
520 + ? "t3/15a6e5ae"
521 + : "feature",
522 + worktreePath: fixture.worktree,
523 + lineage: {
524 + parentThreadId:
525 + scenario === "missing-parent"
526 + ? ThreadId.make("missing")
527 + : scenario === "cycle"
528 + ? ThreadId.make("child")
529 + : scenario === "two-tops"
530 + ? null
531 + : root.id,
532 + rootThreadId:
533 + scenario === "wrong-root" ? ThreadId.make("other-root") : root.lineage.rootThreadId,
534 + relationshipToParent:
535 + scenario === "fork" ? "fork" : scenario === "unrelated" ? null : "subagent",
536 + },
537 + status: scenario === "running" ? "running" : "completed",
538 + pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [],
539 + latestRunCompletedAt:
540 + scenario === "recent-activity" || scenario === "recent-inactive"
541 + ? at(-2 * DAY_MS)
542 + : scenario === "recent-grace"
543 + ? at(-30_000)
544 + : null,
545 + settledAt: scenario === "child-settled-only" ? at(-20 * DAY_MS) : null,
546 + });
547 + const grandchild = {
548 + ...child,
549 + id: ThreadId.make("grandchild"),
550 + lineage: { ...child.lineage, parentThreadId: child.id },
551 + };
552 + // The worktree owner can follow its children in the snapshot.
553 + fixture.setThreads(
554 + scenario === "grandchild"
555 + ? [grandchild, child, root]
556 + : scenario === "isolated-owner" || scenario === "fork-owner"
557 + ? [child, root, shell({ id: ThreadId.make("ancestor") })]
558 + : [child, root],
559 + );
560 + if (scenario === "recent-settle" || scenario === "child-settled-now")
561 + fixture.setThreads([
562 + {
563 + ...child,
564 + settledAt: scenario === "recent-settle" ? at(0) : at(-20 * DAY_MS),
565 + updatedAt: at(0),
566 + },
567 + root,
568 + ]);
569 + const report = yield* fixture.service.runNow;
570 + const removed = ["idle", "grandchild", "isolated-owner", "fork-owner"].includes(scenario);
571 + const shared = [
572 + "unrelated",
573 + "fork",
574 + "missing-parent",
575 + "cycle",
576 + "two-tops",
577 + "wrong-root",
578 + ].includes(scenario);
579 + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed);
580 + expect(report.entries[0]).toMatchObject({
581 + threadId: shared ? child.id : root.id,
582 + outcome: removed ? "removed" : "kept",
583 + reason: removed
584 + ? "Settled for 20 days"
585 + : scenario === "running" || scenario === "pending"
586 + ? "Thread is running or has pending work"
587 + : shared
588 + ? "Shared by 2 threads"
589 + : scenario === "null-branch" || scenario === "stale-branch"
590 + ? "A subagent thread's branch differs from this worktree's branch"
591 + : scenario === "recent-activity"
592 + ? "Settled for 2 of 8 days"
593 + : scenario === "recent-inactive"
594 + ? "Inactive for 2 of 8 days"
595 + : ["recent-grace", "recent-settle", "child-settled-now"].includes(scenario)
596 + ? "Settled moments ago"
597 + : "Not settled",
598 + });
599 + }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
600 + );
601 +
602 + it.live.each([
603 + "running",
604 + "pending",
605 + "activity",
606 + "unrelated",
607 + "settled",
608 + "resettled",
609 + "null-branch",
610 + "stale-branch",
611 + ] as const)("cancels removal when a child changes during measurement (%s)", (change) =>
612 + runCleanupTest(
613 + Effect.gen(function* () {
614 + const fixture = yield* pausedMeasurementFixture();
615 + const root = shell({ branch: "feature", worktreePath: fixture.worktree });
616 + const child = {
617 + ...root,
618 + id: ThreadId.make("child"),
619 + settledAt: change === "resettled" ? at(-20 * DAY_MS) : null,
620 + lineage: {
621 + parentThreadId: root.id,
622 + rootThreadId: root.id,
623 + relationshipToParent: "subagent" as const,
624 + },
625 + };
626 + fixture.setThreads([child, root]);
627 + const run = yield* fixture.service.runNow.pipe(Effect.forkChild);
628 + yield* Deferred.await(fixture.measuring);
629 + fixture.setThreads([
630 + root,
631 + {
632 + ...child,
633 + branch:
634 + change === "null-branch"
635 + ? null
636 + : change === "stale-branch"
637 + ? "t3/15a6e5ae"
638 + : child.branch,
639 + settledAt: change === "settled" ? at(-20 * DAY_MS) : child.settledAt,
640 + updatedAt: change === "settled" || change === "resettled" ? at(0) : child.updatedAt,
641 + status: change === "running" ? "running" : "idle",
642 + pendingBackgroundTasks:
643 + change === "pending" ? [{ taskId: "task", kind: "command" }] : [],
644 + latestRunCompletedAt: change === "activity" ? at(-DAY_MS) : null,
645 + },
646 + ...(change === "unrelated" ? [shell({ ...root, id: ThreadId.make("other") })] : []),
647 + ]);
648 + yield* Deferred.succeed(fixture.resume, undefined);
649 + expect((yield* Fiber.join(run)).entries[0]).toMatchObject({
650 + outcome: "kept",
651 + reason: "Thread activity or shared worktree changed since check",
652 + });
653 + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
654 + }),
655 + ),
656 + );
657 +});
658 +
659 describe("storage cleanup reports and local file policies", () => {
660 it.live("measures nested regular files without following symlinks", () =>
661 runCleanupTest(
@@ -505,6 +698,14 @@ describe("storage cleanup reports and local file policies", () => {
698 ),
699 );
700 it.live.each([
701 + [
702 + "its owner's branch is cleared",
703 + (worktree: string) => [shell({ branch: null, worktreePath: worktree, updatedAt: at(0) })],
704 + ],
705 + [
706 + "its owner's branch changes",
707 + (worktree: string) => [shell({ branch: "other", worktreePath: worktree, updatedAt: at(0) })],
708 + ],
709 [
710 "its thread starts",
711 (worktree: string) => [
apps/server/src/storageCleanup.ts
+69 -20
@@ -107,7 +107,6 @@ function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings
107 /** Live sessions keep their cwd even when no turn is currently running. */
108 export function storageCleanupThreadIdle(thread: OrchestrationV2ThreadShell, now: number): boolean {
109 return (
110 - thread.branch !== null &&
110 thread.worktreePath !== null &&
111 thread.activeRunId === null &&
112 (thread.status === "idle" ||
@@ -135,6 +134,32 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu
134 );
135 }
136
137 +/** Only a complete subagent chain within this worktree shares ownership. */
138 +function worktreeOwner(threads: ReadonlyArray<OrchestrationV2ThreadShell>) {
139 + if (threads.length === 1) return threads[0];
140 + const byId = new Map(threads.map((thread) => [thread.id, thread]));
141 + const tops = threads.filter((thread) => !byId.has(thread.lineage.parentThreadId!));
142 + if (tops.length !== 1) return undefined;
143 + const owner = tops[0]!;
144 + for (const thread of threads) {
145 + let current = thread;
146 + const seen = new Set<string>();
147 + while (current.id !== owner.id) {
148 + if (
149 + seen.has(current.id) ||
150 + current.lineage.relationshipToParent !== "subagent" ||
151 + current.lineage.rootThreadId !== owner.lineage.rootThreadId
152 + )
153 + return undefined;
154 + seen.add(current.id);
155 + const parent = byId.get(current.lineage.parentThreadId!);
156 + if (parent === undefined) return undefined;
157 + current = parent;
158 + }
159 + }
160 + return owner;
161 +}
162 +
163 /**
164 * Whether the host's pull request proves this worktree's head was merged. A
165 * squash or rebase merge leaves the head outside the default branch, so the
@@ -441,13 +466,15 @@ const make = Effect.gen(function* () {
466 (thread) => path.resolve(thread.worktreePath!),
467 );
468 const candidates = [
444 - ...[...groups.values()].map((group) => group[0]!),
469 + ...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!),
470 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
471 ];
472 for (const thread of candidates) {
473 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
474 if (!worktreeCleanupEnabled(settings)) continue;
475 const worktreePath = path.resolve(thread.worktreePath!);
476 + const group = groups.get(worktreePath) ?? [];
477 + const activityAt = Math.max(...group.map(storageCleanupActivityAt));
478 const deleted = "workspaceRoot" in thread;
479 const project = deleted
480 ? { workspaceRoot: thread.workspaceRoot }
@@ -466,11 +493,16 @@ const make = Effect.gen(function* () {
493 yield* Effect.gen(function* () {
494 if (!(yield* fs.exists(worktreePath))) return;
495 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
469 - const shared = groups.get(worktreePath)?.length ?? 0;
470 - if (shared > 1) return keep(`shared by ${shared} threads`);
496 + if (group.length > 1 && worktreeOwner(group) === undefined)
497 + return keep(`shared by ${group.length} threads`);
498 if (project === undefined) return keep("project is unavailable");
472 - if (!deleted && !storageCleanupThreadIdle(thread, now))
499 + if (
500 + thread.branch === null ||
501 + (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
502 + )
503 return keep("thread is running or has pending work");
504 + if (group.some((member) => member.branch !== thread.branch))
505 + return keep("a subagent thread's branch differs from this worktree's branch");
506 if (hasTerminal(worktreePath)) return keep("open terminal");
507 // Roots are canonical, so compare canonical paths. A symlinked parent
508 // (a linked drive) is fine; a symlinked worktree directory is not.
@@ -494,19 +526,23 @@ const make = Effect.gen(function* () {
526 // settlement backdates settledAt to the thread's last activity.
527 if (
528 !deleted &&
497 - thread.settledAt !== null &&
498 - now - DateTime.toEpochMillis(thread.updatedAt) < SETTLE_SCRIPT_GRACE_MS
529 + group.some(
530 + (member) =>
531 + member.settledAt !== null &&
532 + now - Math.max(DateTime.toEpochMillis(member.updatedAt), activityAt) <
533 + SETTLE_SCRIPT_GRACE_MS,
534 + )
535 )
536 return keep("settled moments ago");
537 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
538 const old =
539 !deleted &&
540 settings.worktreeAfterDays !== null &&
505 - storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
541 + activityAt < now - settings.worktreeAfterDays * DAY_MS;
542 const settledFor =
543 deleted || thread.settledAt === null
544 ? null
509 - : now - DateTime.toEpochMillis(thread.settledAt);
545 + : now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
546 const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
547 const settled =
548 settledFor !== null &&
@@ -516,7 +552,7 @@ const make = Effect.gen(function* () {
552 let removalReason = deleted
553 ? "thread was deleted"
554 : old
519 - ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days`
555 + ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
556 : `settled for ${settledDays} days`;
557 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
558 const repositoryCwd = path.resolve(project.workspaceRoot);
@@ -564,7 +600,7 @@ const make = Effect.gen(function* () {
600 if (!eligible)
601 return keep(
602 !deleted && settings.worktreeAfterDays !== null
567 - ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} of ${settings.worktreeAfterDays} days`
603 + ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
604 : settings.worktreeSettledAfterDays !== null
605 ? settledFor === null
606 ? "not settled"
@@ -575,7 +611,7 @@ const make = Effect.gen(function* () {
611 );
612 // Threads, queued deletion work and provider sessions as they are now, so a
613 // queued turn, resumed session or new thread sharing this path cancels
578 - // the removal. Read only this path and this thread: a full snapshot per
614 + // the removal. Read only this path's threads: a full snapshot per
615 // worktree takes seconds on large databases.
616 const blockedSinceCheck = Effect.fnUntraced(function* () {
617 const latestProjects = yield* projectStore.listShells();
@@ -600,15 +636,28 @@ const make = Effect.gen(function* () {
636 `;
637 if (pendingCleanup.length > 0) return "thread deletion is still pending";
638 } else {
603 - const latestShell =
604 - latest.length === 1 && latest[0]!.threadId === thread.id
605 - ? yield* projections.getThreadShell(thread.id)
606 - : null;
639 + const latestShells = yield* Effect.forEach(latest, (entry) =>
640 + projections.getThreadShell(entry.threadId),
641 + );
642 + const latestGroup = latestShells.filter((shell) => shell !== null);
643 + const latestOwner = worktreeOwner(latestGroup);
644 if (
608 - latestShell === null ||
609 - !storageCleanupThreadIdle(latestShell, now) ||
610 - storageCleanupActivityAt(latestShell) !== storageCleanupActivityAt(thread) ||
611 - !Equal.equals(latestShell.settledAt, thread.settledAt)
645 + latestGroup.length !== group.length ||
646 + latestOwner?.id !== thread.id ||
647 + latestOwner?.branch !== thread.branch ||
648 + latestGroup.some((shell) => {
649 + const previous = group.find((member) => member.id === shell.id);
650 + return (
651 + previous === undefined ||
652 + shell.branch !== thread.branch ||
653 + !Equal.equals(shell.settledAt, previous.settledAt) ||
654 + (shell.settledAt !== null &&
655 + !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
656 + !storageCleanupThreadIdle(shell, now) ||
657 + path.resolve(shell.worktreePath!) !== worktreePath ||
658 + storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
659 + );
660 + })
661 )
662 return "thread activity or shared worktree changed since check";
663 }