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

storageCleanup.test.ts

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