Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

storageCleanup.test.ts

1,088 lines42.2 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as Effect from "effect/Effect";
3import * as Context from "effect/Context";
4import * as Deferred from "effect/Deferred";
5import * as Fiber from "effect/Fiber";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import type * as Path from "effect/Path";
9import type * as Scope from "effect/Scope";
10import * as Stream from "effect/Stream";
11import * as Schema from "effect/Schema";
12import { SCAN_CACHE_FILE_NAME } from "./usage/usageScanCache.ts";
13import { TestClock } from "effect/testing";
14import * as SqlClient from "effect/sql/SqlClient";
15import {
16 DEFAULT_SERVER_SETTINGS,
17 StorageCleanupReport,
18 type WorktreeKeepWhen,
19 type StorageCleanupSettings,
20} from "@t3tools/contracts";
21import * as ServerConfig from "./config.ts";
22import * as StorageCleanup from "./storageCleanup.ts";
23import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
24import * as GitManager from "./git/GitManager.ts";
25import * as Settings from "./serverSettings.ts";
26import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
27import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
28import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
29import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
30import * as TerminalManager from "./terminal/Manager.ts";
31import { CodexProviderCapabilitiesV2 } from "./orchestration-v2/Adapters/CodexAdapterV2.ts";
32import { ServerActivation } from "./serverActivation.ts";
33import { describe, expect, it } from "@effect/vitest";
34import {
35 EventId,
36 ProjectId,
37 ProviderDriverKind,
38 ProviderInstanceId,
39 ProviderSessionId,
40 RunId,
41 RuntimeRequestId,
42 ThreadId,
43 type OrchestrationV2DomainEvent,
44 type OrchestrationV2ProviderSession,
45 type OrchestrationV2ThreadShell,
46} from "@t3tools/contracts";
47import * as DateTime from "effect/DateTime";
48import {
49 storageCleanupActivityAt,
50 storageCleanupPullRequestMerged,
51 storageCleanupThreadIdle,
52} from "./storageCleanup.ts";
53​
54const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z");
55const DAY_MS = 24 * 60 * 60 * 1_000;
56const decodeCleanupReport = Schema.decodeSync(StorageCleanupReport);
57​
58function at(offsetMs: number): DateTime.Utc {
59 return DateTime.makeUnsafe(NOW_MS + offsetMs);
61​
62function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
63 return {
64 id: ThreadId.make("thread-1"),
65 projectId: ProjectId.make("project-1"),
66 title: "Thread",
67 providerInstanceId: ProviderInstanceId.make("codex"),
68 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
69 runtimeMode: "full-access",
70 interactionMode: "default",
71 worktreePath: null,
72 activeProviderThreadId: null,
73 lineage: {
74 rootThreadId: ThreadId.make("thread-1"),
75 parentThreadId: null,
76 relationshipToParent: null,
77 },
78 forkedFrom: null,
79 createdBy: "user",
80 creationSource: "web",
81 activeRunId: null,
82 latestVisibleMessage: null,
83 hasActionableProposedPlan: false,
84 itemCount: 0,
85 visibleItemCount: 0,
86 lastVisitedAt: null,
87 deletedAt: null,
88 branch: null,
89 linkedPullRequest: null,
90 status: "idle",
91 activityRunStatus: null,
92 pendingRuntimeRequest: null,
93 pendingBackgroundTasks: [],
94 latestRunId: null,
95 latestRunRequestedAt: null,
96 latestRunStartedAt: null,
97 latestRunCompletedAt: null,
98 latestUserMessageAt: null,
99 createdAt: at(-30 * DAY_MS),
100 updatedAt: at(-10 * DAY_MS),
101 archivedAt: null,
102 settledOverride: null,
103 settledAt: null,
104 snoozedUntil: null,
105 snoozedAt: null,
106 pinnedAt: null,
107 ...overrides,
108 };
110​
111describe("V2 storage cleanup eligibility", () => {
112 const candidate = () => shell({ branch: "feature", worktreePath: "/worktrees/feature" });
113​
114 it("allows an idle worktree and rejects the project checkout", () => {
115 expect(storageCleanupThreadIdle(candidate(), NOW_MS)).toBe(true);
116 expect(storageCleanupThreadIdle(shell(), NOW_MS)).toBe(false);
117 });
118​
119 it.each(["running", "starting", "preparing", "waiting", "queued"] as const)(
120 "retains a worktree while its thread is %s",
121 (status) => {
122 expect(storageCleanupThreadIdle(candidateWithStatus(status), NOW_MS)).toBe(false);
123 },
124 );
125​
126 it.each(["idle", "completed", "interrupted", "failed", "cancelled", "rolled_back"] as const)(
127 "allows cleanup once its thread is %s",
128 (status) => {
129 expect(storageCleanupThreadIdle(candidateWithStatus(status), NOW_MS)).toBe(true);
130 },
131 );
132​
133 it.each(["completed", "interrupted", "cancelled", "rolled_back"] as const)(
134 "retains %s while background work is pending",
135 (status) => {
136 expect(
137 storageCleanupThreadIdle(
138 {
139 ...candidateWithStatus(status),
140 pendingBackgroundTasks: [{ taskId: "task-1", kind: "command" }],
141 },
142 NOW_MS,
143 ),
144 ).toBe(false);
145 },
146 );
147​
148 it.each(["completed", "interrupted", "cancelled", "rolled_back"] as const)(
149 "retains %s while a runtime request is pending",
150 (status) => {
151 expect(
152 storageCleanupThreadIdle(
153 {
154 ...candidateWithStatus(status),
155 pendingRuntimeRequest: {
156 id: RuntimeRequestId.make("request-1"),
157 kind: "command",
158 createdAt: at(0),
159 },
160 },
161 NOW_MS,
162 ),
163 ).toBe(false);
164 },
165 );
166​
167 it("retains an active run even if the shell status is idle", () => {
168 expect(
169 storageCleanupThreadIdle({ ...candidate(), activeRunId: RunId.make("run") }, NOW_MS),
170 ).toBe(false);
171 });
172​
173 it("retains a queued prompt before the new run has been projected", () => {
174 expect(
175 storageCleanupThreadIdle({ ...candidate(), latestUserMessageAt: at(-1_000) }, NOW_MS),
176 ).toBe(false);
177 });
178​
179 it("uses V2 run activity instead of metadata refreshes for retention", () => {
180 const thread = candidate();
181 const runTime = at(-3 * DAY_MS);
182 expect(
183 storageCleanupActivityAt({ ...thread, latestRunCompletedAt: runTime, updatedAt: at(0) }),
184 ).toBe(DateTime.toEpochMillis(runTime));
185 });
186​
187 function candidateWithStatus(status: OrchestrationV2ThreadShell["status"]) {
188 return { ...candidate(), status };
189 }
190});
191​
192describe("merged pull request cleanup", () => {
193 const HEAD_SHA = "a".repeat(40);
194 const integrated = {
195 branch: "feature",
196 defaultBranch: "main",
197 headSha: HEAD_SHA,
198 integrated: true,
199 };
200 const squashed = { ...integrated, integrated: false };
201 const pullRequest = (
202 overrides: Partial<NonNullable<Parameters<typeof storageCleanupPullRequestMerged>[0]>> = {},
203 ) => ({
204 state: "merged" as const,
205 headRef: "feature",
206 baseRef: "main",
207 headSha: HEAD_SHA,
208 ...overrides,
209 });
210​
211 it("removes a worktree whose head reached the default branch through a merged pull request", () => {
212 expect(storageCleanupPullRequestMerged(pullRequest({ headSha: null }), integrated)).toBe(true);
213 });
214​
215 it("removes a squash-merged worktree when the pull request names its exact head", () => {
216 expect(storageCleanupPullRequestMerged(pullRequest(), squashed)).toBe(true);
217 });
218​
219 it.each([
220 ["has a later commit than the merged head", { headSha: "c".repeat(40) }],
221 ["was merged into a release branch", { baseRef: "release" }],
222 ["was merged into its stack parent", { baseRef: "stack-parent" }],
223 ["was merged without a reported head commit", { headSha: null }],
224 ["belongs to a different branch", { headRef: "other" }],
225 ["is still open", { state: "open" }],
226 ["was closed without merging", { state: "closed" }],
227 ] as const)("keeps a squash worktree whose pull request %s", (_name, overrides) => {
228 expect(storageCleanupPullRequestMerged(pullRequest(overrides), squashed)).toBe(false);
229 });
230​
231 it("keeps a worktree with no pull request, or one that is not merged", () => {
232 expect(storageCleanupPullRequestMerged(null, squashed)).toBe(false);
233 expect(storageCleanupPullRequestMerged(null, integrated)).toBe(false);
234 expect(storageCleanupPullRequestMerged(pullRequest({ state: "open" }), integrated)).toBe(false);
235 });
236});
237​
238const cleanupFixture = (
239 storageCleanup: StorageCleanupSettings = {
240 ...DEFAULT_SERVER_SETTINGS.storageCleanup,
241 worktreeAfterDays: 8,
242 worktreeOnDelete: true,
243 },
244) =>
245 Effect.gen(function* () {
246 const fs = yield* FileSystem.FileSystem;
247 const config = yield* ServerConfig.ServerConfig;
248 const git = yield* GitVcsDriver.GitVcsDriver;
249 const repo = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" });
250 const command = (cwd: string, args: string[]) =>
251 git.execute({ operation: "cleanup-test", cwd, args });
252 yield* command(repo, ["init", "-b", "main"]);
253 yield* command(repo, ["config", "user.email", "cleanup@example.test"]);
254 yield* command(repo, ["config", "user.name", "Cleanup test"]);
255 yield* fs.writeFileString(`${repo}/tracked.txt`, "original\n");
256 yield* fs.writeFileString(`${repo}/.gitignore`, ".env\ndist/\nnode_modules/\n");
257 yield* command(repo, ["add", "."]);
258 yield* command(repo, ["commit", "-m", "initial"]);
259 yield* fs.makeDirectory(config.worktreesDir, { recursive: true });
260 const worktree = `${config.worktreesDir}/feature`;
261 yield* command(repo, ["worktree", "add", "-b", "feature", worktree]);
262 // worktreeOnDelete lets domain events request sweeps once a test calls activate.
263 let settings: import("@t3tools/contracts").ServerSettings = {
264 ...DEFAULT_SERVER_SETTINGS,
265 storageCleanup,
266 };
267 let threads = [shell({ branch: "feature", worktreePath: worktree })];
268 let editBeforeRemoval = false;
269 let openSessionCwd: string | null = null;
270 let sessionLive = true;
271 let fullStatusCalls = 0;
272 let snapshotReads = 0;
273 let events: Stream.Stream<OrchestrationV2DomainEvent> = Stream.empty;
274 const activated = yield* Deferred.make<void>();
275 const context = yield* Layer.build(StorageCleanup.layer).pipe(
276 Effect.provideService(GitVcsDriver.GitVcsDriver, {
277 ...git,
278 execute: (input) =>
279 Effect.gen(function* () {
280 if (editBeforeRemoval && input.args.includes("remove"))
281 yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n");
282 return yield* git.execute(input);
283 }),
284 statusDetailsLocal: (...args) => {
285 fullStatusCalls++;
286 return git.statusDetailsLocal(...args);
287 },
288 }),
289 Effect.provideService(Settings.ServerSettingsService, {
290 getSettings: Effect.sync(() => settings),
291 subscribeChanges: Effect.succeed(Stream.empty),
292 } as unknown as Settings.ServerSettingsService["Service"]),
293 Effect.provideService(ProjectStore.ProjectStoreV2, {
294 listShells: () =>
295 Effect.succeed([{ id: ProjectId.make("project-1"), workspaceRoot: repo }]),
296 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
297 Effect.provideService(ProjectionStore.ProjectionStoreV2, {
298 getShellSnapshot: (input?: { location?: string }) =>
299 Effect.sync(() => {
300 snapshotReads++;
301 return { threads: input?.location === "archive" ? [] : threads };
302 }),
303 getThreadWorktreePaths: () =>
304 Effect.sync(() =>
305 threads.flatMap((thread) =>
306 thread.worktreePath === null
307 ? []
308 : [{ threadId: thread.id, worktreePath: thread.worktreePath }],
309 ),
310 ),
311 getThreadShell: (threadId: ThreadId) =>
312 Effect.sync(() => threads.find((thread) => thread.id === threadId) ?? null),
313 } as unknown as ProjectionStore.ProjectionStoreV2["Service"]),
314 Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, {
315 isLive: () => Effect.sync(() => sessionLive),
316 } as unknown as ProviderSessionManager.ProviderSessionManagerV2["Service"]),
317 Effect.provideService(Orchestrator.OrchestratorV2, {
318 streamDomainEvents: Stream.suspend(() => events),
319 } as unknown as Orchestrator.OrchestratorV2["Service"]),
320 Effect.provideService(SqlClient.SqlClient, ((strings: TemplateStringsArray) =>
321 Effect.sync(() =>
322 openSessionCwd !== null && strings.join("").includes("projection_provider_sessions")
323 ? [
324 {
325 payload_json: JSON.stringify({
326 id: "session-1",
327 driver: "codex",
328 providerInstanceId: "codex",
329 status: "ready",
330 cwd: openSessionCwd,
331 model: null,
332 capabilities: CodexProviderCapabilitiesV2,
333 createdAt: "2026-06-01T12:00:00.000Z",
334 updatedAt: "2026-06-01T12:00:00.000Z",
335 lastError: null,
336 }),
337 },
338 ]
339 : [],
340 )) as unknown as SqlClient.SqlClient),
341 Effect.provideService(GitManager.GitManager, {
342 invalidateStatus: () => Effect.void,
343 } as unknown as GitManager.GitManager["Service"]),
344 Effect.provideService(TerminalManager.TerminalManager, {
345 subscribeMetadata: () => Effect.succeed(() => {}),
346 } as unknown as TerminalManager.TerminalManager["Service"]),
347 Effect.provideService(ServerActivation, Deferred.await(activated)),
348 );
349 return {
350 service: Context.get(context, StorageCleanup.StorageCleanup),
351 repo,
352 editBeforeRemoval: () => {
353 editBeforeRemoval = true;
354 },
355 fs,
356 worktree,
357 config,
358 command,
359 enableFiles: () => {
360 settings = {
361 ...settings,
362 storageCleanup: {
363 ...settings.storageCleanup,
364 browserArtifactsAfterDays: 8,
365 logsAfterDays: 8,
366 },
367 };
368 },
369 setSettings: (next: Partial<typeof settings>) => {
370 settings = { ...settings, ...next };
371 },
372 setPolicy: (worktreeKeepWhen: WorktreeKeepWhen) => {
373 settings = {
374 ...settings,
375 storageCleanup: { ...settings.storageCleanup, worktreeKeepWhen },
376 };
377 },
378 disable: () => {
379 settings = {
380 ...settings,
381 storageCleanup: {
382 ...settings.storageCleanup,
383 worktreeAfterDays: null,
384 worktreeOnDelete: false,
385 },
386 };
387 },
388 setThreads: (next: typeof threads) => {
389 threads = next;
390 },
391 setSessionLive: (live: boolean) => {
392 sessionLive = live;
393 },
394 setOpenSessionCwd: (cwd: string | null) => {
395 openSessionCwd = cwd;
396 },
397 fullStatusCalls: () => fullStatusCalls,
398 snapshotReads: () => snapshotReads,
399 /** Starts the hourly sweep and the subscription to `domainEvents`, which wait until now. */
400 activate: (domainEvents: Stream.Stream<OrchestrationV2DomainEvent>) => {
401 events = domainEvents;
402 return Deferred.succeed(activated, undefined);
403 },
404 };
405 });
406/** The fixture, with the size walk of its worktree held until `resume` succeeds. */
407const pausedMeasurementFixture = (storageCleanup?: StorageCleanupSettings) =>
408 Effect.gen(function* () {
409 const fs = yield* FileSystem.FileSystem;
410 const measuring = yield* Deferred.make<void>();
411 const resume = yield* Deferred.make<void>();
412 let measuredPath: string | undefined;
413 const fixture = yield* cleanupFixture(storageCleanup).pipe(
414 Effect.provideService(FileSystem.FileSystem, {
415 ...fs,
416 readDirectory: (directory, options) =>
417 Effect.gen(function* () {
418 if (directory === measuredPath) {
419 yield* Deferred.succeed(measuring, undefined);
420 yield* Deferred.await(resume);
421 }
422 return yield* fs.readDirectory(directory, options);
423 }),
424 }),
425 );
426 measuredPath = yield* fs.realPath(fixture.worktree);
427 return { ...fixture, measuring, resume };
428 });
429const sessionUpdated = (
430 index: number,
431 status: OrchestrationV2ProviderSession["status"],
432): OrchestrationV2DomainEvent => ({
433 id: EventId.make(`event-${index}`),
434 type: "provider-session.updated",
435 threadId: ThreadId.make("thread-1"),
436 occurredAt: at(0),
437 payload: {
438 id: ProviderSessionId.make(`session-${index}`),
439 driver: ProviderDriverKind.make("codex"),
440 providerInstanceId: ProviderInstanceId.make("codex"),
441 status,
442 cwd: "/elsewhere",
443 model: null,
444 capabilities: CodexProviderCapabilitiesV2,
445 createdAt: at(0),
446 updatedAt: at(0),
447 lastError: null,
448 },
449});
450const cleanupTestLayer = GitVcsDriver.layer.pipe(
451 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "storage-cleanup-" })),
452 Layer.provideMerge(NodeServices.layer),
453);
454const runCleanupTest = <A, E>(
455 effect: Effect.Effect<
456 A,
457 E,
458 | FileSystem.FileSystem
459 | ServerConfig.ServerConfig
460 | GitVcsDriver.GitVcsDriver
461 | Path.Path
462 | Scope.Scope
463 >,
464) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped);
465​
466describe("storage cleanup reports and local file policies", () => {
467 it.live("measures nested regular files without following symlinks", () =>
468 runCleanupTest(
469 Effect.gen(function* () {
470 const { service, fs, worktree, setPolicy } = yield* cleanupFixture();
471 setPolicy("tracked-changes");
472 const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) =>
473 fs.stat(`${worktree}/${name}`).pipe(Effect.map((stat) => Number(stat.size))),
474 );
475 const outside = yield* fs.makeTempDirectoryScoped();
476 yield* fs.writeFileString(`${outside}/external`, "must not count");
477 yield* fs.makeDirectory(`${worktree}/node_modules/nested`, { recursive: true });
478 yield* fs.writeFileString(`${worktree}/node_modules/nested/file`, "count me");
479 yield* fs.symlink(outside, `${worktree}/node_modules/directory-link`);
480 yield* fs.symlink(`${outside}/external`, `${worktree}/node_modules/file-link`);
481 yield* fs.symlink(`${outside}/missing`, `${worktree}/node_modules/dangling-link`);
482 const report = yield* service.runNow;
483 const bytes = sizes.reduce((sum, size) => sum + size, 8);
484 expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes, files: null });
485 expect(report.bytesFreed).toBe(bytes);
486 expect(yield* fs.readFileString(`${outside}/external`)).toBe("must not count");
487 }),
488 ),
489 );
490 it.live("still removes a worktree when measuring its size fails", () =>
491 runCleanupTest(
492 Effect.gen(function* () {
493 const fs = yield* FileSystem.FileSystem;
494 const { service, worktree } = yield* cleanupFixture().pipe(
495 Effect.provideService(FileSystem.FileSystem, {
496 ...fs,
497 readDirectory: (directory) => fs.readDirectory(`${directory}/missing-directory`),
498 }),
499 );
500 const report = yield* service.runNow;
501 expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes: null, files: null });
502 expect(report.bytesFreed).toBe(0);
503 expect(yield* fs.exists(worktree)).toBe(false);
504 }),
505 ),
506 );
507 it.live.each([
508 [
509 "its thread starts",
510 (worktree: string) => [
511 shell({ branch: "feature", worktreePath: worktree, status: "running" }),
512 ],
513 ],
514 [
515 "another thread starts using it",
516 (worktree: string) => [
517 shell({ branch: "feature", worktreePath: worktree }),
518 shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }),
519 ],
520 ],
521 ] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) =>
522 runCleanupTest(
523 Effect.gen(function* () {
524 const fixture = yield* pausedMeasurementFixture();
525 const { fs, worktree } = fixture;
526 fixture.setPolicy("tracked-changes");
527 yield* fs.writeFileString(`${worktree}/notes.txt`, "untracked\n");
528 const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild);
529 yield* Deferred.await(fixture.measuring);
530 fixture.setThreads(threadsWhileMeasuring(worktree));
531 yield* Deferred.succeed(fixture.resume, undefined);
532 const report = yield* Fiber.join(cleanup);
533 expect(report.entries[0]).toMatchObject({
534 outcome: "kept",
535 reason: "Thread activity or shared worktree changed since check",
536 bytes: null,
537 });
538 expect(report.bytesFreed).toBe(0);
539 expect(yield* fs.exists(worktree)).toBe(true);
540 expect(yield* fs.readFileString(`${worktree}/notes.txt`)).toBe("untracked\n");
541 }),
542 ),
543 );
544 it.live("reads the thread snapshot once per sweep, not per worktree", () =>
545 runCleanupTest(
546 Effect.gen(function* () {
547 const { service, snapshotReads } = yield* cleanupFixture();
548 expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" });
549 expect(snapshotReads()).toBe(1);
550 }),
551 ),
552 );
553 it.live.each([
554 ["running", "ready", 1],
555 ["stopped", "error", 2],
556 ] as const)(
557 "session updates to %s or %s during a sweep make %i sweep(s) in total",
558 ([first, second, sweeps]) =>
559 runCleanupTest(
560 Effect.gen(function* () {
561 const fixture = yield* pausedMeasurementFixture();
562 const handled = yield* Deferred.make<void>();
563 // 20 updates arrive while the first automatic sweep measures the worktree.
564 yield* fixture.activate(
565 Stream.fromEffect(Deferred.await(fixture.measuring)).pipe(
566 Stream.flatMap(() => Stream.range(0, 19)),
567 Stream.map((index) => sessionUpdated(index, index % 2 === 0 ? first : second)),
568 Stream.concat(
569 Stream.fromEffect(Deferred.succeed(handled, undefined)).pipe(Stream.drain),
570 ),
571 ),
572 );
573 yield* Deferred.await(handled);
574 yield* Deferred.succeed(fixture.resume, undefined);
575 yield* fixture.service.drain;
576 // One snapshot read per sweep.
577 expect(fixture.snapshotReads()).toBe(sweeps);
578 }),
579 ),
580 );
581 it.live("does not measure a worktree kept for an open provider session", () =>
582 runCleanupTest(
583 Effect.gen(function* () {
584 const fs = yield* FileSystem.FileSystem;
585 const walked: Array<string> = [];
586 const fixture = yield* cleanupFixture().pipe(
587 Effect.provideService(FileSystem.FileSystem, {
588 ...fs,
589 readDirectory: (directory, options) => {
590 walked.push(directory);
591 return fs.readDirectory(directory, options);
592 },
593 }),
594 );
595 const root = yield* fs.realPath(fixture.worktree);
596 fixture.setOpenSessionCwd(fixture.worktree);
597 const kept = yield* fixture.service.runNow;
598 expect(kept.entries[0]).toMatchObject({
599 outcome: "kept",
600 reason: "Provider session is still open",
601 bytes: null,
602 });
603 expect(walked.filter((directory) => directory.startsWith(root))).toEqual([]);
604 // The stored session stays ready after its runtime was released.
605 fixture.setSessionLive(false);
606 const removed = yield* fixture.service.runNow;
607 expect(removed.entries[0]).toMatchObject({ outcome: "removed" });
608 expect(removed.entries[0]?.bytes).toBeGreaterThan(0);
609 expect(walked).toContain(root);
610 }),
611 ),
612 );
613 it.live("compares the checked-out branch without a full status", () =>
614 runCleanupTest(
615 Effect.gen(function* () {
616 const { service, fs, worktree, command, setThreads, fullStatusCalls } =
617 yield* cleanupFixture();
618 const changed = { outcome: "kept", reason: "Repository or branch changed" };
619 yield* command(worktree, ["checkout", "--detach"]);
620 expect((yield* service.runNow).entries[0]).toMatchObject(changed);
621 // A branch that has no commit yet is still a different branch.
622 yield* command(worktree, ["switch", "--orphan", "other"]);
623 expect((yield* service.runNow).entries[0]).toMatchObject(changed);
624 // Status output reserves a leading "(" for a detached HEAD.
625 yield* command(worktree, ["switch", "-c", "(feature)", "feature"]);
626 setThreads([shell({ branch: "(feature)", worktreePath: worktree })]);
627 expect((yield* service.runNow).entries[0]).toMatchObject(changed);
628 setThreads([shell({ branch: "feature", worktreePath: worktree })]);
629 // Tags named after the branch or HEAD make Git's short names ambiguous.
630 yield* command(worktree, ["tag", "feature", "feature"]);
631 // Newer Git refuses to create a tag named HEAD, but still reads one.
632 yield* command(worktree, ["update-ref", "refs/tags/HEAD", "refs/heads/feature"]);
633 yield* command(worktree, ["switch", "feature"]);
634 const index = (yield* command(worktree, ["rev-parse", "--git-path", "index"])).stdout;
635 yield* fs.writeFileString(`${index.trim()}.lock`, "");
636 const locked = (yield* service.runNow).entries[0];
637 expect(locked).toMatchObject({ outcome: "failed" });
638 expect(locked?.reason).toContain("Git index is locked");
639 yield* fs.remove(`${index.trim()}.lock`);
640 const gitFile = yield* fs.readFileString(`${worktree}/.git`);
641 yield* fs.writeFileString(`${worktree}/.git`, "gitdir: /missing-git-directory\n");
642 expect((yield* service.runNow).entries[0]).toMatchObject(changed);
643 yield* fs.writeFileString(`${worktree}/.git`, gitFile);
644 expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" });
645 expect(fullStatusCalls()).toBe(0);
646 }),
647 ),
648 );
649 it("decodes reports from servers without size fields", () => {
650 const report = decodeCleanupReport({
651 trigger: "manual",
652 startedAt: "2026-06-10T12:00:00.000Z",
653 finishedAt: "2026-06-10T12:00:01.000Z",
654 entries: [
655 {
656 kind: "worktree",
657 outcome: "removed",
658 reason: "Removed",
659 path: null,
660 threadId: null,
661 threadTitle: null,
662 },
663 ],
664 counts: { removed: 1, kept: 0, failed: 0 },
665 omittedCount: 0,
666 });
667 expect(report.bytesFreed).toBe(0);
668 expect(report.entries[0]).toMatchObject({ bytes: null, files: null });
669 });
670 it.live.each([
671 ["any-local-files", ".env", "kept"],
672 ["uncommitted-changes", ".env", "removed"],
673 ["tracked-changes", ".env", "removed"],
674 ["any-local-files", "notes.txt", "kept"],
675 ["uncommitted-changes", "notes.txt", "kept"],
676 ["tracked-changes", "notes.txt", "removed"],
677 ["any-local-files", "tracked.txt", "kept"],
678 ["uncommitted-changes", "tracked.txt", "kept"],
679 ["tracked-changes", "tracked.txt", "kept"],
680 ] as const)("applies %j", ([policy, file, outcome]) =>
681 runCleanupTest(
682 Effect.gen(function* () {
683 const { service, fs, worktree, setPolicy } = yield* cleanupFixture();
684 setPolicy(policy);
685 expect(yield* service.latestReport).toBeNull();
686 yield* fs.writeFileString(`${worktree}/${file}`, "local data\n");
687 const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) =>
688 fs.stat(`${worktree}/${name}`).pipe(Effect.map((stat) => Number(stat.size))),
689 );
690 const bytes = sizes.reduce((sum, size) => sum + size, 0);
691 const report = yield* service.runNow;
692 yield* service.drain;
693 expect(report.trigger).toBe("manual");
694 expect(report.entries.filter((entry) => entry.kind === "worktree")).toMatchObject([
695 {
696 outcome,
697 path: worktree,
698 threadId: "thread-1",
699 threadTitle: "Thread",
700 bytes: outcome === "removed" ? bytes : null,
701 files: null,
702 },
703 ]);
704 expect(report.bytesFreed).toBe(outcome === "removed" ? bytes : 0);
705 expect(yield* fs.exists(worktree)).toBe(outcome === "kept");
706 expect(yield* service.latestReport).toEqual(report);
707 if (outcome === "kept")
708 expect(report.entries[0]?.reason).toContain(
709 file === ".env" ? "ignored files (.env)" : "uncommitted changes (1 file)",
710 );
711 }),
712 ),
713 );
714 it.live("preserves tracked edits written after the final status check", () =>
715 runCleanupTest(
716 Effect.gen(function* () {
717 const fixture = yield* cleanupFixture();
718 fixture.setPolicy("tracked-changes");
719 fixture.editBeforeRemoval();
720 yield* fixture.fs.writeFileString(`${fixture.worktree}/notes.txt`, "untracked\n");
721 const report = yield* fixture.service.runNow;
722 expect(report.entries[0]).toMatchObject({ outcome: "failed", bytes: null, files: null });
723 expect(report.bytesFreed).toBe(0);
724 expect(report.entries[0]?.reason).toContain("contains modified or untracked files");
725 expect(yield* fixture.fs.readFileString(`${fixture.worktree}/tracked.txt`)).toBe(
726 "late edit\n",
727 );
728 expect(yield* fixture.fs.exists(`${fixture.worktree}/notes.txt`)).toBe(false);
729 }),
730 ),
731 );
732 it.live("streams the current report and subsequent runs", () =>
733 runCleanupTest(
734 Effect.gen(function* () {
735 const { service } = yield* cleanupFixture();
736 const reports = yield* service.reports.pipe(
737 Stream.take(2),
738 Stream.tap((report) => (report === null ? service.runNow : Effect.void)),
739 Stream.runCollect,
740 );
741 expect(reports[0]).toBeNull();
742 expect(reports[1]).toEqual(yield* service.latestReport);
743 expect(reports[1]?.counts).toEqual({ removed: 1, kept: 0, failed: 0 });
744 }),
745 ),
746 );
747 it.live("caps entries while preserving totals and prioritizing removals", () =>
748 runCleanupTest(
749 Effect.gen(function* () {
750 const { service, fs, worktree, setThreads } = yield* cleanupFixture();
751 const threads = [];
752 for (let i = 0; i < 205; i++) {
753 const worktreePath = `${worktree}-${i}`;
754 yield* fs.makeDirectory(worktreePath);
755 threads.push(
756 shell({
757 id: ThreadId.make(`thread-${i + 2}`),
758 branch: "feature",
759 worktreePath,
760 status: "running",
761 }),
762 );
763 }
764 threads.push(shell({ branch: "feature", worktreePath: worktree }));
765 setThreads(threads);
766 const report = yield* service.runNow;
767 expect(report.entries).toHaveLength(200);
768 expect(report.omittedCount).toBe(6);
769 expect(report.counts).toEqual({ removed: 1, kept: 205, failed: 0 });
770 expect(report.entries[0]?.outcome).toBe("removed");
771 expect(report.entries[0]?.bytes).toBeGreaterThan(0);
772 expect(report.bytesFreed).toBe(report.entries[0]?.bytes);
773 }),
774 ),
775 );
776 it.live("keeps staged edits in tracked-only mode", () =>
777 runCleanupTest(
778 Effect.gen(function* () {
779 const { service, fs, worktree, setPolicy, command } = yield* cleanupFixture();
780 setPolicy("tracked-changes");
781 yield* fs.writeFileString(`${worktree}/tracked.txt`, "staged\n");
782 yield* command(worktree, ["add", "tracked.txt"]);
783 expect((yield* service.runNow).entries[0]).toMatchObject({
784 outcome: "kept",
785 reason: "Has uncommitted changes (1 file)",
786 });
787 expect(yield* fs.exists(worktree)).toBe(true);
788 }),
789 ),
790 );
791 it.live(
792 "reports shared and running worktrees but omits disabled rules and missing directories",
793 () =>
794 runCleanupTest(
795 Effect.gen(function* () {
796 const fixture = yield* cleanupFixture();
797 const { service, fs, worktree, setThreads } = fixture;
798 setThreads([shell({ branch: "feature", worktreePath: worktree, status: "running" })]);
799 expect((yield* service.runNow).entries[0]?.reason).toContain("Thread is running");
800 setThreads([
801 shell({ branch: "feature", worktreePath: worktree }),
802 shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }),
803 ]);
804 expect((yield* service.runNow).entries[0]?.reason).toBe("Shared by 2 threads");
805 fixture.disable();
806 expect((yield* service.runNow).entries).toEqual([]);
807 yield* fs.remove(worktree, { recursive: true });
808 expect(
809 (yield* service.runNow).entries.filter((entry) => entry.kind === "worktree"),
810 ).toEqual([]);
811 }),
812 ),
813 );
814 it.live("serializes concurrent requests and returns each run's report", () =>
815 runCleanupTest(
816 Effect.gen(function* () {
817 const { service } = yield* cleanupFixture();
818 const reports = yield* Effect.all([service.runNow, service.runNow], {
819 concurrency: "unbounded",
820 });
821 yield* service.drain;
822 expect(
823 reports.flatMap((report) => report.entries).filter((entry) => entry.kind === "worktree"),
824 ).toMatchObject([{ outcome: "removed" }]);
825 expect(yield* service.latestReport).toEqual(reports[1]);
826 }),
827 ),
828 );
829 it.live("aggregates expired artifacts and rotated logs while retaining current logs", () =>
830 runCleanupTest(
831 Effect.gen(function* () {
832 const { service, fs, config, enableFiles, disable } = yield* cleanupFixture();
833 disable();
834 enableFiles();
835 yield* fs.makeDirectory(config.browserArtifactsDir, { recursive: true });
836 yield* fs.makeDirectory(config.logsDir, { recursive: true });
837 for (const name of ["one.png", "two.webm"]) {
838 const file = config.browserArtifactsDir + "/" + name;
839 yield* fs.writeFileString(file, "capture");
840 yield* fs.utimes(file, 1, 1);
841 }
842 for (const name of ["server.log.1", "server.log.2", "server.log"]) {
843 const file = config.logsDir + "/" + name;
844 yield* fs.writeFileString(file, "log");
845 yield* fs.utimes(file, 1, 1);
846 }
847 const report = yield* service.runNow;
848 expect(report.entries.filter((entry) => entry.kind !== "worktree")).toMatchObject([
849 {
850 kind: "browser-artifacts",
851 outcome: "removed",
852 reason: "Removed 2 browser artifacts",
853 bytes: 14,
854 files: 2,
855 },
856 {
857 kind: "logs",
858 outcome: "removed",
859 reason: "Removed 2 rotated logs",
860 bytes: 6,
861 files: 2,
862 },
863 ]);
864 expect(report.bytesFreed).toBe(20);
865 expect(yield* fs.readDirectory(config.browserArtifactsDir)).toEqual([]);
866 expect(yield* fs.exists(config.logsDir + "/server.log")).toBe(true);
867 expect(yield* fs.exists(config.logsDir + "/server.log.1")).toBe(false);
868 expect(yield* fs.exists(config.logsDir + "/server.log.2")).toBe(false);
869 }),
870 ),
871 );
872 it.live("reports git failures without aborting the remaining categories", () =>
873 runCleanupTest(
874 Effect.gen(function* () {
875 const { service, worktree, command, enableFiles } = yield* cleanupFixture();
876 enableFiles();
877 yield* command(worktree, ["worktree", "lock", worktree]);
878 const report = yield* service.runNow;
879 expect(report.entries[0]).toMatchObject({ outcome: "failed" });
880 expect(report.entries[0]?.reason).toContain("git worktree remove: fatal:");
881 expect(report.entries.map((entry) => entry.kind)).toEqual([
882 "worktree",
883 "browser-artifacts",
884 "logs",
885 ]);
886 }),
887 ),
888 );
889});
890​
891describe("settled worktree retention", () => {
892 it.effect.each([
893 "immediate",
894 "settle-script",
895 "expired",
896 "boundary",
897 "wait",
898 "recent-update",
899 "active",
900 "dirty",
901 "project-off",
902 "project-custom",
903 "inactive-settling",
904 ] as const)("applies retention and safety checks (%s)", (scenario) =>
905 Effect.gen(function* () {
906 yield* TestClock.setTime(NOW_MS);
907 const fixture = yield* cleanupFixture();
908 const days = ["wait", "boundary", "expired", "recent-update"].includes(scenario) ? 8 : 0;
909 const rules = {
910 ...DEFAULT_SERVER_SETTINGS.storageCleanup,
911 worktreeSettledAfterDays:
912 scenario === "project-custom" || scenario === "inactive-settling" ? null : days,
913 // Another rule must not bypass the settle-script grace either.
914 worktreeAfterDays: scenario === "inactive-settling" ? 1 : null,
915 };
916 fixture.setSettings({
917 storageCleanup: rules,
918 projectSettingsOverrides: {
919 [ProjectId.make("project-1")]:
920 scenario === "project-off"
921 ? { worktreeCleanup: { mode: "off" } }
922 : scenario === "project-custom"
923 ? {
924 worktreeCleanup: {
925 mode: "custom",
926 rules: { ...rules, worktreeSettledAfterDays: 0 },
927 },
928 }
929 : {},
930 },
931 });
932 const thread = shell({
933 branch: "feature",
934 worktreePath: fixture.worktree,
935 settledAt:
936 scenario === "active"
937 ? null
938 : at(
939 scenario === "expired" ||
940 scenario === "recent-update" ||
941 scenario === "inactive-settling"
942 ? -20 * DAY_MS
943 : scenario === "boundary"
944 ? -8 * DAY_MS
945 : scenario === "wait"
946 ? -8 * DAY_MS + 1
947 : scenario === "settle-script"
948 ? 0
949 : -60_000,
950 ),
951 updatedAt: at(
952 scenario === "recent-update" ||
953 scenario === "settle-script" ||
954 scenario === "inactive-settling"
955 ? 0
956 : -10 * DAY_MS,
957 ),
958 });
959 fixture.setThreads([thread]);
960 if (scenario === "dirty")
961 yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "edit\n");
962 const report = yield* fixture.service.runNow;
963 const removed = ["immediate", "expired", "boundary", "project-custom"].includes(scenario);
964 expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed);
965 expect(report.counts.removed).toBe(removed ? 1 : 0);
966 if (scenario !== "project-off") {
967 const reason =
968 scenario === "active"
969 ? "Not settled"
970 : scenario === "wait"
971 ? "Settled for 7 of 8 days"
972 : ["settle-script", "recent-update", "inactive-settling"].includes(scenario)
973 ? "Settled moments ago"
974 : scenario === "dirty"
975 ? "Has uncommitted changes (1 file)"
976 : `Settled for ${scenario === "expired" ? 20 : scenario === "boundary" ? 8 : 0} days`;
977 expect(report.entries[0]).toMatchObject({ outcome: removed ? "removed" : "kept", reason });
978 }
979 expect(thread.branch).toBe("feature");
980 expect(
981 (yield* fixture.command(fixture.repo, ["rev-parse", "--verify", "refs/heads/feature"]))
982 .exitCode,
983 ).toBe(0);
984 }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
985 );
986});
987​
988describe("settled worktree rechecks", () => {
989 it.live.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])(
990 "keeps a checkout changed during measurement (%j)",
991 (change) =>
992 runCleanupTest(
993 Effect.gen(function* () {
994 const fixture = yield* pausedMeasurementFixture();
995 const thread = shell({
996 branch: "feature",
997 worktreePath: fixture.worktree,
998 settledAt: at(0),
999 });
1000 fixture.setSettings({
1001 storageCleanup: {
1002 ...DEFAULT_SERVER_SETTINGS.storageCleanup,
1003 worktreeSettledAfterDays: 0,
1004 },
1005 });
1006 fixture.setThreads([thread]);
1007 const run = yield* fixture.service.runNow.pipe(Effect.forkChild);
1008 yield* Deferred.await(fixture.measuring);
1009 fixture.setThreads([{ ...thread, ...change }]);
1010 yield* Deferred.succeed(fixture.resume, undefined);
1011 const report = yield* Fiber.join(run);
1012 expect(report.entries[0]?.reason).toBe(
1013 "Thread activity or shared worktree changed since check",
1014 );
1015 expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
1016 }),
1017 ),
1018 );
1019});
1020​
1021it.live("keeps saved usage data when removing a settled checkout", () =>
1022 runCleanupTest(
1023 Effect.gen(function* () {
1024 const fixture = yield* cleanupFixture();
1025 fixture.setSettings({
1026 storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0 },
1027 });
1028 fixture.setThreads([
1029 shell({ branch: "feature", worktreePath: fixture.worktree, settledAt: at(0) }),
1030 ]);
1031 yield* fixture.fs.makeDirectory(fixture.config.stateDir, { recursive: true });
1032 const cachePath = `${fixture.config.stateDir}/${SCAN_CACHE_FILE_NAME}`;
1033 const savedUsage = JSON.stringify({ tokens: 12345, cost: 1.25 });
1034 yield* fixture.fs.writeFileString(cachePath, savedUsage);
1035 expect((yield* fixture.service.runNow).counts.removed).toBe(1);
1036 expect(yield* fixture.fs.readFileString(cachePath)).toBe(savedUsage);
1037 }),
1038 ),
1040​
1041it.live.each(["thread.settled", "stopped", "ready"] as const)(
1042 "leaves settled cleanup to the regular sweeps after %s",
1043 (trigger) =>
1044 runCleanupTest(
1045 Effect.gen(function* () {
1046 const fixture = yield* pausedMeasurementFixture({
1047 ...DEFAULT_SERVER_SETTINGS.storageCleanup,
1048 worktreeSettledAfterDays: 0,
1049 });
1050 fixture.setSettings({
1051 storageCleanup: {
1052 ...DEFAULT_SERVER_SETTINGS.storageCleanup,
1053 worktreeSettledAfterDays: 0,
1054 },
1055 });
1056 const thread = shell({
1057 branch: "feature",
1058 worktreePath: fixture.worktree,
1059 settledAt: at(0),
1060 });
1061 fixture.setThreads([thread]);
1062 const handled = yield* Deferred.make<void>();
1063 yield* fixture.activate(
1064 Stream.fromEffect(Deferred.await(fixture.measuring)).pipe(
1065 Stream.flatMap(() => Stream.range(0, 19)),
1066 Stream.map((index): OrchestrationV2DomainEvent =>
1067 trigger === "thread.settled"
1068 ? {
1069 id: EventId.make(`settled-${index}`),
1070 type: "thread.settled",
1071 threadId: thread.id,
1072 occurredAt: at(0),
1073 payload: { ...thread, lastVisitedAt: null },
1075 : sessionUpdated(index, trigger),
1076 ),
1077 Stream.concat(
1078 Stream.fromEffect(Deferred.succeed(handled, undefined)).pipe(Stream.drain),
1079 ),
1080 ),
1081 );
1082 yield* Deferred.await(handled);
1083 yield* Deferred.succeed(fixture.resume, undefined);
1084 yield* fixture.service.drain;
1085 expect(fixture.snapshotReads()).toBe(1);
1086 }),
1087 ),