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