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
109export function storageCleanupThreadIdle(thread: OrchestrationV2ThreadShell, now: number): boolean {
110 return (
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/** Only a complete subagent chain within this worktree shares ownership. */
139function worktreeOwner(threads: ReadonlyArray<OrchestrationV2ThreadShell>) {
140 if (threads.length === 1) return threads[0];
141 const byId = new Map(threads.map((thread) => [thread.id, thread]));
142 const tops = threads.filter((thread) => !byId.has(thread.lineage.parentThreadId!));
143 if (tops.length !== 1) return undefined;
144 const owner = tops[0]!;
145 for (const thread of threads) {
146 let current = thread;
147 const seen = new Set<string>();
148 while (current.id !== owner.id) {
149 if (
150 seen.has(current.id) ||
151 current.lineage.relationshipToParent !== "subagent" ||
152 current.lineage.rootThreadId !== owner.lineage.rootThreadId
153 )
154 return undefined;
155 seen.add(current.id);
156 const parent = byId.get(current.lineage.parentThreadId!);
157 if (parent === undefined) return undefined;
158 current = parent;
159 }
160 }
161 return owner;
162}
163
164/**
165 * Whether the host's pull request proves this worktree's head was merged. A
166 * squash or rebase merge leaves the head outside the default branch, so the
167 * merged pull request then has to name this exact commit.
168 */
169export function storageCleanupPullRequestMerged(
170 pullRequest: Pick<
171 GitManager.GitBranchPullRequest,
172 "state" | "headRef" | "baseRef" | "headSha"
173 > | null,
174 worktree: {
175 readonly branch: string;
176 readonly defaultBranch: string;
177 readonly headSha: string;
178 readonly integrated: boolean;
179 },
180): boolean {
181 return (
182 pullRequest?.state === "merged" &&
183 (worktree.integrated ||
184 (pullRequest.headRef === worktree.branch &&
185 pullRequest.baseRef === worktree.defaultBranch &&
186 pullRequest.headSha === worktree.headSha))
187 );
188}
189
190export class StorageCleanup extends Context.Service<
191 StorageCleanup,
192 {
193 readonly runNow: Effect.Effect<StorageCleanupReport, ServerSettingsError>;
194 readonly latestReport: Effect.Effect<StorageCleanupReport | null>;
195 readonly reports: Stream.Stream<StorageCleanupReport | null>;
196 readonly drain: Effect.Effect<void>;
197 }
198>()("t3/storageCleanup") {}
199
200const make = Effect.gen(function* () {
201 const config = yield* ServerConfig.ServerConfig;
202 const settingsService = yield* Settings.ServerSettingsService;
203 const projectStore = yield* ProjectStore.ProjectStoreV2;
204 const engine = yield* Orchestrator.OrchestratorV2;
205 const projections = yield* ProjectionStore.ProjectionStoreV2;
206 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
207 const sql = yield* SqlClient.SqlClient;
208 const git = yield* GitVcsDriver.GitVcsDriver;
209 const gitManager = yield* GitManager.GitManager;
210 const terminals = yield* TerminalManager.TerminalManager;
211 const fs = yield* FileSystem.FileSystem;
212 const path = yield* Path.Path;
213 const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
214 const orphanSizes = new Map<string, number | null>();
215 const noteTerminal = (terminal: TerminalSummary) => {
216 const threadTerminals =
217 liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
218 threadTerminals.set(terminal.terminalId, terminal);
219 liveTerminals.set(terminal.threadId, threadTerminals);
220 };
221
222 const isWindows = yield* HostProcess.isWindows;
223 const pathKey = (target: string) => {
224 const resolved = path.resolve(target);
225 return isWindows ? resolved.toLowerCase() : resolved;
226 };
227 const inside = (root: string, target: string) => {
228 const relative = path.relative(pathKey(root), pathKey(target));
229 return (
230 relative !== "" &&
231 relative !== ".." &&
232 !relative.startsWith(`..${path.sep}`) &&
233 !path.isAbsolute(relative)
234 );
235 };
236 const hasTerminal = (worktreePath: string) =>
237 [...liveTerminals.values()]
238 .flatMap((entries) => [...entries.values()])
239 .some((terminal) => {
240 if (terminal.status !== "starting" && terminal.status !== "running") return false;
241 const cwd = path.resolve(terminal.cwd);
242 return (
243 (terminal.worktreePath !== null &&
244 path.resolve(terminal.worktreePath) === worktreePath) ||
245 cwd === worktreePath ||
246 inside(worktreePath, cwd)
247 );
248 });
249
250 const measureWorktree = (worktreePath: string) =>
251 Effect.gen(function* () {
252 const root = yield* fs.realPath(worktreePath);
253 const pending = [root];
254 let entries = 1;
255 let bytes = 0;
256 while (pending.length > 0) {
257 const target = pending.pop()!;
258 // Effect's stat follows links. Probe with readLink first to get lstat
259 // semantics, including skipping dangling links and directory links.
260 const isLink = yield* fs.readLink(target).pipe(
261 Effect.as(true),
262 Effect.catchIf(
263 (error) =>
264 error.cause instanceof Error &&
265 "code" in error.cause &&
266 error.cause.code === "EINVAL",
267 () => Effect.succeed(false),
268 ),
269 );
270 if (isLink) continue;
271 if ((yield* fs.realPath(target)) !== target) return null;
272 const stat = yield* fs.stat(target);
273 if (stat.type === "File") {
274 // Removing a shared hardlink leaves its blocks allocated.
275 if (Option.getOrElse(stat.nlink, () => 1n) !== 1n) continue;
276 bytes += Option.match(stat.blocks, {
277 onNone: () => Number(stat.size),
278 onSome: (blocks) => Number(blocks * 512n),
279 });
280 } else if (stat.type === "Directory") {
281 const names = yield* fs.readDirectory(target);
282 entries += names.length;
283 if (entries > 2_000_000) return null;
284 for (const name of names) {
285 const child = path.join(target, name);
286 if (!inside(root, child)) return null;
287 pending.push(child);
288 }
289 }
290 }
291 return bytes;
292 }).pipe(
293 Effect.timeout("30 seconds"),
294 Effect.orElseSucceed(() => null),
295 );
296
297 // The snapshot takes seconds on large databases, so it runs on the reader
298 // worker instead of the event loop.
299 const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {
300 const snapshot = yield* projections.getShellSnapshot().pipe(NodeSqliteClient.readOnly);
301 const projects = yield* projectStore.listShells();
302 return { projects, threads: [...snapshot.threads, ...snapshot.archivedThreads] };
303 });
304
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 if (yield* fs.exists(`${path.resolve(cwd, index.stdout.trim())}.lock`))
488 return yield* failure(
489 "Git index is locked. Status will resume when the index lock is removed.",
490 );
491 // Exits 1 for a detached HEAD. Reads the full ref name, which is never
492 // shortened to "heads/<branch>" when a tag shares the branch name.
493 const head = yield* read(["symbolic-ref", "--quiet", "HEAD"], 1);
494 if (head === null) return true;
495 const ref = head.exitCode === 0 ? head.stdout.trim() : "";
496 const name = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length).trim() : null;
497 return (name?.startsWith("(") ? null : name) !== branch;
498 });
499
500 const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* (
501 cwd: string,
502 rules: WorktreeCleanupRules,
503 ) {
504 const status = yield* git.execute({
505 operation: "StorageCleanup.localChanges",
506 cwd,
507 args: [
508 "status",
509 "--porcelain=v1",
510 "-z",
511 "--ignore-submodules=none",
512 rules.worktreeKeepWhen === "tracked-changes"
513 ? "--untracked-files=no"
514 : "--untracked-files=all",
515 ],
516 maxOutputBytes: 64 * 1024,
517 });
518 if (status.stdoutTruncated) return "local changes exceed the inspection limit";
519 const records = status.stdout.split("\0").filter(Boolean);
520 let count = 0;
521 for (let i = 0; i < records.length; i++) {
522 count++;
523 if (/^[RC]|^.[RC]/.test(records[i]!)) i++;
524 }
525 if (count > 0) return `has uncommitted changes (${count} ${count === 1 ? "file" : "files"})`;
526 if (rules.worktreeKeepWhen !== "any-local-files") return null;
527 const ignored = yield* git.execute({
528 operation: "StorageCleanup.ignoredFiles",
529 cwd,
530 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
531 maxOutputBytes: 64 * 1024,
532 });
533 if (ignored.stdoutTruncated) return "ignored files exceed the inspection limit";
534 const file = ignored.stdout
535 .split("\0")
536 .find((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry));
537 return file === undefined ? null : `has ignored files (${file})`;
538 });
539
540 const cleanupGit = Effect.fn("StorageCleanup.cleanupGit")(function* (
541 cwd: string,
542 args: string[],
543 command: string,
544 ) {
545 const result = yield* git.execute({
546 operation: "StorageCleanup.cleanupGit",
547 cwd,
548 args,
549 allowNonZeroExit: true,
550 timeoutMs: 300_000,
551 });
552 if (result.exitCode !== 0)
553 return yield* Effect.fail(
554 new GitCommandError({
555 operation: "StorageCleanup.cleanupGit",
556 command,
557 cwd,
558 detail: result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
559 }),
560 );
561 });
562
563 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
564 serverSettings: ServerSettings,
565 now: number,
566 entries: StorageCleanupReportEntry[],
567 ) {
568 if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
569 const roots: Array<string> = [];
570 for (const directory of managedWorktreesDirectories(
571 serverSettings,
572 config.worktreesDir,
573 path,
574 yield* HostProcess.HomeDirectory,
575 )) {
576 const root = yield* fs.exists(directory).pipe(
577 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
578 Effect.orElseSucceed(() => null),
579 );
580 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
581 }
582 const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
583 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
584 FROM orchestration_v2_projection_threads t
585 JOIN projection_projects p ON p.project_id = t.project_id
586 WHERE t.deleted_at IS NOT NULL
587 `;
588 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
589 decodeCleanupThread(row.payload_json).pipe(
590 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
591 ),
592 )).filter((thread) => thread.worktreePath !== null && thread.branch !== null);
593 const snapshot = yield* readThreads();
594 const refreshedDefaultRefs = new Map<string, Set<string>>();
595 const groups = Map.groupBy(
596 snapshot.threads.filter((thread) => thread.worktreePath !== null),
597 (thread) => path.resolve(thread.worktreePath!),
598 );
599 const candidates = [
600 ...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!),
601 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
602 ];
603 for (const thread of candidates) {
604 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
605 if (!worktreeCleanupEnabled(settings)) continue;
606 const worktreePath = path.resolve(thread.worktreePath!);
607 const group = groups.get(worktreePath) ?? [];
608 const activityAt = Math.max(...group.map(storageCleanupActivityAt));
609 const deleted = "workspaceRoot" in thread;
610 const project = deleted
611 ? { workspaceRoot: thread.workspaceRoot }
612 : snapshot.projects.find((entry) => entry.id === thread.projectId);
613 const entry: StorageCleanupReportEntry = {
614 kind: "worktree",
615 outcome: "kept",
616 reason: "",
617 path: worktreePath,
618 threadId: thread.id,
619 threadTitle: thread.title,
620 bytes: null,
621 files: null,
622 };
623 const keep = (reason: string) => entries.push({ ...entry, reason: sentence(reason) });
624 yield* Effect.gen(function* () {
625 if (!(yield* fs.exists(worktreePath))) return;
626 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
627 if (group.length > 1 && worktreeOwner(group) === undefined)
628 return keep(`shared by ${group.length} threads`);
629 if (project === undefined) return keep("project is unavailable");
630 if (
631 thread.branch === null ||
632 (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
633 )
634 return keep("thread is running or has pending work");
635 if (group.some((member) => member.branch !== thread.branch))
636 return keep("a subagent thread's branch differs from this worktree's branch");
637 if (hasTerminal(worktreePath)) return keep("open terminal");
638 // Roots are canonical, so compare canonical paths. A symlinked parent
639 // (a linked drive) is fine; a symlinked worktree directory is not.
640 const realPath = yield* fs.realPath(worktreePath);
641 const realParent = yield* fs.realPath(path.dirname(worktreePath));
642 if (realPath !== path.join(realParent, path.basename(worktreePath)))
643 return keep("worktree is a symbolic link");
644 if (!roots.some((root) => inside(root, realPath)))
645 return keep("outside the managed worktree folder");
646 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
647 return keep("contains a project checkout");
648 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
649 return keep("not a linked worktree");
650 if (yield* branchChanged(worktreePath, thread.branch))
651 return keep("repository or branch changed");
652 const changes = yield* localChangesReason(worktreePath, settings);
653 if (changes !== null) return keep(changes);
654 if (
655 !deleted &&
656 group.some(
657 (member) =>
658 member.settledAt !== null &&
659 now - Math.max(DateTime.toEpochMillis(member.updatedAt), activityAt) <
660 SETTLE_SCRIPT_GRACE_MS,
661 )
662 )
663 return keep("settled moments ago");
664 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
665 const old =
666 !deleted &&
667 settings.worktreeAfterDays !== null &&
668 activityAt < now - settings.worktreeAfterDays * DAY_MS;
669 const settledFor =
670 deleted || thread.settledAt === null
671 ? null
672 : now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
673 const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
674 const settled =
675 settledFor !== null &&
676 settings.worktreeSettledAfterDays !== null &&
677 settledFor >= settings.worktreeSettledAfterDays * DAY_MS;
678 let eligible = deleted || old || settled;
679 let removalReason = deleted
680 ? "thread was deleted"
681 : old
682 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
683 : `settled for ${settledDays} days`;
684 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
685 const repositoryCwd = path.resolve(project.workspaceRoot);
686 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
687 const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
688 if (branch === null) return keep("default branch is unavailable");
689 const defaultRef = `refs/remotes/${remote}/${branch}`;
690 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
691 if (!refreshed.has(defaultRef)) {
692 yield* git.fetchRemoteTrackingBranch({
693 cwd: repositoryCwd,
694 remoteName: remote,
695 remoteBranch: branch,
696 });
697 refreshed.add(defaultRef);
698 refreshedDefaultRefs.set(repositoryCwd, refreshed);
699 }
700 const base = yield* git.resolveCommit({
701 cwd: worktreePath,
702 revision: defaultRef,
703 });
704 const ancestor = yield* git.execute({
705 operation: "StorageCleanup.integratedBranch",
706 cwd: worktreePath,
707 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
708 allowNonZeroExit: true,
709 });
710 const integrated = ancestor.exitCode === 0;
711 eligible = integrated && settings.worktreeUnchanged;
712 if (eligible) removalReason = "no commits beyond the default branch";
713 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
714 const pullRequest = yield* gitManager.branchPullRequest(
715 { cwd: worktreePath, branch: thread.branch },
716 { refresh: true },
717 );
718 eligible = storageCleanupPullRequestMerged(pullRequest, {
719 branch: thread.branch,
720 defaultBranch: branch,
721 headSha: head.commitSha,
722 integrated,
723 });
724 if (eligible) removalReason = "pull request was merged";
725 }
726 }
727 if (!eligible)
728 return keep(
729 !deleted && settings.worktreeAfterDays !== null
730 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
731 : settings.worktreeSettledAfterDays !== null
732 ? settledFor === null
733 ? "not settled"
734 : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days`
735 : settings.worktreeOnMerge
736 ? "not merged"
737 : "has commits beyond the default branch",
738 );
739 // Threads, queued deletion work and provider sessions as they are now, so a
740 // queued turn, resumed session or new thread sharing this path cancels
741 // the removal. Read only this path's threads: a full snapshot per
742 // worktree takes seconds on large databases.
743 const blockedSinceCheck = Effect.fnUntraced(function* () {
744 const latestProjects = yield* projectStore.listShells();
745 if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects]))
746 return "contains a project checkout";
747 const latest = (yield* projections.getThreadWorktreePaths({
748 includeArchived: true,
749 })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath);
750 if (hasTerminal(worktreePath)) return "open terminal";
751 if (deleted) {
752 if (
753 latest.length > 0 ||
754 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
755 .worktreeOnDelete
756 )
757 return "thread or cleanup settings changed since check";
758 // V2 deletion queues durable cleanup. Do not remove its checkout until
759 // every effect has finished successfully or was explicitly cancelled.
760 const pendingCleanup = yield* sql`
761 SELECT 1 FROM orchestration_v2_effect_outbox
762 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
763 `;
764 if (pendingCleanup.length > 0) return "thread deletion is still pending";
765 } else {
766 const latestShells = yield* Effect.forEach(latest, (entry) =>
767 projections.getThreadShell(entry.threadId),
768 );
769 const latestGroup = latestShells.filter((shell) => shell !== null);
770 const latestOwner = worktreeOwner(latestGroup);
771 if (
772 latestGroup.length !== group.length ||
773 latestOwner?.id !== thread.id ||
774 latestOwner?.branch !== thread.branch ||
775 latestGroup.some((shell) => {
776 const previous = group.find((member) => member.id === shell.id);
777 return (
778 previous === undefined ||
779 shell.branch !== thread.branch ||
780 !Equal.equals(shell.settledAt, previous.settledAt) ||
781 (shell.settledAt !== null &&
782 !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
783 !storageCleanupThreadIdle(shell, now) ||
784 path.resolve(shell.worktreePath!) !== worktreePath ||
785 storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
786 );
787 })
788 )
789 return "thread activity or shared worktree changed since check";
790 }
791 // Sessions can outlive their run and can be shared across app threads.
792 const sessionRows = yield* sql<{ payload_json: string }>`
793 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
794 WHERE status != 'stopped'
795 `;
796 const sessions = yield* Effect.forEach(sessionRows, (row) =>
797 decodeCleanupSession(row.payload_json),
798 );
799 // A stored session can stay ready after its runtime was released,
800 // for example once every thread detached; only a live one holds it.
801 for (const session of sessions) {
802 const cwd = path.resolve(session.cwd);
803 if (
804 (cwd === worktreePath || inside(worktreePath, cwd)) &&
805 (yield* providerSessions.isLive(session.id))
806 )
807 return "provider session is still open";
808 }
809 return null;
810 });
811 const blocked = yield* blockedSinceCheck();
812 if (blocked !== null) return keep(blocked);
813 const bytes = yield* measureWorktree(worktreePath);
814 const blockedWhileMeasuring = yield* blockedSinceCheck();
815 if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring);
816 if (yield* branchChanged(worktreePath, thread.branch))
817 return keep("repository or branch changed since check");
818 if (
819 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
820 head.commitSha
821 )
822 return keep("commit changed since check");
823 const finalChanges = yield* localChangesReason(worktreePath, settings);
824 if (finalChanges !== null) return keep(finalChanges);
825 const current = resolveWorktreeCleanup(
826 yield* settingsService.getSettings,
827 thread.projectId,
828 );
829 if (
830 Object.keys(settings).some(
831 (key) =>
832 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
833 )
834 )
835 return keep("settings changed since check");
836 // Clean only untracked files; Git must still refuse removal if a tracked
837 // edit arrives after our last status check.
838 if (settings.worktreeKeepWhen === "tracked-changes")
839 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
840 yield* cleanupGit(
841 project.workspaceRoot,
842 ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", "--", worktreePath],
843 "git worktree remove",
844 );
845 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
846 yield* gitManager.invalidateStatus(project.workspaceRoot);
847 // Preserve branch and path: ProviderTurnStartService recreates the checkout
848 // from that branch when the thread is resumed.
849 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
850 }).pipe(
851 (effect) => withWorkspaceLease(worktreePath, effect),
852 Effect.catch((error) =>
853 Effect.gen(function* () {
854 entries.push({
855 ...entry,
856 outcome: "failed",
857 reason: cleanupFailureReason(error),
858 });
859 yield* Effect.logWarning("storage cleanup failed for worktree", {
860 threadId: thread.id,
861 error,
862 });
863 }),
864 ),
865 );
866 }
867 yield* reportOrphanWorktrees(
868 roots,
869 yield* projectStore.list({ includeDeleted: true }),
870 entries,
871 );
872 });
873
874 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
875 root: string,
876 days: number | null,
877 now: number,
878 rotatedLogs: boolean,
879 removed: { files: number; bytes: number },
880 ) {
881 if (days === null || !(yield* fs.exists(root))) return removed;
882 const realRoot = yield* fs.realPath(root);
883 if (realRoot !== path.resolve(root)) return removed;
884 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
885 directory: string,
886 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
887 for (const name of yield* fs.readDirectory(directory)) {
888 const target = path.join(directory, name);
889 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
890 const stat = yield* fs.stat(target);
891 if (stat.type === "Directory" && rotatedLogs) {
892 yield* visit(target);
893 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
894 const modified = Option.getOrNull(stat.mtime);
895 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
896 const current = (yield* settingsService.getSettings).storageCleanup;
897 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
898 return;
899 yield* fs.remove(target);
900 removed.files++;
901 removed.bytes += Number(stat.size);
902 }
903 }
904 }
905 });
906 yield* visit(realRoot);
907 return removed;
908 });
909
910 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
911 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
912 trigger: StorageCleanupReport["trigger"],
913 ) {
914 const now = yield* Clock.currentTimeMillis;
915 const serverSettings = yield* settingsService.getSettings;
916 const settings = serverSettings.storageCleanup;
917 const entries: StorageCleanupReportEntry[] = [];
918 yield* cleanWorktrees(serverSettings, now, entries).pipe(
919 Effect.catch((error) =>
920 Effect.gen(function* () {
921 entries.push({
922 kind: "worktree",
923 outcome: "failed",
924 reason: cleanupFailureReason(error),
925 path: null,
926 threadId: null,
927 threadTitle: null,
928 bytes: null,
929 files: null,
930 });
931 yield* Effect.logWarning("worktree cleanup failed", { error });
932 }),
933 ),
934 );
935 for (const category of [
936 {
937 kind: "browser-artifacts" as const,
938 root: config.browserArtifactsDir,
939 days: settings.browserArtifactsAfterDays,
940 label: "browser artifacts",
941 },
942 {
943 kind: "logs" as const,
944 root: config.logsDir,
945 days: settings.logsAfterDays,
946 label: "rotated logs",
947 },
948 ]) {
949 if (category.days === null) continue;
950 const removed = { files: 0, bytes: 0 };
951 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
952 Effect.map(({ files, bytes }) =>
953 entries.push({
954 kind: category.kind,
955 outcome: files > 0 ? "removed" : "kept",
956 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
957 path: null,
958 threadId: null,
959 threadTitle: null,
960 bytes: files > 0 ? bytes : null,
961 files: files > 0 ? files : null,
962 }),
963 ),
964 Effect.catch((error) =>
965 Effect.gen(function* () {
966 entries.push({
967 kind: category.kind,
968 outcome: "failed",
969 reason: cleanupFailureReason(error),
970 path: null,
971 threadId: null,
972 threadTitle: null,
973 bytes: removed.files > 0 ? removed.bytes : null,
974 files: removed.files > 0 ? removed.files : null,
975 });
976 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
977 }),
978 ),
979 );
980 }
981 const counts = { removed: 0, kept: 0, failed: 0 };
982 let bytesFreed = 0;
983 for (const entry of entries) {
984 counts[entry.outcome]++;
985 if (entry.outcome !== "kept") bytesFreed += entry.bytes ?? 0;
986 }
987 const priority = (entry: StorageCleanupReportEntry) =>
988 entry.outcome === "failed"
989 ? 0
990 : entry.outcome === "removed"
991 ? 1
992 : entry.kind === "worktree" && entry.threadId === null
993 ? 2
994 : 3;
995 const latestReport: StorageCleanupReport = {
996 trigger,
997 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
998 finishedAt: DateTime.formatIso(yield* DateTime.now),
999 entries: entries.sort((a, b) => priority(a) - priority(b)).slice(0, REPORT_ENTRY_LIMIT),
1000 counts,
1001 bytesFreed,
1002 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
1003 };
1004 yield* SubscriptionRef.set(reportRef, latestReport);
1005 return latestReport;
1006 });
1007 const automaticSweepQueued = yield* Ref.make(false);
1008 const worker = yield* makeDrainableWorker(
1009 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
1010 (completion === undefined ? Ref.set(automaticSweepQueued, false) : Effect.void).pipe(
1011 Effect.andThen(sweep(completion === undefined ? "automatic" : "manual")),
1012 Effect.exit,
1013 Effect.flatMap((exit) =>
1014 completion === undefined
1015 ? exit.pipe(
1016 Effect.asVoid,
1017 Effect.catchCause((cause) =>
1018 Effect.logWarning("storage cleanup failed", { cause }),
1019 ),
1020 )
1021 : Deferred.done(completion, exit).pipe(Effect.asVoid),
1022 ),
1023 ),
1024 );
1025 const requestSweep = Ref.getAndSet(automaticSweepQueued, true).pipe(
1026 Effect.flatMap((queued) => (queued ? Effect.void : worker.enqueue(undefined))),
1027 );
1028 const runNow = Effect.gen(function* () {
1029 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
1030 yield* worker.enqueue(completion);
1031 return yield* Deferred.await(completion);
1032 });
1033
1034 const start = Effect.fn("StorageCleanup.start")(function* () {
1035 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
1036 Effect.sync(() => {
1037 if (event.type === "snapshot") {
1038 liveTerminals.clear();
1039 for (const terminal of event.terminals) noteTerminal(terminal);
1040 } else if (event.type === "upsert") {
1041 noteTerminal(event.terminal);
1042 } else {
1043 const threadTerminals = liveTerminals.get(event.threadId);
1044 threadTerminals?.delete(event.terminalId);
1045 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
1046 }
1047 }),
1048 );
1049 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1050 const changes = yield* settingsService.subscribeChanges;
1051 const events = engine.streamDomainEvents;
1052 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
1053 yield* forkParked(
1054 requestSweep.pipe(
1055 Effect.andThen(worker.drain),
1056 Effect.repeat(Schedule.spaced("1 hour")),
1057 Effect.asVoid,
1058 ),
1059 );
1060 yield* forkParked(
1061 Stream.runForEach(changes, (settings) => {
1062 if (
1063 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
1064 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
1065 sameProjectWorktreePolicies(settings, lastSettings)
1066 )
1067 return Effect.void;
1068 lastSettings = settings;
1069 return requestSweep;
1070 }),
1071 );
1072 yield* forkParked(
1073 Stream.runForEach(events, (event) =>
1074 (event.type === "thread.deleted" ||
1075 (event.type === "provider-session.updated" &&
1076 (event.payload.status === "stopped" || event.payload.status === "error"))) &&
1077 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
1078 ? requestSweep
1079 : Effect.void,
1080 ).pipe(
1081 Effect.catchCause((cause) =>
1082 Effect.logWarning("Storage cleanup event stream failed", { cause }),
1083 ),
1084 ),
1085 );
1086 });
1087 yield* start();
1088 return StorageCleanup.of({
1089 runNow,
1090 latestReport: SubscriptionRef.get(reportRef),
1091 reports: SubscriptionRef.changes(reportRef),
1092 drain: worker.drain,
1093 });
1094});
1095
1096export const layer = Layer.effect(StorageCleanup, make);