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