import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Context from "effect/Context"; import type * as Digest from "effect/crypto/Digest"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Path from "effect/Path"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { SCAN_CACHE_FILE_NAME } from "./usage/usageScanCache.ts"; import { TestClock } from "effect/testing"; import * as SqlClient from "effect/sql/SqlClient"; import * as Sqlite from "./persistence/Sqlite.ts"; import { checkpointRefForScopeOrdinal } from "./orchestration-v2/CheckpointService.ts"; import { DEFAULT_SERVER_SETTINGS, type WorktreeKeepWhen, type StorageCleanupSettings, type TerminalSummary, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ServerConfig from "./config.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as CheckpointCaptureIndex from "./vcs/checkpointCaptureIndex.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import * as TaskFolders from "./workspace/TaskFolders.ts"; import { layerTaskFoldersWithGit } from "./workspace/TaskFolders.testkit.ts"; import * as GitManager from "./git/GitManager.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as Settings from "./serverSettings.ts"; import * as PendingSettleScripts from "./orchestration-v2/PendingSettleScripts.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { CodexProviderCapabilitiesV2 } from "./orchestration-v2/Adapters/CodexAdapterV2.ts"; import { ServerActivation } from "./serverActivation.ts"; import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import { describe, expect, it } from "@effect/vitest"; import { CheckpointScopeId, EventId, ProjectId, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, RunId, RuntimeRequestId, ThreadId, type OrchestrationV2DomainEvent, type OrchestrationV2ServerCommand, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { storageCleanupActivityAt, storageCleanupPullRequestMerged, storageCleanupThreadIdle, } from "./storageCleanup.ts"; const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z"); const DAY_MS = 24 * 60 * 60 * 1_000; function at(offsetMs: number): DateTime.Utc { return DateTime.makeUnsafe(NOW_MS + offsetMs); } function shell(overrides: Partial = {}): OrchestrationV2ThreadShell { return { id: ThreadId.make("thread-1"), projectId: ProjectId.make("project-1"), title: "Thread", providerInstanceId: ProviderInstanceId.make("codex"), modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", worktreePath: null, activeProviderThreadId: null, lineage: { rootThreadId: ThreadId.make("thread-1"), parentThreadId: null, relationshipToParent: null, }, forkedFrom: null, createdBy: "user", creationSource: "web", activeRunId: null, latestVisibleMessage: null, hasActionableProposedPlan: false, itemCount: 0, visibleItemCount: 0, lastVisitedAt: null, deletedAt: null, branch: null, linkedPullRequest: null, status: "idle", activityRunStatus: null, pendingRuntimeRequest: null, pendingBackgroundTasks: [], latestRunId: null, latestRunRequestedAt: null, latestRunStartedAt: null, latestRunCompletedAt: null, latestUserMessageAt: null, createdAt: at(-30 * DAY_MS), updatedAt: at(-10 * DAY_MS), archivedAt: null, settledOverride: null, settledAt: null, snoozedUntil: null, snoozedAt: null, pinnedAt: null, ...overrides, }; } describe("V2 storage cleanup eligibility", () => { const candidate = () => shell({ branch: "feature", worktreePath: "/worktrees/feature" }); it("allows an idle worktree and rejects the project checkout", () => { expect(storageCleanupThreadIdle(candidate(), NOW_MS, DEFAULT_SERVER_SETTINGS)).toBe(true); expect(storageCleanupThreadIdle(shell(), NOW_MS, DEFAULT_SERVER_SETTINGS)).toBe(false); }); it.each(["running", "starting", "preparing", "waiting", "queued"] as const)( "retains a worktree while its thread is %s", (status) => { expect( storageCleanupThreadIdle(candidateWithStatus(status), NOW_MS, DEFAULT_SERVER_SETTINGS), ).toBe(false); }, ); it.each(["completed", "interrupted", "cancelled", "rolled_back"] as const)( "retains %s while background work is pending", (status) => { expect( storageCleanupThreadIdle( { ...candidateWithStatus(status), pendingBackgroundTasks: [{ taskId: "task-1", kind: "command" }], }, NOW_MS, DEFAULT_SERVER_SETTINGS, ), ).toBe(false); }, ); it.each(["completed", "interrupted", "cancelled", "rolled_back"] as const)( "retains %s while a runtime request is pending", (status) => { expect( storageCleanupThreadIdle( { ...candidateWithStatus(status), pendingRuntimeRequest: { id: RuntimeRequestId.make("request-1"), kind: "command", createdAt: at(0), }, }, NOW_MS, DEFAULT_SERVER_SETTINGS, ), ).toBe(false); }, ); it("retains an active run even if the shell status is idle", () => { expect( storageCleanupThreadIdle( { ...candidate(), activeRunId: RunId.make("run") }, NOW_MS, DEFAULT_SERVER_SETTINGS, ), ).toBe(false); }); it("retains a queued prompt before the new run has been projected", () => { expect( storageCleanupThreadIdle( { ...candidate(), latestUserMessageAt: at(-1_000) }, NOW_MS, DEFAULT_SERVER_SETTINGS, ), ).toBe(false); }); it.each([ { name: "snoozed until a future reset", snooze: true, resetIn: DAY_MS, idle: false }, { name: "set to auto-resume", autoResume: true, resetIn: DAY_MS, idle: false }, { name: "with recovery turned off", resetIn: DAY_MS, idle: true }, { name: "auto-resuming after the reset", autoResume: true, resetIn: -1_000, idle: false }, { name: "snoozed past its reset", snooze: true, resetIn: -1_000, idle: true }, { name: "settled with an auto-resume pending", autoResume: true, settled: true, resetIn: -1_000, idle: true, }, { name: "not yet armed by the recovery worker", armed: false, resetIn: DAY_MS, idle: false }, { name: "not yet armed, auto-resume after reset", armed: false, autoResumeSetting: true, resetIn: -1_000, idle: false, }, { name: "never armed because its reset is days overdue", armed: false, autoResumeSetting: true, resetIn: -5 * DAY_MS, idle: true, }, { name: "not armed with recovery settings off", armed: false, settingsOff: true, resetIn: DAY_MS, idle: true, }, ])( "treats a usage-limited thread $name as idle: $idle", ({ autoResume = false, snooze = false, armed = true, autoResumeSetting = false, settled, settingsOff, resetIn, idle, }) => { const runId = RunId.make("run-1"); const resetAt = DateTime.formatIso(at(resetIn)); expect( storageCleanupThreadIdle( { ...candidateWithStatus("failed"), latestRunId: runId, lastErrorClass: "usage_limit", usageLimitResetAt: resetAt, settledOverride: settled ? "settled" : null, limitRecovery: armed ? { runId, resetAt, autoResume, snooze } : null, }, NOW_MS, { autoResumeLimitedThreads: autoResumeSetting, snoozeLimitedThreads: !settingsOff }, ), ).toBe(idle); }, ); it("uses V2 run activity instead of metadata refreshes for retention", () => { const thread = candidate(); const runTime = at(-3 * DAY_MS); expect( storageCleanupActivityAt({ ...thread, latestRunCompletedAt: runTime, updatedAt: at(0) }), ).toBe(DateTime.toEpochMillis(runTime)); }); function candidateWithStatus(status: OrchestrationV2ThreadShell["status"]) { return { ...candidate(), status }; } }); describe("merged pull request cleanup", () => { const HEAD_SHA = "a".repeat(40); const integrated = { branch: "feature", defaultBranch: "main", headSha: HEAD_SHA, integrated: true, }; const squashed = { ...integrated, integrated: false }; const pullRequest = ( overrides: Partial[0]>> = {}, ) => ({ state: "merged" as const, headRef: "feature", baseRef: "main", headSha: HEAD_SHA, ...overrides, }); it("removes a worktree whose head reached the default branch through a merged pull request", () => { expect(storageCleanupPullRequestMerged(pullRequest({ headSha: null }), integrated)).toBe(true); }); it("removes a squash-merged worktree when the pull request names its exact head", () => { expect(storageCleanupPullRequestMerged(pullRequest(), squashed)).toBe(true); }); it.each([ ["has a later commit than the merged head", { headSha: "c".repeat(40) }], ["was merged into a release branch", { baseRef: "release" }], ["was merged into its stack parent", { baseRef: "stack-parent" }], ["was merged without a reported head commit", { headSha: null }], ["belongs to a different branch", { headRef: "other" }], ["is still open", { state: "open" }], ["was closed without merging", { state: "closed" }], ] as const)("keeps a squash worktree whose pull request %s", (_name, overrides) => { expect(storageCleanupPullRequestMerged(pullRequest(overrides), squashed)).toBe(false); }); it("keeps a worktree with no pull request, or one that is not merged", () => { expect(storageCleanupPullRequestMerged(null, squashed)).toBe(false); expect(storageCleanupPullRequestMerged(null, integrated)).toBe(false); expect(storageCleanupPullRequestMerged(pullRequest({ state: "open" }), integrated)).toBe(false); }); }); const allocatedBytes = (fs: FileSystem.FileSystem, file: string) => fs.stat(file).pipe( Effect.map((stat) => Option.getOrElse( Option.map(stat.blocks, (blocks) => Number(blocks) * 512), () => Number(stat.size), ), ), ); const cleanupFixture = ( storageCleanup: StorageCleanupSettings = { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: 8, worktreeOnDelete: true, }, sqlOverride?: SqlClient.SqlClient, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; const git = yield* GitVcsDriver.GitVcsDriver; const repo = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" })); const command = (cwd: string, args: string[]) => git.execute({ operation: "cleanup-test", cwd, args }); yield* command(repo, ["init", "-b", "main"]); yield* command(repo, ["config", "user.email", "cleanup@example.test"]); yield* command(repo, ["config", "user.name", "Cleanup test"]); yield* fs.writeFileString(`${repo}/tracked.txt`, "original\n"); yield* fs.writeFileString(`${repo}/.gitignore`, ".env\ndist/\nnode_modules/\n"); yield* command(repo, ["add", "."]); yield* command(repo, ["commit", "-m", "initial"]); yield* fs.makeDirectory(config.worktreesDir, { recursive: true }); const worktree = `${config.worktreesDir}/feature`; yield* command(repo, ["worktree", "add", "-b", "feature", worktree]); let settings: import("@t3tools/contracts").ServerSettings = { ...DEFAULT_SERVER_SETTINGS, storageCleanup, }; let threads = [shell({ branch: "feature", worktreePath: worktree })]; let deletedThreads: OrchestrationV2ThreadShell[] = []; let storedWorktreePaths: string[] = [worktree]; let projectRoots = [repo]; let editBeforeRemoval = false; let pendingSettleThreadIds: ReadonlyArray = []; let openSessionCwd: string | null = null; let sessionLive = true; let sessionLiveChecks = 0; let onLiveCheck: Effect.Effect = Effect.void; let outboxStatus: string | null = null; let scheduledThreadIds: string[] = []; let branchPullRequests: Record = {}; let fullStatusCalls = 0; let statusCommands = 0; let gitInspections = 0; const worktreeListCalls: Array = []; let snapshotReads = 0; let terminals: TerminalSummary[] = []; let taskFolders: Pick = { find: () => Effect.succeed(null), remove: () => Effect.succeed({ removed: [], kept: [] }), }; let events: Stream.Stream = Stream.empty; const activated = yield* Deferred.make(); const context = yield* Layer.build(StorageCleanup.layer).pipe( Effect.provideService(GitVcsDriver.GitVcsDriver, { ...git, execute: (input) => Effect.gen(function* () { gitInspections++; if (input.args[0] === "status") statusCommands++; // Before Git's own clean check: inside `git worktree remove`, or on // Windows the same status check the removal makes before deleting. if ( editBeforeRemoval && (input.args.includes("remove") || input.args.includes("--porcelain")) ) yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n"); return yield* git.execute(input); }), statusDetailsLocal: (...args) => { fullStatusCalls++; return git.statusDetailsLocal(...args); }, listWorktreePaths: (cwd) => { worktreeListCalls.push(cwd); return git.listWorktreePaths(cwd); }, }), Effect.provideService(Settings.ServerSettingsService, { getSettings: Effect.sync(() => settings), subscribeChanges: Effect.succeed(Stream.empty), } as unknown as Settings.ServerSettingsService["Service"]), Effect.provideService(ProjectStore.ProjectStoreV2, { list: () => Effect.sync(() => projectRoots.map((workspaceRoot) => ({ workspaceRoot }))), listShells: () => Effect.sync(() => projectRoots.map((workspaceRoot, index) => ({ id: ProjectId.make(`project-${index + 1}`), workspaceRoot, })), ), } as unknown as ProjectStore.ProjectStoreV2["Service"]), Effect.provideService(ProjectionStore.ProjectionStoreV2, { getShellSnapshot: (input?: { location?: string }) => Effect.sync(() => { snapshotReads++; const visible = threads.filter((thread) => thread.deletedAt === null); return { threads: input?.location === "archive" ? [] : visible.filter((thread) => thread.archivedAt === null), archivedThreads: input?.location === "active" ? [] : visible.filter((thread) => thread.archivedAt !== null), }; }), getThreadWorktreePaths: (input?: { includeArchived?: boolean }) => Effect.sync(() => threads.flatMap((thread) => thread.deletedAt === null && (input?.includeArchived === true || thread.archivedAt === null) && thread.worktreePath !== null ? [{ threadId: thread.id, worktreePath: thread.worktreePath }] : [], ), ), getThreadShell: (threadId: ThreadId) => Effect.sync(() => threads.find((thread) => thread.id === threadId) ?? null), } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), Effect.provideService(ThreadManagement.ThreadManagementService, { getShellSnapshot: (input?: { threadIds?: ReadonlyArray }) => Effect.sync(() => ({ threads: threads.filter((thread) => input?.threadIds?.includes(thread.id) ?? true), archivedThreads: [], })), dispatch: (command: OrchestrationV2ServerCommand) => Effect.sync(() => { if (command.type === "thread.metadata.update" && command.branch != null) { const branch = command.branch; threads = threads.map((thread) => thread.id === command.threadId && thread.branch === command.expectedBranch ? { ...thread, branch } : thread, ); } return { sequence: 0, storedEvents: [] }; }), } as unknown as ThreadManagement.ThreadManagementService["Service"]), Effect.provideService(GitWorkflowService.GitWorkflowService, { currentBranch: (cwd: string) => command(cwd, ["branch", "--show-current"]).pipe( Effect.map((result) => result.stdout.trim() || null), ), } as unknown as GitWorkflowService.GitWorkflowService["Service"]), Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, { isLive: () => Effect.sync(() => { sessionLiveChecks++; return sessionLive; }).pipe(Effect.tap(() => Effect.suspend(() => onLiveCheck))), } as unknown as ProviderSessionManager.ProviderSessionManagerV2["Service"]), Effect.provideService(Orchestrator.OrchestratorV2, { streamDomainEvents: Stream.suspend(() => events), } as unknown as Orchestrator.OrchestratorV2["Service"]), Effect.provideService( SqlClient.SqlClient, sqlOverride ?? (((strings: TemplateStringsArray) => Effect.sync(() => strings.join("").includes("retained_checkpoint_threads") ? [] : openSessionCwd !== null && strings.join("").includes("projection_provider_sessions") ? [ { payload_json: JSON.stringify({ id: "session-1", driver: "codex", providerInstanceId: "codex", status: "ready", cwd: openSessionCwd, model: null, capabilities: CodexProviderCapabilitiesV2, createdAt: "2026-06-01T12:00:00.000Z", updatedAt: "2026-06-01T12:00:00.000Z", lastError: null, }), }, ] : outboxStatus !== null && strings.join("").includes("orchestration_v2_effect_outbox") ? [{ status: outboxStatus }] : strings.join("").includes("deleted_at IS NOT NULL") ? deletedThreads.map((thread) => ({ payload_json: JSON.stringify(thread), workspaceRoot: repo, })) : strings.join("").includes('AS "worktreePath"') ? [ ...threads.flatMap((thread) => thread.worktreePath ?? []), ...storedWorktreePaths, ].map((worktreePath) => ({ worktreePath })) : strings.join("").includes("scheduled_tasks") ? scheduledThreadIds.map((threadId) => ({ threadId })) : [], )) as unknown as SqlClient.SqlClient), ), Effect.provideService(GitManager.GitManager, { invalidateStatus: () => Effect.void, branchPullRequest: (input: { branch: string }) => Effect.sync(() => branchPullRequests[input.branch] ?? null), } as unknown as GitManager.GitManager["Service"]), Effect.provideService(TerminalManager.TerminalManager, { listMetadata: Effect.sync(() => terminals), } as unknown as TerminalManager.TerminalManager["Service"]), Effect.provideService(PendingSettleScripts.PendingSettleScripts, { has: (threadId) => pendingSettleThreadIds.includes(threadId), track: () => (effect) => effect, }), Effect.provideService(ServerActivation, Deferred.await(activated)), Effect.provideService(TaskFolders.TaskFolders, { find: (target: string) => taskFolders.find(target), remove: (input: Parameters[0]) => taskFolders.remove(input), } as unknown as TaskFolders.TaskFolders["Service"]), ); return { service: Context.get(context, StorageCleanup.StorageCleanup), repo, setTaskFolders: (service: typeof taskFolders) => { taskFolders = service; }, setTerminals: (next: TerminalSummary[]) => Effect.sync(() => { terminals = next; }), editBeforeRemoval: () => { editBeforeRemoval = true; }, setPendingSettleScripts: (threadIds: ReadonlyArray) => { pendingSettleThreadIds = threadIds; }, fs, worktree, config, command, enableFiles: () => { settings = { ...settings, storageCleanup: { ...settings.storageCleanup, browserArtifactsAfterDays: 8, logsAfterDays: 8, }, }; }, setSettings: (next: Partial) => { settings = { ...settings, ...next }; }, setPolicy: (worktreeKeepWhen: WorktreeKeepWhen) => { settings = { ...settings, storageCleanup: { ...settings.storageCleanup, worktreeKeepWhen }, }; }, disable: () => { settings = { ...settings, storageCleanup: { ...settings.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: false, }, }; }, setThreads: (next: typeof threads) => { threads = next; }, setBranchPullRequests: (next: typeof branchPullRequests) => { branchPullRequests = next; }, threadBranches: () => threads.map((thread) => thread.branch), setOnLiveCheck: (hook: Effect.Effect) => { onLiveCheck = hook; }, setOutboxStatus: (status: string | null) => { outboxStatus = status; }, setScheduledThreadIds: (next: string[]) => { scheduledThreadIds = next; }, setDeletedThreads: (next: OrchestrationV2ThreadShell[]) => { deletedThreads = next; }, setStoredWorktreePaths: (paths: string[]) => { storedWorktreePaths = paths; }, setProjectRoots: (roots: string[]) => { projectRoots = roots; }, setSessionLive: (live: boolean) => { sessionLive = live; }, setOpenSessionCwd: (cwd: string | null) => { openSessionCwd = cwd; }, openTerminal: (paths: { cwd: string; worktreePath: string | null }) => Effect.sync(() => { const terminal: TerminalSummary = { threadId: "thread-1", terminalId: "terminal-1", status: "running", pid: 1, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "Terminal", updatedAt: "2026-06-10T12:00:00.000Z", ...paths, }; terminals = [ ...terminals.filter( (entry) => entry.threadId !== terminal.threadId || entry.terminalId !== terminal.terminalId, ), terminal, ]; }), gitInspections: () => gitInspections, worktreeListCalls: () => [...worktreeListCalls], fullStatusCalls: () => fullStatusCalls, statusCommands: () => statusCommands, snapshotReads: () => snapshotReads, sessionLiveChecks: () => sessionLiveChecks, activate: (domainEvents: Stream.Stream) => { events = domainEvents; return Deferred.succeed(activated, undefined); }, }; }); const pausedMeasurementFixture = (storageCleanup?: StorageCleanupSettings) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const measuring = yield* Deferred.make(); const resume = yield* Deferred.make(); let measuredPath: string | undefined; const fixture = yield* cleanupFixture(storageCleanup).pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory, options) => Effect.gen(function* () { if (directory === measuredPath) { yield* Deferred.succeed(measuring, undefined); yield* Deferred.await(resume); } return yield* fs.readDirectory(directory, options); }), }), ); measuredPath = yield* fs.realPath(fixture.worktree); return { ...fixture, measuring, resume }; }); const cleanupTestLayer = GitVcsDriver.layer.pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "storage-cleanup-" })), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); const annexWorktree = Effect.fnUntraced(function* ( fixture: Effect.Success>, worktree: string, ) { const adminDir = (yield* fixture.command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout; yield* fixture.fs.remove(`${worktree}/.git`); yield* fixture.fs.symlink(adminDir.trim(), `${worktree}/.git`); }); const runCleanupTest = ( effect: Effect.Effect< A, E, | FileSystem.FileSystem | Digest.Digest | ServerConfig.ServerConfig | GitVcsDriver.GitVcsDriver | Path.Path | Scope.Scope >, ) => effect.pipe(Effect.provide(cleanupTestLayer)); const legacyCheckpointRef = (threadId: string, turn: number) => `refs/t3/checkpoints/${Base64Url.encode(threadId)}/turn/${turn}`; const checkpointCleanupFixture = Effect.fn("test.checkpointCleanupFixture")(function* () { const sql = yield* SqlClient.SqlClient; const git = yield* GitVcsDriver.GitVcsDriver; const fixture = yield* cleanupFixture(DEFAULT_SERVER_SETTINGS.storageCleanup, sql); const { repo, worktree, command } = fixture; const timestamp = DateTime.formatIso(at(0)); yield* sql`INSERT INTO projection_projects ${sql.insert({ project_id: "project-1", title: "Checkpoint cleanup", workspace_root: repo, scripts_json: "[]", created_at: timestamp, updated_at: timestamp, deleted_at: timestamp, })}`; const addThread = Effect.fn("test.addCheckpointThread")(function* ( id: string, options: { deleted?: boolean; archived?: boolean; source?: string; legacyOnly?: boolean } = {}, ) { const scopeId = CheckpointScopeId.make(`scope:${id}`); yield* sql`INSERT INTO orchestration_v2_projection_threads ${sql.insert({ thread_id: id, project_id: "project-1", title: id, default_provider: "codex", runtime_mode: "full-access", interaction_mode: "default", created_at: timestamp, updated_at: timestamp, archived_at: options.archived ? timestamp : null, deleted_at: options.deleted ? timestamp : null, payload_json: JSON.stringify({ worktreePath: worktree, forkedFrom: options.source ? { type: "run", threadId: options.source } : null, }), })}`; if (!options.legacyOnly) yield* sql`INSERT INTO orchestration_v2_projection_checkpoint_scopes ${sql.insert({ scope_id: scopeId, thread_id: id, node_id: `node:${id}`, kind: "root_run", ordinal_within_parent: 0, advances_app_run_count: 1, created_at: timestamp, payload_json: JSON.stringify({ cwd: worktree }), })}`; const refs: string[] = options.legacyOnly ? [legacyCheckpointRef(id, 0)] : [ yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 0 }), yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 1 }), legacyCheckpointRef(id, 0), ]; for (const ref of refs) yield* command(repo, ["update-ref", ref, "HEAD"]); return refs; }); const listRefs = () => git .execute({ operation: "cleanup-test.list-checkpoints", cwd: repo, args: ["for-each-ref", "--format=%(refname)", "refs/t3/"], maxOutputBytes: 16 * 1024 * 1024, }) .pipe(Effect.map(({ stdout }) => stdout.trim().split("\n").filter(Boolean).sort())); return { ...fixture, sql, addThread, listRefs }; }); describe("checkpoint ref cleanup", () => { it.live("prunes refs owned by deleted threads after their worktree is removed", () => runCleanupTest( Effect.gen(function* () { const { service, repo, worktree, command, addThread, listRefs } = yield* checkpointCleanupFixture(); const deleted = yield* addThread("deleted", { deleted: true }); yield* addThread("imported-deleted", { deleted: true, legacyOnly: true }); const active = yield* addThread("active"); const retained = [ ...active, ...(yield* addThread("archived", { archived: true })), legacyCheckpointRef("unknown-owner", 0), ]; const fs = yield* FileSystem.FileSystem; const indexRoot = CheckpointCaptureIndex.storeRoot(yield* Path.Path, `${repo}/.git`); const captureIndexOf = (ref: string) => `${indexRoot}/${CheckpointCaptureIndex.scopeDirectoryPrefix(ref.slice(0, ref.lastIndexOf("/") + 1))}cwd`; for (const ref of [deleted.at(-1)!, active.at(-1)!]) { yield* fs.makeDirectory(captureIndexOf(ref), { recursive: true }); } yield* command(repo, ["update-ref", retained.at(-1)!, "HEAD"]); yield* command(repo, ["pack-refs", "--all"]); yield* command(repo, ["worktree", "remove", worktree]); yield* service.runNow; expect(yield* listRefs()).toEqual(retained.sort()); // A deleted thread's capture index goes with its refs; a live thread keeps its own. expect(yield* fs.exists(captureIndexOf(deleted.at(-1)!))).toBe(false); expect(yield* fs.exists(captureIndexOf(active.at(-1)!))).toBe(true); }).pipe(Effect.provide(Sqlite.layerMemory)), ), ); it.live("keeps deleted fork ancestry while a live or archived descendant needs it", () => runCleanupTest( Effect.gen(function* () { const { service, sql, addThread, listRefs } = yield* checkpointCleanupFixture(); const root = yield* addThread("root", { deleted: true }); const intermediate = yield* addThread("intermediate", { deleted: true, source: "root" }); const child = yield* addThread("child", { archived: true, source: "intermediate" }); yield* service.runNow; expect(yield* listRefs()).toEqual([...root, ...intermediate, ...child].sort()); yield* sql`UPDATE orchestration_v2_projection_threads SET deleted_at = 'deleted' WHERE thread_id = 'child'`; yield* service.runNow; expect(yield* listRefs()).toEqual([]); }).pipe(Effect.provide(Sqlite.layerMemory)), ), ); it.live("removes a deleted thread's expired provider event log and keeps a live one", () => runCleanupTest( Effect.gen(function* () { const { service, fs, config, addThread, enableFiles } = yield* checkpointCleanupFixture(); yield* addThread("deleted", { deleted: true }); yield* addThread("active"); enableFiles(); yield* fs.makeDirectory(config.providerLogsDir, { recursive: true }); const deletedLog = `${config.providerLogsDir}/events.deleted.log`; const activeLog = `${config.providerLogsDir}/events.active.log`; for (const file of [deletedLog, activeLog]) { yield* fs.writeFileString(file, "[2026-01-01T00:00:00.000Z] NTIVE: {}\n"); yield* fs.utimes(file, 1, 1); } yield* service.runNow; expect(yield* fs.exists(deletedLog)).toBe(false); expect(yield* fs.exists(activeLog)).toBe(true); }).pipe(Effect.provide(Sqlite.layerMemory)), ), ); it.live("waits for a deleted thread's pending checkpoint effects", () => runCleanupTest( Effect.gen(function* () { const { service, sql, addThread, listRefs } = yield* checkpointCleanupFixture(); const refs = yield* addThread("capturing", { deleted: true }); yield* sql`INSERT INTO orchestration_v2_effect_outbox ${sql.insert({ effect_id: "capture", command_id: "capture", thread_id: "capturing", effect_type: "checkpoint.capture", payload_json: "{}", status: "running", available_at: "2026-01-01T00:00:00Z", created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", })}`; yield* service.runNow; expect(yield* listRefs()).toEqual(refs.toSorted()); yield* sql`UPDATE orchestration_v2_effect_outbox SET status = 'succeeded'`; yield* service.runNow; expect(yield* listRefs()).toEqual([]); }).pipe(Effect.provide(Sqlite.layerMemory)), ), ); it.live("deletes a symbolic checkpoint ref without its target or neighbouring refs", () => runCleanupTest( Effect.gen(function* () { const { service, repo, command, addThread, listRefs } = yield* checkpointCleanupFixture(); const refs = yield* addThread("deleted", { deleted: true }); yield* command(repo, ["symbolic-ref", refs[0]!, "refs/heads/main"]); const retained = [ "refs/t3/unrelated/0", `${refs[1]}-other`, refs[1]!.replace(/1$/, "2/nested"), ]; for (const ref of retained) yield* command(repo, ["update-ref", ref, "HEAD"]); yield* service.runNow; expect(yield* listRefs()).toEqual(retained.sort()); yield* command(repo, ["show-ref", "--verify", "refs/heads/main"]); }).pipe(Effect.provide(Sqlite.layerMemory)), ), ); it.live("cleans many deleted checkpoint scopes without removing live refs", () => runCleanupTest( Effect.gen(function* () { const { service, addThread, listRefs } = yield* checkpointCleanupFixture(); const retained = yield* addThread("active"); // Each deleted thread has two owned ref prefixes; exceed the targeted query limit. for (let index = 0; index < 33; index++) { yield* addThread(`deleted-${index}`, { deleted: true }); } yield* service.runNow; expect(yield* listRefs()).toEqual(retained.toSorted()); }).pipe(Effect.provide(Sqlite.layerMemory)), ), ); it.live("cleans more checkpoint refs than default git output holds", () => runCleanupTest( Effect.gen(function* () { const { service, repo, addThread, listRefs } = yield* checkpointCleanupFixture(); const git = yield* GitVcsDriver.GitVcsDriver; const prefix = (yield* addThread("many-checkpoints", { deleted: true }))[0]!.slice(0, -1); yield* git.execute({ operation: "cleanup-test.seed-checkpoints", cwd: repo, args: ["update-ref", "--stdin"], stdin: Array.from( { length: 12_283 }, (_, ordinal) => `update ${prefix}${ordinal} HEAD\n`, ).join(""), }); yield* service.runNow; expect(yield* listRefs()).toEqual([]); }).pipe(Effect.provide(Sqlite.layerMemory)), ), ); }); it.live.each(["repository", "uppercase", "bare"] as const)( "keeps a worktree holding an ignored nested %s", (kind) => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, command, setPolicy } = yield* cleanupFixture(); setPolicy("tracked-changes"); const nested = `${worktree}/dist/nested`; if (kind === "uppercase") { yield* command(repo, ["worktree", "add", "-b", "nested", nested]); } else { yield* command(repo, [ "clone", "--no-hardlinks", ...(kind === "bare" ? ["--bare"] : []), repo, nested, ]); } if (kind === "uppercase") yield* fs.rename(`${nested}/.git`, `${nested}/.GIT`); yield* fs.writeFileString(`${nested}/uncommitted.txt`, "irreplaceable work\n"); expect((yield* command(worktree, ["status", "--porcelain"])).stdout).toBe(""); const report = yield* service.runNow; expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ outcome: "kept", reason: "Contains a nested Git repository", }); expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("irreplaceable work\n"); expect( (yield* command(nested, [ ...(kind === "uppercase" ? [ `--git-dir=${(yield* fs.readFileString(`${nested}/.GIT`)).trim().slice(8)}`, "--work-tree=.", ] : []), "-c", "safe.bareRepository=all", "rev-parse", "--is-bare-repository", ])).stdout.trim(), ).toBe(String(kind === "bare")); }), ), ); it.live("removes a worktree whose ignored folder holds a gitfile pointing nowhere", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree } = yield* cleanupFixture(); // Packages such as conda-forge's `referencing` ship a test suite's dangling gitlink. yield* fs.makeDirectory(`${worktree}/dist/suite`, { recursive: true }); yield* fs.writeFileString(`${worktree}/dist/suite/.git`, "gitdir: ../.git/modules/x\n"); const [entry] = (yield* service.runNow).entries; expect(entry?.reason).not.toBe("Contains a nested Git repository"); expect(entry).toMatchObject({ outcome: "removed" }); expect(yield* fs.exists(worktree)).toBe(false); }), ), ); it.live("keeps a worktree whose gitfile target exists only with its trailing space", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree } = yield* cleanupFixture(); yield* fs.makeDirectory(`${worktree}/dist/suite/git `, { recursive: true }); yield* fs.writeFileString(`${worktree}/dist/suite/.git`, "gitdir: git \n"); const [entry] = (yield* service.runNow).entries; expect(entry).toMatchObject({ outcome: "kept", reason: "Contains a nested Git repository" }); }), ), ); const submoduleCleanupFixture = () => Effect.gen(function* () { const fixture = yield* cleanupFixture(); const { command, repo, worktree } = fixture; const submodule = `${worktree}/module`; const child = `${submodule}/child`; for (const [cwd, name] of [ [worktree, "module"], [submodule, "child"], ] as const) { yield* command(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", repo, name]); yield* command(`${cwd}/${name}`, ["config", "user.name", "Cleanup test"]); yield* command(`${cwd}/${name}`, ["config", "user.email", "cleanup@example.test"]); } const recordSubmodules = () => Effect.gen(function* () { yield* command(submodule, ["commit", "-am", "record child"]); yield* command(submodule, ["push", "origin", "HEAD:submodule"]); yield* command(worktree, ["commit", "-am", "record module"]); }); yield* recordSubmodules(); return { ...fixture, submodule, child, recordSubmodules }; }); it.live("inspects a pnpm store excluded from reclaimed bytes for nested repositories", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, command, setPolicy } = yield* cleanupFixture(); setPolicy("tracked-changes"); const storeDir = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-store-" }); const nested = `${worktree}/node_modules/.pnpm/nested`; yield* command(repo, ["clone", "--no-hardlinks", repo, nested]); yield* fs.writeFileString(`${nested}/uncommitted.txt`, "keep me"); yield* fs.writeFileString( `${worktree}/node_modules/.modules.yaml`, JSON.stringify({ storeDir, virtualStoreDir: ".pnpm" }), ); const report = yield* service.runNow; expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ outcome: "kept", reason: "Contains a nested Git repository", }); expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("keep me"); }), ), ); it.live("keeps an ignored repository inside a registered submodule", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, submodule, command, setPolicy } = yield* submoduleCleanupFixture(); setPolicy("tracked-changes"); const nested = `${submodule}/dist/nested`; yield* command(repo, ["clone", "--no-hardlinks", repo, nested]); yield* fs.writeFileString(`${nested}/uncommitted.txt`, "keep me"); const report = yield* service.runNow; expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ outcome: "kept", reason: "Contains a nested Git repository", }); expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("keep me"); }), ), ); it.live("removes a task folder's clean worktrees and keeps the one with uncommitted work", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, command, setTaskFolders, setThreads } = yield* cleanupFixture(); const trackedRepository = Effect.fnUntraced(function* (name: string) { const folder = `${repo}/dist/${name}`; yield* fs.makeDirectory(folder, { recursive: true }); yield* command(folder, ["init", "-b", "main"]); yield* command(folder, ["config", "user.email", "cleanup@example.test"]); yield* command(folder, ["config", "user.name", "Cleanup test"]); yield* fs.writeFileString(`${folder}/tracked.txt`, "original\n"); yield* command(folder, ["add", "."]); yield* command(folder, ["commit", "-m", "initial"]); return { name, path: folder }; }); const api = yield* trackedRepository("api"); const web = yield* trackedRepository("web"); const context = yield* Layer.build( layerTaskFoldersWithGit({ workspaceRoot: repo, trackedFolders: [api, web], thread: null, }).pipe(Layer.provide(NodeCrypto.layer)), ); const taskFolders = Context.get(context, TaskFolders.TaskFolders); const plan = yield* taskFolders.plan({ projectId: ProjectId.make("project-1") }); const { taskFolder } = yield* taskFolders.create({ plan: plan!, branch: "task", projectStart: { refName: "main", baseRefName: "main" }, startFromOrigin: false, projectCommands: "permitted", }); const root = taskFolder.root; // A nested worktree's uncommitted work must survive its thread's cleanup. yield* fs.writeFileString(`${root}/dist/api/tracked.txt`, "uncommitted\n"); setTaskFolders(taskFolders); setThreads([shell({ branch: "task", worktreePath: root })]); const report = yield* service.runNow; expect( report.entries .filter((entry) => entry.path?.startsWith(root)) .map(({ path, outcome, reason }) => ({ path, outcome, reason })) .toSorted((left, right) => left.path!.localeCompare(right.path!)), ).toEqual([ { path: root, outcome: "kept", reason: "Holds a repository that was kept" }, { path: `${root}/dist/api`, outcome: "kept", reason: "Has uncommitted changes (1 file)", }, { path: `${root}/dist/web`, outcome: "removed", reason: expect.any(String) }, ]); expect( report.entries.find((entry) => entry.path === `${root}/dist/web`)?.bytes, ).toBeGreaterThan(0); expect(yield* fs.readFileString(`${root}/dist/api/tracked.txt`)).toBe("uncommitted\n"); expect(yield* fs.exists(`${root}/dist/web`)).toBe(false); // The thread is alive, so the record keeps the whole layout for when it resumes. expect((yield* taskFolders.find(root))?.repositories).toHaveLength(2); yield* command(`${root}/dist/api`, ["checkout", "--", "tracked.txt"]); // Git deletes the checkout, then fails on metadata it cannot delete. const adminDir = (yield* command(`${root}/dist/api`, [ "rev-parse", "--absolute-git-dir", ])).stdout.trim(); const stuck = `${adminDir}/scratch`; yield* fs.makeDirectory(stuck); yield* fs.writeFileString(`${stuck}/f`, "x\n"); yield* fs.chmod(stuck, 0o555); yield* Effect.addFinalizer(() => fs.chmod(stuck, 0o755).pipe(Effect.ignore)); const second = yield* service.runNow; expect(second.entries.filter((entry) => entry.path?.startsWith(root))).toEqual( [`${root}/dist/api`, root].map((path) => expect.objectContaining({ path, outcome: "kept" }), ), ); expect(yield* fs.exists(`${root}/dist/api`)).toBe(false); // The checkout is gone, so the folder goes and only the record keeps the metadata in view. expect( (yield* service.runNow).entries.filter((entry) => entry.path?.startsWith(root)), ).toEqual( [ { path: `${root}/dist/api`, outcome: "failed" }, { path: root, outcome: "removed" }, ].map((entry) => expect.objectContaining(entry)), ); expect(yield* fs.exists(root)).toBe(false); yield* fs.chmod(stuck, 0o755); expect((yield* service.runNow).entries).toEqual([ expect.objectContaining({ path: `${root}/dist/api`, outcome: "removed" }), ]); expect(yield* fs.exists(adminDir)).toBe(false); expect(yield* fs.readFileString(`${api.path}/tracked.txt`)).toBe("original\n"); }), ), ); it.live("removes a task folder's clean checkout whose branch was renamed", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, command, setTaskFolders, setThreads } = yield* cleanupFixture(); const trackedRepository = Effect.fnUntraced(function* (name: string) { const folder = `${repo}/dist/${name}`; yield* fs.makeDirectory(folder, { recursive: true }); yield* command(folder, ["init", "-b", "main"]); yield* command(folder, ["config", "user.email", "cleanup@example.test"]); yield* command(folder, ["config", "user.name", "Cleanup test"]); yield* fs.writeFileString(`${folder}/tracked.txt`, "original\n"); yield* command(folder, ["add", "."]); yield* command(folder, ["commit", "-m", "initial"]); return { name, path: folder }; }); const api = yield* trackedRepository("api"); const web = yield* trackedRepository("web"); const context = yield* Layer.build( layerTaskFoldersWithGit({ workspaceRoot: repo, trackedFolders: [api, web], thread: null, }).pipe(Layer.provide(NodeCrypto.layer)), ); const taskFolders = Context.get(context, TaskFolders.TaskFolders); const plan = yield* taskFolders.plan({ projectId: ProjectId.make("project-1") }); const { taskFolder } = yield* taskFolders.create({ plan: plan!, branch: "task", projectStart: { refName: "main", baseRefName: "main" }, startFromOrigin: false, projectCommands: "permitted", }); const root = taskFolder.root; yield* command(`${root}/dist/api`, ["branch", "-m", "task-renamed"]); setTaskFolders(taskFolders); setThreads([shell({ branch: "task", worktreePath: root })]); const report = yield* service.runNow; expect(report.entries.find((entry) => entry.path === `${root}/dist/api`)).toMatchObject({ outcome: "removed", }); expect(yield* fs.exists(`${root}/dist/api`)).toBe(false); expect( (yield* command(repo + "/dist/api", ["branch", "--list", "task-renamed"])).stdout.trim(), ).not.toBe(""); }), ), ); it.live("removes clean submodules recursively, including deinitialized repositories", () => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const git = yield* GitVcsDriver.GitVcsDriver; let editedDuringClean = false; const { service, repo, worktree, submodule, command, recordSubmodules, setPolicy } = yield* submoduleCleanupFixture().pipe( Effect.provideService(GitVcsDriver.GitVcsDriver, { ...git, execute: (input) => git.execute(input).pipe( Effect.tap(() => { if (input.args[0] !== "clean") return Effect.void; editedDuringClean = true; return fs.writeFileString(`${input.cwd}/tracked.txt`, "late edit\n"); }), ), }), ); setPolicy("tracked-changes"); yield* fs.writeFileString(`${worktree}/notes.txt`, "untracked\n"); yield* fs.writeFileString(`${worktree}/.env`, "ignored\n"); yield* command(submodule, [ "-c", "protocol.file.allow=always", "submodule", "add", repo, "stored", ]); const legacy = `${worktree}/legacy`; yield* command(repo, ["clone", "--no-hardlinks", repo, legacy]); yield* command(worktree, ["submodule", "add", repo, "legacy"]); expect((yield* fs.stat(`${legacy}/.git`)).type).toBe("Directory"); yield* command(legacy, [ "-c", "protocol.file.allow=always", "submodule", "add", repo, "child", ]); yield* command(legacy, [ "-c", "protocol.file.allow=always", "submodule", "add", repo, "stored", ]); yield* command(legacy, [ "-c", "user.name=Cleanup test", "-c", "user.email=cleanup@example.test", "commit", "-am", "record legacy children", ]); yield* command(legacy, ["push", "origin", "HEAD:legacy"]); yield* command(legacy, ["submodule", "deinit", "stored"]); yield* recordSubmodules(); yield* command(submodule, ["submodule", "deinit", "stored"]); const checkpoint = (yield* command(submodule, [ "commit-tree", "HEAD^{tree}", "-p", "HEAD", "-m", "checkpoint", ])).stdout.trim(); yield* command(submodule, [ "update-ref", "refs/t3/orchestration-v2/checkpoints/test", checkpoint, ]); const admin = (yield* command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); const report = yield* service.runNow; expect(editedDuringClean).toBe(false); expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ outcome: "removed", }); expect(report.counts).toEqual({ removed: 1, kept: 0, failed: 0 }); expect(yield* fs.exists(worktree)).toBe(false); expect(yield* fs.exists(admin)).toBe(false); }), ), ); it.live("keeps nested submodule files protected by the current keep rule", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, submodule, child, command, setPolicy } = yield* submoduleCleanupFixture(); setPolicy("tracked-changes"); yield* fs.writeFileString(`${child}/tracked.txt`, "local edit\n"); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept" }); expect(yield* fs.readFileString(`${child}/tracked.txt`)).toBe("local edit\n"); yield* fs.writeFileString(`${child}/tracked.txt`, "original\n"); setPolicy("any-local-files"); yield* fs.writeFileString(`${child}/.env`, "local secret\n"); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept" }); expect(yield* fs.readFileString(`${child}/.env`)).toBe("local secret\n"); yield* fs.remove(`${child}/.env`); yield* command(submodule, ["submodule", "deinit", "child"]); yield* fs.writeFileString(`${child}/.env`, "secret after deinit\n"); const report = yield* service.runNow; expect({ outcome: report.entries.find((entry) => entry.path === worktree)?.outcome, contents: (yield* fs.exists(`${child}/.env`)) ? yield* fs.readFileString(`${child}/.env`) : null, }).toEqual({ outcome: "kept", contents: "secret after deinit\n" }); yield* fs.remove(`${child}/.env`); setPolicy("uncommitted-changes"); yield* fs.writeFileString(`${child}/notes.txt`, "notes after deinit\n"); const untrackedReport = yield* service.runNow; expect({ outcome: untrackedReport.entries.find((entry) => entry.path === worktree)?.outcome, contents: (yield* fs.exists(`${child}/notes.txt`)) ? yield* fs.readFileString(`${child}/notes.txt`) : null, }).toEqual({ outcome: "kept", contents: "notes after deinit\n" }); }), ), ); it.live("keeps unpushed submodule history after checkout and deinitialization", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, submodule, child, command, recordSubmodules } = yield* submoduleCleanupFixture(); yield* command(child, ["checkout", "-b", "local-only"]); yield* fs.writeFileString(`${child}/tracked.txt`, "unpublished work\n"); yield* command(child, ["commit", "-am", "local work"]); const local = (yield* command(child, ["rev-parse", "HEAD"])).stdout.trim(); yield* recordSubmodules(); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); expect(yield* fs.readFileString(`${child}/tracked.txt`)).toBe("unpublished work\n"); yield* command(child, ["checkout", "main"]); yield* recordSubmodules(); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); const childGit = (yield* command(child, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); yield* command(submodule, ["submodule", "deinit", "child"]); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); expect( (yield* command(worktree, [ "--git-dir", childGit, "rev-parse", "refs/heads/local-only", ])).stdout.trim(), ).toBe(local); expect( (yield* command(worktree, ["--git-dir", childGit, "show", "local-only:tracked.txt"])) .stdout, ).toBe("unpublished work\n"); yield* command(worktree, ["--git-dir", childGit, "branch", "-D", "local-only"]); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); expect( (yield* command(worktree, ["--git-dir", childGit, "show", `${local}:tracked.txt`])).stdout, ).toBe("unpublished work\n"); }), ), ); it.live("keeps submodules when stored repository metadata is malformed", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, submodule, child, command, setPolicy } = yield* submoduleCleanupFixture(); setPolicy("tracked-changes"); const childGit = (yield* command(child, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); yield* command(submodule, ["submodule", "deinit", "child"]); yield* fs.writeFileString(`${childGit}/HEAD`, "not a ref\n"); yield* fs.writeFileString(`${worktree}/notes.txt`, "keep while the worktree stays\n"); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("inspected") }); expect(yield* fs.exists(worktree)).toBe(true); expect(yield* fs.readFileString(`${childGit}/HEAD`)).toBe("not a ref\n"); expect(yield* fs.readFileString(`${worktree}/notes.txt`)).toBe( "keep while the worktree stays\n", ); }), ), ); it.live("preserves late tracked edits when submodules were never initialized", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); const { service, fs, worktree, command } = fixture; const head = (yield* command(worktree, ["rev-parse", "HEAD"])).stdout.trim(); yield* fs.writeFileString( `${worktree}/.gitmodules`, '[submodule "module"]\n\tpath = module\n\turl = /unused\n', ); yield* command(worktree, ["add", ".gitmodules"]); yield* command(worktree, ["update-index", "--add", "--cacheinfo", `160000,${head},module`]); yield* command(worktree, ["commit", "-m", "record uninitialized module"]); yield* fs.makeDirectory(`${worktree}/module`); fixture.editBeforeRemoval(); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "failed" }); expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("late edit\n"); }), ), ); describe("subagent worktree ownership", () => { it.effect.each([ "child", "grandchild", "immediate", "active-parent", "recent-settle", "settle-grace", "recent-child-activity", "running-child", "pending-child", "running-parent", "pending-parent", "unsettled-child", "pinned-child", "fork", "missing-parent", "cycle", ] as const)("checks isolated subagent settlement (%s)", (scenario) => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: scenario === "immediate" ? 0 : 8, }); const root = shell({ settledAt: scenario === "active-parent" ? null : scenario === "recent-settle" || scenario === "settle-grace" ? at(-30_000) : scenario === "immediate" ? at(-120_000) : at(-20 * DAY_MS), settledOverride: scenario === "active-parent" ? null : "settled", updatedAt: scenario === "settle-grace" ? at(-30_000) : at(-10 * DAY_MS), }); const child = shell({ id: ThreadId.make("child"), branch: "feature", worktreePath: fixture.worktree, lineage: { parentThreadId: scenario === "missing-parent" ? ThreadId.make("missing") : scenario === "cycle" ? ThreadId.make("child") : ["grandchild", "running-parent", "pending-parent"].includes(scenario) ? ThreadId.make("middle") : root.id, rootThreadId: root.id, relationshipToParent: scenario === "fork" ? "fork" : "subagent", }, status: scenario === "running-child" ? "running" : "completed", pendingBackgroundTasks: scenario === "pending-child" ? [{ taskId: "task", kind: "command" }] : [], latestRunCompletedAt: scenario === "recent-child-activity" ? at(-2 * DAY_MS) : null, settledOverride: scenario === "unsettled-child" ? "active" : null, pinnedAt: scenario === "pinned-child" ? at(-DAY_MS) : null, }); const middle = shell({ id: ThreadId.make("middle"), status: scenario === "running-parent" ? "running" : "idle", pendingBackgroundTasks: scenario === "pending-parent" ? [{ taskId: "task", kind: "command" }] : [], lineage: { parentThreadId: root.id, rootThreadId: root.id, relationshipToParent: "subagent", }, }); fixture.setThreads([child, middle, root]); const report = yield* fixture.service.runNow; const removed = ["child", "grandchild", "immediate"].includes(scenario); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed); expect(report.entries[0]).toMatchObject({ threadId: child.id, outcome: removed ? "removed" : "kept", reason: removed ? scenario === "immediate" ? "Settled for 0 days" : "Settled for 20 days" : scenario === "settle-grace" ? "Settled moments ago" : scenario === "recent-settle" ? "Settled for 0 of 8 days" : scenario === "recent-child-activity" ? "Settled for 2 of 8 days" : scenario === "running-child" || scenario === "pending-child" ? "Thread is running or has pending work" : "Not settled", }); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect.each(["merge", "squash"] as const)( "removes an isolated subagent worktree whose branch reached the default branch through its parent's merged pull request (%s)", (strategy) => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeOnMerge: true, worktreeOnDelete: true, worktreeAfterDays: 30, }); const { repo, worktree, command, fs } = fixture; const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "main"]); yield* command(repo, ["remote", "add", "origin", remote]); yield* command(repo, ["push", "origin", "main"]); yield* fs.writeFileString(`${worktree}/tracked.txt`, "subagent work\n"); yield* command(worktree, ["commit", "-am", "subagent work"]); // The parent merges the subagent's branch into its own and ships one pull request. yield* command(repo, ["branch", "parent-branch", "main"]); yield* command(repo, ["checkout", "parent-branch"]); yield* command(repo, ["merge", "--no-ff", "-m", "merge subagent", "feature"]); yield* command(repo, ["checkout", "main"]); if (strategy === "merge") { yield* command(repo, [ "merge", "--no-ff", "-m", "merge parent pull request", "parent-branch", ]); } else { yield* command(repo, ["merge", "--squash", "parent-branch"]); yield* command(repo, ["commit", "-m", "squash parent pull request"]); } yield* command(repo, ["push", "origin", "main"]); const parentHead = (yield* command(repo, ["rev-parse", "parent-branch"])).stdout.trim(); fixture.setBranchPullRequests({ "parent-branch": { number: 7, title: "Parent work", url: "https://github.com/example/repo/pull/7", baseRef: "main", headRef: "parent-branch", headSha: parentHead, state: "merged", repositoryKey: null, updatedAt: "2026-06-08T12:00:00.000Z", } as GitManager.GitBranchPullRequest, }); const parent = shell({ branch: "parent-branch", status: "completed", settledAt: at(-DAY_MS), createdAt: at(-3 * DAY_MS), updatedAt: at(-DAY_MS), }); const child = shell({ id: ThreadId.make("child"), branch: "feature", worktreePath: worktree, status: "completed", createdAt: at(-3 * DAY_MS), latestRunCompletedAt: at(-2 * DAY_MS), updatedAt: at(-2 * DAY_MS), lineage: { parentThreadId: parent.id, rootThreadId: parent.id, relationshipToParent: "subagent", }, }); fixture.setThreads([child, parent]); const report = yield* fixture.service.runNow; expect(report.entries.find((entry) => entry.threadId === child.id)).toMatchObject({ outcome: "removed", }); expect(yield* fs.exists(worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect.each([ "parent-unsettled", "parent-resettled", "child-unsettled", "intermediate-running", "intermediate-pending", ] as const)("cancels inherited settlement during measurement (%s)", (change) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0, }); const root = shell({ settledAt: at(-20 * DAY_MS), settledOverride: "settled" }); const middle = shell({ id: ThreadId.make("middle"), lineage: { parentThreadId: root.id, rootThreadId: root.id, relationshipToParent: "subagent", }, }); const child = shell({ id: ThreadId.make("child"), branch: "feature", worktreePath: fixture.worktree, lineage: { parentThreadId: middle.id, rootThreadId: root.id, relationshipToParent: "subagent", }, }); fixture.setThreads([child, middle, root]); const run = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(fixture.measuring); fixture.setThreads([ { ...child, settledOverride: change === "child-unsettled" ? "active" : null }, { ...middle, status: change === "intermediate-running" ? "running" : "idle", pendingBackgroundTasks: change === "intermediate-pending" ? [{ taskId: "task", kind: "command" }] : [], }, change === "child-unsettled" || change.startsWith("intermediate-") ? root : { ...root, settledAt: change === "parent-resettled" ? at(0) : null, settledOverride: change === "parent-resettled" ? "settled" : "active", updatedAt: at(0), }, ]); yield* Deferred.succeed(fixture.resume, undefined); expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ outcome: "kept", reason: "Parent settlement changed since check", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); it.effect.each([ "idle", "grandchild", "branchless", "branchless-running", "null-branch", "stale-branch", "isolated-owner", "fork-owner", "missing-parent", "cycle", "two-tops", "wrong-root", "running", "pending", "unrelated", "fork", "side-chat", "recent-activity", "recent-inactive", "recent-grace", "recent-settle", "child-settled-now", "child-settled-only", ] as const)("checks the whole owner group (%s)", (scenario) => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); fixture.setSettings({ storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: scenario === "recent-inactive" ? null : 8, worktreeAfterDays: scenario === "recent-inactive" ? 8 : null, }, }); const root = shell({ branch: ["branchless", "branchless-running"].includes(scenario) ? null : "feature", worktreePath: fixture.worktree, settledAt: scenario === "child-settled-only" ? null : at(-20 * DAY_MS), ...(scenario === "isolated-owner" || scenario === "fork-owner" ? { lineage: { parentThreadId: ThreadId.make("ancestor"), rootThreadId: ThreadId.make("ancestor"), relationshipToParent: scenario === "fork-owner" ? ("fork" as const) : ("subagent" as const), }, } : {}), }); const child = shell({ id: ThreadId.make("child"), branch: scenario === "null-branch" ? null : scenario === "stale-branch" ? "t3/15a6e5ae" : "feature", worktreePath: fixture.worktree, lineage: { parentThreadId: scenario === "missing-parent" ? ThreadId.make("missing") : scenario === "cycle" ? ThreadId.make("child") : scenario === "two-tops" ? null : root.id, rootThreadId: scenario === "wrong-root" ? ThreadId.make("other-root") : root.lineage.rootThreadId, relationshipToParent: scenario === "fork" || scenario === "side-chat" ? "fork" : scenario === "unrelated" ? null : "subagent", ...(scenario === "side-chat" ? { sideChat: true } : {}), }, status: ["running", "branchless-running"].includes(scenario) ? "running" : "completed", pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [], latestRunCompletedAt: scenario === "recent-activity" || scenario === "recent-inactive" ? at(-2 * DAY_MS) : scenario === "recent-grace" ? at(-30_000) : null, settledAt: scenario === "child-settled-only" ? at(-20 * DAY_MS) : null, }); const grandchild = { ...child, id: ThreadId.make("grandchild"), lineage: { ...child.lineage, parentThreadId: child.id }, }; fixture.setThreads( scenario === "grandchild" ? [grandchild, child, root] : scenario === "isolated-owner" || scenario === "fork-owner" ? [child, root, shell({ id: ThreadId.make("ancestor") })] : [child, root], ); if (scenario === "recent-settle" || scenario === "child-settled-now") fixture.setThreads([ { ...child, settledAt: scenario === "recent-settle" ? at(0) : at(-20 * DAY_MS), updatedAt: at(0), }, root, ]); const report = yield* fixture.service.runNow; const removed = ["idle", "grandchild", "isolated-owner", "fork-owner", "side-chat"].includes( scenario, ); const shared = [ "unrelated", "fork", "missing-parent", "cycle", "two-tops", "wrong-root", ].includes(scenario); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed); expect(report.entries[0]).toMatchObject({ threadId: shared ? child.id : root.id, outcome: removed ? "removed" : "kept", reason: removed ? "Settled for 20 days" : ["running", "pending", "branchless-running"].includes(scenario) ? "Thread is running or has pending work" : shared ? "Shared by 2 threads" : scenario === "null-branch" || scenario === "stale-branch" ? "A subagent thread's branch differs from this worktree's branch" : scenario === "recent-activity" ? "Settled for 2 of 8 days" : scenario === "recent-inactive" ? "Inactive for 2 of 8 days" : ["recent-grace", "recent-settle", "child-settled-now"].includes(scenario) ? "Settled moments ago" : scenario === "branchless" ? "Thread has no branch" : "Not settled", }); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("keeps a checkout two top-level threads store through a symlinked parent", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 8, }); const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; fixture.setThreads([ shell({ ...settled, worktreePath: fixture.worktree }), shell({ ...settled, id: ThreadId.make("other"), worktreePath: `${linkedParent}/feature` }), ]); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([ expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), ]); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("keeps a checkout two top-level threads store in different case on Windows", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 8, }).pipe(Effect.provideService(HostProcess.Platform, "win32")); const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; fixture.setThreads([ shell({ ...settled, worktreePath: fixture.worktree }), shell({ ...settled, id: ThreadId.make("other"), worktreePath: fixture.worktree.toUpperCase(), }), ]); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([ expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), ]); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect.each([ "running", "pending", "activity", "unrelated", "settled", "resettled", "null-branch", "stale-branch", ] as const)("cancels removal when a child changes during measurement (%s)", (change) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const root = shell({ branch: "feature", worktreePath: fixture.worktree }); const child = { ...root, id: ThreadId.make("child"), settledAt: change === "resettled" ? at(-20 * DAY_MS) : null, lineage: { parentThreadId: root.id, rootThreadId: root.id, relationshipToParent: "subagent" as const, }, }; fixture.setThreads([child, root]); const run = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(fixture.measuring); fixture.setThreads([ root, { ...child, branch: change === "null-branch" ? null : change === "stale-branch" ? "t3/15a6e5ae" : child.branch, settledAt: change === "settled" ? at(-20 * DAY_MS) : child.settledAt, updatedAt: change === "settled" || change === "resettled" ? at(0) : child.updatedAt, status: change === "running" ? "running" : "idle", pendingBackgroundTasks: change === "pending" ? [{ taskId: "task", kind: "command" }] : [], latestRunCompletedAt: change === "activity" ? at(-DAY_MS) : null, }, ...(change === "unrelated" ? [shell({ ...root, id: ThreadId.make("other") })] : []), ]); yield* Deferred.succeed(fixture.resume, undefined); expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ outcome: "kept", reason: "Thread activity or shared worktree changed since check", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); }); describe("deleted thread worktrees", () => { const parent = (worktreePath: string) => shell({ branch: "feature", worktreePath, deletedAt: at(-DAY_MS) }); // Deleting the parent leaves its native subagent thread in the projection. const subagent = ( owner: OrchestrationV2ThreadShell, overrides: Partial = {}, ) => shell({ id: ThreadId.make("child"), title: "Subagent", branch: "feature", worktreePath: owner.worktreePath, status: "completed", createdBy: "agent", creationSource: "provider", lineage: { rootThreadId: owner.id, parentThreadId: owner.id, relationshipToParent: "subagent", }, ...overrides, }); it.effect.each(["no subagents", "native subagent"] as const)( "removes a deleted thread's worktree with %s", (scenario) => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setDeletedThreads([owner]); fixture.setThreads(scenario === "native subagent" ? [subagent(owner)] : []); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject({ threadId: owner.id, outcome: "removed", reason: "Thread was deleted", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("leaves a deleted owner's subagent on the owner's saved branch", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setDeletedThreads([owner]); fixture.setThreads([subagent(owner)]); yield* fixture.command(fixture.worktree, ["switch", "-c", "renamed"]); expect((yield* fixture.service.runNow).entries[0]).toMatchObject({ threadId: owner.id, outcome: "kept", reason: "Repository or branch changed", }); // The deleted owner cannot follow, so moving its subagent would split their records. expect(fixture.threadBranches()).toEqual(["feature"]); }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), ); it.effect("applies the remaining subagent's rules when deletion cleanup is off", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: 8, worktreeOnDelete: false, }); const owner = parent(fixture.worktree); const child = subagent(owner); fixture.setDeletedThreads([owner]); fixture.setThreads([child]); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject({ threadId: child.id, outcome: "removed", reason: "Inactive for 30 days", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); // Releases one stopped-session event after the startup sweep and returns the snapshot reads it caused. const stopSessionAfterStartupSweep = ( fixture: Effect.Success>, threadId: ThreadId, beforeStop: Effect.Effect = Effect.void, cwd = fixture.worktree, ) => Effect.gen(function* () { const startupSwept = yield* Deferred.make(); const delivered = yield* Deferred.make(); const stopped: OrchestrationV2DomainEvent = { id: EventId.make("event:session-stopped"), type: "provider-session.updated", threadId, occurredAt: at(0), payload: { id: ProviderSessionId.make("session-1"), driver: ProviderDriverKind.make("codex"), providerInstanceId: ProviderInstanceId.make("codex"), status: "stopped", cwd, model: null, capabilities: CodexProviderCapabilitiesV2, createdAt: at(-DAY_MS), updatedAt: at(0), lastError: null, }, }; yield* fixture.activate( Stream.fromEffect(Deferred.await(startupSwept)).pipe( Stream.flatMap(() => Stream.make(stopped)), Stream.concat( Stream.fromEffect(Deferred.succeed(delivered, undefined)).pipe(Stream.drain), ), ), ); yield* fixture.service.reports.pipe( Stream.filter((report) => report !== null), Stream.take(1), Stream.runDrain, ); yield* fixture.service.drain; yield* beforeStop; const readsBefore = fixture.snapshotReads(); yield* Deferred.succeed(startupSwept, undefined); yield* Deferred.await(delivered); yield* fixture.service.drain; return fixture.snapshotReads() - readsBefore; }); it.effect("does not sweep when a live thread's session stops and no deleted worktree waits", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); const reads = yield* stopSessionAfterStartupSweep(fixture, ThreadId.make("thread-1")); expect(reads, "a live thread's stopped session re-read every thread").toBe(0); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("removes a deleted No project thread's scratch folder", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, worktreeKeepWhen: "tracked-changes", }); const scratchRoot = `${fixture.config.baseDir}/scratch`; const folder = `${scratchRoot}/quiet-otter`; yield* fixture.fs.makeDirectory(folder, { recursive: true }); yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); fixture.setProjectRoots([scratchRoot]); fixture.setStoredWorktreePaths([]); fixture.setThreads([]); fixture.setDeletedThreads([ shell({ worktreePath: folder, branch: null, deletedAt: at(-DAY_MS) }), ]); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([ expect.objectContaining({ path: folder, outcome: "removed" }), ]); expect(yield* fixture.fs.exists(folder)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("removes a deleted thread's worktree once its session stops", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setDeletedThreads([owner]); fixture.setThreads([]); fixture.setOpenSessionCwd(fixture.worktree); const reads = yield* stopSessionAfterStartupSweep( fixture, owner.id, Effect.sync(() => fixture.setSessionLive(false)), ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("removes a deleted thread's worktree once a live thread's session in it stops", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); const child = subagent(owner); fixture.setDeletedThreads([owner]); fixture.setThreads([child]); fixture.setOpenSessionCwd(fixture.worktree); const reads = yield* stopSessionAfterStartupSweep( fixture, child.id, Effect.gen(function* () { expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ threadId: owner.id, outcome: "kept", reason: "Provider session is still open", }); fixture.setSessionLive(false); }), ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( "removes a deleted thread's worktree once its terminal closes and its session stops", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setDeletedThreads([owner]); fixture.setThreads([]); yield* fixture.setTerminals([ { threadId: owner.id, terminalId: "terminal-1", cwd: fixture.worktree, worktreePath: fixture.worktree, status: "running", pid: 1, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "Terminal", updatedAt: DateTime.formatIso(at(0)), }, ]); const reads = yield* stopSessionAfterStartupSweep( fixture, owner.id, Effect.gen(function* () { expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ threadId: owner.id, outcome: "kept", reason: "Open terminal", }); yield* fixture.setTerminals([]); }), fixture.repo, ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( "retries a deleted thread's worktree kept for another reason when a session in it stops", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setDeletedThreads([owner]); fixture.setThreads([]); yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "agent edit\n"); const reads = yield* stopSessionAfterStartupSweep( fixture, owner.id, Effect.gen(function* () { expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ threadId: owner.id, outcome: "kept", reason: "Has uncommitted changes (1 file)", }); yield* fixture.fs .writeFileString(`${fixture.worktree}/tracked.txt`, "original\n") .pipe(Effect.orDie); }), ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("does not sweep for a kept deleted worktree when a session elsewhere stops", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); fixture.setDeletedThreads([parent(fixture.worktree)]); fixture.setThreads([]); yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "agent edit\n"); const reads = yield* stopSessionAfterStartupSweep( fixture, ThreadId.make("thread-elsewhere"), Effect.void, fixture.repo, ); expect(reads).toBe(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( "does not sweep for a deleted thread whose cleanup effect failed when a session elsewhere stops", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setDeletedThreads([owner]); fixture.setThreads([]); fixture.setOutboxStatus("failed"); const reads = yield* stopSessionAfterStartupSweep( fixture, ThreadId.make("thread-elsewhere"), Effect.gen(function* () { expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ threadId: owner.id, outcome: "kept", reason: "Thread deletion is still pending", }); }), fixture.repo, ); expect(reads).toBe(0); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( "removes a deleted thread's worktree when its session stops during the deletion's sweep", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setThreads([]); const startupSwept = yield* Deferred.make(); const sessionChecked = yield* Deferred.make(); const delivered = yield* Deferred.make(); const deleted = { id: EventId.make("event:thread-deleted"), type: "thread.deleted", threadId: owner.id, occurredAt: at(0), payload: owner, } as unknown as OrchestrationV2DomainEvent; const stopped: OrchestrationV2DomainEvent = { id: EventId.make("event:session-stopped"), type: "provider-session.updated", threadId: owner.id, occurredAt: at(0), payload: { id: ProviderSessionId.make("session-1"), driver: ProviderDriverKind.make("codex"), providerInstanceId: ProviderInstanceId.make("codex"), status: "stopped", cwd: fixture.worktree, model: null, capabilities: CodexProviderCapabilitiesV2, createdAt: at(-DAY_MS), updatedAt: at(0), lastError: null, }, }; yield* fixture.activate( Stream.fromEffect(Deferred.await(startupSwept)).pipe( Stream.flatMap(() => Stream.make(deleted)), Stream.concat(Stream.fromEffect(Deferred.await(sessionChecked)).pipe(Stream.drain)), Stream.concat(Stream.make(stopped)), Stream.concat( Stream.fromEffect(Deferred.succeed(delivered, undefined)).pipe(Stream.drain), ), ), ); yield* fixture.service.reports.pipe( Stream.filter((report) => report !== null), Stream.take(1), Stream.runDrain, ); yield* fixture.service.drain; fixture.setDeletedThreads([owner]); fixture.setOpenSessionCwd(fixture.worktree); // The deletion's sweep sees the session live; it stops before that sweep publishes its result. fixture.setOnLiveCheck( Effect.gen(function* () { fixture.setOnLiveCheck(Effect.void); yield* Deferred.succeed(sessionChecked, undefined); yield* Deferred.await(delivered); fixture.setSessionLive(false); }), ); yield* Deferred.succeed(startupSwept, undefined); yield* Deferred.await(delivered); yield* fixture.service.drain; expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("waits out the settle grace of a subagent that just settled", () => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: null, worktreeOnDelete: true, }); const owner = parent(fixture.worktree); fixture.setDeletedThreads([owner]); fixture.setThreads([subagent(owner, { settledAt: at(0), updatedAt: at(0) })]); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject({ threadId: owner.id, outcome: "kept", reason: "Settled moments ago", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }).pipe(Effect.provide(cleanupTestLayer)), ); }); describe("orphan worktree reports", () => { it.live("keeps orphan results visible when thread results fill the report", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads( Array.from({ length: 205 }, (_, index) => shell({ id: ThreadId.make(`busy-${index}`), branch: "busy", worktreePath: `${fixture.config.worktreesDir}/busy-${index}`, status: "running", }), ), ); for (let index = 0; index < 205; index++) { yield* fixture.fs.makeDirectory(`${fixture.config.worktreesDir}/busy-${index}`); } const orphans = ["one", "two"].map( (name) => `${fixture.config.worktreesDir}/repository/${name}`, ); for (const orphan of orphans) { yield* fixture.fs.makeDirectory(orphan, { recursive: true }); yield* fixture.fs.utimes(orphan, 1, 1); } const report = yield* fixture.service.runNow; expect(report.entries).toHaveLength(200); expect( report.entries .slice(0, 2) .map((entry) => entry.path) .sort(), ).toEqual(orphans); expect(report.counts).toEqual({ removed: 0, kept: 207, failed: 0 }); expect(report.omittedCount).toBe(7); }), ), ); it.live.each(["canonical", "win32", "linux"] as const)( "skips an ancestor of a referenced thread worktree (%s)", (platform) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture().pipe( Effect.provideService(HostProcess.Platform, platform === "win32" ? "win32" : "linux"), ); fixture.setThreads([]); const ancestor = `${fixture.config.worktreesDir}/repository/stack`; const worktree = `${ancestor}/feature`; yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "nested", worktree]); const alias = `${fixture.repo}/alias`; if (platform === "canonical") yield* fixture.fs.symlink(worktree, alias); fixture.setStoredWorktreePaths([ platform === "canonical" ? alias : platform === "win32" ? worktree.toUpperCase() : worktree, ]); yield* fixture.fs.utimes(ancestor, 1, 1); expect((yield* fixture.service.runNow).entries).toEqual([]); expect(yield* fixture.fs.exists(worktree)).toBe(true); }), ), ); it.live("continues reporting when a project root cannot be probed", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const loop = `${fixture.repo}/loop`; yield* fixture.fs.symlink(loop, loop); fixture.setProjectRoots([fixture.repo, loop]); const orphan = `${fixture.config.worktreesDir}/repository/orphan`; yield* fixture.fs.makeDirectory(orphan, { recursive: true }); yield* fixture.fs.utimes(orphan, 1, 1); expect((yield* fixture.service.runNow).entries).toEqual([ expect.objectContaining({ path: orphan, outcome: "kept", bytes: 0 }), ]); }), ), ); it.live.each(["nested", "direct", "annexed"] as const)( "reports a linked orphan's size without removing its files (%s)", (location) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const orphan = `${fixture.config.worktreesDir}/${location === "nested" ? "repository/" : ""}orphan`; yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]); if (location === "annexed") yield* annexWorktree(fixture, orphan); const sizes = yield* Effect.forEach( // Links are not measured, and the annexed `.git` is one. (yield* fixture.fs.readDirectory(orphan)).filter( (name) => location !== "annexed" || name !== ".git", ), (name) => allocatedBytes(fixture.fs, `${orphan}/${name}`), ); const outside = yield* fixture.fs.makeTempDirectoryScoped(); yield* fixture.fs.writeFileString(`${outside}/external`, "outside data"); yield* fixture.fs.symlink(outside, `${orphan}/linked-directory`); yield* fixture.fs.symlink(`${outside}/missing`, `${orphan}/dangling-link`); yield* fixture.fs.utimes(orphan, 1, 1); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([ { kind: "worktree", outcome: "kept", reason: "No thread uses this worktree", path: orphan, projectPath: null, threadId: null, threadTitle: null, bytes: sizes.reduce((sum, size) => sum + size, 0), files: null, }, ]); expect(report.bytesFreed).toBe(0); expect(yield* fixture.fs.readFileString(`${orphan}/tracked.txt`)).toBe("original\n"); expect(yield* fixture.fs.readFileString(`${outside}/external`)).toBe("outside data"); expect( (yield* fixture.command(orphan, ["rev-parse", "--is-inside-work-tree"])).stdout.trim(), ).toBe("true"); }), ), ); it.live.each(["active", "outside-active-snapshot"] as const)( "does not report a folder referenced by a thread (%s)", (location) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); const worktreePath = `${fixture.config.worktreesDir}/repository/referenced`; yield* fixture.command(fixture.repo, [ "worktree", "add", "-b", "referenced", worktreePath, ]); fixture.setThreads( location === "active" ? [shell({ branch: "referenced", worktreePath, status: "running" })] : [], ); if (location !== "active") fixture.setStoredWorktreePaths([fixture.worktree, worktreePath]); yield* fixture.fs.utimes(worktreePath, 1, 1); const report = yield* fixture.service.runNow; expect(report.entries.filter((entry) => entry.threadId === null)).toEqual([]); expect(yield* fixture.fs.exists(worktreePath)).toBe(true); }), ), ); it.live.each(["exact", "nested", "symlink"] as const)( "does not report a folder containing a project checkout (%s)", (location) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const worktreePath = `${fixture.config.worktreesDir}/repository/project-checkout`; yield* fixture.fs.makeDirectory(`${worktreePath}/nested`, { recursive: true }); const alias = `${fixture.repo}/alias`; if (location === "symlink") yield* fixture.fs.symlink(`${worktreePath}/nested`, alias); fixture.setProjectRoots([ fixture.repo, location === "exact" ? worktreePath : location === "nested" ? `${worktreePath}/nested` : alias, ]); yield* fixture.fs.utimes(worktreePath, 1, 1); expect((yield* fixture.service.runNow).entries).toEqual([]); expect(yield* fixture.fs.exists(worktreePath)).toBe(true); }), ), ); it.live.each(["exact", "contains", "symlink"] as const)( "does not report project internals under a custom managed root (%s)", (location) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const source = `${fixture.repo}/src`; yield* fixture.fs.makeDirectory(`${source}/nested/deep`, { recursive: true }); const alias = `${fixture.config.worktreesDir}/project-alias`; if (location === "symlink") { yield* fixture.fs.symlink(fixture.repo, alias); fixture.setProjectRoots([alias]); } if (location === "contains") fixture.setProjectRoots([fixture.repo, `${source}/nested`]); fixture.setSettings({ worktreesDirectory: location === "contains" ? source : fixture.repo, }); expect((yield* fixture.service.runNow).entries).toEqual([]); expect(yield* fixture.fs.exists(`${source}/nested/deep`)).toBe(true); }), ), ); it.live.each([ { home: "an installed", worktreeHome: false, customFolderOutcome: "removed" }, { home: "a git worktree's dev", worktreeHome: true, customFolderOutcome: "kept" }, ] as const)( "on $home home, a custom worktrees folder ends $customFolderOutcome", ({ worktreeHome, customFolderOutcome }) => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; const checkout = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-dev-checkout-" }); yield* fs.writeFileString(`${checkout}/.git`, "gitdir: /repo/.git/worktrees/dev\n"); const baseDir = worktreeHome ? `${checkout}/.t3` : config.baseDir; const fixture = yield* cleanupFixture().pipe( Effect.provideService(ServerConfig.ServerConfig, { ...config, baseDir, worktreesDir: `${baseDir}/worktrees`, }), ); const customFolder = yield* fs.realPath( yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-real-worktrees-" }), ); const realWorktree = `${customFolder}/seeded`; yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "seeded", realWorktree]); fixture.setSettings({ worktreesDirectory: customFolder }); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree }), shell({ id: ThreadId.make("seeded"), lineage: { rootThreadId: ThreadId.make("seeded"), parentThreadId: null, relationshipToParent: null, }, branch: "seeded", worktreePath: realWorktree, }), ]); const { entries } = yield* fixture.service.runNow; expect(entries.find((entry) => entry.path === realWorktree)?.outcome).toBe( customFolderOutcome, ); expect(yield* fs.exists(realWorktree)).toBe(customFolderOutcome === "kept"); expect(yield* fs.exists(fixture.worktree)).toBe(false); }), ), ); it.live("skips symbolic links at both directory levels and disabled cleanup", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const outside = yield* fixture.fs.makeTempDirectoryScoped(); yield* fixture.fs.makeDirectory(`${outside}/checkout`); const projectDirectory = `${fixture.config.worktreesDir}/repository`; yield* fixture.fs.makeDirectory(projectDirectory); yield* fixture.fs.symlink(outside, `${fixture.config.worktreesDir}/linked-project`); yield* fixture.fs.symlink(`${outside}/checkout`, `${projectDirectory}/linked-checkout`); yield* fixture.fs.symlink(`${outside}/missing`, `${projectDirectory}/dangling-link`); expect((yield* fixture.service.runNow).entries).toEqual([]); const orphan = `${projectDirectory}/orphan`; yield* fixture.fs.makeDirectory(orphan); fixture.disable(); expect((yield* fixture.service.runNow).entries).toEqual([]); expect(yield* fixture.fs.exists(orphan)).toBe(true); }), ), ); it.live("reports ordinary folders with an honest reason and keeps their files", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const folder = `${fixture.config.worktreesDir}/repository/leftover`; yield* fixture.fs.makeDirectory(folder, { recursive: true }); yield* fixture.fs.writeFileString(`${folder}/payload`, "leftover data"); yield* fixture.fs.utimes(folder, 1, 1); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([ expect.objectContaining({ path: folder, outcome: "kept", bytes: yield* allocatedBytes(fixture.fs, `${folder}/payload`), reason: "No thread uses this folder, and it isn't a git worktree", }), ]); expect(report.bytesFreed).toBe(0); expect(yield* fixture.fs.readFileString(`${folder}/payload`)).toBe("leftover data"); }), ), ); it.live("reports linked worktrees nested deeper inside a plain folder", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const replay = `${fixture.config.worktreesDir}/repository/replay`; const deep = `${fixture.config.worktreesDir}/repository/deep`; const worktrees = [`${deep}/a/b`, `${replay}/1376`]; for (const [index, worktree] of worktrees.entries()) { yield* fixture.command(fixture.repo, [ "worktree", "add", "-b", `nested-${index}`, worktree, ]); } for (const folder of [...worktrees, `${deep}/a`, deep, replay]) { yield* fixture.fs.utimes(folder, 1, 1); } const report = yield* fixture.service.runNow; expect( report.entries .map((entry) => ({ path: entry.path, reason: entry.reason })) .sort((left, right) => String(left.path).localeCompare(String(right.path))), ).toEqual(worktrees.map((path) => ({ path, reason: "No thread uses this worktree" }))); }), ), ); it.live("still reports a plain folder whose nested worktree registration is stale", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const replay = `${fixture.config.worktreesDir}/repository/replay`; const worktree = `${replay}/1376`; yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "locked", worktree]); yield* fixture.command(fixture.repo, ["worktree", "lock", worktree]); yield* fixture.fs.rename(worktree, `${replay}/moved`); yield* fixture.fs.makeDirectory(worktree); yield* fixture.fs.utimes(replay, 1, 1); expect((yield* fixture.service.runNow).entries.map((entry) => entry.path)).toEqual([ replay, ]); }), ), ); it.live("does not report nested worktrees inside a project checkout", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setThreads([]); const project = `${fixture.config.worktreesDir}/repository/replay/project`; const worktree = `${project}/nested`; yield* fixture.fs.makeDirectory(project, { recursive: true }); fixture.setProjectRoots([fixture.repo, project]); yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "nested", worktree]); for (const folder of [worktree, project]) yield* fixture.fs.utimes(folder, 1, 1); expect((yield* fixture.service.runNow).entries).toEqual([]); }), ), ); it.live("lists worktrees once per enclosing repository and skips non-Git project roots", () => runCleanupTest( Effect.gen(function* () { const path = yield* Path.Path; const fixture = yield* cleanupFixture(); fixture.setThreads([]); const nonGitRoot = yield* fixture.fs.realPath( yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-non-git-" }), ); const repoSubdir = path.join(fixture.repo, "packages", "app"); yield* fixture.fs.makeDirectory(repoSubdir, { recursive: true }); const symlinkParent = yield* fixture.fs.realPath( yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-symlink-" }), ); const repoSymlink = path.join(symlinkParent, "repo-link"); yield* fixture.fs.symlink(fixture.repo, repoSymlink); const replay = path.join(fixture.config.worktreesDir, "repository", "replay"); const repoWorktree = path.join(replay, "repo-wt"); yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "nested", repoWorktree]); for (const folder of [repoWorktree, replay]) { yield* fixture.fs.utimes(folder, 1, 1); } fixture.setProjectRoots([nonGitRoot, repoSubdir, repoSymlink]); const report = yield* fixture.service.runNow; expect(fixture.worktreeListCalls().map((called) => path.resolve(called))).toEqual([ path.resolve(repoSubdir), ]); expect( report.entries.map((entry) => ({ path: entry.path === null ? null : path.resolve(entry.path), reason: entry.reason, })), ).toEqual([{ path: path.resolve(repoWorktree), reason: "No thread uses this worktree" }]); }), ), ); it.effect( "measures new orphans first and rotates cached refreshes when the budget runs out, not counting discovery", () => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const clock = yield* Clock.Clock; let now = NOW_MS; let parent: string | undefined; let slowDirectory: string | undefined; let slowDiscovery: string | undefined; const fixture = yield* cleanupFixture().pipe( Effect.provideService(Clock.Clock, { ...clock, currentTimeMillis: Effect.sync(() => now), }), Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory, options) => fs.readDirectory(directory, options).pipe( Effect.map((names) => { if (directory === slowDirectory || directory === slowDiscovery) now += 30_000; return directory === parent ? names.sort() : names; }), ), }), ); fixture.setThreads([]); parent = `${fixture.config.worktreesDir}/repository`; const cached = `${parent}/a-cached`; const later = `${parent}/b-cached`; const discovered = `${parent}/c-discovered`; for (const directory of [cached, later]) { yield* fs.makeDirectory(`${directory}/build`, { recursive: true }); yield* fs.utimes(directory, 1, 1); } const bundle = `${later}/build/bundle.js`; yield* fs.writeFileString(bundle, "x".repeat(64 * 1024)); const size = yield* allocatedBytes(fs, bundle); const first = yield* fixture.service.runNow; expect(first.entries.find((entry) => entry.path === later)?.bytes).toBe(size); slowDirectory = `${cached}/build`; yield* fs.remove(bundle); yield* fs.makeDirectory(discovered); yield* fs.utimes(discovered, 1, 1); const second = yield* fixture.service.runNow; expect(second.entries.find((entry) => entry.path === discovered)?.bytes).toBe(0); expect(second.entries.find((entry) => entry.path === later)?.bytes).toBe(size); slowDiscovery = parent; const third = yield* fixture.service.runNow; expect(third.entries.find((entry) => entry.path === later)?.bytes).toBe(0); }), ), ); it.live("retains the last orphan size on a failed refresh and can refresh it later", () => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; let unreadable: string | undefined; const fixture = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory, options) => fs.readDirectory( directory === unreadable ? `${directory}/missing-directory` : directory, options, ), }), ); fixture.setThreads([]); const orphan = `${fixture.config.worktreesDir}/repository/orphan`; const build = `${orphan}/build`; const bundle = `${build}/bundle.js`; yield* fs.makeDirectory(build, { recursive: true }); yield* fs.writeFileString(bundle, "build output"); yield* fs.utimes(orphan, 1, 1); const size = yield* allocatedBytes(fs, bundle); const orphanBytes = Effect.map( fixture.service.runNow, (report) => report.entries.find((entry) => entry.path === orphan)?.bytes, ); expect(yield* orphanBytes).toBe(size); yield* fs.remove(bundle); unreadable = build; expect(yield* orphanBytes).toBe(size); unreadable = undefined; expect(yield* orphanBytes).toBe(0); }), ), ); it.live("continues after an inaccessible directory's git probe", (context) => runCleanupTest( Effect.gen(function* () { if ((yield* HostProcess.isWindows) || (yield* HostProcess.UserId) === 0) return context.skip(); const fixture = yield* cleanupFixture(); fixture.setThreads([]); const blocked = `${fixture.config.worktreesDir}/a-inaccessible`; const orphan = `${fixture.config.worktreesDir}/z-repository/orphan`; yield* fixture.fs.makeDirectory(blocked); yield* fixture.fs.makeDirectory(orphan, { recursive: true }); yield* fixture.fs.writeFileString(`${orphan}/file`, "x"); yield* fixture.fs.chmod(blocked, 0); yield* fixture.fs.utimes(orphan, 1, 1); const report = yield* fixture.service.runNow.pipe( Effect.ensuring(fixture.fs.chmod(blocked, 0o700).pipe(Effect.orDie)), ); expect(report.entries).toEqual([ expect.objectContaining({ path: orphan, outcome: "kept", bytes: yield* allocatedBytes(fixture.fs, `${orphan}/file`), }), ]); expect(yield* fixture.fs.exists(orphan)).toBe(true); }), ), ); it.live.each(["win32", "linux"] as const)( "compares thread paths with host casing rules and excludes existing projects (%s)", (platform) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture().pipe( Effect.provideService(HostProcess.Platform, platform), ); fixture.setThreads([]); const parent = `${fixture.config.worktreesDir}/repository`; const referenced = `${parent}/Referenced`; const project = `${parent}/Project`; const nested = `${parent}/Nested`; for (const folder of [referenced, project, nested]) { yield* fixture.fs.makeDirectory(`${folder}/child`, { recursive: true }); yield* fixture.fs.utimes(folder, 1, 1); } fixture.setStoredWorktreePaths([fixture.worktree, referenced.toUpperCase()]); fixture.setProjectRoots([fixture.repo, project, `${nested}/child`]); const report = yield* fixture.service.runNow; expect(report.entries.map((entry) => entry.path).sort()).toEqual( platform === "win32" ? [] : [referenced], ); }), ), ); it.live.each([ ["win32", "cwd"], ["win32", "worktreePath"], ["linux", "cwd"], ["linux", "worktreePath"], ] as const)( "matches a terminal at the worktree root with host casing rules (%s, %s)", ([platform, field]) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture().pipe( Effect.provideService(HostProcess.Platform, platform), ); const upper = fixture.worktree.toUpperCase(); yield* fixture.openTerminal( field === "cwd" ? { cwd: upper, worktreePath: null } : { cwd: fixture.repo, worktreePath: upper }, ); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject( platform === "win32" ? { outcome: "kept", reason: "Open terminal" } : { outcome: "removed" }, ); }), ), ); it.live("keeps a worktree while its thread's settle script is queued", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setPendingSettleScripts([shell().id]); expect((yield* fixture.service.runNow).entries[0]).toMatchObject({ outcome: "kept", reason: "Settle script is queued", }); fixture.setPendingSettleScripts([]); expect((yield* fixture.service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); }), ), ); it.live.each(["win32", "linux"] as const)( "matches a provider session at the worktree root with host casing rules (%s)", (platform) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture().pipe( Effect.provideService(HostProcess.Platform, platform), ); fixture.setOpenSessionCwd(fixture.worktree.toUpperCase()); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject( platform === "win32" ? { outcome: "kept", reason: "Provider session is still open" } : { outcome: "removed" }, ); }), ), ); }); describe("storage cleanup reports and local file policies", () => { it.effect.each([true, false])( "sweeps on runtime retirement rather than live error metadata, worktreeOnDelete=%s", (worktreeOnDelete) => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: 8, worktreeOnDelete, }); fixture.setThreads([]); fixture.setDeletedThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, deletedAt: at(0) }), ]); yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "agent edit\n"); const events = yield* Queue.unbounded<{ readonly event: OrchestrationV2DomainEvent; readonly processed: Deferred.Deferred; }>(); yield* fixture.activate( Stream.fromQueue(events).pipe( Stream.flatMap(({ event, processed }) => Stream.succeed(event).pipe( Stream.concat( // The next pull acknowledges that the listener handled this event. Stream.fromEffect(Deferred.succeed(processed, undefined)).pipe(Stream.drain), ), ), ), ), ); yield* fixture.service.reports.pipe( Stream.filter((report) => report !== null), Stream.take(1), Stream.runDrain, ); yield* fixture.service.drain; const startupReads = fixture.snapshotReads(); const publish = Effect.fn("StorageCleanupTest.publish")(function* ( event: OrchestrationV2DomainEvent, ) { const processed = yield* Deferred.make(); yield* Queue.offer(events, { event, processed }); yield* Deferred.await(processed); yield* fixture.service.drain; }); const sessionUpdated = ( status: "ready" | "error" | "stopped", text: string, ): OrchestrationV2DomainEvent => ({ id: EventId.make(`event:session:${status}:${text}`), type: "provider-session.updated", threadId: ThreadId.make("thread-1"), occurredAt: at(0), payload: { id: ProviderSessionId.make("session-1"), driver: ProviderDriverKind.make("pi"), providerInstanceId: ProviderInstanceId.make("pi"), status, cwd: fixture.worktree, model: null, capabilities: CodexProviderCapabilitiesV2, extensionStatuses: text === "" ? [] : [{ key: "watch", text }], createdAt: at(-DAY_MS), updatedAt: at(0), lastError: status === "error" ? "Rate limited" : null, }, }); yield* publish(sessionUpdated("ready", "Watching")); expect(fixture.snapshotReads()).toBe(startupReads); expect(fixture.sessionLiveChecks()).toBe(0); for (let index = 0; index < 5; index++) { yield* publish(sessionUpdated("error", `Watching ${index} files`)); expect(fixture.snapshotReads()).toBe(startupReads); } expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 5 : 0); // Release removes the live entry before publishing its final error update. fixture.setSessionLive(false); yield* publish(sessionUpdated("error", "")); expect(fixture.snapshotReads()).toBe(startupReads + Number(worktreeOnDelete)); expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0); yield* publish(sessionUpdated("stopped", "")); expect(fixture.snapshotReads()).toBe(startupReads + 2 * Number(worktreeOnDelete)); expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0); fixture.setSessionLive(true); yield* publish({ id: EventId.make("event:thread:deleted"), type: "thread.deleted", threadId: ThreadId.make("thread-1"), occurredAt: at(0), payload: { ...shell({ deletedAt: at(0) }), lastVisitedAt: null }, }); // Deletion always sweeps so the deleted thread's checkpoint refs are pruned. expect(fixture.snapshotReads()).toBe(startupReads + 2 * Number(worktreeOnDelete) + 1); expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0); }), ), ); it.effect("automatically removes an eligible archived thread checkout", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, archivedAt: at(-DAY_MS), }), ]); yield* fixture.activate(Stream.empty); const [report] = yield* fixture.service.reports.pipe( Stream.filter((report) => report !== null), Stream.take(1), Stream.runCollect, ); yield* fixture.service.drain; expect(report).toMatchObject({ trigger: "automatic", counts: { removed: 1, kept: 0, failed: 0 }, entries: [ { threadId: "thread-1", path: fixture.worktree, outcome: "removed", reason: "Inactive for 30 days", }, ], }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }), ), ); it.effect("removes an archived checkout whose branch ends in Unicode whitespace", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); const git = yield* GitVcsDriver.GitVcsDriver; const branch = "feature "; yield* git.execute({ operation: "cleanup-test", cwd: fixture.worktree, args: ["branch", "-m", branch], }); fixture.setThreads([ shell({ branch, worktreePath: fixture.worktree, archivedAt: at(-DAY_MS) }), ]); yield* fixture.activate(Stream.empty); const [report] = yield* fixture.service.reports.pipe( Stream.filter((report) => report !== null), Stream.take(1), Stream.runCollect, ); yield* fixture.service.drain; expect(report).toMatchObject({ counts: { removed: 1, kept: 0, failed: 0 }, entries: [{ path: fixture.worktree, outcome: "removed" }], }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }), ), ); it.effect("removes an idle No project thread's scratch folder past the retention", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); const scratchRoot = `${fixture.config.baseDir}/scratch`; const folder = `${scratchRoot}/quiet-otter`; yield* fixture.fs.makeDirectory(folder, { recursive: true }); yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); fixture.setProjectRoots([scratchRoot]); fixture.setStoredWorktreePaths([]); // Only this rule lets cleanup delete untracked files, which is all a scratch folder has. fixture.setPolicy("tracked-changes"); fixture.setThreads([ shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), ]); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([ expect.objectContaining({ path: folder, outcome: "removed" }), ]); expect(yield* fixture.fs.exists(folder)).toBe(false); }), ), ); it.effect.each([ { name: "a Git repository in a subfolder", policy: "tracked-changes", repository: "clone/.git", reason: "Contains a nested Git repository", }, { name: "a Git repository of its own", policy: "tracked-changes", repository: ".git", reason: "Contains a nested Git repository", }, { name: "files under the default keep rule", reason: "Has local files (notes.md)" }, { name: "a scheduled task", policy: "tracked-changes", scheduled: true, reason: "Thread has a scheduled task", }, ] as const)( "keeps an idle No project thread's scratch folder with $name", ({ policy, repository, scheduled, reason, }: { readonly policy?: WorktreeKeepWhen; readonly repository?: string; readonly scheduled?: boolean; readonly reason: string; }) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); const scratchRoot = `${fixture.config.baseDir}/scratch`; const folder = `${scratchRoot}/quiet-otter`; yield* fixture.fs.makeDirectory( repository === undefined ? folder : `${folder}/${repository}`, { recursive: true }, ); yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); // No thread owns this one, so it is listed and never removed. const leftover = `${scratchRoot}/leftover`; yield* fixture.fs.makeDirectory(leftover); yield* fixture.fs.utimes(leftover, 1, 1); fixture.setProjectRoots([scratchRoot]); fixture.setStoredWorktreePaths([]); if (policy !== undefined) fixture.setPolicy(policy); if (scheduled) fixture.setScheduledThreadIds(["thread-1"]); fixture.setThreads([ shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), ]); const report = yield* fixture.service.runNow; expect( report.entries.map(({ path, outcome, reason }) => ({ path, outcome, reason })), ).toEqual([ { path: leftover, outcome: "kept", reason: "No thread uses this folder" }, { path: folder, outcome: "kept", reason }, ]); expect(yield* fixture.fs.exists(`${folder}/notes.md`)).toBe(true); }), ), ); it.effect("keeps a thread's worktree folder that lost its .git link", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, archivedAt: at(-DAY_MS) }), ]); yield* fixture.fs.remove(`${fixture.worktree}/.git`); yield* fixture.fs.makeDirectory(`${fixture.worktree}/node_modules`); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([ expect.objectContaining({ path: fixture.worktree, outcome: "kept" }), ]); expect(yield* fixture.fs.exists(`${fixture.worktree}/node_modules`)).toBe(true); }), ), ); it.live("keeps reporting a worktree whose git metadata cannot be deleted", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); const adminDir = (yield* fixture.command(fixture.worktree, [ "rev-parse", "--absolute-git-dir", ])).stdout.trim(); // Stands in for root-owned files a container wrote into the worktree's git dir. const stuck = `${adminDir}/scratch/fanal`; yield* fixture.fs.makeDirectory(stuck, { recursive: true }); yield* fixture.fs.writeFileString(`${stuck}/f`, "x\n"); yield* fixture.fs.chmod(stuck, 0o555); yield* Effect.addFinalizer(() => fixture.fs.chmod(stuck, 0o755).pipe(Effect.ignore)); yield* fixture.service.runNow; // Git may delete these before it reaches the folder it cannot, and then stops listing // the worktree. yield* fixture.fs.remove(`${adminDir}/gitdir`, { force: true }); yield* fixture.fs.remove(`${adminDir}/HEAD`, { force: true }); const later = yield* fixture.service.runNow; expect(later.entries).toEqual([ expect.objectContaining({ path: fixture.worktree, outcome: expect.stringMatching(/^(kept|failed)$/), }), ]); expect((yield* fixture.service.runNow).entries).toEqual(later.entries); expect(yield* fixture.fs.exists(stuck)).toBe(true); yield* fixture.fs.chmod(stuck, 0o755); expect((yield* fixture.service.runNow).entries).toEqual([ expect.objectContaining({ path: fixture.worktree, outcome: "removed" }), ]); expect(yield* fixture.fs.exists(adminDir)).toBe(false); expect((yield* fixture.service.runNow).entries).toEqual([]); // An unreadable record may still name leftovers, so it is reported and kept as it is. const record = `${fixture.config.stateDir}/storage-cleanup-leftovers.json`; yield* fixture.fs.writeFileString(record, "{"); expect((yield* fixture.service.runNow).entries).toEqual([ expect.objectContaining({ path: record, outcome: "failed" }), ]); expect(yield* fixture.fs.readFileString(record)).toBe("{"); }), ), ); it.live("leaves git metadata that a recreated worktree took over from a failed removal", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); const adminDir = (yield* fixture.command(fixture.worktree, [ "rev-parse", "--absolute-git-dir", ])).stdout.trim(); const stuck = `${adminDir}/scratch`; yield* fixture.fs.makeDirectory(stuck); yield* fixture.fs.writeFileString(`${stuck}/f`, "x\n"); yield* fixture.fs.chmod(stuck, 0o555); yield* Effect.addFinalizer(() => fixture.fs.chmod(stuck, 0o755).pipe(Effect.ignore)); yield* fixture.service.runNow; // The user repairs and prunes the leftover, then the thread resumes under the same name. yield* fixture.fs.chmod(stuck, 0o755); yield* fixture.command(fixture.repo, ["worktree", "prune"]); yield* fixture.command(fixture.repo, ["worktree", "add", fixture.worktree, "feature"]); // Only the cleanup rules remove it now: its metadata is no longer a leftover. expect((yield* fixture.service.runNow).entries).toEqual([ expect.objectContaining({ path: fixture.worktree, outcome: "removed", reason: expect.stringMatching(/^Inactive for/), }), ]); }), ), ); it.live("skips a stored worktree path whose parent is a regular file", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); const legacyRoot = `${fixture.config.worktreesDir}/legacy-root`; yield* fixture.fs.writeFileString(legacyRoot, ""); fixture.setThreads([ shell({ branch: "feature", worktreePath: `${legacyRoot}/stored-workspace` }), ]); const report = yield* fixture.service.runNow; expect(report.entries).toEqual([]); expect(report.counts).toEqual({ removed: 0, kept: 0, failed: 0 }); }), ), ); it.live.each([ ["before-check", "stored"], ["while-measuring", "stored"], ["before-check", "symlinked parent"], ["while-measuring", "symlinked parent"], ] as const)( "keeps a worktree protected by a missing project root (%s, %s spelling)", ([timing, spelling]) => runCleanupTest( Effect.gen(function* () { const fixture = yield* pausedMeasurementFixture(); let worktree = fixture.worktree; if (spelling === "symlinked parent") { const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); worktree = `${linkedParent}/feature`; fixture.setThreads([shell({ branch: "feature", worktreePath: worktree })]); } if (timing === "before-check") fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); if (timing === "while-measuring") { yield* Deferred.await(fixture.measuring); fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); } yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(cleanup); expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Contains a project checkout", }); expect(yield* fixture.fs.readFileString(`${fixture.worktree}/tracked.txt`)).toBe( "original\n", ); }), ), ); it.live("reports allocated bytes of single-link files without following symlinks", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); setPolicy("tracked-changes"); const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) => allocatedBytes(fs, `${worktree}/${name}`), ); const outside = yield* fs.makeTempDirectoryScoped(); yield* fs.writeFileString(`${outside}/external`, "must not count"); yield* fs.writeFileString(`${outside}/store-file`, "shared ".repeat(10_000)); yield* fs.makeDirectory(`${worktree}/node_modules/nested`, { recursive: true }); yield* fs.writeFileString(`${worktree}/node_modules/nested/file`, "count me"); sizes.push(yield* allocatedBytes(fs, `${worktree}/node_modules/nested/file`)); yield* fs.link(`${outside}/store-file`, `${worktree}/node_modules/hardlinked`); yield* fs.symlink(outside, `${worktree}/node_modules/directory-link`); yield* fs.symlink(`${outside}/external`, `${worktree}/node_modules/file-link`); yield* fs.symlink(`${outside}/missing`, `${worktree}/node_modules/dangling-link`); const report = yield* service.runNow; const bytes = sizes.reduce((sum, size) => sum + size, 0); expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes, files: null }); expect(report.bytesFreed).toBe(bytes); expect(yield* fs.readFileString(`${outside}/external`)).toBe("must not count"); expect(yield* fs.readFileString(`${outside}/store-file`)).toBe("shared ".repeat(10_000)); expect(yield* fs.exists(worktree)).toBe(false); }), ), ); it.live.each(["same-device", "other-device", "no-manifest"] as const)( "counts the pnpm virtual store only when its store forces copies (%s)", (store) => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const storeDir = yield* fs.makeTempDirectoryScoped({ prefix: "pnpm-store-" }); const statted: string[] = []; const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, lstat: (target) => { statted.push(target); return fs.lstat(target); }, stat: (target) => fs .stat(target) .pipe( Effect.map((info) => store === "other-device" && target === storeDir ? { ...info, dev: info.dev + 1n } : info, ), ), }), ); setPolicy("tracked-changes"); const nodeModules = `${worktree}/node_modules`; yield* fs.makeDirectory(`${nodeModules}/.pnpm/pkg@1.0.0`, { recursive: true }); yield* fs.makeDirectory(`${nodeModules}/.vite`); yield* fs.writeFileString( `${nodeModules}/.pnpm/pkg@1.0.0/index.js`, "clone ".repeat(10_000), ); yield* fs.writeFileString(`${nodeModules}/.vite/deps.js`, "cache"); if (store !== "no-manifest") yield* fs.writeFileString( `${nodeModules}/.modules.yaml`, JSON.stringify({ storeDir, virtualStoreDir: ".pnpm" }), ); const counted = [ ...(yield* fs.readDirectory(worktree)).flatMap((name) => name === "node_modules" ? [] : [`${worktree}/${name}`], ), `${nodeModules}/.vite/deps.js`, ...(store === "no-manifest" ? [] : [`${nodeModules}/.modules.yaml`]), ...(store === "same-device" ? [] : [`${nodeModules}/.pnpm/pkg@1.0.0/index.js`]), ]; const bytes = (yield* Effect.forEach(counted, (file) => allocatedBytes(fs, file))).reduce( (sum, size) => sum + size, 0, ); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes }); expect(statted.includes(`${nodeModules}/.pnpm/pkg@1.0.0/index.js`)).toBe( store !== "same-device", ); }), ), ); // An agent can write this manifest. Statting its store sent the Windows // user's NTLM credentials to attacker.test during a background sweep. it.live.each([ { storeDir: "\\\\attacker.test\\s" }, { storeDir: "/local/store", virtualStoreDir: "//attacker.test/s" }, ])("never stats a network pnpm store %o", (manifest) => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const statted: Array = []; const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, stat: (target) => { statted.push(target); return fs.stat(target); }, }), ); setPolicy("tracked-changes"); yield* fs.makeDirectory(`${worktree}/node_modules`); yield* fs.writeFileString( `${worktree}/node_modules/.modules.yaml`, JSON.stringify(manifest), ); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); expect(statted.filter((target) => target.includes("attacker.test"))).toEqual([]); }), ), ); it.effect.each([ { days: 8, reason: "Inactive for 1 of 8 days" }, { days: null, reason: "No rules apply" }, ])("keeps an ineligible age/delete-only worktree without Git ($days)", ({ days, reason }) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: days, worktreeOnDelete: true, }); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, latestUserMessageAt: at(-DAY_MS), }), ]); yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "local edit\n"); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "kept", reason, bytes: null, }); expect(fixture.gitInspections()).toBe(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); it.live("lets a turn acquire the checkout during accounting and protects its new activity", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* pausedMeasurementFixture(); const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(fixture.measuring); yield* withWorkspaceLease( fixture.worktree, Effect.sync(() => { fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, status: "running", }), ]); }), ); yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(cleanup); expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Thread activity or shared worktree changed since check", bytes: null, }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); it.live("removes a worktree whose .git file git-annex replaced with a symlink", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); const { service, worktree, fs } = fixture; yield* annexWorktree(fixture, worktree); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); expect(yield* fs.exists(worktree)).toBe(false); }), ), ); it.live("keeps a worktree when the inspection cannot read its directories", () => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const { service, worktree } = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory) => fs.readDirectory(`${directory}/missing-directory`), }), ); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Worktree could not be fully inspected", bytes: null, files: null, }); expect(report.bytesFreed).toBe(0); expect(yield* fs.exists(worktree)).toBe(true); }), ), ); it.effect("removes an eligible worktree whose ignored files take over 30 seconds to walk", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fs = yield* FileSystem.FileSystem; const walking = yield* Deferred.make(); let slowPath: string | undefined; // Stands in for a flat Bun or npm node_modules with hundreds of thousands of files. const fixture = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, lstat: (target) => Effect.gen(function* () { if (target === slowPath) { yield* Deferred.succeed(walking, undefined); yield* Effect.sleep("31 seconds"); } return yield* fs.lstat(target); }), }), ); yield* fs.makeDirectory(`${fixture.worktree}/node_modules/pkg`, { recursive: true }); yield* fs.writeFileString(`${fixture.worktree}/node_modules/pkg/index.js`, "export {};\n"); slowPath = `${yield* fs.realPath(fixture.worktree)}/node_modules`; const run = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(walking); yield* TestClock.adjust("31 seconds"); expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ outcome: "removed" }); expect(yield* fs.exists(fixture.worktree)).toBe(false); }), ), ); it.effect("removes a worktree owned by a repository other than the project root", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); const { fs, command, config } = fixture; const oldRepo = yield* fs.realPath( yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-old-repo-" }), ); yield* command(oldRepo, ["init", "-b", "main"]); yield* command(oldRepo, ["config", "user.email", "cleanup@example.test"]); yield* command(oldRepo, ["config", "user.name", "Cleanup test"]); yield* fs.writeFileString(`${oldRepo}/tracked.txt`, "original\n"); yield* command(oldRepo, ["add", "."]); yield* command(oldRepo, ["commit", "-m", "initial"]); yield* fs.makeDirectory(`${config.worktreesDir}/old-repo`, { recursive: true }); const oldWorktree = `${config.worktreesDir}/old-repo/feature`; yield* command(oldRepo, ["worktree", "add", "-b", "feature", oldWorktree]); fixture.setThreads([shell({ branch: "feature", worktreePath: oldWorktree })]); const report = yield* fixture.service.runNow; expect(report.entries.find((entry) => entry.path === oldWorktree)).toMatchObject({ outcome: "removed", }); expect(yield* fs.exists(oldWorktree)).toBe(false); expect((yield* command(oldRepo, ["worktree", "list", "--porcelain"])).stdout).not.toContain( oldWorktree, ); }), ), ); it.effect.each([ [ "its owner's branch is cleared", (worktree: string) => [shell({ branch: null, worktreePath: worktree, updatedAt: at(0) })], ], [ "its owner's branch changes", (worktree: string) => [shell({ branch: "other", worktreePath: worktree, updatedAt: at(0) })], ], [ "its thread starts", (worktree: string) => [ shell({ branch: "feature", worktreePath: worktree, status: "running" }), ], ], [ "another thread starts using it", (worktree: string) => [ shell({ branch: "feature", worktreePath: worktree }), shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }), ], ], [ "an archived thread starts using it", (worktree: string) => [ shell({ branch: "feature", worktreePath: worktree }), shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS), }), ], ], ] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const { fs, worktree } = fixture; fixture.setPolicy("tracked-changes"); yield* fs.writeFileString(`${worktree}/notes.txt`, "untracked\n"); const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(fixture.measuring); fixture.setThreads(threadsWhileMeasuring(worktree)); yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(cleanup); expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Thread activity or shared worktree changed since check", bytes: null, }); expect(report.bytesFreed).toBe(0); expect(yield* fs.exists(worktree)).toBe(true); expect(yield* fs.readFileString(`${worktree}/notes.txt`)).toBe("untracked\n"); }), ), ); it.live("follows a branch switched while nothing watched the worktree", () => runCleanupTest( Effect.gen(function* () { const { service, worktree, command, threadBranches } = yield* cleanupFixture(); yield* command(worktree, ["switch", "-c", "renamed"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept", reason: "Repository or branch changed", }); expect(threadBranches()).toEqual(["renamed"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); }), ), ); it.live("does not measure a worktree kept for an open provider session", () => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const walked: Array = []; const fixture = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory, options) => { walked.push(directory); return fs.readDirectory(directory, options); }, }), ); const root = yield* fs.realPath(fixture.worktree); fixture.setOpenSessionCwd(fixture.worktree); const kept = yield* fixture.service.runNow; expect(kept.entries[0]).toMatchObject({ outcome: "kept", reason: "Provider session is still open", bytes: null, }); expect(walked.filter((directory) => directory.startsWith(root))).toEqual([]); fixture.setSessionLive(false); const removed = yield* fixture.service.runNow; expect(removed.entries[0]).toMatchObject({ outcome: "removed" }); expect(removed.entries[0]?.bytes).toBeGreaterThan(0); expect(walked).toContain(root); }), ), ); it.live("keeps a worktree for a live session in a missing folder under its stored alias", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); fixture.setThreads([shell({ branch: "feature", worktreePath: `${linkedParent}/feature` })]); fixture.setOpenSessionCwd(`${linkedParent}/feature/removed-folder`); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Provider session is still open", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); it.live("compares the checked-out branch without a full status", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, command, fullStatusCalls, threadBranches } = yield* cleanupFixture(); const changed = { outcome: "kept", reason: "Repository or branch changed" }; yield* command(worktree, ["switch", "--orphan", "other"]); expect((yield* service.runNow).entries[0]).toMatchObject(changed); yield* command(worktree, ["tag", "feature", "feature"]); // Newer Git refuses to create a tag named HEAD, but still reads one. yield* command(worktree, ["update-ref", "refs/tags/HEAD", "refs/heads/feature"]); yield* command(worktree, ["switch", "feature"]); expect((yield* service.runNow).entries[0]).toMatchObject(changed); expect(threadBranches()).toEqual(["feature"]); const index = (yield* command(worktree, ["rev-parse", "--git-path", "index"])).stdout; yield* fs.writeFileString(`${index.trim()}.lock`, ""); const locked = (yield* service.runNow).entries[0]; expect(locked).toMatchObject({ outcome: "failed", projectPath: repo, path: worktree, threadId: "thread-1", threadTitle: "Thread", }); expect(locked?.reason).toContain("Git index is locked"); expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("original\n"); yield* fs.remove(`${index.trim()}.lock`); const gitFile = yield* fs.readFileString(`${worktree}/.git`); yield* fs.writeFileString(`${worktree}/.git`, "gitdir: /missing-git-directory\n"); expect((yield* service.runNow).entries[0]).toMatchObject(changed); yield* fs.writeFileString(`${worktree}/.git`, gitFile); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); expect(fullStatusCalls()).toBe(0); }), ), ); it.live("removes a clean detached worktree only when every commit is on a branch", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, command } = yield* cleanupFixture(); yield* command(worktree, ["checkout", "--detach"]); yield* fs.writeFileString(`${worktree}/tracked.txt`, "unpushed\n"); yield* command(worktree, ["commit", "-am", "unpushed"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); yield* command(worktree, ["checkout", "--detach", "main"]); yield* command(worktree, ["-c", "sequence.editor=echo break >>", "rebase", "-i", "--root"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); yield* command(worktree, ["rebase", "--abort"]); yield* command(worktree, ["checkout", "-b", "topic", "main"]); yield* command(worktree, ["commit", "--allow-empty", "-m", "topic"]); yield* command(worktree, ["checkout", "--detach", "main"]); yield* fs.writeFileString(`${worktree}/tracked.txt`, "autostashed\n"); yield* command(worktree, ["merge", "--autostash", "--no-ff", "--no-commit", "topic"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); yield* command(worktree, ["merge", "--abort"]); expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("autostashed\n"); yield* command(worktree, ["checkout", "--", "tracked.txt"]); yield* command(worktree, ["bisect", "start"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); yield* command(worktree, ["bisect", "reset"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); }), ), ); it.live.each([ ["any-local-files", ".env", "kept"], ["uncommitted-changes", ".env", "removed"], ["tracked-changes", ".env", "removed"], ["any-local-files", "notes.txt", "kept"], ["uncommitted-changes", "notes.txt", "kept"], ["tracked-changes", "notes.txt", "removed"], ["any-local-files", "tracked.txt", "kept"], ["uncommitted-changes", "tracked.txt", "kept"], ["tracked-changes", "tracked.txt", "kept"], ] as const)("applies %j", ([policy, file, outcome]) => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); setPolicy(policy); expect(yield* service.latestReport).toBeNull(); yield* fs.writeFileString(`${worktree}/${file}`, "local data\n"); const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) => allocatedBytes(fs, `${worktree}/${name}`), ); const bytes = sizes.reduce((sum, size) => sum + size, 0); const report = yield* service.runNow; yield* service.drain; expect(report.trigger).toBe("manual"); expect(report.entries.filter((entry) => entry.kind === "worktree")).toMatchObject([ { outcome, path: worktree, threadId: "thread-1", threadTitle: "Thread", bytes: outcome === "removed" ? bytes : null, files: null, }, ]); expect(report.bytesFreed).toBe(outcome === "removed" ? bytes : 0); expect(yield* fs.exists(worktree)).toBe(outcome === "kept"); expect(yield* service.latestReport).toEqual(report); if (outcome === "kept") expect(report.entries[0]?.reason).toContain( file === ".env" ? "ignored files (.env)" : "uncommitted changes (1 file)", ); }), ), ); it.effect.each([ ["unchanged", "removed", "No commits beyond the project branch"], ["unmerged", "kept", "Has commits beyond the project branch"], ["detached", "kept", "Project branch is unavailable"], ["merged-only", "kept", "No remote is configured for merged-worktree cleanup"], ] as const)("cleans archived local-only worktrees: %s", ([state, outcome, reason]) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const { service, fs, repo, worktree, command, setThreads, statusCommands } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: state !== "merged-only", worktreeOnMerge: true, }); yield* command(repo, ["branch", "-m", "main", "trunk"]); setThreads([shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) })]); if (state === "unmerged") { yield* fs.writeFileString(`${worktree}/tracked.txt`, "unmerged work\n"); yield* command(worktree, ["commit", "-am", "unmerged work"]); } if (state === "detached") yield* command(repo, ["checkout", "--detach"]); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome, reason }); expect(yield* fs.exists(worktree)).toBe(outcome === "kept"); // A full status walks the whole checkout; only a removable worktree pays for it. if (outcome === "kept") expect(statusCommands()).toBe(0); expect( (yield* command(repo, ["show-ref", "--verify", "refs/heads/feature"])).stdout, ).not.toBe(""); }), ), ); it.effect("compares against a project branch that ends in Unicode whitespace", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); yield* command(repo, ["branch", "-m", "main", "trunk "]); setThreads([shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) })]); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "removed", reason: "No commits beyond the project branch", }); expect(yield* fs.exists(worktree)).toBe(false); }), ), ); it.live("keeps an unsettled new thread's unchanged worktree after its first turn", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 11, worktreeOnMerge: true, worktreeUnchanged: true, }); const now = yield* DateTime.now; const minutesAgo = (minutes: number) => DateTime.subtract(now, { minutes }); const thread = shell({ branch: "feature", worktreePath: worktree, status: "completed", createdAt: minutesAgo(40), latestUserMessageAt: minutesAgo(40), latestRunRequestedAt: minutesAgo(40), latestRunStartedAt: minutesAgo(40), latestRunCompletedAt: minutesAgo(20), updatedAt: minutesAgo(20), }); setThreads([thread]); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "kept" }); expect(yield* fs.exists(worktree)).toBe(true); setThreads([{ ...thread, settledAt: minutesAgo(10), updatedAt: minutesAgo(10) }]); const settled = yield* service.runNow; expect(settled.entries[0]).toMatchObject({ outcome: "removed", reason: "No commits beyond the project branch", }); }), ), ); it.live( "discovers trunk without a remote HEAD or tracking ref and removes an integrated worktree", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); setThreads([ shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), ]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); yield* command(repo, ["push", "origin", "main:trunk"]); yield* command(repo, ["update-ref", "-d", "refs/remotes/origin/trunk"]); expect((yield* command(repo, ["for-each-ref", "refs/remotes/origin"])).stdout).toBe(""); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "removed", reason: "No commits beyond the default branch", }); expect(yield* fs.exists(worktree)).toBe(false); }), ), ); it.live( "keeps worktree commits present on nondefault main but absent from advertised trunk", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); setThreads([ shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), ]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); yield* command(repo, ["push", "origin", "main:trunk"]); yield* fs.writeFileString(`${worktree}/tracked.txt`, "unmerged work\n"); yield* command(worktree, ["commit", "-am", "unmerged work"]); yield* command(repo, ["push", "origin", "feature:main"]); expect( (yield* command(repo, ["symbolic-ref", "refs/remotes/origin/HEAD"]).pipe(Effect.exit)) ._tag, ).toBe("Failure"); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Has commits beyond the default branch", }); expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("unmerged work\n"); }), ), ); it.live("keeps the worktree when the remote default is unavailable even if main exists", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); setThreads([shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) })]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); // The remote HEAD names an unborn trunk; main exists but is not its default. yield* command(repo, ["push", "origin", "main"]); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Default branch is unavailable", }); expect(yield* fs.exists(worktree)).toBe(true); }), ), ); it.live("fetches a failing default branch once per sweep and names the broken local ref", () => runCleanupTest( Effect.gen(function* () { const { service, fs, repo, worktree, command, setThreads, setStoredWorktreePaths } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); const second = `${worktree}-2`; yield* command(repo, ["worktree", "add", "-b", "feature-2", second]); setStoredWorktreePaths([worktree, second]); setThreads([ shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), shell({ id: ThreadId.make("thread-2"), branch: "feature-2", worktreePath: second, archivedAt: at(-DAY_MS), }), ]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "main"]); yield* command(repo, ["remote", "add", "origin", remote]); yield* command(repo, ["push", "origin", "main"]); yield* command(repo, ["remote", "set-head", "origin", "main"]); yield* command(repo, ["commit", "--allow-empty", "-m", "remote only"]); yield* command(repo, ["push", "origin", "main"]); yield* command(repo, ["reset", "--hard", "HEAD~1"]); yield* command(repo, ["update-ref", "refs/remotes/origin/main", "HEAD"]); const trackingRef = yield* fs.readFileString(`${repo}/.git/refs/remotes/origin/main`); yield* fs.writeFileString(`${repo}/.git/refs/remotes/origin/main 2`, trackingRef); const fetchLog = `${remote}/fetches.log`; const uploadPack = `${remote}/upload-pack.sh`; yield* fs.writeFileString( uploadPack, `#!/bin/sh\necho fetch >> '${fetchLog}'\nexec git-upload-pack "$@"\n`, ); yield* fs.chmod(uploadPack, 0o755); yield* command(repo, ["config", "remote.origin.uploadpack", uploadPack]); const report = yield* service.runNow; expect((yield* fs.readFileString(fetchLog)).trim().split("\n")).toHaveLength(1); expect(report.entries).toHaveLength(2); for (const entry of report.entries) { expect(entry.outcome).not.toBe("removed"); expect(entry.reason).toContain("broken local ref"); } expect(yield* fs.exists(worktree)).toBe(true); expect(yield* fs.exists(second)).toBe(true); }), ), ); it.live("preserves tracked edits written after the final status check", () => runCleanupTest( Effect.gen(function* () { const fixture = yield* cleanupFixture(); fixture.setPolicy("tracked-changes"); fixture.editBeforeRemoval(); yield* fixture.fs.writeFileString(`${fixture.worktree}/notes.txt`, "untracked\n"); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "failed", bytes: null, files: null }); expect(report.bytesFreed).toBe(0); expect(report.entries[0]?.reason).toContain("contains modified or untracked files"); expect(yield* fixture.fs.readFileString(`${fixture.worktree}/tracked.txt`)).toBe( "late edit\n", ); expect(yield* fixture.fs.exists(`${fixture.worktree}/notes.txt`)).toBe(false); }), ), ); it.live("caps entries while preserving totals and prioritizing removals", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, setThreads } = yield* cleanupFixture(); const threads = []; for (let i = 0; i < 205; i++) { const worktreePath = `${worktree}-${i}`; yield* fs.makeDirectory(worktreePath); threads.push( shell({ id: ThreadId.make(`thread-${i + 2}`), branch: "feature", worktreePath, status: "running", }), ); } threads.push(shell({ branch: "feature", worktreePath: worktree })); setThreads(threads); const report = yield* service.runNow; expect(report.entries).toHaveLength(200); expect(report.omittedCount).toBe(6); expect(report.counts).toEqual({ removed: 1, kept: 205, failed: 0 }); expect(report.entries[0]?.outcome).toBe("removed"); expect(report.entries[0]?.bytes).toBeGreaterThan(0); expect(report.bytesFreed).toBe(report.entries[0]?.bytes); }), ), ); it.live("keeps staged edits in tracked-only mode", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, setPolicy, command } = yield* cleanupFixture(); setPolicy("tracked-changes"); yield* fs.writeFileString(`${worktree}/tracked.txt`, "staged\n"); yield* command(worktree, ["add", "tracked.txt"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept", reason: "Has uncommitted changes (1 file)", }); expect(yield* fs.exists(worktree)).toBe(true); }), ), ); it.live.each(["--assume-unchanged", "--skip-worktree"] as const)( "keeps tracked edits that git status hides (%s)", (flag) => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, command } = yield* cleanupFixture(); yield* command(worktree, ["update-index", flag, "tracked.txt"]); yield* fs.writeFileString(`${worktree}/tracked.txt`, "hidden edit\n"); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("hidden edit\n"); }), ), ); // macOS and Windows file systems reject names that are not valid UTF-8. it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( "keeps hidden edits to files whose names are not valid UTF-8", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, command } = yield* cleanupFixture(); const git = yield* GitVcsDriver.GitVcsDriver; // Git unquotes C-quoted paths on stdin, which reaches a name a JS string cannot. const quoted = '"bad-\\377.txt"'; const stdin = (args: string[], input: string) => git.execute({ operation: "cleanup-test", cwd: worktree, args, stdin: input }); const blob = (content: string) => stdin(["hash-object", "-w", "--stdin"], content).pipe( Effect.map((result) => result.stdout.trim()), ); const original = yield* blob("original\n"); yield* stdin(["update-index", "--index-info"], `100644 ${original}\t${quoted}\n`); yield* stdin(["checkout-index", "--stdin"], `${quoted}\n`); yield* command(worktree, ["commit", "-m", "bad name"]); // The committed content moves on while the file on disk keeps the other version. const edited = yield* blob("edited\n"); yield* stdin(["update-index", "--index-info"], `100644 ${edited}\t${quoted}\n`); yield* command(worktree, ["commit", "-m", "edit"]); yield* stdin(["update-index", "--assume-unchanged", "--stdin"], `${quoted}\n`); expect((yield* command(worktree, ["status", "--porcelain"])).stdout).toBe(""); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); expect((yield* fs.readDirectory(worktree)).some((name) => name.startsWith("bad-"))).toBe( true, ); }), ), ); it.live("removes worktrees whose flagged files are unchanged or outside a sparse checkout", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, command } = yield* cleanupFixture(); yield* command(worktree, ["update-index", "--skip-worktree", "tracked.txt"]); yield* fs.remove(`${worktree}/tracked.txt`); yield* command(worktree, ["update-index", "--assume-unchanged", ".gitignore"]); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); }), ), ); it.live.each([ ["missing", "symlink"], ["tracked.txt", "symlink"], ["missing", "file"], ["tracked.txt", "file"], ] as const)("compares flagged tracked symlinks by target (%s as a %s)", ([target, kind]) => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, command } = yield* cleanupFixture(); yield* fs.symlink("tracked.txt", `${worktree}/link`); yield* command(worktree, ["add", "link"]); yield* command(worktree, ["commit", "-m", "link"]); yield* command(worktree, ["update-index", "--assume-unchanged", "link"]); yield* fs.remove(`${worktree}/link`); // Without core.symlinks, Git checks a link out as a regular file holding its target. if (kind === "file") { yield* command(worktree, ["config", "core.symlinks", "false"]); yield* fs.writeFileString(`${worktree}/link`, target); } else yield* fs.symlink(target, `${worktree}/link`); expect((yield* service.runNow).entries[0]).toMatchObject( target === "missing" ? { outcome: "kept", reason: expect.stringContaining("(link)") } : { outcome: "removed" }, ); }), ), ); it.live.each([ ["uncommitted-changes", "untracked", "Local changes exceed the inspection limit"], ["any-local-files", "ignored", "Ignored files exceed the inspection limit"], ] as const)( "keeps a worktree under %s when its %s file listing exceeds the inspection limit", ([policy, kind, reason]) => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); setPolicy(policy); const files = Array.from({ length: 3000 }, (_, i) => kind === "untracked" ? `${worktree}/many/untracked-file-with-a-long-name-${i}.txt` : `${worktree}/many/ignored-directory-with-a-long-name-${i}/.env`, ); yield* fs.makeDirectory(`${worktree}/many`); yield* Effect.forEach( files, (file) => Effect.gen(function* () { if (kind === "ignored") yield* fs.makeDirectory(file.slice(0, -"/.env".length)); yield* fs.writeFileString(file, "local\n"); }), { concurrency: 64, discard: true }, ); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept", reason }); expect(yield* fs.exists(files[0]!)).toBe(true); }), ), ); it.live("serializes concurrent requests and returns each run's report", () => runCleanupTest( Effect.gen(function* () { const { service } = yield* cleanupFixture(); const reports = yield* Effect.all([service.runNow, service.runNow], { concurrency: "unbounded", }); yield* service.drain; expect( reports.flatMap((report) => report.entries).filter((entry) => entry.kind === "worktree"), ).toMatchObject([{ outcome: "removed" }]); expect(yield* service.latestReport).toEqual(reports[1]); }), ), ); it.live("aggregates expired artifacts and rotated logs while retaining current logs", () => runCleanupTest( Effect.gen(function* () { const { service, fs, config, enableFiles, disable } = yield* cleanupFixture(); disable(); enableFiles(); yield* fs.makeDirectory(config.browserArtifactsDir, { recursive: true }); yield* fs.makeDirectory(config.logsDir, { recursive: true }); for (const name of ["one.png", "two.webm"]) { const file = config.browserArtifactsDir + "/" + name; yield* fs.writeFileString(file, "capture"); yield* fs.utimes(file, 1, 1); } for (const name of ["server.log.1", "server.log.2", "server.log"]) { const file = config.logsDir + "/" + name; yield* fs.writeFileString(file, "log"); yield* fs.utimes(file, 1, 1); } const report = yield* service.runNow; expect(report.entries.filter((entry) => entry.kind !== "worktree")).toMatchObject([ { kind: "browser-artifacts", outcome: "removed", reason: "Removed 2 browser artifacts", bytes: 14, files: 2, }, { kind: "logs", outcome: "removed", reason: "Removed 2 rotated logs", bytes: 6, files: 2, }, ]); expect(report.bytesFreed).toBe(20); expect(yield* fs.readDirectory(config.browserArtifactsDir)).toEqual([]); expect(yield* fs.exists(config.logsDir + "/server.log")).toBe(true); expect(yield* fs.exists(config.logsDir + "/server.log.1")).toBe(false); expect(yield* fs.exists(config.logsDir + "/server.log.2")).toBe(false); }), ), ); it.live.each([ { kind: "logs", name: "server.log.1", label: "rotated logs" }, { kind: "browser-artifacts", name: "capture.png", label: "browser artifacts" }, ] as const)("skips dangling symlinks during $kind cleanup", ({ kind, name, label }) => runCleanupTest( Effect.gen(function* () { const { service, fs, config, enableFiles, disable } = yield* cleanupFixture(); disable(); enableFiles(); const directory = kind === "logs" ? `${config.logsDir}/nested` : config.browserArtifactsDir; yield* fs.makeDirectory(directory, { recursive: true }); const expired = `${directory}/${name}`; const dangling = `${directory}/00-dangling-${name}`; const linked = `${directory}/01-linked-${name}`; yield* fs.symlink("missing", dangling); yield* fs.symlink(directory, linked); yield* fs.writeFileString(expired, "expired"); yield* fs.utimes(expired, 1, 1); const report = yield* service.runNow; expect(report.entries.filter((entry) => entry.kind === kind)).toMatchObject([ { outcome: "removed", reason: `Removed 1 ${label}`, files: 1, bytes: 7 }, ]); expect((yield* fs.readDirectory(directory)).toSorted()).toEqual([ `00-dangling-${name}`, `01-linked-${name}`, ]); }), ), ); it.live.each([ { linked: "home", outcome: "removed", reason: "Removed 1 rotated logs" }, { linked: "logs folder", outcome: "kept", reason: "No expired files" }, ] as const)( "rotated logs behind a symlinked $linked are $outcome", ({ linked, outcome, reason }) => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; const disk = yield* fs.realPath(yield* fs.makeTempDirectoryScoped()); yield* fs.makeDirectory(`${disk}/real/logs`, { recursive: true }); if (linked === "home") { yield* fs.symlink(`${disk}/real`, `${disk}/home`); } else { yield* fs.makeDirectory(`${disk}/home`); yield* fs.symlink(`${disk}/real/logs`, `${disk}/home/logs`); } yield* fs.writeFileString(`${disk}/real/logs/server.log.1`, "log"); yield* fs.utimes(`${disk}/real/logs/server.log.1`, 1, 1); const { service, enableFiles, disable } = yield* cleanupFixture().pipe( Effect.provideService(ServerConfig.ServerConfig, { ...config, logsDir: `${disk}/home/logs`, }), ); disable(); enableFiles(); const report = yield* service.runNow; expect(report.entries.filter((entry) => entry.kind === "logs")).toMatchObject([ { outcome, reason }, ]); expect(yield* fs.exists(`${disk}/real/logs/server.log.1`)).toBe(outcome === "kept"); }), ), ); it.live("keeps external rotated logs when a scanned directory is replaced by a symlink", () => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; yield* fs.makeDirectory(config.logsDir, { recursive: true }); const nested = `${yield* fs.realPath(config.logsDir)}/nested`; const outside = yield* fs.makeTempDirectoryScoped(); const expired = `${outside}/server.log.1`; yield* fs.makeDirectory(nested); yield* fs.writeFileString(expired, "external log"); yield* fs.utimes(expired, 1, 1); const { service, enableFiles, disable } = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory, options) => Effect.gen(function* () { if (directory === nested) { yield* fs.rename(nested, `${nested}-original`); yield* fs.symlink(outside, nested); } return yield* fs.readDirectory(directory, options); }), }), ); disable(); enableFiles(); const report = yield* service.runNow; expect(yield* fs.exists(expired)).toBe(true); expect(report.entries.find((entry) => entry.kind === "logs")).toMatchObject({ outcome: "kept", reason: "No expired files", }); }), ), ); it.live("reports git failures without aborting the remaining categories", () => runCleanupTest( Effect.gen(function* () { const { service, worktree, command, enableFiles } = yield* cleanupFixture(); enableFiles(); yield* command(worktree, ["worktree", "lock", worktree]); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "failed" }); expect(report.entries[0]?.reason).toContain("git worktree remove: fatal:"); expect(report.entries.map((entry) => entry.kind)).toEqual([ "worktree", "browser-artifacts", "logs", ]); }), ), ); }); describe("settled worktree rechecks", () => { it.effect.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)( "keeps a usage-limited checkout when %s is enabled during measurement", (preference) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); fixture.setSettings({ autoResumeLimitedThreads: false, snoozeLimitedThreads: false }); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, status: "failed", latestRunId: RunId.make("limited-run"), lastErrorClass: "usage_limit", usageLimitResetAt: DateTime.formatIso(at(DAY_MS)), }), ]); const run = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(fixture.measuring); fixture.setSettings({ [preference]: true }); yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(run); expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Settings changed since check", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); it.effect("keeps a task folder when settings change after its checks began", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); fixture.setSettings({ autoResumeLimitedThreads: false, storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0, }, }); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, settledAt: at(0) }), ]); let removals = 0; fixture.setTaskFolders({ find: () => Effect.sync(() => { fixture.setSettings({ autoResumeLimitedThreads: true }); return { root: fixture.worktree, projectId: ProjectId.make("project-1"), projectRoot: fixture.repo, anchor: fixture.repo, projectPath: fixture.worktree, projectIsWorktree: true, repositories: [], }; }), remove: () => Effect.sync(() => { removals += 1; return { removed: [], kept: [] }; }), }); const report = yield* fixture.service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Settings changed since check", }); expect(removals).toBe(0); }), ), ); it.effect("keeps a task folder's checkout when settings change while it is measured", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); fixture.setSettings({ autoResumeLimitedThreads: false, storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0, }, }); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, settledAt: at(0) }), ]); fixture.setTaskFolders({ find: () => Effect.succeed({ root: fixture.worktree, projectId: ProjectId.make("project-1"), projectRoot: fixture.repo, anchor: fixture.repo, projectPath: fixture.worktree, projectIsWorktree: true, repositories: [], }), remove: (input) => Effect.gen(function* () { const verdict = yield* input.inspect!({ worktreePath: fixture.worktree, repositoryPath: fixture.repo, }); return { removed: [], kept: verdict.keep === null ? [] : [{ path: fixture.worktree, reason: verdict.keep }], }; }), }); const run = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(fixture.measuring); fixture.setSettings({ autoResumeLimitedThreads: true }); yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(run); expect(report.entries[0]).toMatchObject({ outcome: "kept", reason: "Settings changed since check", }); }), ), ); it.effect.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( "keeps a checkout changed during measurement (%j)", (change) => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const thread = shell({ branch: "feature", worktreePath: fixture.worktree, settledAt: at(0), }); fixture.setSettings({ storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0, }, }); fixture.setThreads([thread]); const run = yield* fixture.service.runNow.pipe(Effect.forkChild); yield* Deferred.await(fixture.measuring); fixture.setThreads([{ ...thread, ...change }]); yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(run); expect(report.entries[0]?.reason).toBe( "Thread activity or shared worktree changed since check", ); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); }); it.effect("keeps saved usage data when removing a settled checkout", () => runCleanupTest( Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); fixture.setSettings({ storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0 }, }); fixture.setThreads([ shell({ branch: "feature", worktreePath: fixture.worktree, settledAt: at(0) }), ]); yield* fixture.fs.makeDirectory(fixture.config.stateDir, { recursive: true }); const cachePath = `${fixture.config.stateDir}/${SCAN_CACHE_FILE_NAME}`; const savedUsage = JSON.stringify({ tokens: 12345, cost: 1.25 }); yield* fixture.fs.writeFileString(cachePath, savedUsage); expect((yield* fixture.service.runNow).counts.removed).toBe(1); expect(yield* fixture.fs.readFileString(cachePath)).toBe(savedUsage); }), ), );