Open History to see the last commit
1import {
2 GitCommandError,
3 OrchestrationV2AppThreadJson,
4 OrchestrationV2ProviderSessionJson,
5} from "@t3tools/contracts";
6import * as Schema from "effect/Schema";
7import * as SqlClient from "effect/sql/SqlClient";
8import type {
9 OrchestrationV2ThreadShell,
10 ProjectId,
11 ServerSettings,
12 ServerSettingsError,
13 TerminalSummary,
14 WorktreeCleanupRules,
15 StorageCleanupReport,
16 StorageCleanupReportEntry,
17} from "@t3tools/contracts";
18import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
19import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
20import * as Context from "effect/Context";
21import * as Deferred from "effect/Deferred";
22import * as Layer from "effect/Layer";
23import * as Clock from "effect/Clock";
24import * as DateTime from "effect/DateTime";
25import * as Effect from "effect/Effect";
26import * as Equal from "effect/Equal";
27import * as FileSystem from "effect/FileSystem";
28import * as Option from "effect/Option";
29import * as Path from "effect/Path";
30import * as Ref from "effect/Ref";
31import type { PlatformError } from "effect/PlatformError";
32import * as Schedule from "effect/Schedule";
33import * as Stream from "effect/Stream";
34import * as SubscriptionRef from "effect/SubscriptionRef";
35
36import * as ServerConfig from "./config.ts";
37import * as GitManager from "./git/GitManager.ts";
38import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
39import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
40import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
41import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
42import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts";
43import { forkParked } from "./serverActivation.ts";
44import * as Settings from "./serverSettings.ts";
45import * as TerminalManager from "./terminal/Manager.ts";
46import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";
47import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
48import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
49import * as HostProcess from "@t3tools/shared/HostProcess";
50import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
51
52const decodeCleanupThread = Schema.decodeUnknownEffect(
53 Schema.fromJsonString(OrchestrationV2AppThreadJson),
54);
55const decodeCleanupSession = Schema.decodeUnknownEffect(
56 Schema.fromJsonString(OrchestrationV2ProviderSessionJson),
57);
58
59const DAY_MS = 86_400_000;
60// After a settle, the project's settle script needs time to open its
61// terminal, which then protects the worktree.
62const SETTLE_SCRIPT_GRACE_MS = 60_000;
63
64const sentence = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
65const REPORT_ENTRY_LIMIT = 200;
66const isGitCommandError = Schema.is(GitCommandError);
67
68function cleanupFailureReason(error: { readonly message: string }) {
69 return isGitCommandError(error)
70 ? `${error.command}: ${error.detail.split(/\r?\n/)[0]}${error.reason ? ` (${error.reason})` : ""}`
71 : (error.message.split(/\r?\n/)[0] ?? error.message);
72}
73
74const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) =>
75 rules.worktreeAfterDays !== null ||
76 rules.worktreeSettledAfterDays !== null ||
77 rules.worktreeOnMerge ||
78 rules.worktreeOnDelete ||
79 rules.worktreeUnchanged;
80
81function anyWorktreePolicy(
82 settings: ServerSettings,
83 predicate: (rules: WorktreeCleanupRules) => boolean,
84): boolean {
85 return (
86 predicate(resolveWorktreeCleanup(settings, null)) ||
87 Object.keys(settings.projectSettingsOverrides).some((projectId) =>
88 predicate(resolveWorktreeCleanup(settings, projectId as ProjectId)),
89 )
90 );
91}
92
93function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings): boolean {
94 return [
95 ...new Set([
96 ...Object.keys(left.projectSettingsOverrides),
97 ...Object.keys(right.projectSettingsOverrides),
98 ]),
99 ].every((projectId) =>
100 Equal.equals(
101 left.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
102 right.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
103 ),
104 );
105}
106
107/** Live sessions keep their cwd even when no turn is currently running. */
108export function storageCleanupThreadIdle(thread: OrchestrationV2ThreadShell, now: number): boolean {
109 return (
110 thread.branch !== null &&
111 thread.worktreePath !== null &&
112 thread.activeRunId === null &&
113 (thread.status === "idle" ||
114 thread.status === "completed" ||
115 thread.status === "interrupted" ||
116 thread.status === "failed" ||
117 thread.status === "cancelled" ||
118 thread.status === "rolled_back") &&
119 (thread.pendingBackgroundTasks?.length ?? 0) === 0 &&
120 thread.pendingRuntimeRequest === null &&
121 !threadHasQueuedTurnStart(thread, now)
122 );
123}
124
125/** PR metadata refreshes must not reset the inactivity clock. */
126export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): number {
127 return Math.max(
128 ...[
129 thread.createdAt,
130 thread.latestUserMessageAt,
131 thread.latestRunRequestedAt,
132 thread.latestRunStartedAt,
133 thread.latestRunCompletedAt,
134 ].flatMap((value) => (value == null ? [] : [DateTime.toEpochMillis(value)])),
135 );
136}
137
138/**
139 * Whether the host's pull request proves this worktree's head was merged. A
140 * squash or rebase merge leaves the head outside the default branch, so the
141 * merged pull request then has to name this exact commit.
142 */
143export function storageCleanupPullRequestMerged(
144 pullRequest: Pick<
145 GitManager.GitBranchPullRequest,
146 "state" | "headRef" | "baseRef" | "headSha"
147 > | null,
148 worktree: {
149 readonly branch: string;
150 readonly defaultBranch: string;
151 readonly headSha: string;
152 readonly integrated: boolean;
153 },
154): boolean {
155 return (
156 pullRequest?.state === "merged" &&
157 (worktree.integrated ||
158 (pullRequest.headRef === worktree.branch &&
159 pullRequest.baseRef === worktree.defaultBranch &&
160 pullRequest.headSha === worktree.headSha))
161 );
162}
163
164export class StorageCleanup extends Context.Service<
165 StorageCleanup,
166 {
167 readonly runNow: Effect.Effect<StorageCleanupReport, ServerSettingsError>;
168 readonly latestReport: Effect.Effect<StorageCleanupReport | null>;
169 readonly reports: Stream.Stream<StorageCleanupReport | null>;
170 readonly drain: Effect.Effect<void>;
171 }
172>()("t3/storageCleanup") {}
173
174const make = Effect.gen(function* () {
175 const config = yield* ServerConfig.ServerConfig;
176 const settingsService = yield* Settings.ServerSettingsService;
177 const projectStore = yield* ProjectStore.ProjectStoreV2;
178 const engine = yield* Orchestrator.OrchestratorV2;
179 const projections = yield* ProjectionStore.ProjectionStoreV2;
180 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
181 const sql = yield* SqlClient.SqlClient;
182 const git = yield* GitVcsDriver.GitVcsDriver;
183 const gitManager = yield* GitManager.GitManager;
184 const terminals = yield* TerminalManager.TerminalManager;
185 const fs = yield* FileSystem.FileSystem;
186 const path = yield* Path.Path;
187 const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
188 const noteTerminal = (terminal: TerminalSummary) => {
189 const threadTerminals =
190 liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
191 threadTerminals.set(terminal.terminalId, terminal);
192 liveTerminals.set(terminal.threadId, threadTerminals);
193 };
194
195 const inside = (root: string, target: string) => {
196 const relative = path.relative(root, target);
197 return (
198 relative !== "" &&
199 relative !== ".." &&
200 !relative.startsWith(`..${path.sep}`) &&
201 !path.isAbsolute(relative)
202 );
203 };
204 const hasTerminal = (worktreePath: string) =>
205 [...liveTerminals.values()]
206 .flatMap((entries) => [...entries.values()])
207 .some((terminal) => {
208 if (terminal.status !== "starting" && terminal.status !== "running") return false;
209 const cwd = path.resolve(terminal.cwd);
210 return (
211 (terminal.worktreePath !== null &&
212 path.resolve(terminal.worktreePath) === worktreePath) ||
213 cwd === worktreePath ||
214 inside(worktreePath, cwd)
215 );
216 });
217
218 const measureWorktree = (worktreePath: string) =>
219 Effect.gen(function* () {
220 const root = yield* fs.realPath(worktreePath);
221 const pending = [root];
222 let entries = 1;
223 let bytes = 0;
224 while (pending.length > 0) {
225 const target = pending.pop()!;
226 // Effect's stat follows links. Probe with readLink first to get lstat
227 // semantics, including skipping dangling links and directory links.
228 const isLink = yield* fs.readLink(target).pipe(
229 Effect.as(true),
230 Effect.catchIf(
231 (error) =>
232 error.cause instanceof Error &&
233 "code" in error.cause &&
234 error.cause.code === "EINVAL",
235 () => Effect.succeed(false),
236 ),
237 );
238 if (isLink) continue;
239 if ((yield* fs.realPath(target)) !== target) return null;
240 const stat = yield* fs.stat(target);
241 if (stat.type === "File") bytes += Number(stat.size);
242 else if (stat.type === "Directory") {
243 const names = yield* fs.readDirectory(target);
244 entries += names.length;
245 if (entries > 2_000_000) return null;
246 for (const name of names) {
247 const child = path.join(target, name);
248 if (!inside(root, child)) return null;
249 pending.push(child);
250 }
251 }
252 }
253 return bytes;
254 }).pipe(
255 Effect.timeout("30 seconds"),
256 Effect.orElseSucceed(() => null),
257 );
258
259 // Active threads only: archived threads are not candidates and do not count
260 // as sharing a worktree. The recheck's getThreadWorktreePaths reads the same set.
261 // The snapshot takes seconds on large databases, so it runs on the reader
262 // worker instead of the event loop.
263 const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {
264 const { threads } = yield* projections
265 .getShellSnapshot({ location: "active" })
266 .pipe(NodeSqliteClient.readOnly);
267 const projects = yield* projectStore.listShells();
268 return { projects, threads };
269 });
270
271 // Local threads under another project need not have a worktreePath of their own.
272 const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* (
273 worktreePath: string,
274 projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
275 ) {
276 for (const project of projects) {
277 const projectPath = path.resolve(project.workspaceRoot);
278 if (projectPath === worktreePath || inside(worktreePath, projectPath)) return true;
279 const realPath = yield* fs
280 .realPath(projectPath)
281 .pipe(Effect.orElseSucceed(() => projectPath));
282 if (realPath === worktreePath || inside(worktreePath, realPath)) return true;
283 }
284 return false;
285 });
286
287 // Whether cwd stopped being a checkout of this branch. Two small Git reads,
288 // since every worktree in a sweep is asked; statusDetailsLocal also diffs and
289 // counts.
290 const branchChanged = Effect.fn("StorageCleanup.branchChanged")(function* (
291 cwd: string,
292 branch: string | null,
293 ) {
294 const failure = (detail: string) =>
295 new GitCommandError({
296 operation: "StorageCleanup.branchChanged",
297 command: "git",
298 cwd,
299 detail,
300 });
301 // Null when cwd is not a repository, or is gone. Git's own messages are
302 // matched, so they must not be translated.
303 const read = Effect.fnUntraced(function* (args: string[], allowedExitCode?: number) {
304 const result = yield* git
305 .execute({
306 operation: "StorageCleanup.branchChanged",
307 cwd,
308 args,
309 env: { LC_ALL: "C" },
310 allowNonZeroExit: true,
311 })
312 .pipe(
313 Effect.catch((error) =>
314 Effect.flatMap(fs.exists(cwd), (exists) =>
315 exists ? Effect.fail(error) : Effect.succeed(null),
316 ),
317 ),
318 );
319 if (result === null) return null;
320 if (result.exitCode === 0 || result.exitCode === allowedExitCode) return result;
321 if (result.stderr.toLowerCase().includes("not a git repository")) return null;
322 return yield* failure(
323 result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
324 );
325 });
326 const index = yield* read(["rev-parse", "--git-path", "index"]);
327 if (index === null) return true;
328 // Another Git process is writing to this checkout.
329 if (yield* fs.exists(`${path.resolve(cwd, index.stdout.trim())}.lock`))
330 return yield* failure(
331 "Git index is locked. Status will resume when the index lock is removed.",
332 );
333 // Exits 1 for a detached HEAD. Reads the full ref name, which is never
334 // shortened to "heads/<branch>" when a tag shares the branch name.
335 const head = yield* read(["symbolic-ref", "--quiet", "HEAD"], 1);
336 if (head === null) return true;
337 const ref = head.exitCode === 0 ? head.stdout.trim() : "";
338 const name = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length).trim() : null;
339 // Status output writes a detached HEAD as "(detached)", so a branch named
340 // with a leading "(" has always been read as one.
341 return (name?.startsWith("(") ? null : name) !== branch;
342 });
343
344 const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* (
345 cwd: string,
346 rules: WorktreeCleanupRules,
347 ) {
348 const status = yield* git.execute({
349 operation: "StorageCleanup.localChanges",
350 cwd,
351 args: [
352 "status",
353 "--porcelain=v1",
354 "-z",
355 "--ignore-submodules=none",
356 rules.worktreeKeepWhen === "tracked-changes"
357 ? "--untracked-files=no"
358 : "--untracked-files=all",
359 ],
360 maxOutputBytes: 64 * 1024,
361 });
362 if (status.stdoutTruncated) return "local changes exceed the inspection limit";
363 const records = status.stdout.split("\0").filter(Boolean);
364 let count = 0;
365 for (let i = 0; i < records.length; i++) {
366 count++;
367 if (/^[RC]|^.[RC]/.test(records[i]!)) i++;
368 }
369 if (count > 0) return `has uncommitted changes (${count} ${count === 1 ? "file" : "files"})`;
370 if (rules.worktreeKeepWhen !== "any-local-files") return null;
371 const ignored = yield* git.execute({
372 operation: "StorageCleanup.ignoredFiles",
373 cwd,
374 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
375 maxOutputBytes: 64 * 1024,
376 });
377 if (ignored.stdoutTruncated) return "ignored files exceed the inspection limit";
378 const file = ignored.stdout
379 .split("\0")
380 .find((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry));
381 return file === undefined ? null : `has ignored files (${file})`;
382 });
383
384 const cleanupGit = Effect.fn("StorageCleanup.cleanupGit")(function* (
385 cwd: string,
386 args: string[],
387 command: string,
388 ) {
389 const result = yield* git.execute({
390 operation: "StorageCleanup.cleanupGit",
391 cwd,
392 args,
393 allowNonZeroExit: true,
394 timeoutMs: 300_000,
395 });
396 if (result.exitCode !== 0)
397 return yield* Effect.fail(
398 new GitCommandError({
399 operation: "StorageCleanup.cleanupGit",
400 command,
401 cwd,
402 detail: result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
403 }),
404 );
405 });
406
407 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
408 serverSettings: ServerSettings,
409 now: number,
410 entries: StorageCleanupReportEntry[],
411 ) {
412 const roots: Array<string> = [];
413 for (const directory of managedWorktreesDirectories(
414 serverSettings,
415 config.worktreesDir,
416 path,
417 yield* HostProcess.HomeDirectory,
418 )) {
419 // An unmounted drive only skips its own worktrees.
420 const root = yield* fs.exists(directory).pipe(
421 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
422 Effect.orElseSucceed(() => null),
423 );
424 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
425 }
426 const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
427 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
428 FROM orchestration_v2_projection_threads t
429 JOIN projection_projects p ON p.project_id = t.project_id
430 WHERE t.deleted_at IS NOT NULL
431 `;
432 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
433 decodeCleanupThread(row.payload_json).pipe(
434 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
435 ),
436 )).filter((thread) => thread.worktreePath !== null && thread.branch !== null);
437 const snapshot = yield* readThreads();
438 const refreshedDefaultRefs = new Map<string, Set<string>>();
439 const groups = Map.groupBy(
440 snapshot.threads.filter((thread) => thread.worktreePath !== null),
441 (thread) => path.resolve(thread.worktreePath!),
442 );
443 const candidates = [
444 ...[...groups.values()].map((group) => group[0]!),
445 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
446 ];
447 for (const thread of candidates) {
448 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
449 if (!worktreeCleanupEnabled(settings)) continue;
450 const worktreePath = path.resolve(thread.worktreePath!);
451 const deleted = "workspaceRoot" in thread;
452 const project = deleted
453 ? { workspaceRoot: thread.workspaceRoot }
454 : snapshot.projects.find((entry) => entry.id === thread.projectId);
455 const entry: StorageCleanupReportEntry = {
456 kind: "worktree",
457 outcome: "kept",
458 reason: "",
459 path: worktreePath,
460 threadId: thread.id,
461 threadTitle: thread.title,
462 bytes: null,
463 files: null,
464 };
465 const keep = (reason: string) => entries.push({ ...entry, reason: sentence(reason) });
466 yield* Effect.gen(function* () {
467 if (!(yield* fs.exists(worktreePath))) return;
468 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
469 const shared = groups.get(worktreePath)?.length ?? 0;
470 if (shared > 1) return keep(`shared by ${shared} threads`);
471 if (project === undefined) return keep("project is unavailable");
472 if (!deleted && !storageCleanupThreadIdle(thread, now))
473 return keep("thread is running or has pending work");
474 if (hasTerminal(worktreePath)) return keep("open terminal");
475 // Roots are canonical, so compare canonical paths. A symlinked parent
476 // (a linked drive) is fine; a symlinked worktree directory is not.
477 const realPath = yield* fs.realPath(worktreePath);
478 const realParent = yield* fs.realPath(path.dirname(worktreePath));
479 if (realPath !== path.join(realParent, path.basename(worktreePath)))
480 return keep("worktree is a symbolic link");
481 if (!roots.some((root) => inside(root, realPath)))
482 return keep("outside the managed worktree folder");
483 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
484 return keep("contains a project checkout");
485 // A linked worktree has a .git file. Never remove a main checkout.
486 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
487 return keep("not a linked worktree");
488 if (yield* branchChanged(worktreePath, thread.branch))
489 return keep("repository or branch changed");
490 const changes = yield* localChangesReason(worktreePath, settings);
491 if (changes !== null) return keep(changes);
492 // The project's settle script starts in the worktree right after a
493 // settle. Settling stamps updatedAt now, even when automatic
494 // settlement backdates settledAt to the thread's last activity.
495 if (
496 !deleted &&
497 thread.settledAt !== null &&
498 now - DateTime.toEpochMillis(thread.updatedAt) < SETTLE_SCRIPT_GRACE_MS
499 )
500 return keep("settled moments ago");
501 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
502 const old =
503 !deleted &&
504 settings.worktreeAfterDays !== null &&
505 storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
506 const settledFor =
507 deleted || thread.settledAt === null
508 ? null
509 : now - DateTime.toEpochMillis(thread.settledAt);
510 const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
511 const settled =
512 settledFor !== null &&
513 settings.worktreeSettledAfterDays !== null &&
514 settledFor >= settings.worktreeSettledAfterDays * DAY_MS;
515 let eligible = deleted || old || settled;
516 let removalReason = deleted
517 ? "thread was deleted"
518 : old
519 ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days`
520 : `settled for ${settledDays} days`;
521 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
522 const repositoryCwd = path.resolve(project.workspaceRoot);
523 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
524 const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
525 if (branch === null) return keep("default branch is unavailable");
526 const defaultRef = `refs/remotes/${remote}/${branch}`;
527 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
528 if (!refreshed.has(defaultRef)) {
529 yield* git.fetchRemoteTrackingBranch({
530 cwd: repositoryCwd,
531 remoteName: remote,
532 remoteBranch: branch,
533 });
534 refreshed.add(defaultRef);
535 refreshedDefaultRefs.set(repositoryCwd, refreshed);
536 }
537 const base = yield* git.resolveCommit({
538 cwd: worktreePath,
539 revision: defaultRef,
540 });
541 const ancestor = yield* git.execute({
542 operation: "StorageCleanup.integratedBranch",
543 cwd: worktreePath,
544 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
545 allowNonZeroExit: true,
546 });
547 const integrated = ancestor.exitCode === 0;
548 eligible = integrated && settings.worktreeUnchanged;
549 if (eligible) removalReason = "no commits beyond the default branch";
550 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
551 const pullRequest = yield* gitManager.branchPullRequest(
552 { cwd: worktreePath, branch: thread.branch },
553 { refresh: true },
554 );
555 eligible = storageCleanupPullRequestMerged(pullRequest, {
556 branch: thread.branch,
557 defaultBranch: branch,
558 headSha: head.commitSha,
559 integrated,
560 });
561 if (eligible) removalReason = "pull request was merged";
562 }
563 }
564 if (!eligible)
565 return keep(
566 !deleted && settings.worktreeAfterDays !== null
567 ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} of ${settings.worktreeAfterDays} days`
568 : settings.worktreeSettledAfterDays !== null
569 ? settledFor === null
570 ? "not settled"
571 : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days`
572 : settings.worktreeOnMerge
573 ? "not merged"
574 : "has commits beyond the default branch",
575 );
576 // Threads, queued deletion work and provider sessions as they are now, so a
577 // queued turn, resumed session or new thread sharing this path cancels
578 // the removal. Read only this path and this thread: a full snapshot per
579 // worktree takes seconds on large databases.
580 const blockedSinceCheck = Effect.fnUntraced(function* () {
581 const latestProjects = yield* projectStore.listShells();
582 if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects]))
583 return "contains a project checkout";
584 const latest = (yield* projections.getThreadWorktreePaths()).filter(
585 (entry) => path.resolve(entry.worktreePath) === worktreePath,
586 );
587 if (hasTerminal(worktreePath)) return "open terminal";
588 if (deleted) {
589 if (
590 latest.length > 0 ||
591 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
592 .worktreeOnDelete
593 )
594 return "thread or cleanup settings changed since check";
595 // V2 deletion queues durable cleanup. Do not remove its checkout until
596 // every effect has finished successfully or was explicitly cancelled.
597 const pendingCleanup = yield* sql`
598 SELECT 1 FROM orchestration_v2_effect_outbox
599 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
600 `;
601 if (pendingCleanup.length > 0) return "thread deletion is still pending";
602 } else {
603 const latestShell =
604 latest.length === 1 && latest[0]!.threadId === thread.id
605 ? yield* projections.getThreadShell(thread.id)
606 : null;
607 if (
608 latestShell === null ||
609 !storageCleanupThreadIdle(latestShell, now) ||
610 storageCleanupActivityAt(latestShell) !== storageCleanupActivityAt(thread) ||
611 !Equal.equals(latestShell.settledAt, thread.settledAt)
612 )
613 return "thread activity or shared worktree changed since check";
614 }
615 // Sessions can outlive their run and can be shared across app threads.
616 const sessionRows = yield* sql<{ payload_json: string }>`
617 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
618 WHERE status != 'stopped'
619 `;
620 const sessions = yield* Effect.forEach(sessionRows, (row) =>
621 decodeCleanupSession(row.payload_json),
622 );
623 // A stored session can stay ready after its runtime was released,
624 // for example once every thread detached; only a live one holds it.
625 for (const session of sessions) {
626 const cwd = path.resolve(session.cwd);
627 if (
628 (cwd === worktreePath || inside(worktreePath, cwd)) &&
629 (yield* providerSessions.isLive(session.id))
630 )
631 return "provider session is still open";
632 }
633 return null;
634 });
635 // Most cancelled removals are caught here, before the worktree is walked.
636 const blocked = yield* blockedSinceCheck();
637 if (blocked !== null) return keep(blocked);
638 const bytes = yield* measureWorktree(worktreePath);
639 // The walk can take a while; ask again for anything that started during it.
640 const blockedWhileMeasuring = yield* blockedSinceCheck();
641 if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring);
642 if (yield* branchChanged(worktreePath, thread.branch))
643 return keep("repository or branch changed since check");
644 if (
645 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
646 head.commitSha
647 )
648 return keep("commit changed since check");
649 const finalChanges = yield* localChangesReason(worktreePath, settings);
650 if (finalChanges !== null) return keep(finalChanges);
651 const current = resolveWorktreeCleanup(
652 yield* settingsService.getSettings,
653 thread.projectId,
654 );
655 if (
656 Object.keys(settings).some(
657 (key) =>
658 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
659 )
660 )
661 return keep("settings changed since check");
662 // Clean only untracked files; Git must still refuse removal if a tracked
663 // edit arrives after our last status check.
664 if (settings.worktreeKeepWhen === "tracked-changes")
665 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
666 yield* cleanupGit(
667 project.workspaceRoot,
668 ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", worktreePath],
669 "git worktree remove",
670 );
671 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
672 yield* gitManager.invalidateStatus(project.workspaceRoot);
673 // Preserve branch and path: ProviderTurnStartService recreates the checkout
674 // from that branch when the thread is resumed.
675 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
676 }).pipe(
677 (effect) => withWorkspaceLease(worktreePath, effect),
678 Effect.catch((error) =>
679 Effect.gen(function* () {
680 entries.push({
681 ...entry,
682 outcome: "failed",
683 reason: cleanupFailureReason(error),
684 });
685 yield* Effect.logWarning("storage cleanup failed for worktree", {
686 threadId: thread.id,
687 error,
688 });
689 }),
690 ),
691 );
692 }
693 });
694
695 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
696 root: string,
697 days: number | null,
698 now: number,
699 rotatedLogs: boolean,
700 // Owned by the caller so files removed before a failure still count.
701 removed: { files: number; bytes: number },
702 ) {
703 if (days === null || !(yield* fs.exists(root))) return removed;
704 const realRoot = yield* fs.realPath(root);
705 if (realRoot !== path.resolve(root)) return removed;
706 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
707 directory: string,
708 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
709 for (const name of yield* fs.readDirectory(directory)) {
710 const target = path.join(directory, name);
711 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
712 const stat = yield* fs.stat(target);
713 if (stat.type === "Directory" && rotatedLogs) {
714 yield* visit(target);
715 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
716 const modified = Option.getOrNull(stat.mtime);
717 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
718 const current = (yield* settingsService.getSettings).storageCleanup;
719 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
720 return;
721 yield* fs.remove(target);
722 removed.files++;
723 removed.bytes += Number(stat.size);
724 }
725 }
726 }
727 });
728 yield* visit(realRoot);
729 return removed;
730 });
731
732 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
733 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
734 trigger: StorageCleanupReport["trigger"],
735 ) {
736 const now = yield* Clock.currentTimeMillis;
737 const serverSettings = yield* settingsService.getSettings;
738 const settings = serverSettings.storageCleanup;
739 const entries: StorageCleanupReportEntry[] = [];
740 yield* cleanWorktrees(serverSettings, now, entries).pipe(
741 Effect.catch((error) =>
742 Effect.gen(function* () {
743 entries.push({
744 kind: "worktree",
745 outcome: "failed",
746 reason: cleanupFailureReason(error),
747 path: null,
748 threadId: null,
749 threadTitle: null,
750 bytes: null,
751 files: null,
752 });
753 yield* Effect.logWarning("worktree cleanup failed", { error });
754 }),
755 ),
756 );
757 for (const category of [
758 {
759 kind: "browser-artifacts" as const,
760 root: config.browserArtifactsDir,
761 days: settings.browserArtifactsAfterDays,
762 label: "browser artifacts",
763 },
764 {
765 kind: "logs" as const,
766 root: config.logsDir,
767 days: settings.logsAfterDays,
768 label: "rotated logs",
769 },
770 ]) {
771 if (category.days === null) continue;
772 const removed = { files: 0, bytes: 0 };
773 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
774 Effect.map(({ files, bytes }) =>
775 entries.push({
776 kind: category.kind,
777 outcome: files > 0 ? "removed" : "kept",
778 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
779 path: null,
780 threadId: null,
781 threadTitle: null,
782 bytes: files > 0 ? bytes : null,
783 files: files > 0 ? files : null,
784 }),
785 ),
786 Effect.catch((error) =>
787 Effect.gen(function* () {
788 entries.push({
789 kind: category.kind,
790 outcome: "failed",
791 reason: cleanupFailureReason(error),
792 path: null,
793 threadId: null,
794 threadTitle: null,
795 bytes: removed.files > 0 ? removed.bytes : null,
796 files: removed.files > 0 ? removed.files : null,
797 });
798 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
799 }),
800 ),
801 );
802 }
803 const counts = { removed: 0, kept: 0, failed: 0 };
804 let bytesFreed = 0;
805 for (const entry of entries) {
806 counts[entry.outcome]++;
807 bytesFreed += entry.bytes ?? 0;
808 }
809 const priority = { failed: 0, removed: 1, kept: 2 };
810 const latestReport: StorageCleanupReport = {
811 trigger,
812 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
813 finishedAt: DateTime.formatIso(yield* DateTime.now),
814 entries: entries
815 .sort((a, b) => priority[a.outcome] - priority[b.outcome])
816 .slice(0, REPORT_ENTRY_LIMIT),
817 counts,
818 bytesFreed,
819 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
820 };
821 yield* SubscriptionRef.set(reportRef, latestReport);
822 return latestReport;
823 });
824 // At most one automatic sweep waits at a time. An automatic request made
825 // while one is waiting joins it, since that sweep has not read any state yet.
826 // Each manual run still gets its own sweep and report.
827 const automaticSweepQueued = yield* Ref.make(false);
828 const worker = yield* makeDrainableWorker(
829 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
830 (completion === undefined ? Ref.set(automaticSweepQueued, false) : Effect.void).pipe(
831 Effect.andThen(sweep(completion === undefined ? "automatic" : "manual")),
832 Effect.exit,
833 Effect.flatMap((exit) =>
834 completion === undefined
835 ? exit.pipe(
836 Effect.asVoid,
837 Effect.catchCause((cause) =>
838 Effect.logWarning("storage cleanup failed", { cause }),
839 ),
840 )
841 : Deferred.done(completion, exit).pipe(Effect.asVoid),
842 ),
843 ),
844 );
845 const requestSweep = Ref.getAndSet(automaticSweepQueued, true).pipe(
846 Effect.flatMap((queued) => (queued ? Effect.void : worker.enqueue(undefined))),
847 );
848 const runNow = Effect.gen(function* () {
849 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
850 yield* worker.enqueue(completion);
851 return yield* Deferred.await(completion);
852 });
853
854 const start = Effect.fn("StorageCleanup.start")(function* () {
855 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
856 Effect.sync(() => {
857 if (event.type === "snapshot") {
858 liveTerminals.clear();
859 for (const terminal of event.terminals) noteTerminal(terminal);
860 } else if (event.type === "upsert") {
861 noteTerminal(event.terminal);
862 } else {
863 const threadTerminals = liveTerminals.get(event.threadId);
864 threadTerminals?.delete(event.terminalId);
865 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
866 }
867 }),
868 );
869 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
870 const changes = yield* settingsService.subscribeChanges;
871 const events = engine.streamDomainEvents;
872 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
873 yield* forkParked(
874 requestSweep.pipe(
875 Effect.andThen(worker.drain),
876 Effect.repeat(Schedule.spaced("1 hour")),
877 Effect.asVoid,
878 ),
879 );
880 yield* forkParked(
881 Stream.runForEach(changes, (settings) => {
882 if (
883 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
884 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
885 sameProjectWorktreePolicies(settings, lastSettings)
886 )
887 return Effect.void;
888 lastSettings = settings;
889 return requestSweep;
890 }),
891 );
892 yield* forkParked(
893 // A deleted thread's worktree waits for its sessions to end. Moving
894 // between live statuses, such as running to ready, cannot free one.
895 Stream.runForEach(events, (event) =>
896 (event.type === "thread.deleted" ||
897 (event.type === "provider-session.updated" &&
898 (event.payload.status === "stopped" || event.payload.status === "error"))) &&
899 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
900 ? requestSweep
901 : Effect.void,
902 ).pipe(
903 Effect.catchCause((cause) =>
904 Effect.logWarning("Storage cleanup event stream failed", { cause }),
905 ),
906 ),
907 );
908 });
909 yield* start();
910 return StorageCleanup.of({
911 runNow,
912 latestReport: SubscriptionRef.get(reportRef),
913 reports: SubscriptionRef.changes(reportRef),
914 drain: worker.drain,
915 });
916});
917
918export const layer = Layer.effect(StorageCleanup, make);