Skip to content

Commit 5ca426a

Browse files
committed
fix(server): group subagent worktree owners
1 parent 21bedfb commit 5ca426a

2 files changed

Lines changed: 176 additions & 18 deletions

File tree

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

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,127 @@ const runCleanupTest = <A, E>(
463463
>,
464464
) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped);
465465

466+
describe("subagent worktree ownership", () => {
467+
it.effect.each([
468+
"idle",
469+
"grandchild",
470+
"running",
471+
"pending",
472+
"unrelated",
473+
"fork",
474+
"recent-activity",
475+
"recent-inactive",
476+
"recent-grace",
477+
"recent-settle",
478+
"child-settled-only",
479+
] as const)("checks the whole owner group (%s)", (scenario) =>
480+
Effect.gen(function* () {
481+
yield* TestClock.setTime(NOW_MS);
482+
const fixture = yield* cleanupFixture();
483+
fixture.setSettings({
484+
storageCleanup: {
485+
...DEFAULT_SERVER_SETTINGS.storageCleanup,
486+
worktreeSettledAfterDays: scenario === "recent-inactive" ? null : 8,
487+
worktreeAfterDays: scenario === "recent-inactive" ? 8 : null,
488+
},
489+
});
490+
const root = shell({
491+
branch: "feature",
492+
worktreePath: fixture.worktree,
493+
settledAt: scenario === "child-settled-only" ? null : at(-20 * DAY_MS),
494+
});
495+
const child = shell({
496+
id: ThreadId.make("child"),
497+
branch: "feature",
498+
worktreePath: fixture.worktree,
499+
lineage: {
500+
parentThreadId: root.id,
501+
rootThreadId: root.id,
502+
relationshipToParent:
503+
scenario === "fork" ? "fork" : scenario === "unrelated" ? null : "subagent",
504+
},
505+
status: scenario === "running" ? "running" : "completed",
506+
pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [],
507+
latestRunCompletedAt:
508+
scenario === "recent-activity" || scenario === "recent-inactive"
509+
? at(-2 * DAY_MS)
510+
: scenario === "recent-grace"
511+
? at(-30_000)
512+
: null,
513+
settledAt: scenario === "child-settled-only" ? at(-20 * DAY_MS) : null,
514+
});
515+
const grandchild = {
516+
...child,
517+
id: ThreadId.make("grandchild"),
518+
lineage: { ...child.lineage, parentThreadId: child.id },
519+
};
520+
// The root can follow its children in the snapshot.
521+
fixture.setThreads(scenario === "grandchild" ? [grandchild, child, root] : [child, root]);
522+
if (scenario === "recent-settle") fixture.setThreads([{ ...child, settledAt: at(0) }, root]);
523+
const report = yield* fixture.service.runNow;
524+
const removed = ["idle", "grandchild", "recent-settle"].includes(scenario);
525+
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed);
526+
expect(report.entries[0]).toMatchObject({
527+
threadId: scenario === "unrelated" || scenario === "fork" ? child.id : root.id,
528+
outcome: removed ? "removed" : "kept",
529+
reason: removed
530+
? "Settled for 20 days"
531+
: scenario === "running" || scenario === "pending"
532+
? "Thread is running or has pending work"
533+
: scenario === "unrelated" || scenario === "fork"
534+
? "Shared by 2 threads"
535+
: scenario === "recent-activity"
536+
? "Settled for 2 of 8 days"
537+
: scenario === "recent-inactive"
538+
? "Inactive for 2 of 8 days"
539+
: scenario === "recent-grace"
540+
? "Settled moments ago"
541+
: "Not settled",
542+
});
543+
}).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
544+
);
545+
546+
it.live.each(["running", "pending", "activity", "unrelated"] as const)(
547+
"cancels removal when a child changes during measurement (%s)",
548+
(change) =>
549+
runCleanupTest(
550+
Effect.gen(function* () {
551+
const fixture = yield* pausedMeasurementFixture();
552+
const root = shell({ branch: "feature", worktreePath: fixture.worktree });
553+
const child = {
554+
...root,
555+
id: ThreadId.make("child"),
556+
lineage: {
557+
parentThreadId: root.id,
558+
rootThreadId: root.id,
559+
relationshipToParent: "subagent" as const,
560+
},
561+
};
562+
fixture.setThreads([child, root]);
563+
const run = yield* fixture.service.runNow.pipe(Effect.forkChild);
564+
yield* Deferred.await(fixture.measuring);
565+
fixture.setThreads([
566+
root,
567+
{
568+
...child,
569+
status: change === "running" ? "running" : "idle",
570+
pendingBackgroundTasks:
571+
change === "pending" ? [{ taskId: "task", kind: "command" }] : [],
572+
latestRunCompletedAt: change === "activity" ? at(-DAY_MS) : null,
573+
},
574+
...(change === "unrelated" ? [shell({ ...root, id: ThreadId.make("other") })] : []),
575+
]);
576+
yield* Deferred.succeed(fixture.resume, undefined);
577+
expect((yield* Fiber.join(run)).entries[0]).toMatchObject({
578+
outcome: "kept",
579+
reason: "Thread activity or shared worktree changed since check",
580+
});
581+
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
582+
}),
583+
),
584+
);
585+
});
586+
466587
describe("storage cleanup reports and local file policies", () => {
467588
it.live("measures nested regular files without following symlinks", () =>
468589
runCleanupTest(

‎apps/server/src/storageCleanup.ts‎

Lines changed: 55 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,31 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu
135135
);
136136
}
137137

138+
/** Only a complete subagent chain shares ownership; forks remain separate. */
139+
function worktreeOwner(threads: ReadonlyArray<OrchestrationV2ThreadShell>) {
140+
if (threads.length === 1) return threads[0];
141+
const owner = threads.find((thread) => thread.id === thread.lineage.rootThreadId);
142+
if (owner === undefined) return undefined;
143+
const byId = new Map(threads.map((thread) => [thread.id, thread]));
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.id
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+
138163
/**
139164
* Whether the host's pull request proves this worktree's head was merged. A
140165
* squash or rebase merge leaves the head outside the default branch, so the
@@ -441,13 +466,15 @@ const make = Effect.gen(function* () {
441466
(thread) => path.resolve(thread.worktreePath!),
442467
);
443468
const candidates = [
444-
...[...groups.values()].map((group) => group[0]!),
469+
...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!),
445470
...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
446471
];
447472
for (const thread of candidates) {
448473
const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
449474
if (!worktreeCleanupEnabled(settings)) continue;
450475
const worktreePath = path.resolve(thread.worktreePath!);
476+
const group = groups.get(worktreePath) ?? [];
477+
const activityAt = Math.max(...group.map(storageCleanupActivityAt));
451478
const deleted = "workspaceRoot" in thread;
452479
const project = deleted
453480
? { workspaceRoot: thread.workspaceRoot }
@@ -466,10 +493,10 @@ const make = Effect.gen(function* () {
466493
yield* Effect.gen(function* () {
467494
if (!(yield* fs.exists(worktreePath))) return;
468495
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`);
471498
if (project === undefined) return keep("project is unavailable");
472-
if (!deleted && !storageCleanupThreadIdle(thread, now))
499+
if (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
473500
return keep("thread is running or has pending work");
474501
if (hasTerminal(worktreePath)) return keep("open terminal");
475502
// Roots are canonical, so compare canonical paths. A symlinked parent
@@ -495,18 +522,19 @@ const make = Effect.gen(function* () {
495522
if (
496523
!deleted &&
497524
thread.settledAt !== null &&
498-
now - DateTime.toEpochMillis(thread.updatedAt) < SETTLE_SCRIPT_GRACE_MS
525+
now - Math.max(DateTime.toEpochMillis(thread.updatedAt), activityAt) <
526+
SETTLE_SCRIPT_GRACE_MS
499527
)
500528
return keep("settled moments ago");
501529
const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
502530
const old =
503531
!deleted &&
504532
settings.worktreeAfterDays !== null &&
505-
storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
533+
activityAt < now - settings.worktreeAfterDays * DAY_MS;
506534
const settledFor =
507535
deleted || thread.settledAt === null
508536
? null
509-
: now - DateTime.toEpochMillis(thread.settledAt);
537+
: now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
510538
const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
511539
const settled =
512540
settledFor !== null &&
@@ -516,7 +544,7 @@ const make = Effect.gen(function* () {
516544
let removalReason = deleted
517545
? "thread was deleted"
518546
: old
519-
? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days`
547+
? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
520548
: `settled for ${settledDays} days`;
521549
if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
522550
const repositoryCwd = path.resolve(project.workspaceRoot);
@@ -564,7 +592,7 @@ const make = Effect.gen(function* () {
564592
if (!eligible)
565593
return keep(
566594
!deleted && settings.worktreeAfterDays !== null
567-
? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} of ${settings.worktreeAfterDays} days`
595+
? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
568596
: settings.worktreeSettledAfterDays !== null
569597
? settledFor === null
570598
? "not settled"
@@ -575,7 +603,7 @@ const make = Effect.gen(function* () {
575603
);
576604
// Threads, queued deletion work and provider sessions as they are now, so a
577605
// 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
606+
// the removal. Read only this path's threads: a full snapshot per
579607
// worktree takes seconds on large databases.
580608
const blockedSinceCheck = Effect.fnUntraced(function* () {
581609
const latestProjects = yield* projectStore.listShells();
@@ -600,15 +628,24 @@ const make = Effect.gen(function* () {
600628
`;
601629
if (pendingCleanup.length > 0) return "thread deletion is still pending";
602630
} else {
603-
const latestShell =
604-
latest.length === 1 && latest[0]!.threadId === thread.id
605-
? yield* projections.getThreadShell(thread.id)
606-
: null;
631+
const latestShells = yield* Effect.forEach(latest, (entry) =>
632+
projections.getThreadShell(entry.threadId),
633+
);
634+
const latestGroup = latestShells.filter((shell) => shell !== null);
635+
const latestOwner = worktreeOwner(latestGroup);
607636
if (
608-
latestShell === null ||
609-
!storageCleanupThreadIdle(latestShell, now) ||
610-
storageCleanupActivityAt(latestShell) !== storageCleanupActivityAt(thread) ||
611-
!Equal.equals(latestShell.settledAt, thread.settledAt)
637+
latestGroup.length !== group.length ||
638+
latestOwner?.id !== thread.id ||
639+
!Equal.equals(latestOwner.settledAt, thread.settledAt) ||
640+
latestGroup.some((shell) => {
641+
const previous = group.find((member) => member.id === shell.id);
642+
return (
643+
previous === undefined ||
644+
!storageCleanupThreadIdle(shell, now) ||
645+
path.resolve(shell.worktreePath!) !== worktreePath ||
646+
storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
647+
);
648+
})
612649
)
613650
return "thread activity or shared worktree changed since check";
614651
}

0 commit comments

Comments
 (0)