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