The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import * as Clock from "effect/Clock"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Context from "effect/Context"; |
| 6 | import type * as Digest from "effect/crypto/Digest"; |
| 7 | import * as Base64Url from "effect/encoding/Base64Url"; |
| 8 | import * as Deferred from "effect/Deferred"; |
| 9 | import * as Fiber from "effect/Fiber"; |
| 10 | import * as FileSystem from "effect/FileSystem"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Queue from "effect/Queue"; |
| 14 | import type * as Path from "effect/Path"; |
| 15 | import type * as Scope from "effect/Scope"; |
| 16 | import * as Stream from "effect/Stream"; |
| 17 | import { SCAN_CACHE_FILE_NAME } from "./usage/usageScanCache.ts"; |
| 18 | import { TestClock } from "effect/testing"; |
| 19 | import * as SqlClient from "effect/sql/SqlClient"; |
| 20 | import * as Sqlite from "./persistence/Sqlite.ts"; |
| 21 | import { checkpointRefForScopeOrdinal } from "./orchestration-v2/CheckpointService.ts"; |
| 22 | import { |
| 23 | DEFAULT_SERVER_SETTINGS, |
| 24 | type WorktreeKeepWhen, |
| 25 | type StorageCleanupSettings, |
| 26 | type TerminalMetadataStreamEvent, |
| 27 | type TerminalSummary, |
| 28 | } from "@t3tools/contracts"; |
| 29 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 30 | import * as ServerConfig from "./config.ts"; |
| 31 | import * as StorageCleanup from "./storageCleanup.ts"; |
| 32 | import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; |
| 33 | import * as GitManager from "./git/GitManager.ts"; |
| 34 | import * as GitWorkflowService from "./git/GitWorkflowService.ts"; |
| 35 | import * as Settings from "./serverSettings.ts"; |
| 36 | import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; |
| 37 | import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; |
| 38 | import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; |
| 39 | import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; |
| 40 | import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; |
| 41 | import * as TerminalManager from "./terminal/Manager.ts"; |
| 42 | import { CodexProviderCapabilitiesV2 } from "./orchestration-v2/Adapters/CodexAdapterV2.ts"; |
| 43 | import { ServerActivation } from "./serverActivation.ts"; |
| 44 | import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; |
| 45 | import { describe, expect, it } from "@effect/vitest"; |
| 46 | import { |
| 47 | CheckpointScopeId, |
| 48 | EventId, |
| 49 | ProjectId, |
| 50 | ProviderDriverKind, |
| 51 | ProviderInstanceId, |
| 52 | ProviderSessionId, |
| 53 | RunId, |
| 54 | RuntimeRequestId, |
| 55 | ThreadId, |
| 56 | type OrchestrationV2DomainEvent, |
| 57 | type OrchestrationV2ServerCommand, |
| 58 | type OrchestrationV2ThreadShell, |
| 59 | } from "@t3tools/contracts"; |
| 60 | import * as DateTime from "effect/DateTime"; |
| 61 | import { |
| 62 | storageCleanupActivityAt, |
| 63 | storageCleanupPullRequestMerged, |
| 64 | storageCleanupThreadIdle, |
| 65 | } from "./storageCleanup.ts"; |
| 66 | |
| 67 | const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z"); |
| 68 | const DAY_MS = 24 * 60 * 60 * 1_000; |
| 69 | |
| 70 | function at(offsetMs: number): DateTime.Utc { |
| 71 | return DateTime.makeUnsafe(NOW_MS + offsetMs); |
| 72 | } |
| 73 | |
| 74 | function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell { |
| 75 | return { |
| 76 | id: ThreadId.make("thread-1"), |
| 77 | projectId: ProjectId.make("project-1"), |
| 78 | title: "Thread", |
| 79 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 80 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, |
| 81 | runtimeMode: "full-access", |
| 82 | interactionMode: "default", |
| 83 | worktreePath: null, |
| 84 | activeProviderThreadId: null, |
| 85 | lineage: { |
| 86 | rootThreadId: ThreadId.make("thread-1"), |
| 87 | parentThreadId: null, |
| 88 | relationshipToParent: null, |
| 89 | }, |
| 90 | forkedFrom: null, |
| 91 | createdBy: "user", |
| 92 | creationSource: "web", |
| 93 | activeRunId: null, |
| 94 | latestVisibleMessage: null, |
| 95 | hasActionableProposedPlan: false, |
| 96 | itemCount: 0, |
| 97 | visibleItemCount: 0, |
| 98 | lastVisitedAt: null, |
| 99 | deletedAt: null, |
| 100 | branch: null, |
| 101 | linkedPullRequest: null, |
| 102 | status: "idle", |
| 103 | activityRunStatus: null, |
| 104 | pendingRuntimeRequest: null, |
| 105 | pendingBackgroundTasks: [], |
| 106 | latestRunId: null, |
| 107 | latestRunRequestedAt: null, |
| 108 | latestRunStartedAt: null, |
| 109 | latestRunCompletedAt: null, |
| 110 | latestUserMessageAt: null, |
| 111 | createdAt: at(-30 * DAY_MS), |
| 112 | updatedAt: at(-10 * DAY_MS), |
| 113 | archivedAt: null, |
| 114 | settledOverride: null, |
| 115 | settledAt: null, |
| 116 | snoozedUntil: null, |
| 117 | snoozedAt: null, |
| 118 | pinnedAt: null, |
| 119 | ...overrides, |
| 120 | }; |
| 121 | } |
| 122 | |
| 123 | describe("V2 storage cleanup eligibility", () => { |
| 124 | const candidate = () => shell({ branch: "feature", worktreePath: "/worktrees/feature" }); |
| 125 | |
| 126 | it("allows an idle worktree and rejects the project checkout", () => { |
| 127 | expect(storageCleanupThreadIdle(candidate(), NOW_MS, DEFAULT_SERVER_SETTINGS)).toBe(true); |
| 128 | expect(storageCleanupThreadIdle(shell(), NOW_MS, DEFAULT_SERVER_SETTINGS)).toBe(false); |
| 129 | }); |
| 130 | |
| 131 | it.each(["running", "starting", "preparing", "waiting", "queued"] as const)( |
| 132 | "retains a worktree while its thread is %s", |
| 133 | (status) => { |
| 134 | expect( |
| 135 | storageCleanupThreadIdle(candidateWithStatus(status), NOW_MS, DEFAULT_SERVER_SETTINGS), |
| 136 | ).toBe(false); |
| 137 | }, |
| 138 | ); |
| 139 | |
| 140 | it.each(["completed", "interrupted", "cancelled", "rolled_back"] as const)( |
| 141 | "retains %s while background work is pending", |
| 142 | (status) => { |
| 143 | expect( |
| 144 | storageCleanupThreadIdle( |
| 145 | { |
| 146 | ...candidateWithStatus(status), |
| 147 | pendingBackgroundTasks: [{ taskId: "task-1", kind: "command" }], |
| 148 | }, |
| 149 | NOW_MS, |
| 150 | DEFAULT_SERVER_SETTINGS, |
| 151 | ), |
| 152 | ).toBe(false); |
| 153 | }, |
| 154 | ); |
| 155 | |
| 156 | it.each(["completed", "interrupted", "cancelled", "rolled_back"] as const)( |
| 157 | "retains %s while a runtime request is pending", |
| 158 | (status) => { |
| 159 | expect( |
| 160 | storageCleanupThreadIdle( |
| 161 | { |
| 162 | ...candidateWithStatus(status), |
| 163 | pendingRuntimeRequest: { |
| 164 | id: RuntimeRequestId.make("request-1"), |
| 165 | kind: "command", |
| 166 | createdAt: at(0), |
| 167 | }, |
| 168 | }, |
| 169 | NOW_MS, |
| 170 | DEFAULT_SERVER_SETTINGS, |
| 171 | ), |
| 172 | ).toBe(false); |
| 173 | }, |
| 174 | ); |
| 175 | |
| 176 | it("retains an active run even if the shell status is idle", () => { |
| 177 | expect( |
| 178 | storageCleanupThreadIdle( |
| 179 | { ...candidate(), activeRunId: RunId.make("run") }, |
| 180 | NOW_MS, |
| 181 | DEFAULT_SERVER_SETTINGS, |
| 182 | ), |
| 183 | ).toBe(false); |
| 184 | }); |
| 185 | |
| 186 | it("retains a queued prompt before the new run has been projected", () => { |
| 187 | expect( |
| 188 | storageCleanupThreadIdle( |
| 189 | { ...candidate(), latestUserMessageAt: at(-1_000) }, |
| 190 | NOW_MS, |
| 191 | DEFAULT_SERVER_SETTINGS, |
| 192 | ), |
| 193 | ).toBe(false); |
| 194 | }); |
| 195 | |
| 196 | it.each([ |
| 197 | { name: "snoozed until a future reset", snooze: true, resetIn: DAY_MS, idle: false }, |
| 198 | { name: "set to auto-resume", autoResume: true, resetIn: DAY_MS, idle: false }, |
| 199 | { name: "with recovery turned off", resetIn: DAY_MS, idle: true }, |
| 200 | { name: "auto-resuming after the reset", autoResume: true, resetIn: -1_000, idle: false }, |
| 201 | { name: "snoozed past its reset", snooze: true, resetIn: -1_000, idle: true }, |
| 202 | { |
| 203 | name: "settled with an auto-resume pending", |
| 204 | autoResume: true, |
| 205 | settled: true, |
| 206 | resetIn: -1_000, |
| 207 | idle: true, |
| 208 | }, |
| 209 | { name: "not yet armed by the recovery worker", armed: false, resetIn: DAY_MS, idle: false }, |
| 210 | { |
| 211 | name: "not yet armed, auto-resume after reset", |
| 212 | armed: false, |
| 213 | autoResumeSetting: true, |
| 214 | resetIn: -1_000, |
| 215 | idle: false, |
| 216 | }, |
| 217 | { |
| 218 | name: "never armed because its reset is days overdue", |
| 219 | armed: false, |
| 220 | autoResumeSetting: true, |
| 221 | resetIn: -5 * DAY_MS, |
| 222 | idle: true, |
| 223 | }, |
| 224 | { |
| 225 | name: "not armed with recovery settings off", |
| 226 | armed: false, |
| 227 | settingsOff: true, |
| 228 | resetIn: DAY_MS, |
| 229 | idle: true, |
| 230 | }, |
| 231 | ])( |
| 232 | "treats a usage-limited thread $name as idle: $idle", |
| 233 | ({ |
| 234 | autoResume = false, |
| 235 | snooze = false, |
| 236 | armed = true, |
| 237 | autoResumeSetting = false, |
| 238 | settled, |
| 239 | settingsOff, |
| 240 | resetIn, |
| 241 | idle, |
| 242 | }) => { |
| 243 | const runId = RunId.make("run-1"); |
| 244 | const resetAt = DateTime.formatIso(at(resetIn)); |
| 245 | expect( |
| 246 | storageCleanupThreadIdle( |
| 247 | { |
| 248 | ...candidateWithStatus("failed"), |
| 249 | latestRunId: runId, |
| 250 | lastErrorClass: "usage_limit", |
| 251 | usageLimitResetAt: resetAt, |
| 252 | settledOverride: settled ? "settled" : null, |
| 253 | limitRecovery: armed ? { runId, resetAt, autoResume, snooze } : null, |
| 254 | }, |
| 255 | NOW_MS, |
| 256 | { autoResumeLimitedThreads: autoResumeSetting, snoozeLimitedThreads: !settingsOff }, |
| 257 | ), |
| 258 | ).toBe(idle); |
| 259 | }, |
| 260 | ); |
| 261 | |
| 262 | it("uses V2 run activity instead of metadata refreshes for retention", () => { |
| 263 | const thread = candidate(); |
| 264 | const runTime = at(-3 * DAY_MS); |
| 265 | expect( |
| 266 | storageCleanupActivityAt({ ...thread, latestRunCompletedAt: runTime, updatedAt: at(0) }), |
| 267 | ).toBe(DateTime.toEpochMillis(runTime)); |
| 268 | }); |
| 269 | |
| 270 | function candidateWithStatus(status: OrchestrationV2ThreadShell["status"]) { |
| 271 | return { ...candidate(), status }; |
| 272 | } |
| 273 | }); |
| 274 | |
| 275 | describe("merged pull request cleanup", () => { |
| 276 | const HEAD_SHA = "a".repeat(40); |
| 277 | const integrated = { |
| 278 | branch: "feature", |
| 279 | defaultBranch: "main", |
| 280 | headSha: HEAD_SHA, |
| 281 | integrated: true, |
| 282 | }; |
| 283 | const squashed = { ...integrated, integrated: false }; |
| 284 | const pullRequest = ( |
| 285 | overrides: Partial<NonNullable<Parameters<typeof storageCleanupPullRequestMerged>[0]>> = {}, |
| 286 | ) => ({ |
| 287 | state: "merged" as const, |
| 288 | headRef: "feature", |
| 289 | baseRef: "main", |
| 290 | headSha: HEAD_SHA, |
| 291 | ...overrides, |
| 292 | }); |
| 293 | |
| 294 | it("removes a worktree whose head reached the default branch through a merged pull request", () => { |
| 295 | expect(storageCleanupPullRequestMerged(pullRequest({ headSha: null }), integrated)).toBe(true); |
| 296 | }); |
| 297 | |
| 298 | it("removes a squash-merged worktree when the pull request names its exact head", () => { |
| 299 | expect(storageCleanupPullRequestMerged(pullRequest(), squashed)).toBe(true); |
| 300 | }); |
| 301 | |
| 302 | it.each([ |
| 303 | ["has a later commit than the merged head", { headSha: "c".repeat(40) }], |
| 304 | ["was merged into a release branch", { baseRef: "release" }], |
| 305 | ["was merged into its stack parent", { baseRef: "stack-parent" }], |
| 306 | ["was merged without a reported head commit", { headSha: null }], |
| 307 | ["belongs to a different branch", { headRef: "other" }], |
| 308 | ["is still open", { state: "open" }], |
| 309 | ["was closed without merging", { state: "closed" }], |
| 310 | ] as const)("keeps a squash worktree whose pull request %s", (_name, overrides) => { |
| 311 | expect(storageCleanupPullRequestMerged(pullRequest(overrides), squashed)).toBe(false); |
| 312 | }); |
| 313 | |
| 314 | it("keeps a worktree with no pull request, or one that is not merged", () => { |
| 315 | expect(storageCleanupPullRequestMerged(null, squashed)).toBe(false); |
| 316 | expect(storageCleanupPullRequestMerged(null, integrated)).toBe(false); |
| 317 | expect(storageCleanupPullRequestMerged(pullRequest({ state: "open" }), integrated)).toBe(false); |
| 318 | }); |
| 319 | }); |
| 320 | |
| 321 | const allocatedBytes = (fs: FileSystem.FileSystem, file: string) => |
| 322 | fs.stat(file).pipe( |
| 323 | Effect.map((stat) => |
| 324 | Option.getOrElse( |
| 325 | Option.map(stat.blocks, (blocks) => Number(blocks) * 512), |
| 326 | () => Number(stat.size), |
| 327 | ), |
| 328 | ), |
| 329 | ); |
| 330 | |
| 331 | const cleanupFixture = ( |
| 332 | storageCleanup: StorageCleanupSettings = { |
| 333 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 334 | worktreeAfterDays: 8, |
| 335 | worktreeOnDelete: true, |
| 336 | }, |
| 337 | sqlOverride?: SqlClient.SqlClient, |
| 338 | ) => |
| 339 | Effect.gen(function* () { |
| 340 | const fs = yield* FileSystem.FileSystem; |
| 341 | const config = yield* ServerConfig.ServerConfig; |
| 342 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 343 | const repo = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" })); |
| 344 | const command = (cwd: string, args: string[]) => |
| 345 | git.execute({ operation: "cleanup-test", cwd, args }); |
| 346 | yield* command(repo, ["init", "-b", "main"]); |
| 347 | yield* command(repo, ["config", "user.email", "cleanup@example.test"]); |
| 348 | yield* command(repo, ["config", "user.name", "Cleanup test"]); |
| 349 | yield* fs.writeFileString(`${repo}/tracked.txt`, "original\n"); |
| 350 | yield* fs.writeFileString(`${repo}/.gitignore`, ".env\ndist/\nnode_modules/\n"); |
| 351 | yield* command(repo, ["add", "."]); |
| 352 | yield* command(repo, ["commit", "-m", "initial"]); |
| 353 | yield* fs.makeDirectory(config.worktreesDir, { recursive: true }); |
| 354 | const worktree = `${config.worktreesDir}/feature`; |
| 355 | yield* command(repo, ["worktree", "add", "-b", "feature", worktree]); |
| 356 | let settings: import("@t3tools/contracts").ServerSettings = { |
| 357 | ...DEFAULT_SERVER_SETTINGS, |
| 358 | storageCleanup, |
| 359 | }; |
| 360 | let threads = [shell({ branch: "feature", worktreePath: worktree })]; |
| 361 | let deletedThreads: OrchestrationV2ThreadShell[] = []; |
| 362 | let storedWorktreePaths: string[] = [worktree]; |
| 363 | let projectRoots = [repo]; |
| 364 | let editBeforeRemoval = false; |
| 365 | let openSessionCwd: string | null = null; |
| 366 | let sessionLive = true; |
| 367 | let sessionLiveChecks = 0; |
| 368 | let onLiveCheck: Effect.Effect<void> = Effect.void; |
| 369 | let outboxStatus: string | null = null; |
| 370 | let scheduledThreadIds: string[] = []; |
| 371 | let fullStatusCalls = 0; |
| 372 | let gitInspections = 0; |
| 373 | let snapshotReads = 0; |
| 374 | let terminalListener: ((event: TerminalMetadataStreamEvent) => Effect.Effect<void>) | undefined; |
| 375 | let events: Stream.Stream<OrchestrationV2DomainEvent> = Stream.empty; |
| 376 | const activated = yield* Deferred.make<void>(); |
| 377 | const context = yield* Layer.build(StorageCleanup.layer).pipe( |
| 378 | Effect.provideService(GitVcsDriver.GitVcsDriver, { |
| 379 | ...git, |
| 380 | execute: (input) => |
| 381 | Effect.gen(function* () { |
| 382 | gitInspections++; |
| 383 | // Before Git's own clean check: inside `git worktree remove`, or on |
| 384 | // Windows the same status check the removal makes before deleting. |
| 385 | if ( |
| 386 | editBeforeRemoval && |
| 387 | (input.args.includes("remove") || input.args.includes("--porcelain")) |
| 388 | ) |
| 389 | yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n"); |
| 390 | return yield* git.execute(input); |
| 391 | }), |
| 392 | statusDetailsLocal: (...args) => { |
| 393 | fullStatusCalls++; |
| 394 | return git.statusDetailsLocal(...args); |
| 395 | }, |
| 396 | }), |
| 397 | Effect.provideService(Settings.ServerSettingsService, { |
| 398 | getSettings: Effect.sync(() => settings), |
| 399 | subscribeChanges: Effect.succeed(Stream.empty), |
| 400 | } as unknown as Settings.ServerSettingsService["Service"]), |
| 401 | Effect.provideService(ProjectStore.ProjectStoreV2, { |
| 402 | list: () => Effect.sync(() => projectRoots.map((workspaceRoot) => ({ workspaceRoot }))), |
| 403 | listShells: () => |
| 404 | Effect.sync(() => |
| 405 | projectRoots.map((workspaceRoot, index) => ({ |
| 406 | id: ProjectId.make(`project-${index + 1}`), |
| 407 | workspaceRoot, |
| 408 | })), |
| 409 | ), |
| 410 | } as unknown as ProjectStore.ProjectStoreV2["Service"]), |
| 411 | Effect.provideService(ProjectionStore.ProjectionStoreV2, { |
| 412 | getShellSnapshot: (input?: { location?: string }) => |
| 413 | Effect.sync(() => { |
| 414 | snapshotReads++; |
| 415 | const visible = threads.filter((thread) => thread.deletedAt === null); |
| 416 | return { |
| 417 | threads: |
| 418 | input?.location === "archive" |
| 419 | ? [] |
| 420 | : visible.filter((thread) => thread.archivedAt === null), |
| 421 | archivedThreads: |
| 422 | input?.location === "active" |
| 423 | ? [] |
| 424 | : visible.filter((thread) => thread.archivedAt !== null), |
| 425 | }; |
| 426 | }), |
| 427 | getThreadWorktreePaths: (input?: { includeArchived?: boolean }) => |
| 428 | Effect.sync(() => |
| 429 | threads.flatMap((thread) => |
| 430 | thread.deletedAt === null && |
| 431 | (input?.includeArchived === true || thread.archivedAt === null) && |
| 432 | thread.worktreePath !== null |
| 433 | ? [{ threadId: thread.id, worktreePath: thread.worktreePath }] |
| 434 | : [], |
| 435 | ), |
| 436 | ), |
| 437 | getThreadShell: (threadId: ThreadId) => |
| 438 | Effect.sync(() => threads.find((thread) => thread.id === threadId) ?? null), |
| 439 | } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), |
| 440 | Effect.provideService(ThreadManagement.ThreadManagementService, { |
| 441 | getShellSnapshot: (input?: { threadIds?: ReadonlyArray<ThreadId> }) => |
| 442 | Effect.sync(() => ({ |
| 443 | threads: threads.filter((thread) => input?.threadIds?.includes(thread.id) ?? true), |
| 444 | archivedThreads: [], |
| 445 | })), |
| 446 | dispatch: (command: OrchestrationV2ServerCommand) => |
| 447 | Effect.sync(() => { |
| 448 | if (command.type === "thread.metadata.update" && command.branch != null) { |
| 449 | const branch = command.branch; |
| 450 | threads = threads.map((thread) => |
| 451 | thread.id === command.threadId && thread.branch === command.expectedBranch |
| 452 | ? { ...thread, branch } |
| 453 | : thread, |
| 454 | ); |
| 455 | } |
| 456 | return { sequence: 0, storedEvents: [] }; |
| 457 | }), |
| 458 | } as unknown as ThreadManagement.ThreadManagementService["Service"]), |
| 459 | Effect.provideService(GitWorkflowService.GitWorkflowService, { |
| 460 | currentBranch: (cwd: string) => |
| 461 | command(cwd, ["branch", "--show-current"]).pipe( |
| 462 | Effect.map((result) => result.stdout.trim() || null), |
| 463 | ), |
| 464 | } as unknown as GitWorkflowService.GitWorkflowService["Service"]), |
| 465 | Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, { |
| 466 | isLive: () => |
| 467 | Effect.sync(() => { |
| 468 | sessionLiveChecks++; |
| 469 | return sessionLive; |
| 470 | }).pipe(Effect.tap(() => Effect.suspend(() => onLiveCheck))), |
| 471 | } as unknown as ProviderSessionManager.ProviderSessionManagerV2["Service"]), |
| 472 | Effect.provideService(Orchestrator.OrchestratorV2, { |
| 473 | streamDomainEvents: Stream.suspend(() => events), |
| 474 | } as unknown as Orchestrator.OrchestratorV2["Service"]), |
| 475 | Effect.provideService( |
| 476 | SqlClient.SqlClient, |
| 477 | sqlOverride ?? |
| 478 | (((strings: TemplateStringsArray) => |
| 479 | Effect.sync(() => |
| 480 | strings.join("").includes("retained_checkpoint_threads") |
| 481 | ? [] |
| 482 | : openSessionCwd !== null && |
| 483 | strings.join("").includes("projection_provider_sessions") |
| 484 | ? [ |
| 485 | { |
| 486 | payload_json: JSON.stringify({ |
| 487 | id: "session-1", |
| 488 | driver: "codex", |
| 489 | providerInstanceId: "codex", |
| 490 | status: "ready", |
| 491 | cwd: openSessionCwd, |
| 492 | model: null, |
| 493 | capabilities: CodexProviderCapabilitiesV2, |
| 494 | createdAt: "2026-06-01T12:00:00.000Z", |
| 495 | updatedAt: "2026-06-01T12:00:00.000Z", |
| 496 | lastError: null, |
| 497 | }), |
| 498 | }, |
| 499 | ] |
| 500 | : outboxStatus !== null && |
| 501 | strings.join("").includes("orchestration_v2_effect_outbox") |
| 502 | ? [{ status: outboxStatus }] |
| 503 | : strings.join("").includes("deleted_at IS NOT NULL") |
| 504 | ? deletedThreads.map((thread) => ({ |
| 505 | payload_json: JSON.stringify(thread), |
| 506 | workspaceRoot: repo, |
| 507 | })) |
| 508 | : strings.join("").includes('AS "worktreePath"') |
| 509 | ? [ |
| 510 | ...threads.flatMap((thread) => thread.worktreePath ?? []), |
| 511 | ...storedWorktreePaths, |
| 512 | ].map((worktreePath) => ({ worktreePath })) |
| 513 | : strings.join("").includes("scheduled_tasks") |
| 514 | ? scheduledThreadIds.map((threadId) => ({ threadId })) |
| 515 | : [], |
| 516 | )) as unknown as SqlClient.SqlClient), |
| 517 | ), |
| 518 | Effect.provideService(GitManager.GitManager, { |
| 519 | invalidateStatus: () => Effect.void, |
| 520 | } as unknown as GitManager.GitManager["Service"]), |
| 521 | Effect.provideService(TerminalManager.TerminalManager, { |
| 522 | subscribeMetadata: ( |
| 523 | listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>, |
| 524 | ) => |
| 525 | Effect.sync(() => { |
| 526 | terminalListener = listener; |
| 527 | return () => {}; |
| 528 | }), |
| 529 | } as unknown as TerminalManager.TerminalManager["Service"]), |
| 530 | Effect.provideService(ServerActivation, Deferred.await(activated)), |
| 531 | ); |
| 532 | return { |
| 533 | service: Context.get(context, StorageCleanup.StorageCleanup), |
| 534 | repo, |
| 535 | setTerminals: (terminals: TerminalSummary[]) => |
| 536 | terminalListener?.({ type: "snapshot", terminals }) ?? Effect.void, |
| 537 | editBeforeRemoval: () => { |
| 538 | editBeforeRemoval = true; |
| 539 | }, |
| 540 | fs, |
| 541 | worktree, |
| 542 | config, |
| 543 | command, |
| 544 | enableFiles: () => { |
| 545 | settings = { |
| 546 | ...settings, |
| 547 | storageCleanup: { |
| 548 | ...settings.storageCleanup, |
| 549 | browserArtifactsAfterDays: 8, |
| 550 | logsAfterDays: 8, |
| 551 | }, |
| 552 | }; |
| 553 | }, |
| 554 | setSettings: (next: Partial<typeof settings>) => { |
| 555 | settings = { ...settings, ...next }; |
| 556 | }, |
| 557 | setPolicy: (worktreeKeepWhen: WorktreeKeepWhen) => { |
| 558 | settings = { |
| 559 | ...settings, |
| 560 | storageCleanup: { ...settings.storageCleanup, worktreeKeepWhen }, |
| 561 | }; |
| 562 | }, |
| 563 | disable: () => { |
| 564 | settings = { |
| 565 | ...settings, |
| 566 | storageCleanup: { |
| 567 | ...settings.storageCleanup, |
| 568 | worktreeAfterDays: null, |
| 569 | worktreeOnDelete: false, |
| 570 | }, |
| 571 | }; |
| 572 | }, |
| 573 | setThreads: (next: typeof threads) => { |
| 574 | threads = next; |
| 575 | }, |
| 576 | threadBranches: () => threads.map((thread) => thread.branch), |
| 577 | setOnLiveCheck: (hook: Effect.Effect<void>) => { |
| 578 | onLiveCheck = hook; |
| 579 | }, |
| 580 | setOutboxStatus: (status: string | null) => { |
| 581 | outboxStatus = status; |
| 582 | }, |
| 583 | setScheduledThreadIds: (next: string[]) => { |
| 584 | scheduledThreadIds = next; |
| 585 | }, |
| 586 | setDeletedThreads: (next: OrchestrationV2ThreadShell[]) => { |
| 587 | deletedThreads = next; |
| 588 | }, |
| 589 | setStoredWorktreePaths: (paths: string[]) => { |
| 590 | storedWorktreePaths = paths; |
| 591 | }, |
| 592 | setProjectRoots: (roots: string[]) => { |
| 593 | projectRoots = roots; |
| 594 | }, |
| 595 | setSessionLive: (live: boolean) => { |
| 596 | sessionLive = live; |
| 597 | }, |
| 598 | setOpenSessionCwd: (cwd: string | null) => { |
| 599 | openSessionCwd = cwd; |
| 600 | }, |
| 601 | openTerminal: (paths: { cwd: string; worktreePath: string | null }) => |
| 602 | terminalListener?.({ |
| 603 | type: "upsert", |
| 604 | terminal: { |
| 605 | threadId: "thread-1", |
| 606 | terminalId: "terminal-1", |
| 607 | status: "running", |
| 608 | pid: 1, |
| 609 | exitCode: null, |
| 610 | exitSignal: null, |
| 611 | hasRunningSubprocess: false, |
| 612 | label: "Terminal", |
| 613 | updatedAt: "2026-06-10T12:00:00.000Z", |
| 614 | ...paths, |
| 615 | }, |
| 616 | }) ?? Effect.void, |
| 617 | gitInspections: () => gitInspections, |
| 618 | fullStatusCalls: () => fullStatusCalls, |
| 619 | snapshotReads: () => snapshotReads, |
| 620 | sessionLiveChecks: () => sessionLiveChecks, |
| 621 | activate: (domainEvents: Stream.Stream<OrchestrationV2DomainEvent>) => { |
| 622 | events = domainEvents; |
| 623 | return Deferred.succeed(activated, undefined); |
| 624 | }, |
| 625 | }; |
| 626 | }); |
| 627 | const pausedMeasurementFixture = (storageCleanup?: StorageCleanupSettings) => |
| 628 | Effect.gen(function* () { |
| 629 | const fs = yield* FileSystem.FileSystem; |
| 630 | const measuring = yield* Deferred.make<void>(); |
| 631 | const resume = yield* Deferred.make<void>(); |
| 632 | let measuredPath: string | undefined; |
| 633 | const fixture = yield* cleanupFixture(storageCleanup).pipe( |
| 634 | Effect.provideService(FileSystem.FileSystem, { |
| 635 | ...fs, |
| 636 | readDirectory: (directory, options) => |
| 637 | Effect.gen(function* () { |
| 638 | if (directory === measuredPath) { |
| 639 | yield* Deferred.succeed(measuring, undefined); |
| 640 | yield* Deferred.await(resume); |
| 641 | } |
| 642 | return yield* fs.readDirectory(directory, options); |
| 643 | }), |
| 644 | }), |
| 645 | ); |
| 646 | measuredPath = yield* fs.realPath(fixture.worktree); |
| 647 | return { ...fixture, measuring, resume }; |
| 648 | }); |
| 649 | const cleanupTestLayer = GitVcsDriver.layer.pipe( |
| 650 | Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "storage-cleanup-" })), |
| 651 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 652 | ); |
| 653 | const annexWorktree = Effect.fnUntraced(function* ( |
| 654 | fixture: Effect.Success<ReturnType<typeof cleanupFixture>>, |
| 655 | worktree: string, |
| 656 | ) { |
| 657 | const adminDir = (yield* fixture.command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout; |
| 658 | yield* fixture.fs.remove(`${worktree}/.git`); |
| 659 | yield* fixture.fs.symlink(adminDir.trim(), `${worktree}/.git`); |
| 660 | }); |
| 661 | |
| 662 | const runCleanupTest = <A, E>( |
| 663 | effect: Effect.Effect< |
| 664 | A, |
| 665 | E, |
| 666 | | FileSystem.FileSystem |
| 667 | | Digest.Digest |
| 668 | | ServerConfig.ServerConfig |
| 669 | | GitVcsDriver.GitVcsDriver |
| 670 | | Path.Path |
| 671 | | Scope.Scope |
| 672 | >, |
| 673 | ) => effect.pipe(Effect.provide(cleanupTestLayer)); |
| 674 | |
| 675 | const legacyCheckpointRef = (threadId: string, turn: number) => |
| 676 | `refs/t3/checkpoints/${Base64Url.encode(threadId)}/turn/${turn}`; |
| 677 | |
| 678 | const checkpointCleanupFixture = Effect.fn("test.checkpointCleanupFixture")(function* () { |
| 679 | const sql = yield* SqlClient.SqlClient; |
| 680 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 681 | const fixture = yield* cleanupFixture(DEFAULT_SERVER_SETTINGS.storageCleanup, sql); |
| 682 | const { repo, worktree, command } = fixture; |
| 683 | const timestamp = DateTime.formatIso(at(0)); |
| 684 | yield* sql`INSERT INTO projection_projects ${sql.insert({ |
| 685 | project_id: "project-1", |
| 686 | title: "Checkpoint cleanup", |
| 687 | workspace_root: repo, |
| 688 | scripts_json: "[]", |
| 689 | created_at: timestamp, |
| 690 | updated_at: timestamp, |
| 691 | deleted_at: timestamp, |
| 692 | })}`; |
| 693 | const addThread = Effect.fn("test.addCheckpointThread")(function* ( |
| 694 | id: string, |
| 695 | options: { deleted?: boolean; archived?: boolean; source?: string; legacyOnly?: boolean } = {}, |
| 696 | ) { |
| 697 | const scopeId = CheckpointScopeId.make(`scope:${id}`); |
| 698 | yield* sql`INSERT INTO orchestration_v2_projection_threads ${sql.insert({ |
| 699 | thread_id: id, |
| 700 | project_id: "project-1", |
| 701 | title: id, |
| 702 | default_provider: "codex", |
| 703 | runtime_mode: "full-access", |
| 704 | interaction_mode: "default", |
| 705 | created_at: timestamp, |
| 706 | updated_at: timestamp, |
| 707 | archived_at: options.archived ? timestamp : null, |
| 708 | deleted_at: options.deleted ? timestamp : null, |
| 709 | payload_json: JSON.stringify({ |
| 710 | worktreePath: worktree, |
| 711 | forkedFrom: options.source ? { type: "run", threadId: options.source } : null, |
| 712 | }), |
| 713 | })}`; |
| 714 | if (!options.legacyOnly) |
| 715 | yield* sql`INSERT INTO orchestration_v2_projection_checkpoint_scopes ${sql.insert({ |
| 716 | scope_id: scopeId, |
| 717 | thread_id: id, |
| 718 | node_id: `node:${id}`, |
| 719 | kind: "root_run", |
| 720 | ordinal_within_parent: 0, |
| 721 | advances_app_run_count: 1, |
| 722 | created_at: timestamp, |
| 723 | payload_json: JSON.stringify({ cwd: worktree }), |
| 724 | })}`; |
| 725 | const refs: string[] = options.legacyOnly |
| 726 | ? [legacyCheckpointRef(id, 0)] |
| 727 | : [ |
| 728 | yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 0 }), |
| 729 | yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 1 }), |
| 730 | legacyCheckpointRef(id, 0), |
| 731 | ]; |
| 732 | for (const ref of refs) yield* command(repo, ["update-ref", ref, "HEAD"]); |
| 733 | return refs; |
| 734 | }); |
| 735 | const listRefs = () => |
| 736 | git |
| 737 | .execute({ |
| 738 | operation: "cleanup-test.list-checkpoints", |
| 739 | cwd: repo, |
| 740 | args: ["for-each-ref", "--format=%(refname)", "refs/t3/"], |
| 741 | maxOutputBytes: 16 * 1024 * 1024, |
| 742 | }) |
| 743 | .pipe(Effect.map(({ stdout }) => stdout.trim().split("\n").filter(Boolean).sort())); |
| 744 | return { ...fixture, sql, addThread, listRefs }; |
| 745 | }); |
| 746 | |
| 747 | describe("checkpoint ref cleanup", () => { |
| 748 | it.live("prunes refs owned by deleted threads after their worktree is removed", () => |
| 749 | runCleanupTest( |
| 750 | Effect.gen(function* () { |
| 751 | const { service, repo, worktree, command, addThread, listRefs } = |
| 752 | yield* checkpointCleanupFixture(); |
| 753 | yield* addThread("deleted", { deleted: true }); |
| 754 | yield* addThread("imported-deleted", { deleted: true, legacyOnly: true }); |
| 755 | const retained = [ |
| 756 | ...(yield* addThread("active")), |
| 757 | ...(yield* addThread("archived", { archived: true })), |
| 758 | legacyCheckpointRef("unknown-owner", 0), |
| 759 | ]; |
| 760 | yield* command(repo, ["update-ref", retained.at(-1)!, "HEAD"]); |
| 761 | yield* command(repo, ["pack-refs", "--all"]); |
| 762 | yield* command(repo, ["worktree", "remove", worktree]); |
| 763 | yield* service.runNow; |
| 764 | expect(yield* listRefs()).toEqual(retained.sort()); |
| 765 | }).pipe(Effect.provide(Sqlite.layerMemory)), |
| 766 | ), |
| 767 | ); |
| 768 | |
| 769 | it.live("keeps deleted fork ancestry while a live or archived descendant needs it", () => |
| 770 | runCleanupTest( |
| 771 | Effect.gen(function* () { |
| 772 | const { service, sql, addThread, listRefs } = yield* checkpointCleanupFixture(); |
| 773 | const root = yield* addThread("root", { deleted: true }); |
| 774 | const intermediate = yield* addThread("intermediate", { deleted: true, source: "root" }); |
| 775 | const child = yield* addThread("child", { archived: true, source: "intermediate" }); |
| 776 | yield* service.runNow; |
| 777 | expect(yield* listRefs()).toEqual([...root, ...intermediate, ...child].sort()); |
| 778 | yield* sql`UPDATE orchestration_v2_projection_threads SET deleted_at = 'deleted' WHERE thread_id = 'child'`; |
| 779 | yield* service.runNow; |
| 780 | expect(yield* listRefs()).toEqual([]); |
| 781 | }).pipe(Effect.provide(Sqlite.layerMemory)), |
| 782 | ), |
| 783 | ); |
| 784 | |
| 785 | it.live("waits for a deleted thread's pending checkpoint effects", () => |
| 786 | runCleanupTest( |
| 787 | Effect.gen(function* () { |
| 788 | const { service, sql, addThread, listRefs } = yield* checkpointCleanupFixture(); |
| 789 | const refs = yield* addThread("capturing", { deleted: true }); |
| 790 | yield* sql`INSERT INTO orchestration_v2_effect_outbox ${sql.insert({ |
| 791 | effect_id: "capture", |
| 792 | command_id: "capture", |
| 793 | thread_id: "capturing", |
| 794 | effect_type: "checkpoint.capture", |
| 795 | payload_json: "{}", |
| 796 | status: "running", |
| 797 | available_at: "2026-01-01T00:00:00Z", |
| 798 | created_at: "2026-01-01T00:00:00Z", |
| 799 | updated_at: "2026-01-01T00:00:00Z", |
| 800 | })}`; |
| 801 | yield* service.runNow; |
| 802 | expect(yield* listRefs()).toEqual(refs.toSorted()); |
| 803 | yield* sql`UPDATE orchestration_v2_effect_outbox SET status = 'succeeded'`; |
| 804 | yield* service.runNow; |
| 805 | expect(yield* listRefs()).toEqual([]); |
| 806 | }).pipe(Effect.provide(Sqlite.layerMemory)), |
| 807 | ), |
| 808 | ); |
| 809 | |
| 810 | it.live("deletes a symbolic checkpoint ref without its target or neighbouring refs", () => |
| 811 | runCleanupTest( |
| 812 | Effect.gen(function* () { |
| 813 | const { service, repo, command, addThread, listRefs } = yield* checkpointCleanupFixture(); |
| 814 | const refs = yield* addThread("deleted", { deleted: true }); |
| 815 | yield* command(repo, ["symbolic-ref", refs[0]!, "refs/heads/main"]); |
| 816 | const retained = [ |
| 817 | "refs/t3/unrelated/0", |
| 818 | `${refs[1]}-other`, |
| 819 | refs[1]!.replace(/1$/, "2/nested"), |
| 820 | ]; |
| 821 | for (const ref of retained) yield* command(repo, ["update-ref", ref, "HEAD"]); |
| 822 | yield* service.runNow; |
| 823 | expect(yield* listRefs()).toEqual(retained.sort()); |
| 824 | yield* command(repo, ["show-ref", "--verify", "refs/heads/main"]); |
| 825 | }).pipe(Effect.provide(Sqlite.layerMemory)), |
| 826 | ), |
| 827 | ); |
| 828 | |
| 829 | it.live("cleans more checkpoint refs than default git output holds", () => |
| 830 | runCleanupTest( |
| 831 | Effect.gen(function* () { |
| 832 | const { service, repo, addThread, listRefs } = yield* checkpointCleanupFixture(); |
| 833 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 834 | const prefix = (yield* addThread("many-checkpoints", { deleted: true }))[0]!.slice(0, -1); |
| 835 | yield* git.execute({ |
| 836 | operation: "cleanup-test.seed-checkpoints", |
| 837 | cwd: repo, |
| 838 | args: ["update-ref", "--stdin"], |
| 839 | stdin: Array.from( |
| 840 | { length: 12_283 }, |
| 841 | (_, ordinal) => `update ${prefix}${ordinal} HEAD\n`, |
| 842 | ).join(""), |
| 843 | }); |
| 844 | yield* service.runNow; |
| 845 | expect(yield* listRefs()).toEqual([]); |
| 846 | }).pipe(Effect.provide(Sqlite.layerMemory)), |
| 847 | ), |
| 848 | ); |
| 849 | }); |
| 850 | |
| 851 | it.live.each(["repository", "uppercase", "bare"] as const)( |
| 852 | "keeps a worktree holding an ignored nested %s", |
| 853 | (kind) => |
| 854 | runCleanupTest( |
| 855 | Effect.gen(function* () { |
| 856 | const { service, fs, repo, worktree, command, setPolicy } = yield* cleanupFixture(); |
| 857 | setPolicy("tracked-changes"); |
| 858 | const nested = `${worktree}/dist/nested`; |
| 859 | if (kind === "uppercase") { |
| 860 | yield* command(repo, ["worktree", "add", "-b", "nested", nested]); |
| 861 | } else { |
| 862 | yield* command(repo, [ |
| 863 | "clone", |
| 864 | "--no-hardlinks", |
| 865 | ...(kind === "bare" ? ["--bare"] : []), |
| 866 | repo, |
| 867 | nested, |
| 868 | ]); |
| 869 | } |
| 870 | if (kind === "uppercase") yield* fs.rename(`${nested}/.git`, `${nested}/.GIT`); |
| 871 | yield* fs.writeFileString(`${nested}/uncommitted.txt`, "irreplaceable work\n"); |
| 872 | expect((yield* command(worktree, ["status", "--porcelain"])).stdout).toBe(""); |
| 873 | const report = yield* service.runNow; |
| 874 | expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ |
| 875 | outcome: "kept", |
| 876 | reason: "Contains a nested Git repository", |
| 877 | }); |
| 878 | expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("irreplaceable work\n"); |
| 879 | expect( |
| 880 | (yield* command(nested, [ |
| 881 | ...(kind === "uppercase" |
| 882 | ? [ |
| 883 | `--git-dir=${(yield* fs.readFileString(`${nested}/.GIT`)).trim().slice(8)}`, |
| 884 | "--work-tree=.", |
| 885 | ] |
| 886 | : []), |
| 887 | "-c", |
| 888 | "safe.bareRepository=all", |
| 889 | "rev-parse", |
| 890 | "--is-bare-repository", |
| 891 | ])).stdout.trim(), |
| 892 | ).toBe(String(kind === "bare")); |
| 893 | }), |
| 894 | ), |
| 895 | ); |
| 896 | |
| 897 | const submoduleCleanupFixture = () => |
| 898 | Effect.gen(function* () { |
| 899 | const fixture = yield* cleanupFixture(); |
| 900 | const { command, repo, worktree } = fixture; |
| 901 | const submodule = `${worktree}/module`; |
| 902 | const child = `${submodule}/child`; |
| 903 | for (const [cwd, name] of [ |
| 904 | [worktree, "module"], |
| 905 | [submodule, "child"], |
| 906 | ] as const) { |
| 907 | yield* command(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", repo, name]); |
| 908 | yield* command(`${cwd}/${name}`, ["config", "user.name", "Cleanup test"]); |
| 909 | yield* command(`${cwd}/${name}`, ["config", "user.email", "cleanup@example.test"]); |
| 910 | } |
| 911 | const recordSubmodules = () => |
| 912 | Effect.gen(function* () { |
| 913 | yield* command(submodule, ["commit", "-am", "record child"]); |
| 914 | yield* command(submodule, ["push", "origin", "HEAD:submodule"]); |
| 915 | yield* command(worktree, ["commit", "-am", "record module"]); |
| 916 | }); |
| 917 | yield* recordSubmodules(); |
| 918 | return { ...fixture, submodule, child, recordSubmodules }; |
| 919 | }); |
| 920 | |
| 921 | it.live("inspects a pnpm store excluded from reclaimed bytes for nested repositories", () => |
| 922 | runCleanupTest( |
| 923 | Effect.gen(function* () { |
| 924 | const { service, fs, repo, worktree, command, setPolicy } = yield* cleanupFixture(); |
| 925 | setPolicy("tracked-changes"); |
| 926 | const storeDir = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-store-" }); |
| 927 | const nested = `${worktree}/node_modules/.pnpm/nested`; |
| 928 | yield* command(repo, ["clone", "--no-hardlinks", repo, nested]); |
| 929 | yield* fs.writeFileString(`${nested}/uncommitted.txt`, "keep me"); |
| 930 | yield* fs.writeFileString( |
| 931 | `${worktree}/node_modules/.modules.yaml`, |
| 932 | JSON.stringify({ storeDir, virtualStoreDir: ".pnpm" }), |
| 933 | ); |
| 934 | const report = yield* service.runNow; |
| 935 | expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ |
| 936 | outcome: "kept", |
| 937 | reason: "Contains a nested Git repository", |
| 938 | }); |
| 939 | expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("keep me"); |
| 940 | }), |
| 941 | ), |
| 942 | ); |
| 943 | |
| 944 | it.live("keeps an ignored repository inside a registered submodule", () => |
| 945 | runCleanupTest( |
| 946 | Effect.gen(function* () { |
| 947 | const { service, fs, repo, worktree, submodule, command, setPolicy } = |
| 948 | yield* submoduleCleanupFixture(); |
| 949 | setPolicy("tracked-changes"); |
| 950 | const nested = `${submodule}/dist/nested`; |
| 951 | yield* command(repo, ["clone", "--no-hardlinks", repo, nested]); |
| 952 | yield* fs.writeFileString(`${nested}/uncommitted.txt`, "keep me"); |
| 953 | const report = yield* service.runNow; |
| 954 | expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ |
| 955 | outcome: "kept", |
| 956 | reason: "Contains a nested Git repository", |
| 957 | }); |
| 958 | expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("keep me"); |
| 959 | }), |
| 960 | ), |
| 961 | ); |
| 962 | |
| 963 | it.live("removes clean submodules recursively, including deinitialized repositories", () => |
| 964 | runCleanupTest( |
| 965 | Effect.gen(function* () { |
| 966 | const fs = yield* FileSystem.FileSystem; |
| 967 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 968 | let editedDuringClean = false; |
| 969 | const { service, repo, worktree, submodule, command, recordSubmodules, setPolicy } = |
| 970 | yield* submoduleCleanupFixture().pipe( |
| 971 | Effect.provideService(GitVcsDriver.GitVcsDriver, { |
| 972 | ...git, |
| 973 | execute: (input) => |
| 974 | git.execute(input).pipe( |
| 975 | Effect.tap(() => { |
| 976 | if (input.args[0] !== "clean") return Effect.void; |
| 977 | editedDuringClean = true; |
| 978 | return fs.writeFileString(`${input.cwd}/tracked.txt`, "late edit\n"); |
| 979 | }), |
| 980 | ), |
| 981 | }), |
| 982 | ); |
| 983 | setPolicy("tracked-changes"); |
| 984 | yield* fs.writeFileString(`${worktree}/notes.txt`, "untracked\n"); |
| 985 | yield* fs.writeFileString(`${worktree}/.env`, "ignored\n"); |
| 986 | yield* command(submodule, [ |
| 987 | "-c", |
| 988 | "protocol.file.allow=always", |
| 989 | "submodule", |
| 990 | "add", |
| 991 | repo, |
| 992 | "stored", |
| 993 | ]); |
| 994 | const legacy = `${worktree}/legacy`; |
| 995 | yield* command(repo, ["clone", "--no-hardlinks", repo, legacy]); |
| 996 | yield* command(worktree, ["submodule", "add", repo, "legacy"]); |
| 997 | expect((yield* fs.stat(`${legacy}/.git`)).type).toBe("Directory"); |
| 998 | yield* command(legacy, [ |
| 999 | "-c", |
| 1000 | "protocol.file.allow=always", |
| 1001 | "submodule", |
| 1002 | "add", |
| 1003 | repo, |
| 1004 | "child", |
| 1005 | ]); |
| 1006 | yield* command(legacy, [ |
| 1007 | "-c", |
| 1008 | "protocol.file.allow=always", |
| 1009 | "submodule", |
| 1010 | "add", |
| 1011 | repo, |
| 1012 | "stored", |
| 1013 | ]); |
| 1014 | yield* command(legacy, [ |
| 1015 | "-c", |
| 1016 | "user.name=Cleanup test", |
| 1017 | "-c", |
| 1018 | "user.email=cleanup@example.test", |
| 1019 | "commit", |
| 1020 | "-am", |
| 1021 | "record legacy children", |
| 1022 | ]); |
| 1023 | yield* command(legacy, ["push", "origin", "HEAD:legacy"]); |
| 1024 | yield* command(legacy, ["submodule", "deinit", "stored"]); |
| 1025 | yield* recordSubmodules(); |
| 1026 | yield* command(submodule, ["submodule", "deinit", "stored"]); |
| 1027 | const checkpoint = (yield* command(submodule, [ |
| 1028 | "commit-tree", |
| 1029 | "HEAD^{tree}", |
| 1030 | "-p", |
| 1031 | "HEAD", |
| 1032 | "-m", |
| 1033 | "checkpoint", |
| 1034 | ])).stdout.trim(); |
| 1035 | yield* command(submodule, [ |
| 1036 | "update-ref", |
| 1037 | "refs/t3/orchestration-v2/checkpoints/test", |
| 1038 | checkpoint, |
| 1039 | ]); |
| 1040 | const admin = (yield* command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); |
| 1041 | const report = yield* service.runNow; |
| 1042 | expect(editedDuringClean).toBe(false); |
| 1043 | expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ |
| 1044 | outcome: "removed", |
| 1045 | }); |
| 1046 | expect(report.counts).toEqual({ removed: 1, kept: 0, failed: 0 }); |
| 1047 | expect(yield* fs.exists(worktree)).toBe(false); |
| 1048 | expect(yield* fs.exists(admin)).toBe(false); |
| 1049 | }), |
| 1050 | ), |
| 1051 | ); |
| 1052 | |
| 1053 | it.live("keeps nested submodule files protected by the current keep rule", () => |
| 1054 | runCleanupTest( |
| 1055 | Effect.gen(function* () { |
| 1056 | const { service, fs, worktree, submodule, child, command, setPolicy } = |
| 1057 | yield* submoduleCleanupFixture(); |
| 1058 | setPolicy("tracked-changes"); |
| 1059 | yield* fs.writeFileString(`${child}/tracked.txt`, "local edit\n"); |
| 1060 | expect( |
| 1061 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1062 | ).toMatchObject({ outcome: "kept" }); |
| 1063 | expect(yield* fs.readFileString(`${child}/tracked.txt`)).toBe("local edit\n"); |
| 1064 | yield* fs.writeFileString(`${child}/tracked.txt`, "original\n"); |
| 1065 | setPolicy("any-local-files"); |
| 1066 | yield* fs.writeFileString(`${child}/.env`, "local secret\n"); |
| 1067 | expect( |
| 1068 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1069 | ).toMatchObject({ outcome: "kept" }); |
| 1070 | expect(yield* fs.readFileString(`${child}/.env`)).toBe("local secret\n"); |
| 1071 | |
| 1072 | yield* fs.remove(`${child}/.env`); |
| 1073 | yield* command(submodule, ["submodule", "deinit", "child"]); |
| 1074 | yield* fs.writeFileString(`${child}/.env`, "secret after deinit\n"); |
| 1075 | const report = yield* service.runNow; |
| 1076 | expect({ |
| 1077 | outcome: report.entries.find((entry) => entry.path === worktree)?.outcome, |
| 1078 | contents: (yield* fs.exists(`${child}/.env`)) |
| 1079 | ? yield* fs.readFileString(`${child}/.env`) |
| 1080 | : null, |
| 1081 | }).toEqual({ outcome: "kept", contents: "secret after deinit\n" }); |
| 1082 | |
| 1083 | yield* fs.remove(`${child}/.env`); |
| 1084 | setPolicy("uncommitted-changes"); |
| 1085 | yield* fs.writeFileString(`${child}/notes.txt`, "notes after deinit\n"); |
| 1086 | const untrackedReport = yield* service.runNow; |
| 1087 | expect({ |
| 1088 | outcome: untrackedReport.entries.find((entry) => entry.path === worktree)?.outcome, |
| 1089 | contents: (yield* fs.exists(`${child}/notes.txt`)) |
| 1090 | ? yield* fs.readFileString(`${child}/notes.txt`) |
| 1091 | : null, |
| 1092 | }).toEqual({ outcome: "kept", contents: "notes after deinit\n" }); |
| 1093 | }), |
| 1094 | ), |
| 1095 | ); |
| 1096 | |
| 1097 | it.live("keeps unpushed submodule history after checkout and deinitialization", () => |
| 1098 | runCleanupTest( |
| 1099 | Effect.gen(function* () { |
| 1100 | const { service, fs, worktree, submodule, child, command, recordSubmodules } = |
| 1101 | yield* submoduleCleanupFixture(); |
| 1102 | yield* command(child, ["checkout", "-b", "local-only"]); |
| 1103 | yield* fs.writeFileString(`${child}/tracked.txt`, "unpublished work\n"); |
| 1104 | yield* command(child, ["commit", "-am", "local work"]); |
| 1105 | const local = (yield* command(child, ["rev-parse", "HEAD"])).stdout.trim(); |
| 1106 | yield* recordSubmodules(); |
| 1107 | expect( |
| 1108 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1109 | ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); |
| 1110 | expect(yield* fs.readFileString(`${child}/tracked.txt`)).toBe("unpublished work\n"); |
| 1111 | |
| 1112 | yield* command(child, ["checkout", "main"]); |
| 1113 | yield* recordSubmodules(); |
| 1114 | expect( |
| 1115 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1116 | ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); |
| 1117 | const childGit = (yield* command(child, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); |
| 1118 | yield* command(submodule, ["submodule", "deinit", "child"]); |
| 1119 | expect( |
| 1120 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1121 | ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); |
| 1122 | expect( |
| 1123 | (yield* command(worktree, [ |
| 1124 | "--git-dir", |
| 1125 | childGit, |
| 1126 | "rev-parse", |
| 1127 | "refs/heads/local-only", |
| 1128 | ])).stdout.trim(), |
| 1129 | ).toBe(local); |
| 1130 | expect( |
| 1131 | (yield* command(worktree, ["--git-dir", childGit, "show", "local-only:tracked.txt"])) |
| 1132 | .stdout, |
| 1133 | ).toBe("unpublished work\n"); |
| 1134 | yield* command(worktree, ["--git-dir", childGit, "branch", "-D", "local-only"]); |
| 1135 | expect( |
| 1136 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1137 | ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); |
| 1138 | expect( |
| 1139 | (yield* command(worktree, ["--git-dir", childGit, "show", `${local}:tracked.txt`])).stdout, |
| 1140 | ).toBe("unpublished work\n"); |
| 1141 | }), |
| 1142 | ), |
| 1143 | ); |
| 1144 | |
| 1145 | it.live("keeps submodules when stored repository metadata is malformed", () => |
| 1146 | runCleanupTest( |
| 1147 | Effect.gen(function* () { |
| 1148 | const { service, fs, worktree, submodule, child, command, setPolicy } = |
| 1149 | yield* submoduleCleanupFixture(); |
| 1150 | setPolicy("tracked-changes"); |
| 1151 | const childGit = (yield* command(child, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); |
| 1152 | yield* command(submodule, ["submodule", "deinit", "child"]); |
| 1153 | yield* fs.writeFileString(`${childGit}/HEAD`, "not a ref\n"); |
| 1154 | yield* fs.writeFileString(`${worktree}/notes.txt`, "keep while the worktree stays\n"); |
| 1155 | expect( |
| 1156 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1157 | ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("inspected") }); |
| 1158 | expect(yield* fs.exists(worktree)).toBe(true); |
| 1159 | expect(yield* fs.readFileString(`${childGit}/HEAD`)).toBe("not a ref\n"); |
| 1160 | expect(yield* fs.readFileString(`${worktree}/notes.txt`)).toBe( |
| 1161 | "keep while the worktree stays\n", |
| 1162 | ); |
| 1163 | }), |
| 1164 | ), |
| 1165 | ); |
| 1166 | |
| 1167 | it.live("preserves late tracked edits when submodules were never initialized", () => |
| 1168 | runCleanupTest( |
| 1169 | Effect.gen(function* () { |
| 1170 | const fixture = yield* cleanupFixture(); |
| 1171 | const { service, fs, worktree, command } = fixture; |
| 1172 | const head = (yield* command(worktree, ["rev-parse", "HEAD"])).stdout.trim(); |
| 1173 | yield* fs.writeFileString( |
| 1174 | `${worktree}/.gitmodules`, |
| 1175 | '[submodule "module"]\n\tpath = module\n\turl = /unused\n', |
| 1176 | ); |
| 1177 | yield* command(worktree, ["add", ".gitmodules"]); |
| 1178 | yield* command(worktree, ["update-index", "--add", "--cacheinfo", `160000,${head},module`]); |
| 1179 | yield* command(worktree, ["commit", "-m", "record uninitialized module"]); |
| 1180 | yield* fs.makeDirectory(`${worktree}/module`); |
| 1181 | fixture.editBeforeRemoval(); |
| 1182 | expect( |
| 1183 | (yield* service.runNow).entries.find((entry) => entry.path === worktree), |
| 1184 | ).toMatchObject({ outcome: "failed" }); |
| 1185 | expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("late edit\n"); |
| 1186 | }), |
| 1187 | ), |
| 1188 | ); |
| 1189 | |
| 1190 | describe("subagent worktree ownership", () => { |
| 1191 | it.effect.each([ |
| 1192 | "child", |
| 1193 | "grandchild", |
| 1194 | "immediate", |
| 1195 | "active-parent", |
| 1196 | "recent-settle", |
| 1197 | "settle-grace", |
| 1198 | "recent-child-activity", |
| 1199 | "running-child", |
| 1200 | "pending-child", |
| 1201 | "running-parent", |
| 1202 | "pending-parent", |
| 1203 | "unsettled-child", |
| 1204 | "pinned-child", |
| 1205 | "fork", |
| 1206 | "missing-parent", |
| 1207 | "cycle", |
| 1208 | ] as const)("checks isolated subagent settlement (%s)", (scenario) => |
| 1209 | Effect.gen(function* () { |
| 1210 | yield* TestClock.setTime(NOW_MS); |
| 1211 | const fixture = yield* cleanupFixture({ |
| 1212 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1213 | worktreeSettledAfterDays: scenario === "immediate" ? 0 : 8, |
| 1214 | }); |
| 1215 | const root = shell({ |
| 1216 | settledAt: |
| 1217 | scenario === "active-parent" |
| 1218 | ? null |
| 1219 | : scenario === "recent-settle" || scenario === "settle-grace" |
| 1220 | ? at(-30_000) |
| 1221 | : scenario === "immediate" |
| 1222 | ? at(-120_000) |
| 1223 | : at(-20 * DAY_MS), |
| 1224 | settledOverride: scenario === "active-parent" ? null : "settled", |
| 1225 | updatedAt: scenario === "settle-grace" ? at(-30_000) : at(-10 * DAY_MS), |
| 1226 | }); |
| 1227 | const child = shell({ |
| 1228 | id: ThreadId.make("child"), |
| 1229 | branch: "feature", |
| 1230 | worktreePath: fixture.worktree, |
| 1231 | lineage: { |
| 1232 | parentThreadId: |
| 1233 | scenario === "missing-parent" |
| 1234 | ? ThreadId.make("missing") |
| 1235 | : scenario === "cycle" |
| 1236 | ? ThreadId.make("child") |
| 1237 | : ["grandchild", "running-parent", "pending-parent"].includes(scenario) |
| 1238 | ? ThreadId.make("middle") |
| 1239 | : root.id, |
| 1240 | rootThreadId: root.id, |
| 1241 | relationshipToParent: scenario === "fork" ? "fork" : "subagent", |
| 1242 | }, |
| 1243 | status: scenario === "running-child" ? "running" : "completed", |
| 1244 | pendingBackgroundTasks: |
| 1245 | scenario === "pending-child" ? [{ taskId: "task", kind: "command" }] : [], |
| 1246 | latestRunCompletedAt: scenario === "recent-child-activity" ? at(-2 * DAY_MS) : null, |
| 1247 | settledOverride: scenario === "unsettled-child" ? "active" : null, |
| 1248 | pinnedAt: scenario === "pinned-child" ? at(-DAY_MS) : null, |
| 1249 | }); |
| 1250 | const middle = shell({ |
| 1251 | id: ThreadId.make("middle"), |
| 1252 | status: scenario === "running-parent" ? "running" : "idle", |
| 1253 | pendingBackgroundTasks: |
| 1254 | scenario === "pending-parent" ? [{ taskId: "task", kind: "command" }] : [], |
| 1255 | lineage: { |
| 1256 | parentThreadId: root.id, |
| 1257 | rootThreadId: root.id, |
| 1258 | relationshipToParent: "subagent", |
| 1259 | }, |
| 1260 | }); |
| 1261 | fixture.setThreads([child, middle, root]); |
| 1262 | const report = yield* fixture.service.runNow; |
| 1263 | const removed = ["child", "grandchild", "immediate"].includes(scenario); |
| 1264 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed); |
| 1265 | expect(report.entries[0]).toMatchObject({ |
| 1266 | threadId: child.id, |
| 1267 | outcome: removed ? "removed" : "kept", |
| 1268 | reason: removed |
| 1269 | ? scenario === "immediate" |
| 1270 | ? "Settled for 0 days" |
| 1271 | : "Settled for 20 days" |
| 1272 | : scenario === "settle-grace" |
| 1273 | ? "Settled moments ago" |
| 1274 | : scenario === "recent-settle" |
| 1275 | ? "Settled for 0 of 8 days" |
| 1276 | : scenario === "recent-child-activity" |
| 1277 | ? "Settled for 2 of 8 days" |
| 1278 | : scenario === "running-child" || scenario === "pending-child" |
| 1279 | ? "Thread is running or has pending work" |
| 1280 | : "Not settled", |
| 1281 | }); |
| 1282 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1283 | ); |
| 1284 | |
| 1285 | it.effect.each([ |
| 1286 | "parent-unsettled", |
| 1287 | "parent-resettled", |
| 1288 | "child-unsettled", |
| 1289 | "intermediate-running", |
| 1290 | "intermediate-pending", |
| 1291 | ] as const)("cancels inherited settlement during measurement (%s)", (change) => |
| 1292 | runCleanupTest( |
| 1293 | Effect.gen(function* () { |
| 1294 | yield* TestClock.setTime(NOW_MS); |
| 1295 | const fixture = yield* pausedMeasurementFixture({ |
| 1296 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1297 | worktreeSettledAfterDays: 0, |
| 1298 | }); |
| 1299 | const root = shell({ settledAt: at(-20 * DAY_MS), settledOverride: "settled" }); |
| 1300 | const middle = shell({ |
| 1301 | id: ThreadId.make("middle"), |
| 1302 | lineage: { |
| 1303 | parentThreadId: root.id, |
| 1304 | rootThreadId: root.id, |
| 1305 | relationshipToParent: "subagent", |
| 1306 | }, |
| 1307 | }); |
| 1308 | const child = shell({ |
| 1309 | id: ThreadId.make("child"), |
| 1310 | branch: "feature", |
| 1311 | worktreePath: fixture.worktree, |
| 1312 | lineage: { |
| 1313 | parentThreadId: middle.id, |
| 1314 | rootThreadId: root.id, |
| 1315 | relationshipToParent: "subagent", |
| 1316 | }, |
| 1317 | }); |
| 1318 | fixture.setThreads([child, middle, root]); |
| 1319 | const run = yield* fixture.service.runNow.pipe(Effect.forkChild); |
| 1320 | yield* Deferred.await(fixture.measuring); |
| 1321 | fixture.setThreads([ |
| 1322 | { ...child, settledOverride: change === "child-unsettled" ? "active" : null }, |
| 1323 | { |
| 1324 | ...middle, |
| 1325 | status: change === "intermediate-running" ? "running" : "idle", |
| 1326 | pendingBackgroundTasks: |
| 1327 | change === "intermediate-pending" ? [{ taskId: "task", kind: "command" }] : [], |
| 1328 | }, |
| 1329 | change === "child-unsettled" || change.startsWith("intermediate-") |
| 1330 | ? root |
| 1331 | : { |
| 1332 | ...root, |
| 1333 | settledAt: change === "parent-resettled" ? at(0) : null, |
| 1334 | settledOverride: change === "parent-resettled" ? "settled" : "active", |
| 1335 | updatedAt: at(0), |
| 1336 | }, |
| 1337 | ]); |
| 1338 | yield* Deferred.succeed(fixture.resume, undefined); |
| 1339 | expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ |
| 1340 | outcome: "kept", |
| 1341 | reason: "Parent settlement changed since check", |
| 1342 | }); |
| 1343 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 1344 | }), |
| 1345 | ), |
| 1346 | ); |
| 1347 | |
| 1348 | it.effect.each([ |
| 1349 | "idle", |
| 1350 | "grandchild", |
| 1351 | "branchless", |
| 1352 | "branchless-running", |
| 1353 | "null-branch", |
| 1354 | "stale-branch", |
| 1355 | "isolated-owner", |
| 1356 | "fork-owner", |
| 1357 | "missing-parent", |
| 1358 | "cycle", |
| 1359 | "two-tops", |
| 1360 | "wrong-root", |
| 1361 | "running", |
| 1362 | "pending", |
| 1363 | "unrelated", |
| 1364 | "fork", |
| 1365 | "side-chat", |
| 1366 | "recent-activity", |
| 1367 | "recent-inactive", |
| 1368 | "recent-grace", |
| 1369 | "recent-settle", |
| 1370 | "child-settled-now", |
| 1371 | "child-settled-only", |
| 1372 | ] as const)("checks the whole owner group (%s)", (scenario) => |
| 1373 | Effect.gen(function* () { |
| 1374 | yield* TestClock.setTime(NOW_MS); |
| 1375 | const fixture = yield* cleanupFixture(); |
| 1376 | fixture.setSettings({ |
| 1377 | storageCleanup: { |
| 1378 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1379 | worktreeSettledAfterDays: scenario === "recent-inactive" ? null : 8, |
| 1380 | worktreeAfterDays: scenario === "recent-inactive" ? 8 : null, |
| 1381 | }, |
| 1382 | }); |
| 1383 | const root = shell({ |
| 1384 | branch: ["branchless", "branchless-running"].includes(scenario) ? null : "feature", |
| 1385 | worktreePath: fixture.worktree, |
| 1386 | settledAt: scenario === "child-settled-only" ? null : at(-20 * DAY_MS), |
| 1387 | ...(scenario === "isolated-owner" || scenario === "fork-owner" |
| 1388 | ? { |
| 1389 | lineage: { |
| 1390 | parentThreadId: ThreadId.make("ancestor"), |
| 1391 | rootThreadId: ThreadId.make("ancestor"), |
| 1392 | relationshipToParent: |
| 1393 | scenario === "fork-owner" ? ("fork" as const) : ("subagent" as const), |
| 1394 | }, |
| 1395 | } |
| 1396 | : {}), |
| 1397 | }); |
| 1398 | const child = shell({ |
| 1399 | id: ThreadId.make("child"), |
| 1400 | branch: |
| 1401 | scenario === "null-branch" |
| 1402 | ? null |
| 1403 | : scenario === "stale-branch" |
| 1404 | ? "t3/15a6e5ae" |
| 1405 | : "feature", |
| 1406 | worktreePath: fixture.worktree, |
| 1407 | lineage: { |
| 1408 | parentThreadId: |
| 1409 | scenario === "missing-parent" |
| 1410 | ? ThreadId.make("missing") |
| 1411 | : scenario === "cycle" |
| 1412 | ? ThreadId.make("child") |
| 1413 | : scenario === "two-tops" |
| 1414 | ? null |
| 1415 | : root.id, |
| 1416 | rootThreadId: |
| 1417 | scenario === "wrong-root" ? ThreadId.make("other-root") : root.lineage.rootThreadId, |
| 1418 | relationshipToParent: |
| 1419 | scenario === "fork" || scenario === "side-chat" |
| 1420 | ? "fork" |
| 1421 | : scenario === "unrelated" |
| 1422 | ? null |
| 1423 | : "subagent", |
| 1424 | ...(scenario === "side-chat" ? { sideChat: true } : {}), |
| 1425 | }, |
| 1426 | status: ["running", "branchless-running"].includes(scenario) ? "running" : "completed", |
| 1427 | pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [], |
| 1428 | latestRunCompletedAt: |
| 1429 | scenario === "recent-activity" || scenario === "recent-inactive" |
| 1430 | ? at(-2 * DAY_MS) |
| 1431 | : scenario === "recent-grace" |
| 1432 | ? at(-30_000) |
| 1433 | : null, |
| 1434 | settledAt: scenario === "child-settled-only" ? at(-20 * DAY_MS) : null, |
| 1435 | }); |
| 1436 | const grandchild = { |
| 1437 | ...child, |
| 1438 | id: ThreadId.make("grandchild"), |
| 1439 | lineage: { ...child.lineage, parentThreadId: child.id }, |
| 1440 | }; |
| 1441 | fixture.setThreads( |
| 1442 | scenario === "grandchild" |
| 1443 | ? [grandchild, child, root] |
| 1444 | : scenario === "isolated-owner" || scenario === "fork-owner" |
| 1445 | ? [child, root, shell({ id: ThreadId.make("ancestor") })] |
| 1446 | : [child, root], |
| 1447 | ); |
| 1448 | if (scenario === "recent-settle" || scenario === "child-settled-now") |
| 1449 | fixture.setThreads([ |
| 1450 | { |
| 1451 | ...child, |
| 1452 | settledAt: scenario === "recent-settle" ? at(0) : at(-20 * DAY_MS), |
| 1453 | updatedAt: at(0), |
| 1454 | }, |
| 1455 | root, |
| 1456 | ]); |
| 1457 | const report = yield* fixture.service.runNow; |
| 1458 | const removed = ["idle", "grandchild", "isolated-owner", "fork-owner", "side-chat"].includes( |
| 1459 | scenario, |
| 1460 | ); |
| 1461 | const shared = [ |
| 1462 | "unrelated", |
| 1463 | "fork", |
| 1464 | "missing-parent", |
| 1465 | "cycle", |
| 1466 | "two-tops", |
| 1467 | "wrong-root", |
| 1468 | ].includes(scenario); |
| 1469 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed); |
| 1470 | expect(report.entries[0]).toMatchObject({ |
| 1471 | threadId: shared ? child.id : root.id, |
| 1472 | outcome: removed ? "removed" : "kept", |
| 1473 | reason: removed |
| 1474 | ? "Settled for 20 days" |
| 1475 | : ["running", "pending", "branchless-running"].includes(scenario) |
| 1476 | ? "Thread is running or has pending work" |
| 1477 | : shared |
| 1478 | ? "Shared by 2 threads" |
| 1479 | : scenario === "null-branch" || scenario === "stale-branch" |
| 1480 | ? "A subagent thread's branch differs from this worktree's branch" |
| 1481 | : scenario === "recent-activity" |
| 1482 | ? "Settled for 2 of 8 days" |
| 1483 | : scenario === "recent-inactive" |
| 1484 | ? "Inactive for 2 of 8 days" |
| 1485 | : ["recent-grace", "recent-settle", "child-settled-now"].includes(scenario) |
| 1486 | ? "Settled moments ago" |
| 1487 | : scenario === "branchless" |
| 1488 | ? "Thread has no branch" |
| 1489 | : "Not settled", |
| 1490 | }); |
| 1491 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1492 | ); |
| 1493 | |
| 1494 | it.effect("keeps a checkout two top-level threads store through a symlinked parent", () => |
| 1495 | Effect.gen(function* () { |
| 1496 | yield* TestClock.setTime(NOW_MS); |
| 1497 | const fixture = yield* cleanupFixture({ |
| 1498 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1499 | worktreeSettledAfterDays: 8, |
| 1500 | }); |
| 1501 | const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; |
| 1502 | yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); |
| 1503 | const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; |
| 1504 | fixture.setThreads([ |
| 1505 | shell({ ...settled, worktreePath: fixture.worktree }), |
| 1506 | shell({ ...settled, id: ThreadId.make("other"), worktreePath: `${linkedParent}/feature` }), |
| 1507 | ]); |
| 1508 | const report = yield* fixture.service.runNow; |
| 1509 | expect(report.entries).toEqual([ |
| 1510 | expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), |
| 1511 | ]); |
| 1512 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 1513 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1514 | ); |
| 1515 | |
| 1516 | it.effect("keeps a checkout two top-level threads store in different case on Windows", () => |
| 1517 | Effect.gen(function* () { |
| 1518 | yield* TestClock.setTime(NOW_MS); |
| 1519 | const fixture = yield* cleanupFixture({ |
| 1520 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1521 | worktreeSettledAfterDays: 8, |
| 1522 | }).pipe(Effect.provideService(HostProcess.Platform, "win32")); |
| 1523 | const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; |
| 1524 | fixture.setThreads([ |
| 1525 | shell({ ...settled, worktreePath: fixture.worktree }), |
| 1526 | shell({ |
| 1527 | ...settled, |
| 1528 | id: ThreadId.make("other"), |
| 1529 | worktreePath: fixture.worktree.toUpperCase(), |
| 1530 | }), |
| 1531 | ]); |
| 1532 | const report = yield* fixture.service.runNow; |
| 1533 | expect(report.entries).toEqual([ |
| 1534 | expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), |
| 1535 | ]); |
| 1536 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 1537 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1538 | ); |
| 1539 | |
| 1540 | it.effect.each([ |
| 1541 | "running", |
| 1542 | "pending", |
| 1543 | "activity", |
| 1544 | "unrelated", |
| 1545 | "settled", |
| 1546 | "resettled", |
| 1547 | "null-branch", |
| 1548 | "stale-branch", |
| 1549 | ] as const)("cancels removal when a child changes during measurement (%s)", (change) => |
| 1550 | runCleanupTest( |
| 1551 | Effect.gen(function* () { |
| 1552 | yield* TestClock.setTime(NOW_MS); |
| 1553 | const fixture = yield* pausedMeasurementFixture(); |
| 1554 | const root = shell({ branch: "feature", worktreePath: fixture.worktree }); |
| 1555 | const child = { |
| 1556 | ...root, |
| 1557 | id: ThreadId.make("child"), |
| 1558 | settledAt: change === "resettled" ? at(-20 * DAY_MS) : null, |
| 1559 | lineage: { |
| 1560 | parentThreadId: root.id, |
| 1561 | rootThreadId: root.id, |
| 1562 | relationshipToParent: "subagent" as const, |
| 1563 | }, |
| 1564 | }; |
| 1565 | fixture.setThreads([child, root]); |
| 1566 | const run = yield* fixture.service.runNow.pipe(Effect.forkChild); |
| 1567 | yield* Deferred.await(fixture.measuring); |
| 1568 | fixture.setThreads([ |
| 1569 | root, |
| 1570 | { |
| 1571 | ...child, |
| 1572 | branch: |
| 1573 | change === "null-branch" |
| 1574 | ? null |
| 1575 | : change === "stale-branch" |
| 1576 | ? "t3/15a6e5ae" |
| 1577 | : child.branch, |
| 1578 | settledAt: change === "settled" ? at(-20 * DAY_MS) : child.settledAt, |
| 1579 | updatedAt: change === "settled" || change === "resettled" ? at(0) : child.updatedAt, |
| 1580 | status: change === "running" ? "running" : "idle", |
| 1581 | pendingBackgroundTasks: |
| 1582 | change === "pending" ? [{ taskId: "task", kind: "command" }] : [], |
| 1583 | latestRunCompletedAt: change === "activity" ? at(-DAY_MS) : null, |
| 1584 | }, |
| 1585 | ...(change === "unrelated" ? [shell({ ...root, id: ThreadId.make("other") })] : []), |
| 1586 | ]); |
| 1587 | yield* Deferred.succeed(fixture.resume, undefined); |
| 1588 | expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ |
| 1589 | outcome: "kept", |
| 1590 | reason: "Thread activity or shared worktree changed since check", |
| 1591 | }); |
| 1592 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 1593 | }), |
| 1594 | ), |
| 1595 | ); |
| 1596 | }); |
| 1597 | |
| 1598 | describe("deleted thread worktrees", () => { |
| 1599 | const parent = (worktreePath: string) => |
| 1600 | shell({ branch: "feature", worktreePath, deletedAt: at(-DAY_MS) }); |
| 1601 | // Deleting the parent leaves its native subagent thread in the projection. |
| 1602 | const subagent = ( |
| 1603 | owner: OrchestrationV2ThreadShell, |
| 1604 | overrides: Partial<OrchestrationV2ThreadShell> = {}, |
| 1605 | ) => |
| 1606 | shell({ |
| 1607 | id: ThreadId.make("child"), |
| 1608 | title: "Subagent", |
| 1609 | branch: "feature", |
| 1610 | worktreePath: owner.worktreePath, |
| 1611 | status: "completed", |
| 1612 | createdBy: "agent", |
| 1613 | creationSource: "provider", |
| 1614 | lineage: { |
| 1615 | rootThreadId: owner.id, |
| 1616 | parentThreadId: owner.id, |
| 1617 | relationshipToParent: "subagent", |
| 1618 | }, |
| 1619 | ...overrides, |
| 1620 | }); |
| 1621 | |
| 1622 | it.effect.each(["no subagents", "native subagent"] as const)( |
| 1623 | "removes a deleted thread's worktree with %s", |
| 1624 | (scenario) => |
| 1625 | Effect.gen(function* () { |
| 1626 | yield* TestClock.setTime(NOW_MS); |
| 1627 | const fixture = yield* cleanupFixture({ |
| 1628 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1629 | worktreeAfterDays: null, |
| 1630 | worktreeOnDelete: true, |
| 1631 | }); |
| 1632 | const owner = parent(fixture.worktree); |
| 1633 | fixture.setDeletedThreads([owner]); |
| 1634 | fixture.setThreads(scenario === "native subagent" ? [subagent(owner)] : []); |
| 1635 | const report = yield* fixture.service.runNow; |
| 1636 | expect(report.entries[0]).toMatchObject({ |
| 1637 | threadId: owner.id, |
| 1638 | outcome: "removed", |
| 1639 | reason: "Thread was deleted", |
| 1640 | }); |
| 1641 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 1642 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1643 | ); |
| 1644 | |
| 1645 | it.effect("leaves a deleted owner's subagent on the owner's saved branch", () => |
| 1646 | Effect.gen(function* () { |
| 1647 | yield* TestClock.setTime(NOW_MS); |
| 1648 | const fixture = yield* cleanupFixture({ |
| 1649 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1650 | worktreeAfterDays: null, |
| 1651 | worktreeOnDelete: true, |
| 1652 | }); |
| 1653 | const owner = parent(fixture.worktree); |
| 1654 | fixture.setDeletedThreads([owner]); |
| 1655 | fixture.setThreads([subagent(owner)]); |
| 1656 | yield* fixture.command(fixture.worktree, ["switch", "-c", "renamed"]); |
| 1657 | expect((yield* fixture.service.runNow).entries[0]).toMatchObject({ |
| 1658 | threadId: owner.id, |
| 1659 | outcome: "kept", |
| 1660 | reason: "Repository or branch changed", |
| 1661 | }); |
| 1662 | // The deleted owner cannot follow, so moving its subagent would split their records. |
| 1663 | expect(fixture.threadBranches()).toEqual(["feature"]); |
| 1664 | }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), |
| 1665 | ); |
| 1666 | |
| 1667 | it.effect("applies the remaining subagent's rules when deletion cleanup is off", () => |
| 1668 | Effect.gen(function* () { |
| 1669 | yield* TestClock.setTime(NOW_MS); |
| 1670 | const fixture = yield* cleanupFixture({ |
| 1671 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1672 | worktreeAfterDays: 8, |
| 1673 | worktreeOnDelete: false, |
| 1674 | }); |
| 1675 | const owner = parent(fixture.worktree); |
| 1676 | const child = subagent(owner); |
| 1677 | fixture.setDeletedThreads([owner]); |
| 1678 | fixture.setThreads([child]); |
| 1679 | const report = yield* fixture.service.runNow; |
| 1680 | expect(report.entries[0]).toMatchObject({ |
| 1681 | threadId: child.id, |
| 1682 | outcome: "removed", |
| 1683 | reason: "Inactive for 30 days", |
| 1684 | }); |
| 1685 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 1686 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1687 | ); |
| 1688 | |
| 1689 | // Releases one stopped-session event after the startup sweep and returns the snapshot reads it caused. |
| 1690 | const stopSessionAfterStartupSweep = ( |
| 1691 | fixture: Effect.Success<ReturnType<typeof cleanupFixture>>, |
| 1692 | threadId: ThreadId, |
| 1693 | beforeStop: Effect.Effect<void> = Effect.void, |
| 1694 | cwd = fixture.worktree, |
| 1695 | ) => |
| 1696 | Effect.gen(function* () { |
| 1697 | const startupSwept = yield* Deferred.make<void>(); |
| 1698 | const delivered = yield* Deferred.make<void>(); |
| 1699 | const stopped: OrchestrationV2DomainEvent = { |
| 1700 | id: EventId.make("event:session-stopped"), |
| 1701 | type: "provider-session.updated", |
| 1702 | threadId, |
| 1703 | occurredAt: at(0), |
| 1704 | payload: { |
| 1705 | id: ProviderSessionId.make("session-1"), |
| 1706 | driver: ProviderDriverKind.make("codex"), |
| 1707 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 1708 | status: "stopped", |
| 1709 | cwd, |
| 1710 | model: null, |
| 1711 | capabilities: CodexProviderCapabilitiesV2, |
| 1712 | createdAt: at(-DAY_MS), |
| 1713 | updatedAt: at(0), |
| 1714 | lastError: null, |
| 1715 | }, |
| 1716 | }; |
| 1717 | yield* fixture.activate( |
| 1718 | Stream.fromEffect(Deferred.await(startupSwept)).pipe( |
| 1719 | Stream.flatMap(() => Stream.make(stopped)), |
| 1720 | Stream.concat( |
| 1721 | Stream.fromEffect(Deferred.succeed(delivered, undefined)).pipe(Stream.drain), |
| 1722 | ), |
| 1723 | ), |
| 1724 | ); |
| 1725 | yield* fixture.service.reports.pipe( |
| 1726 | Stream.filter((report) => report !== null), |
| 1727 | Stream.take(1), |
| 1728 | Stream.runDrain, |
| 1729 | ); |
| 1730 | yield* fixture.service.drain; |
| 1731 | yield* beforeStop; |
| 1732 | const readsBefore = fixture.snapshotReads(); |
| 1733 | yield* Deferred.succeed(startupSwept, undefined); |
| 1734 | yield* Deferred.await(delivered); |
| 1735 | yield* fixture.service.drain; |
| 1736 | return fixture.snapshotReads() - readsBefore; |
| 1737 | }); |
| 1738 | |
| 1739 | it.effect("does not sweep when a live thread's session stops and no deleted worktree waits", () => |
| 1740 | Effect.gen(function* () { |
| 1741 | yield* TestClock.setTime(NOW_MS); |
| 1742 | const fixture = yield* cleanupFixture(); |
| 1743 | const reads = yield* stopSessionAfterStartupSweep(fixture, ThreadId.make("thread-1")); |
| 1744 | expect(reads, "a live thread's stopped session re-read every thread").toBe(0); |
| 1745 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1746 | ); |
| 1747 | |
| 1748 | it.effect("removes a deleted thread's worktree once its session stops", () => |
| 1749 | Effect.gen(function* () { |
| 1750 | yield* TestClock.setTime(NOW_MS); |
| 1751 | const fixture = yield* cleanupFixture({ |
| 1752 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1753 | worktreeAfterDays: null, |
| 1754 | worktreeOnDelete: true, |
| 1755 | }); |
| 1756 | const owner = parent(fixture.worktree); |
| 1757 | fixture.setDeletedThreads([owner]); |
| 1758 | fixture.setThreads([]); |
| 1759 | fixture.setOpenSessionCwd(fixture.worktree); |
| 1760 | const reads = yield* stopSessionAfterStartupSweep( |
| 1761 | fixture, |
| 1762 | owner.id, |
| 1763 | Effect.sync(() => fixture.setSessionLive(false)), |
| 1764 | ); |
| 1765 | expect(reads).toBeGreaterThan(0); |
| 1766 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 1767 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1768 | ); |
| 1769 | |
| 1770 | it.effect("removes a deleted thread's worktree once a live thread's session in it stops", () => |
| 1771 | Effect.gen(function* () { |
| 1772 | yield* TestClock.setTime(NOW_MS); |
| 1773 | const fixture = yield* cleanupFixture({ |
| 1774 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1775 | worktreeAfterDays: null, |
| 1776 | worktreeOnDelete: true, |
| 1777 | }); |
| 1778 | const owner = parent(fixture.worktree); |
| 1779 | const child = subagent(owner); |
| 1780 | fixture.setDeletedThreads([owner]); |
| 1781 | fixture.setThreads([child]); |
| 1782 | fixture.setOpenSessionCwd(fixture.worktree); |
| 1783 | const reads = yield* stopSessionAfterStartupSweep( |
| 1784 | fixture, |
| 1785 | child.id, |
| 1786 | Effect.gen(function* () { |
| 1787 | expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ |
| 1788 | threadId: owner.id, |
| 1789 | outcome: "kept", |
| 1790 | reason: "Provider session is still open", |
| 1791 | }); |
| 1792 | fixture.setSessionLive(false); |
| 1793 | }), |
| 1794 | ); |
| 1795 | expect(reads).toBeGreaterThan(0); |
| 1796 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 1797 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1798 | ); |
| 1799 | |
| 1800 | it.effect( |
| 1801 | "removes a deleted thread's worktree once its terminal closes and its session stops", |
| 1802 | () => |
| 1803 | Effect.gen(function* () { |
| 1804 | yield* TestClock.setTime(NOW_MS); |
| 1805 | const fixture = yield* cleanupFixture({ |
| 1806 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1807 | worktreeAfterDays: null, |
| 1808 | worktreeOnDelete: true, |
| 1809 | }); |
| 1810 | const owner = parent(fixture.worktree); |
| 1811 | fixture.setDeletedThreads([owner]); |
| 1812 | fixture.setThreads([]); |
| 1813 | yield* fixture.setTerminals([ |
| 1814 | { |
| 1815 | threadId: owner.id, |
| 1816 | terminalId: "terminal-1", |
| 1817 | cwd: fixture.worktree, |
| 1818 | worktreePath: fixture.worktree, |
| 1819 | status: "running", |
| 1820 | pid: 1, |
| 1821 | exitCode: null, |
| 1822 | exitSignal: null, |
| 1823 | hasRunningSubprocess: false, |
| 1824 | label: "Terminal", |
| 1825 | updatedAt: DateTime.formatIso(at(0)), |
| 1826 | }, |
| 1827 | ]); |
| 1828 | const reads = yield* stopSessionAfterStartupSweep( |
| 1829 | fixture, |
| 1830 | owner.id, |
| 1831 | Effect.gen(function* () { |
| 1832 | expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ |
| 1833 | threadId: owner.id, |
| 1834 | outcome: "kept", |
| 1835 | reason: "Open terminal", |
| 1836 | }); |
| 1837 | yield* fixture.setTerminals([]); |
| 1838 | }), |
| 1839 | fixture.repo, |
| 1840 | ); |
| 1841 | expect(reads).toBeGreaterThan(0); |
| 1842 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 1843 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1844 | ); |
| 1845 | |
| 1846 | it.effect( |
| 1847 | "retries a deleted thread's worktree kept for another reason when a session in it stops", |
| 1848 | () => |
| 1849 | Effect.gen(function* () { |
| 1850 | yield* TestClock.setTime(NOW_MS); |
| 1851 | const fixture = yield* cleanupFixture({ |
| 1852 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1853 | worktreeAfterDays: null, |
| 1854 | worktreeOnDelete: true, |
| 1855 | }); |
| 1856 | const owner = parent(fixture.worktree); |
| 1857 | fixture.setDeletedThreads([owner]); |
| 1858 | fixture.setThreads([]); |
| 1859 | yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "agent edit\n"); |
| 1860 | const reads = yield* stopSessionAfterStartupSweep( |
| 1861 | fixture, |
| 1862 | owner.id, |
| 1863 | Effect.gen(function* () { |
| 1864 | expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ |
| 1865 | threadId: owner.id, |
| 1866 | outcome: "kept", |
| 1867 | reason: "Has uncommitted changes (1 file)", |
| 1868 | }); |
| 1869 | yield* fixture.fs |
| 1870 | .writeFileString(`${fixture.worktree}/tracked.txt`, "original\n") |
| 1871 | .pipe(Effect.orDie); |
| 1872 | }), |
| 1873 | ); |
| 1874 | expect(reads).toBeGreaterThan(0); |
| 1875 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 1876 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1877 | ); |
| 1878 | |
| 1879 | it.effect("does not sweep for a kept deleted worktree when a session elsewhere stops", () => |
| 1880 | Effect.gen(function* () { |
| 1881 | yield* TestClock.setTime(NOW_MS); |
| 1882 | const fixture = yield* cleanupFixture({ |
| 1883 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1884 | worktreeAfterDays: null, |
| 1885 | worktreeOnDelete: true, |
| 1886 | }); |
| 1887 | fixture.setDeletedThreads([parent(fixture.worktree)]); |
| 1888 | fixture.setThreads([]); |
| 1889 | yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "agent edit\n"); |
| 1890 | const reads = yield* stopSessionAfterStartupSweep( |
| 1891 | fixture, |
| 1892 | ThreadId.make("thread-elsewhere"), |
| 1893 | Effect.void, |
| 1894 | fixture.repo, |
| 1895 | ); |
| 1896 | expect(reads).toBe(0); |
| 1897 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 1898 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1899 | ); |
| 1900 | |
| 1901 | it.effect( |
| 1902 | "does not sweep for a deleted thread whose cleanup effect failed when a session elsewhere stops", |
| 1903 | () => |
| 1904 | Effect.gen(function* () { |
| 1905 | yield* TestClock.setTime(NOW_MS); |
| 1906 | const fixture = yield* cleanupFixture({ |
| 1907 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1908 | worktreeAfterDays: null, |
| 1909 | worktreeOnDelete: true, |
| 1910 | }); |
| 1911 | const owner = parent(fixture.worktree); |
| 1912 | fixture.setDeletedThreads([owner]); |
| 1913 | fixture.setThreads([]); |
| 1914 | fixture.setOutboxStatus("failed"); |
| 1915 | const reads = yield* stopSessionAfterStartupSweep( |
| 1916 | fixture, |
| 1917 | ThreadId.make("thread-elsewhere"), |
| 1918 | Effect.gen(function* () { |
| 1919 | expect((yield* fixture.service.latestReport)?.entries[0]).toMatchObject({ |
| 1920 | threadId: owner.id, |
| 1921 | outcome: "kept", |
| 1922 | reason: "Thread deletion is still pending", |
| 1923 | }); |
| 1924 | }), |
| 1925 | fixture.repo, |
| 1926 | ); |
| 1927 | expect(reads).toBe(0); |
| 1928 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 1929 | ); |
| 1930 | |
| 1931 | it.effect( |
| 1932 | "removes a deleted thread's worktree when its session stops during the deletion's sweep", |
| 1933 | () => |
| 1934 | Effect.gen(function* () { |
| 1935 | yield* TestClock.setTime(NOW_MS); |
| 1936 | const fixture = yield* cleanupFixture({ |
| 1937 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 1938 | worktreeAfterDays: null, |
| 1939 | worktreeOnDelete: true, |
| 1940 | }); |
| 1941 | const owner = parent(fixture.worktree); |
| 1942 | fixture.setThreads([]); |
| 1943 | const startupSwept = yield* Deferred.make<void>(); |
| 1944 | const sessionChecked = yield* Deferred.make<void>(); |
| 1945 | const delivered = yield* Deferred.make<void>(); |
| 1946 | const deleted = { |
| 1947 | id: EventId.make("event:thread-deleted"), |
| 1948 | type: "thread.deleted", |
| 1949 | threadId: owner.id, |
| 1950 | occurredAt: at(0), |
| 1951 | payload: owner, |
| 1952 | } as unknown as OrchestrationV2DomainEvent; |
| 1953 | const stopped: OrchestrationV2DomainEvent = { |
| 1954 | id: EventId.make("event:session-stopped"), |
| 1955 | type: "provider-session.updated", |
| 1956 | threadId: owner.id, |
| 1957 | occurredAt: at(0), |
| 1958 | payload: { |
| 1959 | id: ProviderSessionId.make("session-1"), |
| 1960 | driver: ProviderDriverKind.make("codex"), |
| 1961 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 1962 | status: "stopped", |
| 1963 | cwd: fixture.worktree, |
| 1964 | model: null, |
| 1965 | capabilities: CodexProviderCapabilitiesV2, |
| 1966 | createdAt: at(-DAY_MS), |
| 1967 | updatedAt: at(0), |
| 1968 | lastError: null, |
| 1969 | }, |
| 1970 | }; |
| 1971 | yield* fixture.activate( |
| 1972 | Stream.fromEffect(Deferred.await(startupSwept)).pipe( |
| 1973 | Stream.flatMap(() => Stream.make(deleted)), |
| 1974 | Stream.concat(Stream.fromEffect(Deferred.await(sessionChecked)).pipe(Stream.drain)), |
| 1975 | Stream.concat(Stream.make(stopped)), |
| 1976 | Stream.concat( |
| 1977 | Stream.fromEffect(Deferred.succeed(delivered, undefined)).pipe(Stream.drain), |
| 1978 | ), |
| 1979 | ), |
| 1980 | ); |
| 1981 | yield* fixture.service.reports.pipe( |
| 1982 | Stream.filter((report) => report !== null), |
| 1983 | Stream.take(1), |
| 1984 | Stream.runDrain, |
| 1985 | ); |
| 1986 | yield* fixture.service.drain; |
| 1987 | fixture.setDeletedThreads([owner]); |
| 1988 | fixture.setOpenSessionCwd(fixture.worktree); |
| 1989 | // The deletion's sweep sees the session live; it stops before that sweep publishes its result. |
| 1990 | fixture.setOnLiveCheck( |
| 1991 | Effect.gen(function* () { |
| 1992 | fixture.setOnLiveCheck(Effect.void); |
| 1993 | yield* Deferred.succeed(sessionChecked, undefined); |
| 1994 | yield* Deferred.await(delivered); |
| 1995 | fixture.setSessionLive(false); |
| 1996 | }), |
| 1997 | ); |
| 1998 | yield* Deferred.succeed(startupSwept, undefined); |
| 1999 | yield* Deferred.await(delivered); |
| 2000 | yield* fixture.service.drain; |
| 2001 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 2002 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 2003 | ); |
| 2004 | |
| 2005 | it.effect("waits out the settle grace of a subagent that just settled", () => |
| 2006 | Effect.gen(function* () { |
| 2007 | yield* TestClock.setTime(NOW_MS); |
| 2008 | const fixture = yield* cleanupFixture({ |
| 2009 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 2010 | worktreeAfterDays: null, |
| 2011 | worktreeOnDelete: true, |
| 2012 | }); |
| 2013 | const owner = parent(fixture.worktree); |
| 2014 | fixture.setDeletedThreads([owner]); |
| 2015 | fixture.setThreads([subagent(owner, { settledAt: at(0), updatedAt: at(0) })]); |
| 2016 | const report = yield* fixture.service.runNow; |
| 2017 | expect(report.entries[0]).toMatchObject({ |
| 2018 | threadId: owner.id, |
| 2019 | outcome: "kept", |
| 2020 | reason: "Settled moments ago", |
| 2021 | }); |
| 2022 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 2023 | }).pipe(Effect.provide(cleanupTestLayer)), |
| 2024 | ); |
| 2025 | }); |
| 2026 | |
| 2027 | describe("orphan worktree reports", () => { |
| 2028 | it.live("keeps orphan results visible when thread results fill the report", () => |
| 2029 | runCleanupTest( |
| 2030 | Effect.gen(function* () { |
| 2031 | const fixture = yield* cleanupFixture(); |
| 2032 | fixture.setThreads( |
| 2033 | Array.from({ length: 205 }, (_, index) => |
| 2034 | shell({ |
| 2035 | id: ThreadId.make(`busy-${index}`), |
| 2036 | branch: "busy", |
| 2037 | worktreePath: `${fixture.config.worktreesDir}/busy-${index}`, |
| 2038 | status: "running", |
| 2039 | }), |
| 2040 | ), |
| 2041 | ); |
| 2042 | for (let index = 0; index < 205; index++) { |
| 2043 | yield* fixture.fs.makeDirectory(`${fixture.config.worktreesDir}/busy-${index}`); |
| 2044 | } |
| 2045 | const orphans = ["one", "two"].map( |
| 2046 | (name) => `${fixture.config.worktreesDir}/repository/${name}`, |
| 2047 | ); |
| 2048 | for (const orphan of orphans) { |
| 2049 | yield* fixture.fs.makeDirectory(orphan, { recursive: true }); |
| 2050 | yield* fixture.fs.utimes(orphan, 1, 1); |
| 2051 | } |
| 2052 | const report = yield* fixture.service.runNow; |
| 2053 | expect(report.entries).toHaveLength(200); |
| 2054 | expect( |
| 2055 | report.entries |
| 2056 | .slice(0, 2) |
| 2057 | .map((entry) => entry.path) |
| 2058 | .sort(), |
| 2059 | ).toEqual(orphans); |
| 2060 | expect(report.counts).toEqual({ removed: 0, kept: 207, failed: 0 }); |
| 2061 | expect(report.omittedCount).toBe(7); |
| 2062 | }), |
| 2063 | ), |
| 2064 | ); |
| 2065 | |
| 2066 | it.live.each(["canonical", "win32", "linux"] as const)( |
| 2067 | "skips an ancestor of a referenced thread worktree (%s)", |
| 2068 | (platform) => |
| 2069 | runCleanupTest( |
| 2070 | Effect.gen(function* () { |
| 2071 | const fixture = yield* cleanupFixture().pipe( |
| 2072 | Effect.provideService(HostProcess.Platform, platform === "win32" ? "win32" : "linux"), |
| 2073 | ); |
| 2074 | fixture.setThreads([]); |
| 2075 | const ancestor = `${fixture.config.worktreesDir}/repository/stack`; |
| 2076 | const worktree = `${ancestor}/feature`; |
| 2077 | yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "nested", worktree]); |
| 2078 | const alias = `${fixture.repo}/alias`; |
| 2079 | if (platform === "canonical") yield* fixture.fs.symlink(worktree, alias); |
| 2080 | fixture.setStoredWorktreePaths([ |
| 2081 | platform === "canonical" |
| 2082 | ? alias |
| 2083 | : platform === "win32" |
| 2084 | ? worktree.toUpperCase() |
| 2085 | : worktree, |
| 2086 | ]); |
| 2087 | yield* fixture.fs.utimes(ancestor, 1, 1); |
| 2088 | expect((yield* fixture.service.runNow).entries).toEqual([]); |
| 2089 | expect(yield* fixture.fs.exists(worktree)).toBe(true); |
| 2090 | }), |
| 2091 | ), |
| 2092 | ); |
| 2093 | |
| 2094 | it.live("continues reporting when a project root cannot be probed", () => |
| 2095 | runCleanupTest( |
| 2096 | Effect.gen(function* () { |
| 2097 | const fixture = yield* cleanupFixture(); |
| 2098 | fixture.setThreads([]); |
| 2099 | const loop = `${fixture.repo}/loop`; |
| 2100 | yield* fixture.fs.symlink(loop, loop); |
| 2101 | fixture.setProjectRoots([fixture.repo, loop]); |
| 2102 | const orphan = `${fixture.config.worktreesDir}/repository/orphan`; |
| 2103 | yield* fixture.fs.makeDirectory(orphan, { recursive: true }); |
| 2104 | yield* fixture.fs.utimes(orphan, 1, 1); |
| 2105 | expect((yield* fixture.service.runNow).entries).toEqual([ |
| 2106 | expect.objectContaining({ path: orphan, outcome: "kept", bytes: 0 }), |
| 2107 | ]); |
| 2108 | }), |
| 2109 | ), |
| 2110 | ); |
| 2111 | |
| 2112 | it.live.each(["nested", "direct", "annexed"] as const)( |
| 2113 | "reports a linked orphan's size without removing its files (%s)", |
| 2114 | (location) => |
| 2115 | runCleanupTest( |
| 2116 | Effect.gen(function* () { |
| 2117 | const fixture = yield* cleanupFixture(); |
| 2118 | fixture.setThreads([]); |
| 2119 | const orphan = `${fixture.config.worktreesDir}/${location === "nested" ? "repository/" : ""}orphan`; |
| 2120 | yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]); |
| 2121 | if (location === "annexed") yield* annexWorktree(fixture, orphan); |
| 2122 | const sizes = yield* Effect.forEach( |
| 2123 | // Links are not measured, and the annexed `.git` is one. |
| 2124 | (yield* fixture.fs.readDirectory(orphan)).filter( |
| 2125 | (name) => location !== "annexed" || name !== ".git", |
| 2126 | ), |
| 2127 | (name) => allocatedBytes(fixture.fs, `${orphan}/${name}`), |
| 2128 | ); |
| 2129 | const outside = yield* fixture.fs.makeTempDirectoryScoped(); |
| 2130 | yield* fixture.fs.writeFileString(`${outside}/external`, "outside data"); |
| 2131 | yield* fixture.fs.symlink(outside, `${orphan}/linked-directory`); |
| 2132 | yield* fixture.fs.symlink(`${outside}/missing`, `${orphan}/dangling-link`); |
| 2133 | yield* fixture.fs.utimes(orphan, 1, 1); |
| 2134 | const report = yield* fixture.service.runNow; |
| 2135 | expect(report.entries).toEqual([ |
| 2136 | { |
| 2137 | kind: "worktree", |
| 2138 | outcome: "kept", |
| 2139 | reason: "No thread uses this worktree", |
| 2140 | path: orphan, |
| 2141 | projectPath: null, |
| 2142 | threadId: null, |
| 2143 | threadTitle: null, |
| 2144 | bytes: sizes.reduce((sum, size) => sum + size, 0), |
| 2145 | files: null, |
| 2146 | }, |
| 2147 | ]); |
| 2148 | expect(report.bytesFreed).toBe(0); |
| 2149 | expect(yield* fixture.fs.readFileString(`${orphan}/tracked.txt`)).toBe("original\n"); |
| 2150 | expect(yield* fixture.fs.readFileString(`${outside}/external`)).toBe("outside data"); |
| 2151 | expect( |
| 2152 | (yield* fixture.command(orphan, ["rev-parse", "--is-inside-work-tree"])).stdout.trim(), |
| 2153 | ).toBe("true"); |
| 2154 | }), |
| 2155 | ), |
| 2156 | ); |
| 2157 | |
| 2158 | it.live.each(["active", "outside-active-snapshot"] as const)( |
| 2159 | "does not report a folder referenced by a thread (%s)", |
| 2160 | (location) => |
| 2161 | runCleanupTest( |
| 2162 | Effect.gen(function* () { |
| 2163 | const fixture = yield* cleanupFixture(); |
| 2164 | const worktreePath = `${fixture.config.worktreesDir}/repository/referenced`; |
| 2165 | yield* fixture.command(fixture.repo, [ |
| 2166 | "worktree", |
| 2167 | "add", |
| 2168 | "-b", |
| 2169 | "referenced", |
| 2170 | worktreePath, |
| 2171 | ]); |
| 2172 | fixture.setThreads( |
| 2173 | location === "active" |
| 2174 | ? [shell({ branch: "referenced", worktreePath, status: "running" })] |
| 2175 | : [], |
| 2176 | ); |
| 2177 | if (location !== "active") |
| 2178 | fixture.setStoredWorktreePaths([fixture.worktree, worktreePath]); |
| 2179 | yield* fixture.fs.utimes(worktreePath, 1, 1); |
| 2180 | const report = yield* fixture.service.runNow; |
| 2181 | expect(report.entries.filter((entry) => entry.threadId === null)).toEqual([]); |
| 2182 | expect(yield* fixture.fs.exists(worktreePath)).toBe(true); |
| 2183 | }), |
| 2184 | ), |
| 2185 | ); |
| 2186 | |
| 2187 | it.live.each(["exact", "nested", "symlink"] as const)( |
| 2188 | "does not report a folder containing a project checkout (%s)", |
| 2189 | (location) => |
| 2190 | runCleanupTest( |
| 2191 | Effect.gen(function* () { |
| 2192 | const fixture = yield* cleanupFixture(); |
| 2193 | fixture.setThreads([]); |
| 2194 | const worktreePath = `${fixture.config.worktreesDir}/repository/project-checkout`; |
| 2195 | yield* fixture.fs.makeDirectory(`${worktreePath}/nested`, { recursive: true }); |
| 2196 | const alias = `${fixture.repo}/alias`; |
| 2197 | if (location === "symlink") yield* fixture.fs.symlink(`${worktreePath}/nested`, alias); |
| 2198 | fixture.setProjectRoots([ |
| 2199 | fixture.repo, |
| 2200 | location === "exact" |
| 2201 | ? worktreePath |
| 2202 | : location === "nested" |
| 2203 | ? `${worktreePath}/nested` |
| 2204 | : alias, |
| 2205 | ]); |
| 2206 | yield* fixture.fs.utimes(worktreePath, 1, 1); |
| 2207 | expect((yield* fixture.service.runNow).entries).toEqual([]); |
| 2208 | expect(yield* fixture.fs.exists(worktreePath)).toBe(true); |
| 2209 | }), |
| 2210 | ), |
| 2211 | ); |
| 2212 | |
| 2213 | it.live.each(["exact", "contains", "symlink"] as const)( |
| 2214 | "does not report project internals under a custom managed root (%s)", |
| 2215 | (location) => |
| 2216 | runCleanupTest( |
| 2217 | Effect.gen(function* () { |
| 2218 | const fixture = yield* cleanupFixture(); |
| 2219 | fixture.setThreads([]); |
| 2220 | const source = `${fixture.repo}/src`; |
| 2221 | yield* fixture.fs.makeDirectory(`${source}/nested/deep`, { recursive: true }); |
| 2222 | const alias = `${fixture.config.worktreesDir}/project-alias`; |
| 2223 | if (location === "symlink") { |
| 2224 | yield* fixture.fs.symlink(fixture.repo, alias); |
| 2225 | fixture.setProjectRoots([alias]); |
| 2226 | } |
| 2227 | if (location === "contains") fixture.setProjectRoots([fixture.repo, `${source}/nested`]); |
| 2228 | fixture.setSettings({ |
| 2229 | worktreesDirectory: location === "contains" ? source : fixture.repo, |
| 2230 | }); |
| 2231 | expect((yield* fixture.service.runNow).entries).toEqual([]); |
| 2232 | expect(yield* fixture.fs.exists(`${source}/nested/deep`)).toBe(true); |
| 2233 | }), |
| 2234 | ), |
| 2235 | ); |
| 2236 | |
| 2237 | it.live.each([ |
| 2238 | { home: "an installed", worktreeHome: false, customFolderOutcome: "removed" }, |
| 2239 | { home: "a git worktree's dev", worktreeHome: true, customFolderOutcome: "kept" }, |
| 2240 | ] as const)( |
| 2241 | "on $home home, a custom worktrees folder ends $customFolderOutcome", |
| 2242 | ({ worktreeHome, customFolderOutcome }) => |
| 2243 | runCleanupTest( |
| 2244 | Effect.gen(function* () { |
| 2245 | const fs = yield* FileSystem.FileSystem; |
| 2246 | const config = yield* ServerConfig.ServerConfig; |
| 2247 | const checkout = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-dev-checkout-" }); |
| 2248 | yield* fs.writeFileString(`${checkout}/.git`, "gitdir: /repo/.git/worktrees/dev\n"); |
| 2249 | const baseDir = worktreeHome ? `${checkout}/.t3` : config.baseDir; |
| 2250 | const fixture = yield* cleanupFixture().pipe( |
| 2251 | Effect.provideService(ServerConfig.ServerConfig, { |
| 2252 | ...config, |
| 2253 | baseDir, |
| 2254 | worktreesDir: `${baseDir}/worktrees`, |
| 2255 | }), |
| 2256 | ); |
| 2257 | const customFolder = yield* fs.realPath( |
| 2258 | yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-real-worktrees-" }), |
| 2259 | ); |
| 2260 | const realWorktree = `${customFolder}/seeded`; |
| 2261 | yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "seeded", realWorktree]); |
| 2262 | fixture.setSettings({ worktreesDirectory: customFolder }); |
| 2263 | fixture.setThreads([ |
| 2264 | shell({ branch: "feature", worktreePath: fixture.worktree }), |
| 2265 | shell({ |
| 2266 | id: ThreadId.make("seeded"), |
| 2267 | lineage: { |
| 2268 | rootThreadId: ThreadId.make("seeded"), |
| 2269 | parentThreadId: null, |
| 2270 | relationshipToParent: null, |
| 2271 | }, |
| 2272 | branch: "seeded", |
| 2273 | worktreePath: realWorktree, |
| 2274 | }), |
| 2275 | ]); |
| 2276 | |
| 2277 | const { entries } = yield* fixture.service.runNow; |
| 2278 | |
| 2279 | expect(entries.find((entry) => entry.path === realWorktree)?.outcome).toBe( |
| 2280 | customFolderOutcome, |
| 2281 | ); |
| 2282 | expect(yield* fs.exists(realWorktree)).toBe(customFolderOutcome === "kept"); |
| 2283 | expect(yield* fs.exists(fixture.worktree)).toBe(false); |
| 2284 | }), |
| 2285 | ), |
| 2286 | ); |
| 2287 | |
| 2288 | it.live("skips symbolic links at both directory levels and disabled cleanup", () => |
| 2289 | runCleanupTest( |
| 2290 | Effect.gen(function* () { |
| 2291 | const fixture = yield* cleanupFixture(); |
| 2292 | fixture.setThreads([]); |
| 2293 | const outside = yield* fixture.fs.makeTempDirectoryScoped(); |
| 2294 | yield* fixture.fs.makeDirectory(`${outside}/checkout`); |
| 2295 | const projectDirectory = `${fixture.config.worktreesDir}/repository`; |
| 2296 | yield* fixture.fs.makeDirectory(projectDirectory); |
| 2297 | yield* fixture.fs.symlink(outside, `${fixture.config.worktreesDir}/linked-project`); |
| 2298 | yield* fixture.fs.symlink(`${outside}/checkout`, `${projectDirectory}/linked-checkout`); |
| 2299 | yield* fixture.fs.symlink(`${outside}/missing`, `${projectDirectory}/dangling-link`); |
| 2300 | expect((yield* fixture.service.runNow).entries).toEqual([]); |
| 2301 | const orphan = `${projectDirectory}/orphan`; |
| 2302 | yield* fixture.fs.makeDirectory(orphan); |
| 2303 | fixture.disable(); |
| 2304 | expect((yield* fixture.service.runNow).entries).toEqual([]); |
| 2305 | expect(yield* fixture.fs.exists(orphan)).toBe(true); |
| 2306 | }), |
| 2307 | ), |
| 2308 | ); |
| 2309 | |
| 2310 | it.live("reports ordinary folders with an honest reason and keeps their files", () => |
| 2311 | runCleanupTest( |
| 2312 | Effect.gen(function* () { |
| 2313 | const fixture = yield* cleanupFixture(); |
| 2314 | fixture.setThreads([]); |
| 2315 | const folder = `${fixture.config.worktreesDir}/repository/leftover`; |
| 2316 | yield* fixture.fs.makeDirectory(folder, { recursive: true }); |
| 2317 | yield* fixture.fs.writeFileString(`${folder}/payload`, "leftover data"); |
| 2318 | yield* fixture.fs.utimes(folder, 1, 1); |
| 2319 | const report = yield* fixture.service.runNow; |
| 2320 | expect(report.entries).toEqual([ |
| 2321 | expect.objectContaining({ |
| 2322 | path: folder, |
| 2323 | outcome: "kept", |
| 2324 | bytes: yield* allocatedBytes(fixture.fs, `${folder}/payload`), |
| 2325 | reason: "No thread uses this folder, and it isn't a git worktree", |
| 2326 | }), |
| 2327 | ]); |
| 2328 | expect(report.bytesFreed).toBe(0); |
| 2329 | expect(yield* fixture.fs.readFileString(`${folder}/payload`)).toBe("leftover data"); |
| 2330 | }), |
| 2331 | ), |
| 2332 | ); |
| 2333 | |
| 2334 | it.live("reports linked worktrees nested deeper inside a plain folder", () => |
| 2335 | runCleanupTest( |
| 2336 | Effect.gen(function* () { |
| 2337 | const fixture = yield* cleanupFixture(); |
| 2338 | fixture.setThreads([]); |
| 2339 | const replay = `${fixture.config.worktreesDir}/repository/replay`; |
| 2340 | const deep = `${fixture.config.worktreesDir}/repository/deep`; |
| 2341 | const worktrees = [`${deep}/a/b`, `${replay}/1376`]; |
| 2342 | for (const [index, worktree] of worktrees.entries()) { |
| 2343 | yield* fixture.command(fixture.repo, [ |
| 2344 | "worktree", |
| 2345 | "add", |
| 2346 | "-b", |
| 2347 | `nested-${index}`, |
| 2348 | worktree, |
| 2349 | ]); |
| 2350 | } |
| 2351 | for (const folder of [...worktrees, `${deep}/a`, deep, replay]) { |
| 2352 | yield* fixture.fs.utimes(folder, 1, 1); |
| 2353 | } |
| 2354 | const report = yield* fixture.service.runNow; |
| 2355 | expect( |
| 2356 | report.entries |
| 2357 | .map((entry) => ({ path: entry.path, reason: entry.reason })) |
| 2358 | .sort((left, right) => String(left.path).localeCompare(String(right.path))), |
| 2359 | ).toEqual(worktrees.map((path) => ({ path, reason: "No thread uses this worktree" }))); |
| 2360 | }), |
| 2361 | ), |
| 2362 | ); |
| 2363 | |
| 2364 | it.live("still reports a plain folder whose nested worktree registration is stale", () => |
| 2365 | runCleanupTest( |
| 2366 | Effect.gen(function* () { |
| 2367 | const fixture = yield* cleanupFixture(); |
| 2368 | fixture.setThreads([]); |
| 2369 | const replay = `${fixture.config.worktreesDir}/repository/replay`; |
| 2370 | const worktree = `${replay}/1376`; |
| 2371 | yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "locked", worktree]); |
| 2372 | yield* fixture.command(fixture.repo, ["worktree", "lock", worktree]); |
| 2373 | yield* fixture.fs.rename(worktree, `${replay}/moved`); |
| 2374 | yield* fixture.fs.makeDirectory(worktree); |
| 2375 | yield* fixture.fs.utimes(replay, 1, 1); |
| 2376 | expect((yield* fixture.service.runNow).entries.map((entry) => entry.path)).toEqual([ |
| 2377 | replay, |
| 2378 | ]); |
| 2379 | }), |
| 2380 | ), |
| 2381 | ); |
| 2382 | |
| 2383 | it.live("does not report nested worktrees inside a project checkout", () => |
| 2384 | runCleanupTest( |
| 2385 | Effect.gen(function* () { |
| 2386 | const fixture = yield* cleanupFixture(); |
| 2387 | fixture.setThreads([]); |
| 2388 | const project = `${fixture.config.worktreesDir}/repository/replay/project`; |
| 2389 | const worktree = `${project}/nested`; |
| 2390 | yield* fixture.fs.makeDirectory(project, { recursive: true }); |
| 2391 | fixture.setProjectRoots([fixture.repo, project]); |
| 2392 | yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "nested", worktree]); |
| 2393 | for (const folder of [worktree, project]) yield* fixture.fs.utimes(folder, 1, 1); |
| 2394 | expect((yield* fixture.service.runNow).entries).toEqual([]); |
| 2395 | }), |
| 2396 | ), |
| 2397 | ); |
| 2398 | |
| 2399 | it.effect( |
| 2400 | "measures new orphans first and rotates cached refreshes when the budget runs out, not counting discovery", |
| 2401 | () => |
| 2402 | runCleanupTest( |
| 2403 | Effect.gen(function* () { |
| 2404 | const fs = yield* FileSystem.FileSystem; |
| 2405 | const clock = yield* Clock.Clock; |
| 2406 | let now = NOW_MS; |
| 2407 | let parent: string | undefined; |
| 2408 | let slowDirectory: string | undefined; |
| 2409 | let slowDiscovery: string | undefined; |
| 2410 | const fixture = yield* cleanupFixture().pipe( |
| 2411 | Effect.provideService(Clock.Clock, { |
| 2412 | ...clock, |
| 2413 | currentTimeMillis: Effect.sync(() => now), |
| 2414 | }), |
| 2415 | Effect.provideService(FileSystem.FileSystem, { |
| 2416 | ...fs, |
| 2417 | readDirectory: (directory, options) => |
| 2418 | fs.readDirectory(directory, options).pipe( |
| 2419 | Effect.map((names) => { |
| 2420 | if (directory === slowDirectory || directory === slowDiscovery) now += 30_000; |
| 2421 | return directory === parent ? names.sort() : names; |
| 2422 | }), |
| 2423 | ), |
| 2424 | }), |
| 2425 | ); |
| 2426 | fixture.setThreads([]); |
| 2427 | parent = `${fixture.config.worktreesDir}/repository`; |
| 2428 | const cached = `${parent}/a-cached`; |
| 2429 | const later = `${parent}/b-cached`; |
| 2430 | const discovered = `${parent}/c-discovered`; |
| 2431 | for (const directory of [cached, later]) { |
| 2432 | yield* fs.makeDirectory(`${directory}/build`, { recursive: true }); |
| 2433 | yield* fs.utimes(directory, 1, 1); |
| 2434 | } |
| 2435 | const bundle = `${later}/build/bundle.js`; |
| 2436 | yield* fs.writeFileString(bundle, "x".repeat(64 * 1024)); |
| 2437 | const size = yield* allocatedBytes(fs, bundle); |
| 2438 | const first = yield* fixture.service.runNow; |
| 2439 | expect(first.entries.find((entry) => entry.path === later)?.bytes).toBe(size); |
| 2440 | |
| 2441 | slowDirectory = `${cached}/build`; |
| 2442 | yield* fs.remove(bundle); |
| 2443 | yield* fs.makeDirectory(discovered); |
| 2444 | yield* fs.utimes(discovered, 1, 1); |
| 2445 | const second = yield* fixture.service.runNow; |
| 2446 | expect(second.entries.find((entry) => entry.path === discovered)?.bytes).toBe(0); |
| 2447 | expect(second.entries.find((entry) => entry.path === later)?.bytes).toBe(size); |
| 2448 | |
| 2449 | slowDiscovery = parent; |
| 2450 | const third = yield* fixture.service.runNow; |
| 2451 | expect(third.entries.find((entry) => entry.path === later)?.bytes).toBe(0); |
| 2452 | }), |
| 2453 | ), |
| 2454 | ); |
| 2455 | |
| 2456 | it.live("retains the last orphan size on a failed refresh and can refresh it later", () => |
| 2457 | runCleanupTest( |
| 2458 | Effect.gen(function* () { |
| 2459 | const fs = yield* FileSystem.FileSystem; |
| 2460 | let unreadable: string | undefined; |
| 2461 | const fixture = yield* cleanupFixture().pipe( |
| 2462 | Effect.provideService(FileSystem.FileSystem, { |
| 2463 | ...fs, |
| 2464 | readDirectory: (directory, options) => |
| 2465 | fs.readDirectory( |
| 2466 | directory === unreadable ? `${directory}/missing-directory` : directory, |
| 2467 | options, |
| 2468 | ), |
| 2469 | }), |
| 2470 | ); |
| 2471 | fixture.setThreads([]); |
| 2472 | const orphan = `${fixture.config.worktreesDir}/repository/orphan`; |
| 2473 | const build = `${orphan}/build`; |
| 2474 | const bundle = `${build}/bundle.js`; |
| 2475 | yield* fs.makeDirectory(build, { recursive: true }); |
| 2476 | yield* fs.writeFileString(bundle, "build output"); |
| 2477 | yield* fs.utimes(orphan, 1, 1); |
| 2478 | const size = yield* allocatedBytes(fs, bundle); |
| 2479 | const orphanBytes = Effect.map( |
| 2480 | fixture.service.runNow, |
| 2481 | (report) => report.entries.find((entry) => entry.path === orphan)?.bytes, |
| 2482 | ); |
| 2483 | expect(yield* orphanBytes).toBe(size); |
| 2484 | yield* fs.remove(bundle); |
| 2485 | unreadable = build; |
| 2486 | expect(yield* orphanBytes).toBe(size); |
| 2487 | unreadable = undefined; |
| 2488 | expect(yield* orphanBytes).toBe(0); |
| 2489 | }), |
| 2490 | ), |
| 2491 | ); |
| 2492 | |
| 2493 | it.live("continues after an inaccessible directory's git probe", (context) => |
| 2494 | runCleanupTest( |
| 2495 | Effect.gen(function* () { |
| 2496 | if ((yield* HostProcess.isWindows) || (yield* HostProcess.UserId) === 0) |
| 2497 | return context.skip(); |
| 2498 | const fixture = yield* cleanupFixture(); |
| 2499 | fixture.setThreads([]); |
| 2500 | const blocked = `${fixture.config.worktreesDir}/a-inaccessible`; |
| 2501 | const orphan = `${fixture.config.worktreesDir}/z-repository/orphan`; |
| 2502 | yield* fixture.fs.makeDirectory(blocked); |
| 2503 | yield* fixture.fs.makeDirectory(orphan, { recursive: true }); |
| 2504 | yield* fixture.fs.writeFileString(`${orphan}/file`, "x"); |
| 2505 | yield* fixture.fs.chmod(blocked, 0); |
| 2506 | yield* fixture.fs.utimes(orphan, 1, 1); |
| 2507 | const report = yield* fixture.service.runNow.pipe( |
| 2508 | Effect.ensuring(fixture.fs.chmod(blocked, 0o700).pipe(Effect.orDie)), |
| 2509 | ); |
| 2510 | expect(report.entries).toEqual([ |
| 2511 | expect.objectContaining({ |
| 2512 | path: orphan, |
| 2513 | outcome: "kept", |
| 2514 | bytes: yield* allocatedBytes(fixture.fs, `${orphan}/file`), |
| 2515 | }), |
| 2516 | ]); |
| 2517 | expect(yield* fixture.fs.exists(orphan)).toBe(true); |
| 2518 | }), |
| 2519 | ), |
| 2520 | ); |
| 2521 | |
| 2522 | it.live.each(["win32", "linux"] as const)( |
| 2523 | "compares thread paths with host casing rules and excludes existing projects (%s)", |
| 2524 | (platform) => |
| 2525 | runCleanupTest( |
| 2526 | Effect.gen(function* () { |
| 2527 | const fixture = yield* cleanupFixture().pipe( |
| 2528 | Effect.provideService(HostProcess.Platform, platform), |
| 2529 | ); |
| 2530 | fixture.setThreads([]); |
| 2531 | const parent = `${fixture.config.worktreesDir}/repository`; |
| 2532 | const referenced = `${parent}/Referenced`; |
| 2533 | const project = `${parent}/Project`; |
| 2534 | const nested = `${parent}/Nested`; |
| 2535 | for (const folder of [referenced, project, nested]) { |
| 2536 | yield* fixture.fs.makeDirectory(`${folder}/child`, { recursive: true }); |
| 2537 | yield* fixture.fs.utimes(folder, 1, 1); |
| 2538 | } |
| 2539 | fixture.setStoredWorktreePaths([fixture.worktree, referenced.toUpperCase()]); |
| 2540 | fixture.setProjectRoots([fixture.repo, project, `${nested}/child`]); |
| 2541 | const report = yield* fixture.service.runNow; |
| 2542 | expect(report.entries.map((entry) => entry.path).sort()).toEqual( |
| 2543 | platform === "win32" ? [] : [referenced], |
| 2544 | ); |
| 2545 | }), |
| 2546 | ), |
| 2547 | ); |
| 2548 | |
| 2549 | it.live.each([ |
| 2550 | ["win32", "cwd"], |
| 2551 | ["win32", "worktreePath"], |
| 2552 | ["linux", "cwd"], |
| 2553 | ["linux", "worktreePath"], |
| 2554 | ] as const)( |
| 2555 | "matches a terminal at the worktree root with host casing rules (%s, %s)", |
| 2556 | ([platform, field]) => |
| 2557 | runCleanupTest( |
| 2558 | Effect.gen(function* () { |
| 2559 | const fixture = yield* cleanupFixture().pipe( |
| 2560 | Effect.provideService(HostProcess.Platform, platform), |
| 2561 | ); |
| 2562 | const upper = fixture.worktree.toUpperCase(); |
| 2563 | yield* fixture.openTerminal( |
| 2564 | field === "cwd" |
| 2565 | ? { cwd: upper, worktreePath: null } |
| 2566 | : { cwd: fixture.repo, worktreePath: upper }, |
| 2567 | ); |
| 2568 | const report = yield* fixture.service.runNow; |
| 2569 | expect(report.entries[0]).toMatchObject( |
| 2570 | platform === "win32" |
| 2571 | ? { outcome: "kept", reason: "Open terminal" } |
| 2572 | : { outcome: "removed" }, |
| 2573 | ); |
| 2574 | }), |
| 2575 | ), |
| 2576 | ); |
| 2577 | |
| 2578 | it.live.each(["win32", "linux"] as const)( |
| 2579 | "matches a provider session at the worktree root with host casing rules (%s)", |
| 2580 | (platform) => |
| 2581 | runCleanupTest( |
| 2582 | Effect.gen(function* () { |
| 2583 | const fixture = yield* cleanupFixture().pipe( |
| 2584 | Effect.provideService(HostProcess.Platform, platform), |
| 2585 | ); |
| 2586 | fixture.setOpenSessionCwd(fixture.worktree.toUpperCase()); |
| 2587 | const report = yield* fixture.service.runNow; |
| 2588 | expect(report.entries[0]).toMatchObject( |
| 2589 | platform === "win32" |
| 2590 | ? { outcome: "kept", reason: "Provider session is still open" } |
| 2591 | : { outcome: "removed" }, |
| 2592 | ); |
| 2593 | }), |
| 2594 | ), |
| 2595 | ); |
| 2596 | }); |
| 2597 | |
| 2598 | describe("storage cleanup reports and local file policies", () => { |
| 2599 | it.effect.each([true, false])( |
| 2600 | "sweeps on runtime retirement rather than live error metadata, worktreeOnDelete=%s", |
| 2601 | (worktreeOnDelete) => |
| 2602 | runCleanupTest( |
| 2603 | Effect.gen(function* () { |
| 2604 | const fixture = yield* cleanupFixture({ |
| 2605 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 2606 | worktreeAfterDays: 8, |
| 2607 | worktreeOnDelete, |
| 2608 | }); |
| 2609 | fixture.setThreads([]); |
| 2610 | fixture.setDeletedThreads([ |
| 2611 | shell({ branch: "feature", worktreePath: fixture.worktree, deletedAt: at(0) }), |
| 2612 | ]); |
| 2613 | yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "agent edit\n"); |
| 2614 | const events = yield* Queue.unbounded<{ |
| 2615 | readonly event: OrchestrationV2DomainEvent; |
| 2616 | readonly processed: Deferred.Deferred<void>; |
| 2617 | }>(); |
| 2618 | yield* fixture.activate( |
| 2619 | Stream.fromQueue(events).pipe( |
| 2620 | Stream.flatMap(({ event, processed }) => |
| 2621 | Stream.succeed(event).pipe( |
| 2622 | Stream.concat( |
| 2623 | // The next pull acknowledges that the listener handled this event. |
| 2624 | Stream.fromEffect(Deferred.succeed(processed, undefined)).pipe(Stream.drain), |
| 2625 | ), |
| 2626 | ), |
| 2627 | ), |
| 2628 | ), |
| 2629 | ); |
| 2630 | yield* fixture.service.reports.pipe( |
| 2631 | Stream.filter((report) => report !== null), |
| 2632 | Stream.take(1), |
| 2633 | Stream.runDrain, |
| 2634 | ); |
| 2635 | yield* fixture.service.drain; |
| 2636 | const startupReads = fixture.snapshotReads(); |
| 2637 | const publish = Effect.fn("StorageCleanupTest.publish")(function* ( |
| 2638 | event: OrchestrationV2DomainEvent, |
| 2639 | ) { |
| 2640 | const processed = yield* Deferred.make<void>(); |
| 2641 | yield* Queue.offer(events, { event, processed }); |
| 2642 | yield* Deferred.await(processed); |
| 2643 | yield* fixture.service.drain; |
| 2644 | }); |
| 2645 | const sessionUpdated = ( |
| 2646 | status: "ready" | "error" | "stopped", |
| 2647 | text: string, |
| 2648 | ): OrchestrationV2DomainEvent => ({ |
| 2649 | id: EventId.make(`event:session:${status}:${text}`), |
| 2650 | type: "provider-session.updated", |
| 2651 | threadId: ThreadId.make("thread-1"), |
| 2652 | occurredAt: at(0), |
| 2653 | payload: { |
| 2654 | id: ProviderSessionId.make("session-1"), |
| 2655 | driver: ProviderDriverKind.make("pi"), |
| 2656 | providerInstanceId: ProviderInstanceId.make("pi"), |
| 2657 | status, |
| 2658 | cwd: fixture.worktree, |
| 2659 | model: null, |
| 2660 | capabilities: CodexProviderCapabilitiesV2, |
| 2661 | extensionStatuses: text === "" ? [] : [{ key: "watch", text }], |
| 2662 | createdAt: at(-DAY_MS), |
| 2663 | updatedAt: at(0), |
| 2664 | lastError: status === "error" ? "Rate limited" : null, |
| 2665 | }, |
| 2666 | }); |
| 2667 | yield* publish(sessionUpdated("ready", "Watching")); |
| 2668 | expect(fixture.snapshotReads()).toBe(startupReads); |
| 2669 | expect(fixture.sessionLiveChecks()).toBe(0); |
| 2670 | for (let index = 0; index < 5; index++) { |
| 2671 | yield* publish(sessionUpdated("error", `Watching ${index} files`)); |
| 2672 | expect(fixture.snapshotReads()).toBe(startupReads); |
| 2673 | } |
| 2674 | expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 5 : 0); |
| 2675 | |
| 2676 | // Release removes the live entry before publishing its final error update. |
| 2677 | fixture.setSessionLive(false); |
| 2678 | yield* publish(sessionUpdated("error", "")); |
| 2679 | expect(fixture.snapshotReads()).toBe(startupReads + Number(worktreeOnDelete)); |
| 2680 | expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0); |
| 2681 | |
| 2682 | yield* publish(sessionUpdated("stopped", "")); |
| 2683 | expect(fixture.snapshotReads()).toBe(startupReads + 2 * Number(worktreeOnDelete)); |
| 2684 | expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0); |
| 2685 | |
| 2686 | fixture.setSessionLive(true); |
| 2687 | yield* publish({ |
| 2688 | id: EventId.make("event:thread:deleted"), |
| 2689 | type: "thread.deleted", |
| 2690 | threadId: ThreadId.make("thread-1"), |
| 2691 | occurredAt: at(0), |
| 2692 | payload: { ...shell({ deletedAt: at(0) }), lastVisitedAt: null }, |
| 2693 | }); |
| 2694 | // Deletion always sweeps so the deleted thread's checkpoint refs are pruned. |
| 2695 | expect(fixture.snapshotReads()).toBe(startupReads + 2 * Number(worktreeOnDelete) + 1); |
| 2696 | expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0); |
| 2697 | }), |
| 2698 | ), |
| 2699 | ); |
| 2700 | it.effect("automatically removes an eligible archived thread checkout", () => |
| 2701 | runCleanupTest( |
| 2702 | Effect.gen(function* () { |
| 2703 | yield* TestClock.setTime(NOW_MS); |
| 2704 | const fixture = yield* cleanupFixture(); |
| 2705 | fixture.setThreads([ |
| 2706 | shell({ |
| 2707 | branch: "feature", |
| 2708 | worktreePath: fixture.worktree, |
| 2709 | archivedAt: at(-DAY_MS), |
| 2710 | }), |
| 2711 | ]); |
| 2712 | yield* fixture.activate(Stream.empty); |
| 2713 | const [report] = yield* fixture.service.reports.pipe( |
| 2714 | Stream.filter((report) => report !== null), |
| 2715 | Stream.take(1), |
| 2716 | Stream.runCollect, |
| 2717 | ); |
| 2718 | yield* fixture.service.drain; |
| 2719 | expect(report).toMatchObject({ |
| 2720 | trigger: "automatic", |
| 2721 | counts: { removed: 1, kept: 0, failed: 0 }, |
| 2722 | entries: [ |
| 2723 | { |
| 2724 | threadId: "thread-1", |
| 2725 | path: fixture.worktree, |
| 2726 | outcome: "removed", |
| 2727 | reason: "Inactive for 30 days", |
| 2728 | }, |
| 2729 | ], |
| 2730 | }); |
| 2731 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); |
| 2732 | }), |
| 2733 | ), |
| 2734 | ); |
| 2735 | it.effect("removes an idle No project thread's scratch folder past the retention", () => |
| 2736 | runCleanupTest( |
| 2737 | Effect.gen(function* () { |
| 2738 | yield* TestClock.setTime(NOW_MS); |
| 2739 | const fixture = yield* cleanupFixture(); |
| 2740 | const scratchRoot = `${fixture.config.baseDir}/scratch`; |
| 2741 | const folder = `${scratchRoot}/quiet-otter`; |
| 2742 | yield* fixture.fs.makeDirectory(folder, { recursive: true }); |
| 2743 | yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); |
| 2744 | fixture.setProjectRoots([scratchRoot]); |
| 2745 | fixture.setStoredWorktreePaths([]); |
| 2746 | // Only this rule lets cleanup delete untracked files, which is all a scratch folder has. |
| 2747 | fixture.setPolicy("tracked-changes"); |
| 2748 | fixture.setThreads([ |
| 2749 | shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), |
| 2750 | ]); |
| 2751 | const report = yield* fixture.service.runNow; |
| 2752 | expect(report.entries).toEqual([ |
| 2753 | expect.objectContaining({ path: folder, outcome: "removed" }), |
| 2754 | ]); |
| 2755 | expect(yield* fixture.fs.exists(folder)).toBe(false); |
| 2756 | }), |
| 2757 | ), |
| 2758 | ); |
| 2759 | it.effect.each([ |
| 2760 | { |
| 2761 | name: "a Git repository in a subfolder", |
| 2762 | policy: "tracked-changes", |
| 2763 | repository: "clone/.git", |
| 2764 | reason: "Contains a nested Git repository", |
| 2765 | }, |
| 2766 | { |
| 2767 | name: "a Git repository of its own", |
| 2768 | policy: "tracked-changes", |
| 2769 | repository: ".git", |
| 2770 | reason: "Contains a nested Git repository", |
| 2771 | }, |
| 2772 | { name: "files under the default keep rule", reason: "Has local files (notes.md)" }, |
| 2773 | { |
| 2774 | name: "a scheduled task", |
| 2775 | policy: "tracked-changes", |
| 2776 | scheduled: true, |
| 2777 | reason: "Thread has a scheduled task", |
| 2778 | }, |
| 2779 | ] as const)( |
| 2780 | "keeps an idle No project thread's scratch folder with $name", |
| 2781 | ({ |
| 2782 | policy, |
| 2783 | repository, |
| 2784 | scheduled, |
| 2785 | reason, |
| 2786 | }: { |
| 2787 | readonly policy?: WorktreeKeepWhen; |
| 2788 | readonly repository?: string; |
| 2789 | readonly scheduled?: boolean; |
| 2790 | readonly reason: string; |
| 2791 | }) => |
| 2792 | runCleanupTest( |
| 2793 | Effect.gen(function* () { |
| 2794 | yield* TestClock.setTime(NOW_MS); |
| 2795 | const fixture = yield* cleanupFixture(); |
| 2796 | const scratchRoot = `${fixture.config.baseDir}/scratch`; |
| 2797 | const folder = `${scratchRoot}/quiet-otter`; |
| 2798 | yield* fixture.fs.makeDirectory( |
| 2799 | repository === undefined ? folder : `${folder}/${repository}`, |
| 2800 | { recursive: true }, |
| 2801 | ); |
| 2802 | yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); |
| 2803 | // No thread owns this one, so it is listed and never removed. |
| 2804 | const leftover = `${scratchRoot}/leftover`; |
| 2805 | yield* fixture.fs.makeDirectory(leftover); |
| 2806 | yield* fixture.fs.utimes(leftover, 1, 1); |
| 2807 | fixture.setProjectRoots([scratchRoot]); |
| 2808 | fixture.setStoredWorktreePaths([]); |
| 2809 | if (policy !== undefined) fixture.setPolicy(policy); |
| 2810 | if (scheduled) fixture.setScheduledThreadIds(["thread-1"]); |
| 2811 | fixture.setThreads([ |
| 2812 | shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), |
| 2813 | ]); |
| 2814 | const report = yield* fixture.service.runNow; |
| 2815 | expect( |
| 2816 | report.entries.map(({ path, outcome, reason }) => ({ path, outcome, reason })), |
| 2817 | ).toEqual([ |
| 2818 | { path: leftover, outcome: "kept", reason: "No thread uses this folder" }, |
| 2819 | { path: folder, outcome: "kept", reason }, |
| 2820 | ]); |
| 2821 | expect(yield* fixture.fs.exists(`${folder}/notes.md`)).toBe(true); |
| 2822 | }), |
| 2823 | ), |
| 2824 | ); |
| 2825 | it.effect("keeps a thread's worktree folder that lost its .git link", () => |
| 2826 | runCleanupTest( |
| 2827 | Effect.gen(function* () { |
| 2828 | yield* TestClock.setTime(NOW_MS); |
| 2829 | const fixture = yield* cleanupFixture(); |
| 2830 | fixture.setThreads([ |
| 2831 | shell({ branch: "feature", worktreePath: fixture.worktree, archivedAt: at(-DAY_MS) }), |
| 2832 | ]); |
| 2833 | yield* fixture.fs.remove(`${fixture.worktree}/.git`); |
| 2834 | yield* fixture.fs.makeDirectory(`${fixture.worktree}/node_modules`); |
| 2835 | const report = yield* fixture.service.runNow; |
| 2836 | expect(report.entries).toEqual([ |
| 2837 | expect.objectContaining({ path: fixture.worktree, outcome: "kept" }), |
| 2838 | ]); |
| 2839 | expect(yield* fixture.fs.exists(`${fixture.worktree}/node_modules`)).toBe(true); |
| 2840 | }), |
| 2841 | ), |
| 2842 | ); |
| 2843 | it.live("skips a stored worktree path whose parent is a regular file", () => |
| 2844 | runCleanupTest( |
| 2845 | Effect.gen(function* () { |
| 2846 | const fixture = yield* cleanupFixture(); |
| 2847 | const legacyRoot = `${fixture.config.worktreesDir}/legacy-root`; |
| 2848 | yield* fixture.fs.writeFileString(legacyRoot, ""); |
| 2849 | fixture.setThreads([ |
| 2850 | shell({ branch: "feature", worktreePath: `${legacyRoot}/stored-workspace` }), |
| 2851 | ]); |
| 2852 | const report = yield* fixture.service.runNow; |
| 2853 | expect(report.entries).toEqual([]); |
| 2854 | expect(report.counts).toEqual({ removed: 0, kept: 0, failed: 0 }); |
| 2855 | }), |
| 2856 | ), |
| 2857 | ); |
| 2858 | it.live.each([ |
| 2859 | ["before-check", "stored"], |
| 2860 | ["while-measuring", "stored"], |
| 2861 | ["before-check", "symlinked parent"], |
| 2862 | ["while-measuring", "symlinked parent"], |
| 2863 | ] as const)( |
| 2864 | "keeps a worktree protected by a missing project root (%s, %s spelling)", |
| 2865 | ([timing, spelling]) => |
| 2866 | runCleanupTest( |
| 2867 | Effect.gen(function* () { |
| 2868 | const fixture = yield* pausedMeasurementFixture(); |
| 2869 | let worktree = fixture.worktree; |
| 2870 | if (spelling === "symlinked parent") { |
| 2871 | const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; |
| 2872 | yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); |
| 2873 | worktree = `${linkedParent}/feature`; |
| 2874 | fixture.setThreads([shell({ branch: "feature", worktreePath: worktree })]); |
| 2875 | } |
| 2876 | if (timing === "before-check") |
| 2877 | fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); |
| 2878 | const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); |
| 2879 | if (timing === "while-measuring") { |
| 2880 | yield* Deferred.await(fixture.measuring); |
| 2881 | fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); |
| 2882 | } |
| 2883 | yield* Deferred.succeed(fixture.resume, undefined); |
| 2884 | const report = yield* Fiber.join(cleanup); |
| 2885 | expect(report.entries[0]).toMatchObject({ |
| 2886 | outcome: "kept", |
| 2887 | reason: "Contains a project checkout", |
| 2888 | }); |
| 2889 | expect(yield* fixture.fs.readFileString(`${fixture.worktree}/tracked.txt`)).toBe( |
| 2890 | "original\n", |
| 2891 | ); |
| 2892 | }), |
| 2893 | ), |
| 2894 | ); |
| 2895 | |
| 2896 | it.live("reports allocated bytes of single-link files without following symlinks", () => |
| 2897 | runCleanupTest( |
| 2898 | Effect.gen(function* () { |
| 2899 | const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); |
| 2900 | setPolicy("tracked-changes"); |
| 2901 | const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) => |
| 2902 | allocatedBytes(fs, `${worktree}/${name}`), |
| 2903 | ); |
| 2904 | const outside = yield* fs.makeTempDirectoryScoped(); |
| 2905 | yield* fs.writeFileString(`${outside}/external`, "must not count"); |
| 2906 | yield* fs.writeFileString(`${outside}/store-file`, "shared ".repeat(10_000)); |
| 2907 | yield* fs.makeDirectory(`${worktree}/node_modules/nested`, { recursive: true }); |
| 2908 | yield* fs.writeFileString(`${worktree}/node_modules/nested/file`, "count me"); |
| 2909 | sizes.push(yield* allocatedBytes(fs, `${worktree}/node_modules/nested/file`)); |
| 2910 | yield* fs.link(`${outside}/store-file`, `${worktree}/node_modules/hardlinked`); |
| 2911 | yield* fs.symlink(outside, `${worktree}/node_modules/directory-link`); |
| 2912 | yield* fs.symlink(`${outside}/external`, `${worktree}/node_modules/file-link`); |
| 2913 | yield* fs.symlink(`${outside}/missing`, `${worktree}/node_modules/dangling-link`); |
| 2914 | const report = yield* service.runNow; |
| 2915 | const bytes = sizes.reduce((sum, size) => sum + size, 0); |
| 2916 | expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes, files: null }); |
| 2917 | expect(report.bytesFreed).toBe(bytes); |
| 2918 | expect(yield* fs.readFileString(`${outside}/external`)).toBe("must not count"); |
| 2919 | expect(yield* fs.readFileString(`${outside}/store-file`)).toBe("shared ".repeat(10_000)); |
| 2920 | expect(yield* fs.exists(worktree)).toBe(false); |
| 2921 | }), |
| 2922 | ), |
| 2923 | ); |
| 2924 | it.live.each(["same-device", "other-device", "no-manifest"] as const)( |
| 2925 | "counts the pnpm virtual store only when its store forces copies (%s)", |
| 2926 | (store) => |
| 2927 | runCleanupTest( |
| 2928 | Effect.gen(function* () { |
| 2929 | const fs = yield* FileSystem.FileSystem; |
| 2930 | const storeDir = yield* fs.makeTempDirectoryScoped({ prefix: "pnpm-store-" }); |
| 2931 | const statted: string[] = []; |
| 2932 | const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( |
| 2933 | Effect.provideService(FileSystem.FileSystem, { |
| 2934 | ...fs, |
| 2935 | lstat: (target) => { |
| 2936 | statted.push(target); |
| 2937 | return fs.lstat(target); |
| 2938 | }, |
| 2939 | stat: (target) => |
| 2940 | fs |
| 2941 | .stat(target) |
| 2942 | .pipe( |
| 2943 | Effect.map((info) => |
| 2944 | store === "other-device" && target === storeDir |
| 2945 | ? { ...info, dev: info.dev + 1n } |
| 2946 | : info, |
| 2947 | ), |
| 2948 | ), |
| 2949 | }), |
| 2950 | ); |
| 2951 | setPolicy("tracked-changes"); |
| 2952 | const nodeModules = `${worktree}/node_modules`; |
| 2953 | yield* fs.makeDirectory(`${nodeModules}/.pnpm/pkg@1.0.0`, { recursive: true }); |
| 2954 | yield* fs.makeDirectory(`${nodeModules}/.vite`); |
| 2955 | yield* fs.writeFileString( |
| 2956 | `${nodeModules}/.pnpm/pkg@1.0.0/index.js`, |
| 2957 | "clone ".repeat(10_000), |
| 2958 | ); |
| 2959 | yield* fs.writeFileString(`${nodeModules}/.vite/deps.js`, "cache"); |
| 2960 | if (store !== "no-manifest") |
| 2961 | yield* fs.writeFileString( |
| 2962 | `${nodeModules}/.modules.yaml`, |
| 2963 | JSON.stringify({ storeDir, virtualStoreDir: ".pnpm" }), |
| 2964 | ); |
| 2965 | const counted = [ |
| 2966 | ...(yield* fs.readDirectory(worktree)).flatMap((name) => |
| 2967 | name === "node_modules" ? [] : [`${worktree}/${name}`], |
| 2968 | ), |
| 2969 | `${nodeModules}/.vite/deps.js`, |
| 2970 | ...(store === "no-manifest" ? [] : [`${nodeModules}/.modules.yaml`]), |
| 2971 | ...(store === "same-device" ? [] : [`${nodeModules}/.pnpm/pkg@1.0.0/index.js`]), |
| 2972 | ]; |
| 2973 | const bytes = (yield* Effect.forEach(counted, (file) => allocatedBytes(fs, file))).reduce( |
| 2974 | (sum, size) => sum + size, |
| 2975 | 0, |
| 2976 | ); |
| 2977 | const report = yield* service.runNow; |
| 2978 | expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes }); |
| 2979 | expect(statted.includes(`${nodeModules}/.pnpm/pkg@1.0.0/index.js`)).toBe( |
| 2980 | store !== "same-device", |
| 2981 | ); |
| 2982 | }), |
| 2983 | ), |
| 2984 | ); |
| 2985 | // An agent can write this manifest. Statting its store sent the Windows |
| 2986 | // user's NTLM credentials to attacker.test during a background sweep. |
| 2987 | it.live.each([ |
| 2988 | { storeDir: "\\\\attacker.test\\s" }, |
| 2989 | { storeDir: "/local/store", virtualStoreDir: "//attacker.test/s" }, |
| 2990 | ])("never stats a network pnpm store %o", (manifest) => |
| 2991 | runCleanupTest( |
| 2992 | Effect.gen(function* () { |
| 2993 | const fs = yield* FileSystem.FileSystem; |
| 2994 | const statted: Array<string> = []; |
| 2995 | const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( |
| 2996 | Effect.provideService(FileSystem.FileSystem, { |
| 2997 | ...fs, |
| 2998 | stat: (target) => { |
| 2999 | statted.push(target); |
| 3000 | return fs.stat(target); |
| 3001 | }, |
| 3002 | }), |
| 3003 | ); |
| 3004 | setPolicy("tracked-changes"); |
| 3005 | yield* fs.makeDirectory(`${worktree}/node_modules`); |
| 3006 | yield* fs.writeFileString( |
| 3007 | `${worktree}/node_modules/.modules.yaml`, |
| 3008 | JSON.stringify(manifest), |
| 3009 | ); |
| 3010 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); |
| 3011 | expect(statted.filter((target) => target.includes("attacker.test"))).toEqual([]); |
| 3012 | }), |
| 3013 | ), |
| 3014 | ); |
| 3015 | it.effect.each([ |
| 3016 | { days: 8, reason: "Inactive for 1 of 8 days" }, |
| 3017 | { days: null, reason: "No rules apply" }, |
| 3018 | ])("keeps an ineligible age/delete-only worktree without Git ($days)", ({ days, reason }) => |
| 3019 | runCleanupTest( |
| 3020 | Effect.gen(function* () { |
| 3021 | yield* TestClock.setTime(NOW_MS); |
| 3022 | const fixture = yield* cleanupFixture({ |
| 3023 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3024 | worktreeAfterDays: days, |
| 3025 | worktreeOnDelete: true, |
| 3026 | }); |
| 3027 | fixture.setThreads([ |
| 3028 | shell({ |
| 3029 | branch: "feature", |
| 3030 | worktreePath: fixture.worktree, |
| 3031 | latestUserMessageAt: at(-DAY_MS), |
| 3032 | }), |
| 3033 | ]); |
| 3034 | yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "local edit\n"); |
| 3035 | const report = yield* fixture.service.runNow; |
| 3036 | expect(report.entries[0]).toMatchObject({ |
| 3037 | outcome: "kept", |
| 3038 | reason, |
| 3039 | bytes: null, |
| 3040 | }); |
| 3041 | expect(fixture.gitInspections()).toBe(0); |
| 3042 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 3043 | }), |
| 3044 | ), |
| 3045 | ); |
| 3046 | it.live("lets a turn acquire the checkout during accounting and protects its new activity", () => |
| 3047 | runCleanupTest( |
| 3048 | Effect.gen(function* () { |
| 3049 | const fixture = yield* pausedMeasurementFixture(); |
| 3050 | const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); |
| 3051 | yield* Deferred.await(fixture.measuring); |
| 3052 | yield* withWorkspaceLease( |
| 3053 | fixture.worktree, |
| 3054 | Effect.sync(() => { |
| 3055 | fixture.setThreads([ |
| 3056 | shell({ |
| 3057 | branch: "feature", |
| 3058 | worktreePath: fixture.worktree, |
| 3059 | status: "running", |
| 3060 | }), |
| 3061 | ]); |
| 3062 | }), |
| 3063 | ); |
| 3064 | yield* Deferred.succeed(fixture.resume, undefined); |
| 3065 | const report = yield* Fiber.join(cleanup); |
| 3066 | expect(report.entries[0]).toMatchObject({ |
| 3067 | outcome: "kept", |
| 3068 | reason: "Thread activity or shared worktree changed since check", |
| 3069 | bytes: null, |
| 3070 | }); |
| 3071 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 3072 | }), |
| 3073 | ), |
| 3074 | ); |
| 3075 | it.live("removes a worktree whose .git file git-annex replaced with a symlink", () => |
| 3076 | runCleanupTest( |
| 3077 | Effect.gen(function* () { |
| 3078 | const fixture = yield* cleanupFixture(); |
| 3079 | const { service, worktree, fs } = fixture; |
| 3080 | yield* annexWorktree(fixture, worktree); |
| 3081 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); |
| 3082 | expect(yield* fs.exists(worktree)).toBe(false); |
| 3083 | }), |
| 3084 | ), |
| 3085 | ); |
| 3086 | it.live("keeps a worktree when the inspection cannot read its directories", () => |
| 3087 | runCleanupTest( |
| 3088 | Effect.gen(function* () { |
| 3089 | const fs = yield* FileSystem.FileSystem; |
| 3090 | const { service, worktree } = yield* cleanupFixture().pipe( |
| 3091 | Effect.provideService(FileSystem.FileSystem, { |
| 3092 | ...fs, |
| 3093 | readDirectory: (directory) => fs.readDirectory(`${directory}/missing-directory`), |
| 3094 | }), |
| 3095 | ); |
| 3096 | const report = yield* service.runNow; |
| 3097 | expect(report.entries[0]).toMatchObject({ |
| 3098 | outcome: "kept", |
| 3099 | reason: "Worktree could not be fully inspected", |
| 3100 | bytes: null, |
| 3101 | files: null, |
| 3102 | }); |
| 3103 | expect(report.bytesFreed).toBe(0); |
| 3104 | expect(yield* fs.exists(worktree)).toBe(true); |
| 3105 | }), |
| 3106 | ), |
| 3107 | ); |
| 3108 | it.effect("removes a worktree owned by a repository other than the project root", () => |
| 3109 | runCleanupTest( |
| 3110 | Effect.gen(function* () { |
| 3111 | yield* TestClock.setTime(NOW_MS); |
| 3112 | const fixture = yield* cleanupFixture(); |
| 3113 | const { fs, command, config } = fixture; |
| 3114 | const oldRepo = yield* fs.realPath( |
| 3115 | yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-old-repo-" }), |
| 3116 | ); |
| 3117 | yield* command(oldRepo, ["init", "-b", "main"]); |
| 3118 | yield* command(oldRepo, ["config", "user.email", "cleanup@example.test"]); |
| 3119 | yield* command(oldRepo, ["config", "user.name", "Cleanup test"]); |
| 3120 | yield* fs.writeFileString(`${oldRepo}/tracked.txt`, "original\n"); |
| 3121 | yield* command(oldRepo, ["add", "."]); |
| 3122 | yield* command(oldRepo, ["commit", "-m", "initial"]); |
| 3123 | yield* fs.makeDirectory(`${config.worktreesDir}/old-repo`, { recursive: true }); |
| 3124 | const oldWorktree = `${config.worktreesDir}/old-repo/feature`; |
| 3125 | yield* command(oldRepo, ["worktree", "add", "-b", "feature", oldWorktree]); |
| 3126 | fixture.setThreads([shell({ branch: "feature", worktreePath: oldWorktree })]); |
| 3127 | const report = yield* fixture.service.runNow; |
| 3128 | expect(report.entries.find((entry) => entry.path === oldWorktree)).toMatchObject({ |
| 3129 | outcome: "removed", |
| 3130 | }); |
| 3131 | expect(yield* fs.exists(oldWorktree)).toBe(false); |
| 3132 | expect((yield* command(oldRepo, ["worktree", "list", "--porcelain"])).stdout).not.toContain( |
| 3133 | oldWorktree, |
| 3134 | ); |
| 3135 | }), |
| 3136 | ), |
| 3137 | ); |
| 3138 | it.effect.each([ |
| 3139 | [ |
| 3140 | "its owner's branch is cleared", |
| 3141 | (worktree: string) => [shell({ branch: null, worktreePath: worktree, updatedAt: at(0) })], |
| 3142 | ], |
| 3143 | [ |
| 3144 | "its owner's branch changes", |
| 3145 | (worktree: string) => [shell({ branch: "other", worktreePath: worktree, updatedAt: at(0) })], |
| 3146 | ], |
| 3147 | [ |
| 3148 | "its thread starts", |
| 3149 | (worktree: string) => [ |
| 3150 | shell({ branch: "feature", worktreePath: worktree, status: "running" }), |
| 3151 | ], |
| 3152 | ], |
| 3153 | [ |
| 3154 | "another thread starts using it", |
| 3155 | (worktree: string) => [ |
| 3156 | shell({ branch: "feature", worktreePath: worktree }), |
| 3157 | shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }), |
| 3158 | ], |
| 3159 | ], |
| 3160 | [ |
| 3161 | "an archived thread starts using it", |
| 3162 | (worktree: string) => [ |
| 3163 | shell({ branch: "feature", worktreePath: worktree }), |
| 3164 | shell({ |
| 3165 | id: ThreadId.make("thread-2"), |
| 3166 | branch: "feature", |
| 3167 | worktreePath: worktree, |
| 3168 | archivedAt: at(-DAY_MS), |
| 3169 | }), |
| 3170 | ], |
| 3171 | ], |
| 3172 | ] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) => |
| 3173 | runCleanupTest( |
| 3174 | Effect.gen(function* () { |
| 3175 | yield* TestClock.setTime(NOW_MS); |
| 3176 | const fixture = yield* pausedMeasurementFixture(); |
| 3177 | const { fs, worktree } = fixture; |
| 3178 | fixture.setPolicy("tracked-changes"); |
| 3179 | yield* fs.writeFileString(`${worktree}/notes.txt`, "untracked\n"); |
| 3180 | const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); |
| 3181 | yield* Deferred.await(fixture.measuring); |
| 3182 | fixture.setThreads(threadsWhileMeasuring(worktree)); |
| 3183 | yield* Deferred.succeed(fixture.resume, undefined); |
| 3184 | const report = yield* Fiber.join(cleanup); |
| 3185 | expect(report.entries[0]).toMatchObject({ |
| 3186 | outcome: "kept", |
| 3187 | reason: "Thread activity or shared worktree changed since check", |
| 3188 | bytes: null, |
| 3189 | }); |
| 3190 | expect(report.bytesFreed).toBe(0); |
| 3191 | expect(yield* fs.exists(worktree)).toBe(true); |
| 3192 | expect(yield* fs.readFileString(`${worktree}/notes.txt`)).toBe("untracked\n"); |
| 3193 | }), |
| 3194 | ), |
| 3195 | ); |
| 3196 | it.live("follows a branch switched while nothing watched the worktree", () => |
| 3197 | runCleanupTest( |
| 3198 | Effect.gen(function* () { |
| 3199 | const { service, worktree, command, threadBranches } = yield* cleanupFixture(); |
| 3200 | yield* command(worktree, ["switch", "-c", "renamed"]); |
| 3201 | expect((yield* service.runNow).entries[0]).toMatchObject({ |
| 3202 | outcome: "kept", |
| 3203 | reason: "Repository or branch changed", |
| 3204 | }); |
| 3205 | expect(threadBranches()).toEqual(["renamed"]); |
| 3206 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); |
| 3207 | }), |
| 3208 | ), |
| 3209 | ); |
| 3210 | it.live("does not measure a worktree kept for an open provider session", () => |
| 3211 | runCleanupTest( |
| 3212 | Effect.gen(function* () { |
| 3213 | const fs = yield* FileSystem.FileSystem; |
| 3214 | const walked: Array<string> = []; |
| 3215 | const fixture = yield* cleanupFixture().pipe( |
| 3216 | Effect.provideService(FileSystem.FileSystem, { |
| 3217 | ...fs, |
| 3218 | readDirectory: (directory, options) => { |
| 3219 | walked.push(directory); |
| 3220 | return fs.readDirectory(directory, options); |
| 3221 | }, |
| 3222 | }), |
| 3223 | ); |
| 3224 | const root = yield* fs.realPath(fixture.worktree); |
| 3225 | fixture.setOpenSessionCwd(fixture.worktree); |
| 3226 | const kept = yield* fixture.service.runNow; |
| 3227 | expect(kept.entries[0]).toMatchObject({ |
| 3228 | outcome: "kept", |
| 3229 | reason: "Provider session is still open", |
| 3230 | bytes: null, |
| 3231 | }); |
| 3232 | expect(walked.filter((directory) => directory.startsWith(root))).toEqual([]); |
| 3233 | fixture.setSessionLive(false); |
| 3234 | const removed = yield* fixture.service.runNow; |
| 3235 | expect(removed.entries[0]).toMatchObject({ outcome: "removed" }); |
| 3236 | expect(removed.entries[0]?.bytes).toBeGreaterThan(0); |
| 3237 | expect(walked).toContain(root); |
| 3238 | }), |
| 3239 | ), |
| 3240 | ); |
| 3241 | it.live("keeps a worktree for a live session in a missing folder under its stored alias", () => |
| 3242 | runCleanupTest( |
| 3243 | Effect.gen(function* () { |
| 3244 | const fixture = yield* cleanupFixture(); |
| 3245 | const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; |
| 3246 | yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); |
| 3247 | fixture.setThreads([shell({ branch: "feature", worktreePath: `${linkedParent}/feature` })]); |
| 3248 | fixture.setOpenSessionCwd(`${linkedParent}/feature/removed-folder`); |
| 3249 | const report = yield* fixture.service.runNow; |
| 3250 | expect(report.entries[0]).toMatchObject({ |
| 3251 | outcome: "kept", |
| 3252 | reason: "Provider session is still open", |
| 3253 | }); |
| 3254 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 3255 | }), |
| 3256 | ), |
| 3257 | ); |
| 3258 | it.live("compares the checked-out branch without a full status", () => |
| 3259 | runCleanupTest( |
| 3260 | Effect.gen(function* () { |
| 3261 | const { service, fs, repo, worktree, command, fullStatusCalls, threadBranches } = |
| 3262 | yield* cleanupFixture(); |
| 3263 | const changed = { outcome: "kept", reason: "Repository or branch changed" }; |
| 3264 | yield* command(worktree, ["switch", "--orphan", "other"]); |
| 3265 | expect((yield* service.runNow).entries[0]).toMatchObject(changed); |
| 3266 | yield* command(worktree, ["tag", "feature", "feature"]); |
| 3267 | // Newer Git refuses to create a tag named HEAD, but still reads one. |
| 3268 | yield* command(worktree, ["update-ref", "refs/tags/HEAD", "refs/heads/feature"]); |
| 3269 | yield* command(worktree, ["switch", "feature"]); |
| 3270 | expect((yield* service.runNow).entries[0]).toMatchObject(changed); |
| 3271 | expect(threadBranches()).toEqual(["feature"]); |
| 3272 | const index = (yield* command(worktree, ["rev-parse", "--git-path", "index"])).stdout; |
| 3273 | yield* fs.writeFileString(`${index.trim()}.lock`, ""); |
| 3274 | const locked = (yield* service.runNow).entries[0]; |
| 3275 | expect(locked).toMatchObject({ |
| 3276 | outcome: "failed", |
| 3277 | projectPath: repo, |
| 3278 | path: worktree, |
| 3279 | threadId: "thread-1", |
| 3280 | threadTitle: "Thread", |
| 3281 | }); |
| 3282 | expect(locked?.reason).toContain("Git index is locked"); |
| 3283 | expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("original\n"); |
| 3284 | yield* fs.remove(`${index.trim()}.lock`); |
| 3285 | const gitFile = yield* fs.readFileString(`${worktree}/.git`); |
| 3286 | yield* fs.writeFileString(`${worktree}/.git`, "gitdir: /missing-git-directory\n"); |
| 3287 | expect((yield* service.runNow).entries[0]).toMatchObject(changed); |
| 3288 | yield* fs.writeFileString(`${worktree}/.git`, gitFile); |
| 3289 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); |
| 3290 | expect(fullStatusCalls()).toBe(0); |
| 3291 | }), |
| 3292 | ), |
| 3293 | ); |
| 3294 | it.live("removes a clean detached worktree only when every commit is on a branch", () => |
| 3295 | runCleanupTest( |
| 3296 | Effect.gen(function* () { |
| 3297 | const { service, fs, worktree, command } = yield* cleanupFixture(); |
| 3298 | yield* command(worktree, ["checkout", "--detach"]); |
| 3299 | yield* fs.writeFileString(`${worktree}/tracked.txt`, "unpushed\n"); |
| 3300 | yield* command(worktree, ["commit", "-am", "unpushed"]); |
| 3301 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); |
| 3302 | yield* command(worktree, ["checkout", "--detach", "main"]); |
| 3303 | yield* command(worktree, ["-c", "sequence.editor=echo break >>", "rebase", "-i", "--root"]); |
| 3304 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); |
| 3305 | yield* command(worktree, ["rebase", "--abort"]); |
| 3306 | yield* command(worktree, ["checkout", "-b", "topic", "main"]); |
| 3307 | yield* command(worktree, ["commit", "--allow-empty", "-m", "topic"]); |
| 3308 | yield* command(worktree, ["checkout", "--detach", "main"]); |
| 3309 | yield* fs.writeFileString(`${worktree}/tracked.txt`, "autostashed\n"); |
| 3310 | yield* command(worktree, ["merge", "--autostash", "--no-ff", "--no-commit", "topic"]); |
| 3311 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); |
| 3312 | yield* command(worktree, ["merge", "--abort"]); |
| 3313 | expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("autostashed\n"); |
| 3314 | yield* command(worktree, ["checkout", "--", "tracked.txt"]); |
| 3315 | yield* command(worktree, ["bisect", "start"]); |
| 3316 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); |
| 3317 | yield* command(worktree, ["bisect", "reset"]); |
| 3318 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); |
| 3319 | }), |
| 3320 | ), |
| 3321 | ); |
| 3322 | it.live.each([ |
| 3323 | ["any-local-files", ".env", "kept"], |
| 3324 | ["uncommitted-changes", ".env", "removed"], |
| 3325 | ["tracked-changes", ".env", "removed"], |
| 3326 | ["any-local-files", "notes.txt", "kept"], |
| 3327 | ["uncommitted-changes", "notes.txt", "kept"], |
| 3328 | ["tracked-changes", "notes.txt", "removed"], |
| 3329 | ["any-local-files", "tracked.txt", "kept"], |
| 3330 | ["uncommitted-changes", "tracked.txt", "kept"], |
| 3331 | ["tracked-changes", "tracked.txt", "kept"], |
| 3332 | ] as const)("applies %j", ([policy, file, outcome]) => |
| 3333 | runCleanupTest( |
| 3334 | Effect.gen(function* () { |
| 3335 | const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); |
| 3336 | setPolicy(policy); |
| 3337 | expect(yield* service.latestReport).toBeNull(); |
| 3338 | yield* fs.writeFileString(`${worktree}/${file}`, "local data\n"); |
| 3339 | const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) => |
| 3340 | allocatedBytes(fs, `${worktree}/${name}`), |
| 3341 | ); |
| 3342 | const bytes = sizes.reduce((sum, size) => sum + size, 0); |
| 3343 | const report = yield* service.runNow; |
| 3344 | yield* service.drain; |
| 3345 | expect(report.trigger).toBe("manual"); |
| 3346 | expect(report.entries.filter((entry) => entry.kind === "worktree")).toMatchObject([ |
| 3347 | { |
| 3348 | outcome, |
| 3349 | path: worktree, |
| 3350 | threadId: "thread-1", |
| 3351 | threadTitle: "Thread", |
| 3352 | bytes: outcome === "removed" ? bytes : null, |
| 3353 | files: null, |
| 3354 | }, |
| 3355 | ]); |
| 3356 | expect(report.bytesFreed).toBe(outcome === "removed" ? bytes : 0); |
| 3357 | expect(yield* fs.exists(worktree)).toBe(outcome === "kept"); |
| 3358 | expect(yield* service.latestReport).toEqual(report); |
| 3359 | if (outcome === "kept") |
| 3360 | expect(report.entries[0]?.reason).toContain( |
| 3361 | file === ".env" ? "ignored files (.env)" : "uncommitted changes (1 file)", |
| 3362 | ); |
| 3363 | }), |
| 3364 | ), |
| 3365 | ); |
| 3366 | it.effect.each([ |
| 3367 | ["unchanged", "removed", "No commits beyond the project branch"], |
| 3368 | ["unmerged", "kept", "Has commits beyond the project branch"], |
| 3369 | ["detached", "kept", "Project branch is unavailable"], |
| 3370 | ["merged-only", "kept", "No remote is configured for merged-worktree cleanup"], |
| 3371 | ] as const)("cleans archived local-only worktrees: %s", ([state, outcome, reason]) => |
| 3372 | runCleanupTest( |
| 3373 | Effect.gen(function* () { |
| 3374 | yield* TestClock.setTime(NOW_MS); |
| 3375 | const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ |
| 3376 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3377 | worktreeUnchanged: state !== "merged-only", |
| 3378 | worktreeOnMerge: true, |
| 3379 | }); |
| 3380 | yield* command(repo, ["branch", "-m", "main", "trunk"]); |
| 3381 | setThreads([shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) })]); |
| 3382 | if (state === "unmerged") { |
| 3383 | yield* fs.writeFileString(`${worktree}/tracked.txt`, "unmerged work\n"); |
| 3384 | yield* command(worktree, ["commit", "-am", "unmerged work"]); |
| 3385 | } |
| 3386 | if (state === "detached") yield* command(repo, ["checkout", "--detach"]); |
| 3387 | |
| 3388 | const report = yield* service.runNow; |
| 3389 | expect(report.entries[0]).toMatchObject({ outcome, reason }); |
| 3390 | expect(yield* fs.exists(worktree)).toBe(outcome === "kept"); |
| 3391 | expect( |
| 3392 | (yield* command(repo, ["show-ref", "--verify", "refs/heads/feature"])).stdout, |
| 3393 | ).not.toBe(""); |
| 3394 | }), |
| 3395 | ), |
| 3396 | ); |
| 3397 | it.live("keeps an unsettled new thread's unchanged worktree after its first turn", () => |
| 3398 | runCleanupTest( |
| 3399 | Effect.gen(function* () { |
| 3400 | const { service, fs, worktree, setThreads } = yield* cleanupFixture({ |
| 3401 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3402 | worktreeSettledAfterDays: 11, |
| 3403 | worktreeOnMerge: true, |
| 3404 | worktreeUnchanged: true, |
| 3405 | }); |
| 3406 | const now = yield* DateTime.now; |
| 3407 | const minutesAgo = (minutes: number) => DateTime.subtract(now, { minutes }); |
| 3408 | const thread = shell({ |
| 3409 | branch: "feature", |
| 3410 | worktreePath: worktree, |
| 3411 | status: "completed", |
| 3412 | createdAt: minutesAgo(40), |
| 3413 | latestUserMessageAt: minutesAgo(40), |
| 3414 | latestRunRequestedAt: minutesAgo(40), |
| 3415 | latestRunStartedAt: minutesAgo(40), |
| 3416 | latestRunCompletedAt: minutesAgo(20), |
| 3417 | updatedAt: minutesAgo(20), |
| 3418 | }); |
| 3419 | setThreads([thread]); |
| 3420 | |
| 3421 | const report = yield* service.runNow; |
| 3422 | expect(report.entries[0]).toMatchObject({ outcome: "kept" }); |
| 3423 | expect(yield* fs.exists(worktree)).toBe(true); |
| 3424 | |
| 3425 | setThreads([{ ...thread, settledAt: minutesAgo(10), updatedAt: minutesAgo(10) }]); |
| 3426 | const settled = yield* service.runNow; |
| 3427 | expect(settled.entries[0]).toMatchObject({ |
| 3428 | outcome: "removed", |
| 3429 | reason: "No commits beyond the project branch", |
| 3430 | }); |
| 3431 | }), |
| 3432 | ), |
| 3433 | ); |
| 3434 | it.live( |
| 3435 | "discovers trunk without a remote HEAD or tracking ref and removes an integrated worktree", |
| 3436 | () => |
| 3437 | runCleanupTest( |
| 3438 | Effect.gen(function* () { |
| 3439 | const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ |
| 3440 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3441 | worktreeUnchanged: true, |
| 3442 | }); |
| 3443 | setThreads([ |
| 3444 | shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), |
| 3445 | ]); |
| 3446 | const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); |
| 3447 | yield* command(remote, ["init", "--bare", "-b", "trunk"]); |
| 3448 | yield* command(repo, ["remote", "add", "origin", remote]); |
| 3449 | yield* command(repo, ["push", "origin", "main:trunk"]); |
| 3450 | yield* command(repo, ["update-ref", "-d", "refs/remotes/origin/trunk"]); |
| 3451 | expect((yield* command(repo, ["for-each-ref", "refs/remotes/origin"])).stdout).toBe(""); |
| 3452 | |
| 3453 | const report = yield* service.runNow; |
| 3454 | expect(report.entries[0]).toMatchObject({ |
| 3455 | outcome: "removed", |
| 3456 | reason: "No commits beyond the default branch", |
| 3457 | }); |
| 3458 | expect(yield* fs.exists(worktree)).toBe(false); |
| 3459 | }), |
| 3460 | ), |
| 3461 | ); |
| 3462 | it.live( |
| 3463 | "keeps worktree commits present on nondefault main but absent from advertised trunk", |
| 3464 | () => |
| 3465 | runCleanupTest( |
| 3466 | Effect.gen(function* () { |
| 3467 | const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ |
| 3468 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3469 | worktreeUnchanged: true, |
| 3470 | }); |
| 3471 | setThreads([ |
| 3472 | shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), |
| 3473 | ]); |
| 3474 | const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); |
| 3475 | yield* command(remote, ["init", "--bare", "-b", "trunk"]); |
| 3476 | yield* command(repo, ["remote", "add", "origin", remote]); |
| 3477 | yield* command(repo, ["push", "origin", "main:trunk"]); |
| 3478 | yield* fs.writeFileString(`${worktree}/tracked.txt`, "unmerged work\n"); |
| 3479 | yield* command(worktree, ["commit", "-am", "unmerged work"]); |
| 3480 | yield* command(repo, ["push", "origin", "feature:main"]); |
| 3481 | expect( |
| 3482 | (yield* command(repo, ["symbolic-ref", "refs/remotes/origin/HEAD"]).pipe(Effect.exit)) |
| 3483 | ._tag, |
| 3484 | ).toBe("Failure"); |
| 3485 | |
| 3486 | const report = yield* service.runNow; |
| 3487 | expect(report.entries[0]).toMatchObject({ |
| 3488 | outcome: "kept", |
| 3489 | reason: "Has commits beyond the default branch", |
| 3490 | }); |
| 3491 | expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("unmerged work\n"); |
| 3492 | }), |
| 3493 | ), |
| 3494 | ); |
| 3495 | it.live("keeps the worktree when the remote default is unavailable even if main exists", () => |
| 3496 | runCleanupTest( |
| 3497 | Effect.gen(function* () { |
| 3498 | const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ |
| 3499 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3500 | worktreeUnchanged: true, |
| 3501 | }); |
| 3502 | setThreads([shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) })]); |
| 3503 | const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); |
| 3504 | yield* command(remote, ["init", "--bare", "-b", "trunk"]); |
| 3505 | yield* command(repo, ["remote", "add", "origin", remote]); |
| 3506 | // The remote HEAD names an unborn trunk; main exists but is not its default. |
| 3507 | yield* command(repo, ["push", "origin", "main"]); |
| 3508 | |
| 3509 | const report = yield* service.runNow; |
| 3510 | expect(report.entries[0]).toMatchObject({ |
| 3511 | outcome: "kept", |
| 3512 | reason: "Default branch is unavailable", |
| 3513 | }); |
| 3514 | expect(yield* fs.exists(worktree)).toBe(true); |
| 3515 | }), |
| 3516 | ), |
| 3517 | ); |
| 3518 | it.live("fetches a failing default branch once per sweep and names the broken local ref", () => |
| 3519 | runCleanupTest( |
| 3520 | Effect.gen(function* () { |
| 3521 | const { service, fs, repo, worktree, command, setThreads, setStoredWorktreePaths } = |
| 3522 | yield* cleanupFixture({ |
| 3523 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3524 | worktreeUnchanged: true, |
| 3525 | }); |
| 3526 | const second = `${worktree}-2`; |
| 3527 | yield* command(repo, ["worktree", "add", "-b", "feature-2", second]); |
| 3528 | setStoredWorktreePaths([worktree, second]); |
| 3529 | setThreads([ |
| 3530 | shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), |
| 3531 | shell({ |
| 3532 | id: ThreadId.make("thread-2"), |
| 3533 | branch: "feature-2", |
| 3534 | worktreePath: second, |
| 3535 | archivedAt: at(-DAY_MS), |
| 3536 | }), |
| 3537 | ]); |
| 3538 | const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); |
| 3539 | yield* command(remote, ["init", "--bare", "-b", "main"]); |
| 3540 | yield* command(repo, ["remote", "add", "origin", remote]); |
| 3541 | yield* command(repo, ["push", "origin", "main"]); |
| 3542 | yield* command(repo, ["remote", "set-head", "origin", "main"]); |
| 3543 | yield* command(repo, ["commit", "--allow-empty", "-m", "remote only"]); |
| 3544 | yield* command(repo, ["push", "origin", "main"]); |
| 3545 | yield* command(repo, ["reset", "--hard", "HEAD~1"]); |
| 3546 | yield* command(repo, ["update-ref", "refs/remotes/origin/main", "HEAD"]); |
| 3547 | const trackingRef = yield* fs.readFileString(`${repo}/.git/refs/remotes/origin/main`); |
| 3548 | yield* fs.writeFileString(`${repo}/.git/refs/remotes/origin/main 2`, trackingRef); |
| 3549 | const fetchLog = `${remote}/fetches.log`; |
| 3550 | const uploadPack = `${remote}/upload-pack.sh`; |
| 3551 | yield* fs.writeFileString( |
| 3552 | uploadPack, |
| 3553 | `#!/bin/sh\necho fetch >> '${fetchLog}'\nexec git-upload-pack "$@"\n`, |
| 3554 | ); |
| 3555 | yield* fs.chmod(uploadPack, 0o755); |
| 3556 | yield* command(repo, ["config", "remote.origin.uploadpack", uploadPack]); |
| 3557 | |
| 3558 | const report = yield* service.runNow; |
| 3559 | expect((yield* fs.readFileString(fetchLog)).trim().split("\n")).toHaveLength(1); |
| 3560 | expect(report.entries).toHaveLength(2); |
| 3561 | for (const entry of report.entries) { |
| 3562 | expect(entry.outcome).not.toBe("removed"); |
| 3563 | expect(entry.reason).toContain("broken local ref"); |
| 3564 | } |
| 3565 | expect(yield* fs.exists(worktree)).toBe(true); |
| 3566 | expect(yield* fs.exists(second)).toBe(true); |
| 3567 | }), |
| 3568 | ), |
| 3569 | ); |
| 3570 | it.live("preserves tracked edits written after the final status check", () => |
| 3571 | runCleanupTest( |
| 3572 | Effect.gen(function* () { |
| 3573 | const fixture = yield* cleanupFixture(); |
| 3574 | fixture.setPolicy("tracked-changes"); |
| 3575 | fixture.editBeforeRemoval(); |
| 3576 | yield* fixture.fs.writeFileString(`${fixture.worktree}/notes.txt`, "untracked\n"); |
| 3577 | const report = yield* fixture.service.runNow; |
| 3578 | expect(report.entries[0]).toMatchObject({ outcome: "failed", bytes: null, files: null }); |
| 3579 | expect(report.bytesFreed).toBe(0); |
| 3580 | expect(report.entries[0]?.reason).toContain("contains modified or untracked files"); |
| 3581 | expect(yield* fixture.fs.readFileString(`${fixture.worktree}/tracked.txt`)).toBe( |
| 3582 | "late edit\n", |
| 3583 | ); |
| 3584 | expect(yield* fixture.fs.exists(`${fixture.worktree}/notes.txt`)).toBe(false); |
| 3585 | }), |
| 3586 | ), |
| 3587 | ); |
| 3588 | it.live("caps entries while preserving totals and prioritizing removals", () => |
| 3589 | runCleanupTest( |
| 3590 | Effect.gen(function* () { |
| 3591 | const { service, fs, worktree, setThreads } = yield* cleanupFixture(); |
| 3592 | const threads = []; |
| 3593 | for (let i = 0; i < 205; i++) { |
| 3594 | const worktreePath = `${worktree}-${i}`; |
| 3595 | yield* fs.makeDirectory(worktreePath); |
| 3596 | threads.push( |
| 3597 | shell({ |
| 3598 | id: ThreadId.make(`thread-${i + 2}`), |
| 3599 | branch: "feature", |
| 3600 | worktreePath, |
| 3601 | status: "running", |
| 3602 | }), |
| 3603 | ); |
| 3604 | } |
| 3605 | threads.push(shell({ branch: "feature", worktreePath: worktree })); |
| 3606 | setThreads(threads); |
| 3607 | const report = yield* service.runNow; |
| 3608 | expect(report.entries).toHaveLength(200); |
| 3609 | expect(report.omittedCount).toBe(6); |
| 3610 | expect(report.counts).toEqual({ removed: 1, kept: 205, failed: 0 }); |
| 3611 | expect(report.entries[0]?.outcome).toBe("removed"); |
| 3612 | expect(report.entries[0]?.bytes).toBeGreaterThan(0); |
| 3613 | expect(report.bytesFreed).toBe(report.entries[0]?.bytes); |
| 3614 | }), |
| 3615 | ), |
| 3616 | ); |
| 3617 | it.live("keeps staged edits in tracked-only mode", () => |
| 3618 | runCleanupTest( |
| 3619 | Effect.gen(function* () { |
| 3620 | const { service, fs, worktree, setPolicy, command } = yield* cleanupFixture(); |
| 3621 | setPolicy("tracked-changes"); |
| 3622 | yield* fs.writeFileString(`${worktree}/tracked.txt`, "staged\n"); |
| 3623 | yield* command(worktree, ["add", "tracked.txt"]); |
| 3624 | expect((yield* service.runNow).entries[0]).toMatchObject({ |
| 3625 | outcome: "kept", |
| 3626 | reason: "Has uncommitted changes (1 file)", |
| 3627 | }); |
| 3628 | expect(yield* fs.exists(worktree)).toBe(true); |
| 3629 | }), |
| 3630 | ), |
| 3631 | ); |
| 3632 | it.live.each(["--assume-unchanged", "--skip-worktree"] as const)( |
| 3633 | "keeps tracked edits that git status hides (%s)", |
| 3634 | (flag) => |
| 3635 | runCleanupTest( |
| 3636 | Effect.gen(function* () { |
| 3637 | const { service, fs, worktree, command } = yield* cleanupFixture(); |
| 3638 | yield* command(worktree, ["update-index", flag, "tracked.txt"]); |
| 3639 | yield* fs.writeFileString(`${worktree}/tracked.txt`, "hidden edit\n"); |
| 3640 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); |
| 3641 | expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("hidden edit\n"); |
| 3642 | }), |
| 3643 | ), |
| 3644 | ); |
| 3645 | // macOS and Windows file systems reject names that are not valid UTF-8. |
| 3646 | it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( |
| 3647 | "keeps hidden edits to files whose names are not valid UTF-8", |
| 3648 | () => |
| 3649 | runCleanupTest( |
| 3650 | Effect.gen(function* () { |
| 3651 | const { service, fs, worktree, command } = yield* cleanupFixture(); |
| 3652 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 3653 | // Git unquotes C-quoted paths on stdin, which reaches a name a JS string cannot. |
| 3654 | const quoted = '"bad-\\377.txt"'; |
| 3655 | const stdin = (args: string[], input: string) => |
| 3656 | git.execute({ operation: "cleanup-test", cwd: worktree, args, stdin: input }); |
| 3657 | const blob = (content: string) => |
| 3658 | stdin(["hash-object", "-w", "--stdin"], content).pipe( |
| 3659 | Effect.map((result) => result.stdout.trim()), |
| 3660 | ); |
| 3661 | const original = yield* blob("original\n"); |
| 3662 | yield* stdin(["update-index", "--index-info"], `100644 ${original}\t${quoted}\n`); |
| 3663 | yield* stdin(["checkout-index", "--stdin"], `${quoted}\n`); |
| 3664 | yield* command(worktree, ["commit", "-m", "bad name"]); |
| 3665 | // The committed content moves on while the file on disk keeps the other version. |
| 3666 | const edited = yield* blob("edited\n"); |
| 3667 | yield* stdin(["update-index", "--index-info"], `100644 ${edited}\t${quoted}\n`); |
| 3668 | yield* command(worktree, ["commit", "-m", "edit"]); |
| 3669 | yield* stdin(["update-index", "--assume-unchanged", "--stdin"], `${quoted}\n`); |
| 3670 | expect((yield* command(worktree, ["status", "--porcelain"])).stdout).toBe(""); |
| 3671 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); |
| 3672 | expect((yield* fs.readDirectory(worktree)).some((name) => name.startsWith("bad-"))).toBe( |
| 3673 | true, |
| 3674 | ); |
| 3675 | }), |
| 3676 | ), |
| 3677 | ); |
| 3678 | it.live("removes worktrees whose flagged files are unchanged or outside a sparse checkout", () => |
| 3679 | runCleanupTest( |
| 3680 | Effect.gen(function* () { |
| 3681 | const { service, fs, worktree, command } = yield* cleanupFixture(); |
| 3682 | yield* command(worktree, ["update-index", "--skip-worktree", "tracked.txt"]); |
| 3683 | yield* fs.remove(`${worktree}/tracked.txt`); |
| 3684 | yield* command(worktree, ["update-index", "--assume-unchanged", ".gitignore"]); |
| 3685 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); |
| 3686 | }), |
| 3687 | ), |
| 3688 | ); |
| 3689 | it.live.each([ |
| 3690 | ["missing", "symlink"], |
| 3691 | ["tracked.txt", "symlink"], |
| 3692 | ["missing", "file"], |
| 3693 | ["tracked.txt", "file"], |
| 3694 | ] as const)("compares flagged tracked symlinks by target (%s as a %s)", ([target, kind]) => |
| 3695 | runCleanupTest( |
| 3696 | Effect.gen(function* () { |
| 3697 | const { service, fs, worktree, command } = yield* cleanupFixture(); |
| 3698 | yield* fs.symlink("tracked.txt", `${worktree}/link`); |
| 3699 | yield* command(worktree, ["add", "link"]); |
| 3700 | yield* command(worktree, ["commit", "-m", "link"]); |
| 3701 | yield* command(worktree, ["update-index", "--assume-unchanged", "link"]); |
| 3702 | yield* fs.remove(`${worktree}/link`); |
| 3703 | // Without core.symlinks, Git checks a link out as a regular file holding its target. |
| 3704 | if (kind === "file") { |
| 3705 | yield* command(worktree, ["config", "core.symlinks", "false"]); |
| 3706 | yield* fs.writeFileString(`${worktree}/link`, target); |
| 3707 | } else yield* fs.symlink(target, `${worktree}/link`); |
| 3708 | expect((yield* service.runNow).entries[0]).toMatchObject( |
| 3709 | target === "missing" |
| 3710 | ? { outcome: "kept", reason: expect.stringContaining("(link)") } |
| 3711 | : { outcome: "removed" }, |
| 3712 | ); |
| 3713 | }), |
| 3714 | ), |
| 3715 | ); |
| 3716 | it.live.each([ |
| 3717 | ["uncommitted-changes", "untracked", "Local changes exceed the inspection limit"], |
| 3718 | ["any-local-files", "ignored", "Ignored files exceed the inspection limit"], |
| 3719 | ] as const)( |
| 3720 | "keeps a worktree under %s when its %s file listing exceeds the inspection limit", |
| 3721 | ([policy, kind, reason]) => |
| 3722 | runCleanupTest( |
| 3723 | Effect.gen(function* () { |
| 3724 | const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); |
| 3725 | setPolicy(policy); |
| 3726 | const files = Array.from({ length: 3000 }, (_, i) => |
| 3727 | kind === "untracked" |
| 3728 | ? `${worktree}/many/untracked-file-with-a-long-name-${i}.txt` |
| 3729 | : `${worktree}/many/ignored-directory-with-a-long-name-${i}/.env`, |
| 3730 | ); |
| 3731 | yield* fs.makeDirectory(`${worktree}/many`); |
| 3732 | yield* Effect.forEach( |
| 3733 | files, |
| 3734 | (file) => |
| 3735 | Effect.gen(function* () { |
| 3736 | if (kind === "ignored") yield* fs.makeDirectory(file.slice(0, -"/.env".length)); |
| 3737 | yield* fs.writeFileString(file, "local\n"); |
| 3738 | }), |
| 3739 | { concurrency: 64, discard: true }, |
| 3740 | ); |
| 3741 | expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept", reason }); |
| 3742 | expect(yield* fs.exists(files[0]!)).toBe(true); |
| 3743 | }), |
| 3744 | ), |
| 3745 | ); |
| 3746 | it.live("serializes concurrent requests and returns each run's report", () => |
| 3747 | runCleanupTest( |
| 3748 | Effect.gen(function* () { |
| 3749 | const { service } = yield* cleanupFixture(); |
| 3750 | const reports = yield* Effect.all([service.runNow, service.runNow], { |
| 3751 | concurrency: "unbounded", |
| 3752 | }); |
| 3753 | yield* service.drain; |
| 3754 | expect( |
| 3755 | reports.flatMap((report) => report.entries).filter((entry) => entry.kind === "worktree"), |
| 3756 | ).toMatchObject([{ outcome: "removed" }]); |
| 3757 | expect(yield* service.latestReport).toEqual(reports[1]); |
| 3758 | }), |
| 3759 | ), |
| 3760 | ); |
| 3761 | it.live("aggregates expired artifacts and rotated logs while retaining current logs", () => |
| 3762 | runCleanupTest( |
| 3763 | Effect.gen(function* () { |
| 3764 | const { service, fs, config, enableFiles, disable } = yield* cleanupFixture(); |
| 3765 | disable(); |
| 3766 | enableFiles(); |
| 3767 | yield* fs.makeDirectory(config.browserArtifactsDir, { recursive: true }); |
| 3768 | yield* fs.makeDirectory(config.logsDir, { recursive: true }); |
| 3769 | for (const name of ["one.png", "two.webm"]) { |
| 3770 | const file = config.browserArtifactsDir + "/" + name; |
| 3771 | yield* fs.writeFileString(file, "capture"); |
| 3772 | yield* fs.utimes(file, 1, 1); |
| 3773 | } |
| 3774 | for (const name of ["server.log.1", "server.log.2", "server.log"]) { |
| 3775 | const file = config.logsDir + "/" + name; |
| 3776 | yield* fs.writeFileString(file, "log"); |
| 3777 | yield* fs.utimes(file, 1, 1); |
| 3778 | } |
| 3779 | const report = yield* service.runNow; |
| 3780 | expect(report.entries.filter((entry) => entry.kind !== "worktree")).toMatchObject([ |
| 3781 | { |
| 3782 | kind: "browser-artifacts", |
| 3783 | outcome: "removed", |
| 3784 | reason: "Removed 2 browser artifacts", |
| 3785 | bytes: 14, |
| 3786 | files: 2, |
| 3787 | }, |
| 3788 | { |
| 3789 | kind: "logs", |
| 3790 | outcome: "removed", |
| 3791 | reason: "Removed 2 rotated logs", |
| 3792 | bytes: 6, |
| 3793 | files: 2, |
| 3794 | }, |
| 3795 | ]); |
| 3796 | expect(report.bytesFreed).toBe(20); |
| 3797 | expect(yield* fs.readDirectory(config.browserArtifactsDir)).toEqual([]); |
| 3798 | expect(yield* fs.exists(config.logsDir + "/server.log")).toBe(true); |
| 3799 | expect(yield* fs.exists(config.logsDir + "/server.log.1")).toBe(false); |
| 3800 | expect(yield* fs.exists(config.logsDir + "/server.log.2")).toBe(false); |
| 3801 | }), |
| 3802 | ), |
| 3803 | ); |
| 3804 | it.live.each([ |
| 3805 | { linked: "home", outcome: "removed", reason: "Removed 1 rotated logs" }, |
| 3806 | { linked: "logs folder", outcome: "kept", reason: "No expired files" }, |
| 3807 | ] as const)( |
| 3808 | "rotated logs behind a symlinked $linked are $outcome", |
| 3809 | ({ linked, outcome, reason }) => |
| 3810 | runCleanupTest( |
| 3811 | Effect.gen(function* () { |
| 3812 | const fs = yield* FileSystem.FileSystem; |
| 3813 | const config = yield* ServerConfig.ServerConfig; |
| 3814 | const disk = yield* fs.realPath(yield* fs.makeTempDirectoryScoped()); |
| 3815 | yield* fs.makeDirectory(`${disk}/real/logs`, { recursive: true }); |
| 3816 | if (linked === "home") { |
| 3817 | yield* fs.symlink(`${disk}/real`, `${disk}/home`); |
| 3818 | } else { |
| 3819 | yield* fs.makeDirectory(`${disk}/home`); |
| 3820 | yield* fs.symlink(`${disk}/real/logs`, `${disk}/home/logs`); |
| 3821 | } |
| 3822 | yield* fs.writeFileString(`${disk}/real/logs/server.log.1`, "log"); |
| 3823 | yield* fs.utimes(`${disk}/real/logs/server.log.1`, 1, 1); |
| 3824 | const { service, enableFiles, disable } = yield* cleanupFixture().pipe( |
| 3825 | Effect.provideService(ServerConfig.ServerConfig, { |
| 3826 | ...config, |
| 3827 | logsDir: `${disk}/home/logs`, |
| 3828 | }), |
| 3829 | ); |
| 3830 | disable(); |
| 3831 | enableFiles(); |
| 3832 | const report = yield* service.runNow; |
| 3833 | expect(report.entries.filter((entry) => entry.kind === "logs")).toMatchObject([ |
| 3834 | { outcome, reason }, |
| 3835 | ]); |
| 3836 | expect(yield* fs.exists(`${disk}/real/logs/server.log.1`)).toBe(outcome === "kept"); |
| 3837 | }), |
| 3838 | ), |
| 3839 | ); |
| 3840 | it.live("reports git failures without aborting the remaining categories", () => |
| 3841 | runCleanupTest( |
| 3842 | Effect.gen(function* () { |
| 3843 | const { service, worktree, command, enableFiles } = yield* cleanupFixture(); |
| 3844 | enableFiles(); |
| 3845 | yield* command(worktree, ["worktree", "lock", worktree]); |
| 3846 | const report = yield* service.runNow; |
| 3847 | expect(report.entries[0]).toMatchObject({ outcome: "failed" }); |
| 3848 | expect(report.entries[0]?.reason).toContain("git worktree remove: fatal:"); |
| 3849 | expect(report.entries.map((entry) => entry.kind)).toEqual([ |
| 3850 | "worktree", |
| 3851 | "browser-artifacts", |
| 3852 | "logs", |
| 3853 | ]); |
| 3854 | }), |
| 3855 | ), |
| 3856 | ); |
| 3857 | }); |
| 3858 | |
| 3859 | describe("settled worktree rechecks", () => { |
| 3860 | it.effect.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)( |
| 3861 | "keeps a usage-limited checkout when %s is enabled during measurement", |
| 3862 | (preference) => |
| 3863 | runCleanupTest( |
| 3864 | Effect.gen(function* () { |
| 3865 | yield* TestClock.setTime(NOW_MS); |
| 3866 | const fixture = yield* pausedMeasurementFixture(); |
| 3867 | fixture.setSettings({ autoResumeLimitedThreads: false, snoozeLimitedThreads: false }); |
| 3868 | fixture.setThreads([ |
| 3869 | shell({ |
| 3870 | branch: "feature", |
| 3871 | worktreePath: fixture.worktree, |
| 3872 | status: "failed", |
| 3873 | latestRunId: RunId.make("limited-run"), |
| 3874 | lastErrorClass: "usage_limit", |
| 3875 | usageLimitResetAt: DateTime.formatIso(at(DAY_MS)), |
| 3876 | }), |
| 3877 | ]); |
| 3878 | const run = yield* fixture.service.runNow.pipe(Effect.forkChild); |
| 3879 | yield* Deferred.await(fixture.measuring); |
| 3880 | fixture.setSettings({ [preference]: true }); |
| 3881 | yield* Deferred.succeed(fixture.resume, undefined); |
| 3882 | const report = yield* Fiber.join(run); |
| 3883 | expect(report.entries[0]).toMatchObject({ |
| 3884 | outcome: "kept", |
| 3885 | reason: "Settings changed since check", |
| 3886 | }); |
| 3887 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 3888 | }), |
| 3889 | ), |
| 3890 | ); |
| 3891 | it.effect.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( |
| 3892 | "keeps a checkout changed during measurement (%j)", |
| 3893 | (change) => |
| 3894 | runCleanupTest( |
| 3895 | Effect.gen(function* () { |
| 3896 | yield* TestClock.setTime(NOW_MS); |
| 3897 | const fixture = yield* pausedMeasurementFixture(); |
| 3898 | const thread = shell({ |
| 3899 | branch: "feature", |
| 3900 | worktreePath: fixture.worktree, |
| 3901 | settledAt: at(0), |
| 3902 | }); |
| 3903 | fixture.setSettings({ |
| 3904 | storageCleanup: { |
| 3905 | ...DEFAULT_SERVER_SETTINGS.storageCleanup, |
| 3906 | worktreeSettledAfterDays: 0, |
| 3907 | }, |
| 3908 | }); |
| 3909 | fixture.setThreads([thread]); |
| 3910 | const run = yield* fixture.service.runNow.pipe(Effect.forkChild); |
| 3911 | yield* Deferred.await(fixture.measuring); |
| 3912 | fixture.setThreads([{ ...thread, ...change }]); |
| 3913 | yield* Deferred.succeed(fixture.resume, undefined); |
| 3914 | const report = yield* Fiber.join(run); |
| 3915 | expect(report.entries[0]?.reason).toBe( |
| 3916 | "Thread activity or shared worktree changed since check", |
| 3917 | ); |
| 3918 | expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); |
| 3919 | }), |
| 3920 | ), |
| 3921 | ); |
| 3922 | }); |
| 3923 | |
| 3924 | it.effect("keeps saved usage data when removing a settled checkout", () => |
| 3925 | runCleanupTest( |
| 3926 | Effect.gen(function* () { |
| 3927 | yield* TestClock.setTime(NOW_MS); |
| 3928 | const fixture = yield* cleanupFixture(); |
| 3929 | fixture.setSettings({ |
| 3930 | storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0 }, |
| 3931 | }); |
| 3932 | fixture.setThreads([ |
| 3933 | shell({ branch: "feature", worktreePath: fixture.worktree, settledAt: at(0) }), |
| 3934 | ]); |
| 3935 | yield* fixture.fs.makeDirectory(fixture.config.stateDir, { recursive: true }); |
| 3936 | const cachePath = `${fixture.config.stateDir}/${SCAN_CACHE_FILE_NAME}`; |
| 3937 | const savedUsage = JSON.stringify({ tokens: 12345, cost: 1.25 }); |
| 3938 | yield* fixture.fs.writeFileString(cachePath, savedUsage); |
| 3939 | expect((yield* fixture.service.runNow).counts.removed).toBe(1); |
| 3940 | expect(yield* fixture.fs.readFileString(cachePath)).toBe(savedUsage); |
| 3941 | }), |
| 3942 | ), |
| 3943 | ); |