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