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 = Effect.fn("storageCleanup.measureWorktree")(
251 function* (worktreePath: string) {
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 },
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 projectPath: null,
418 threadId: null,
419 threadTitle: null,
420 bytes,
421 files: null,
422 });
423 },
424 Effect.orElseSucceed(() => undefined),
425 );
426 for (const root of roots) {
427 // Worktrees can be <root>/<repository>/<branch> or explicitly <root>/<name>.
428 for (const projectDirectory of yield* directories(root, root)) {
429 yield* Effect.gen(function* () {
430 if (referenced.has(pathKey(projectDirectory))) return;
431 const gitPath = path.join(projectDirectory, ".git");
432 if (yield* fs.exists(gitPath)) {
433 if ((yield* fs.stat(gitPath)).type === "File") yield* report(projectDirectory);
434 return;
435 }
436 for (const worktreePath of yield* directories(projectDirectory, root)) {
437 yield* report(worktreePath);
438 }
439 }).pipe(Effect.orElseSucceed(() => undefined));
440 }
441 }
442 for (const key of orphanSizes.keys()) {
443 if (!reported.has(key)) orphanSizes.delete(key);
444 }
445 });
446
447 // Whether cwd stopped being a checkout of this branch. Two small Git reads,
448 // since every worktree in a sweep is asked; statusDetailsLocal also diffs and
449 // counts.
450 const branchChanged = Effect.fn("StorageCleanup.branchChanged")(function* (
451 cwd: string,
452 branch: string | null,
453 ) {
454 const failure = (detail: string) =>
455 new GitCommandError({
456 operation: "StorageCleanup.branchChanged",
457 command: "git",
458 cwd,
459 detail,
460 });
461 // Null when cwd is not a repository, or is gone. Git's own messages are
462 // matched, so they must not be translated.
463 const read = Effect.fnUntraced(function* (args: string[], allowedExitCode?: number) {
464 const result = yield* git
465 .execute({
466 operation: "StorageCleanup.branchChanged",
467 cwd,
468 args,
469 env: { LC_ALL: "C" },
470 allowNonZeroExit: true,
471 })
472 .pipe(
473 Effect.catch((error) =>
474 Effect.flatMap(fs.exists(cwd), (exists) =>
475 exists ? Effect.fail(error) : Effect.succeed(null),
476 ),
477 ),
478 );
479 if (result === null) return null;
480 if (result.exitCode === 0 || result.exitCode === allowedExitCode) return result;
481 if (result.stderr.toLowerCase().includes("not a git repository")) return null;
482 return yield* failure(
483 result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
484 );
485 });
486 const index = yield* read(["rev-parse", "--git-path", "index"]);
487 if (index === null) return true;
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 return (name?.startsWith("(") ? null : name) !== branch;
499 });
500
501 const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* (
502 cwd: string,
503 rules: WorktreeCleanupRules,
504 ) {
505 const status = yield* git.execute({
506 operation: "StorageCleanup.localChanges",
507 cwd,
508 args: [
509 "status",
510 "--porcelain=v1",
511 "-z",
512 "--ignore-submodules=none",
513 rules.worktreeKeepWhen === "tracked-changes"
514 ? "--untracked-files=no"
515 : "--untracked-files=all",
516 ],
517 maxOutputBytes: 64 * 1024,
518 });
519 if (status.stdoutTruncated) return "local changes exceed the inspection limit";
520 const records = status.stdout.split("\0").filter(Boolean);
521 let count = 0;
522 for (let i = 0; i < records.length; i++) {
523 count++;
524 if (/^[RC]|^.[RC]/.test(records[i]!)) i++;
525 }
526 if (count > 0) return `has uncommitted changes (${count} ${count === 1 ? "file" : "files"})`;
527 if (rules.worktreeKeepWhen !== "any-local-files") return null;
528 const ignored = yield* git.execute({
529 operation: "StorageCleanup.ignoredFiles",
530 cwd,
531 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
532 maxOutputBytes: 64 * 1024,
533 });
534 if (ignored.stdoutTruncated) return "ignored files exceed the inspection limit";
535 const file = ignored.stdout
536 .split("\0")
537 .find((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry));
538 return file === undefined ? null : `has ignored files (${file})`;
539 });
540
541 const cleanupGit = Effect.fn("StorageCleanup.cleanupGit")(function* (
542 cwd: string,
543 args: string[],
544 command: string,
545 ) {
546 const result = yield* git.execute({
547 operation: "StorageCleanup.cleanupGit",
548 cwd,
549 args,
550 allowNonZeroExit: true,
551 timeoutMs: 300_000,
552 });
553 if (result.exitCode !== 0)
554 return yield* Effect.fail(
555 new GitCommandError({
556 operation: "StorageCleanup.cleanupGit",
557 command,
558 cwd,
559 detail: result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
560 }),
561 );
562 });
563
564 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
565 serverSettings: ServerSettings,
566 now: number,
567 entries: StorageCleanupReportEntry[],
568 ) {
569 if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
570 const roots: Array<string> = [];
571 for (const directory of managedWorktreesDirectories(
572 serverSettings,
573 config.worktreesDir,
574 path,
575 yield* HostProcess.HomeDirectory,
576 )) {
577 const root = yield* fs.exists(directory).pipe(
578 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
579 Effect.orElseSucceed(() => null),
580 );
581 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
582 }
583 const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
584 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
585 FROM orchestration_v2_projection_threads t
586 JOIN projection_projects p ON p.project_id = t.project_id
587 WHERE t.deleted_at IS NOT NULL
588 `;
589 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
590 decodeCleanupThread(row.payload_json).pipe(
591 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
592 ),
593 )).filter((thread) => thread.worktreePath !== null && thread.branch !== null);
594 const snapshot = yield* readThreads();
595 const refreshedDefaultRefs = new Map<string, Set<string>>();
596 const defaultBranches = new Map<string, string | null>();
597 const groups = Map.groupBy(
598 snapshot.threads.filter((thread) => thread.worktreePath !== null),
599 (thread) => path.resolve(thread.worktreePath!),
600 );
601 const candidates = [
602 ...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!),
603 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
604 ];
605 for (const thread of candidates) {
606 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
607 if (!worktreeCleanupEnabled(settings)) continue;
608 const worktreePath = path.resolve(thread.worktreePath!);
609 const group = groups.get(worktreePath) ?? [];
610 const activityAt = Math.max(...group.map(storageCleanupActivityAt));
611 const deleted = "workspaceRoot" in thread;
612 const project = deleted
613 ? { workspaceRoot: thread.workspaceRoot }
614 : snapshot.projects.find((entry) => entry.id === thread.projectId);
615 const entry: StorageCleanupReportEntry = {
616 kind: "worktree",
617 outcome: "kept",
618 reason: "",
619 path: worktreePath,
620 projectPath: project?.workspaceRoot ?? null,
621 threadId: thread.id,
622 threadTitle: thread.title,
623 bytes: null,
624 files: null,
625 };
626 const keep = (reason: string) => entries.push({ ...entry, reason: sentence(reason) });
627 yield* Effect.gen(function* () {
628 if (!(yield* fs.exists(worktreePath))) return;
629 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
630 if (group.length > 1 && worktreeOwner(group) === undefined)
631 return keep(`shared by ${group.length} threads`);
632 if (project === undefined) return keep("project is unavailable");
633 if (
634 thread.branch === null ||
635 (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
636 )
637 return keep("thread is running or has pending work");
638 if (group.some((member) => member.branch !== thread.branch))
639 return keep("a subagent thread's branch differs from this worktree's branch");
640 if (hasTerminal(worktreePath)) return keep("open terminal");
641 // Roots are canonical, so compare canonical paths. A symlinked parent
642 // (a linked drive) is fine; a symlinked worktree directory is not.
643 const realPath = yield* fs.realPath(worktreePath);
644 const realParent = yield* fs.realPath(path.dirname(worktreePath));
645 if (realPath !== path.join(realParent, path.basename(worktreePath)))
646 return keep("worktree is a symbolic link");
647 if (!roots.some((root) => inside(root, realPath)))
648 return keep("outside the managed worktree folder");
649 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
650 return keep("contains a project checkout");
651 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
652 return keep("not a linked worktree");
653 if (yield* branchChanged(worktreePath, thread.branch))
654 return keep("repository or branch changed");
655 const changes = yield* localChangesReason(worktreePath, settings);
656 if (changes !== null) return keep(changes);
657 if (
658 !deleted &&
659 group.some(
660 (member) =>
661 member.settledAt !== null &&
662 now - Math.max(DateTime.toEpochMillis(member.updatedAt), activityAt) <
663 SETTLE_SCRIPT_GRACE_MS,
664 )
665 )
666 return keep("settled moments ago");
667 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
668 const old =
669 !deleted &&
670 settings.worktreeAfterDays !== null &&
671 activityAt < now - settings.worktreeAfterDays * DAY_MS;
672 const settledFor =
673 deleted || thread.settledAt === null
674 ? null
675 : now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
676 const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
677 const settled =
678 settledFor !== null &&
679 settings.worktreeSettledAfterDays !== null &&
680 settledFor >= settings.worktreeSettledAfterDays * DAY_MS;
681 let eligible = deleted || old || settled;
682 let removalReason = deleted
683 ? "thread was deleted"
684 : old
685 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
686 : `settled for ${settledDays} days`;
687 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
688 const repositoryCwd = path.resolve(project.workspaceRoot);
689 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
690 const defaultBranchKey = `${repositoryCwd}\0${remote}`;
691 let branch = defaultBranches.get(defaultBranchKey);
692 if (branch === undefined) {
693 branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
694 // Without a local HEAD ref, only the remote can identify its default;
695 // a conventional name may be a feature branch.
696 if (branch === null) {
697 branch = yield* git
698 .execute({
699 operation: "StorageCleanup.resolveDefaultBranch",
700 cwd: repositoryCwd,
701 args: ["ls-remote", "--symref", "--", remote, "HEAD"],
702 timeoutMs: 20_000,
703 })
704 .pipe(
705 Effect.map(
706 (result) =>
707 /^ref: refs\/heads\/(.+)\tHEAD\r?$/m.exec(result.stdout)?.[1] ?? null,
708 ),
709 Effect.orElseSucceed(() => null),
710 );
711 }
712 defaultBranches.set(defaultBranchKey, branch);
713 }
714 if (branch === null) return keep("default branch is unavailable");
715 const defaultRef = `refs/remotes/${remote}/${branch}`;
716 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
717 if (!refreshed.has(defaultRef)) {
718 yield* git.fetchRemoteTrackingBranch({
719 cwd: repositoryCwd,
720 remoteName: remote,
721 remoteBranch: branch,
722 });
723 refreshed.add(defaultRef);
724 refreshedDefaultRefs.set(repositoryCwd, refreshed);
725 }
726 const base = yield* git.resolveCommit({
727 cwd: worktreePath,
728 revision: defaultRef,
729 });
730 const ancestor = yield* git.execute({
731 operation: "StorageCleanup.integratedBranch",
732 cwd: worktreePath,
733 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
734 allowNonZeroExit: true,
735 });
736 const integrated = ancestor.exitCode === 0;
737 eligible = integrated && settings.worktreeUnchanged;
738 if (eligible) removalReason = "no commits beyond the default branch";
739 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
740 const pullRequest = yield* gitManager.branchPullRequest(
741 { cwd: worktreePath, branch: thread.branch },
742 { refresh: true },
743 );
744 eligible = storageCleanupPullRequestMerged(pullRequest, {
745 branch: thread.branch,
746 defaultBranch: branch,
747 headSha: head.commitSha,
748 integrated,
749 });
750 if (eligible) removalReason = "pull request was merged";
751 }
752 }
753 if (!eligible)
754 return keep(
755 !deleted && settings.worktreeAfterDays !== null
756 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
757 : settings.worktreeSettledAfterDays !== null
758 ? settledFor === null
759 ? "not settled"
760 : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days`
761 : settings.worktreeOnMerge
762 ? "not merged"
763 : "has commits beyond the default branch",
764 );
765 // Threads, queued deletion work and provider sessions as they are now, so a
766 // queued turn, resumed session or new thread sharing this path cancels
767 // the removal. Read only this path's threads: a full snapshot per
768 // worktree takes seconds on large databases.
769 const blockedSinceCheck = Effect.fnUntraced(function* () {
770 const latestProjects = yield* projectStore.listShells();
771 if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects]))
772 return "contains a project checkout";
773 const latest = (yield* projections.getThreadWorktreePaths({
774 includeArchived: true,
775 })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath);
776 if (hasTerminal(worktreePath)) return "open terminal";
777 if (deleted) {
778 if (
779 latest.length > 0 ||
780 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
781 .worktreeOnDelete
782 )
783 return "thread or cleanup settings changed since check";
784 // V2 deletion queues durable cleanup. Do not remove its checkout until
785 // every effect has finished successfully or was explicitly cancelled.
786 const pendingCleanup = yield* sql`
787 SELECT 1 FROM orchestration_v2_effect_outbox
788 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
789 `;
790 if (pendingCleanup.length > 0) return "thread deletion is still pending";
791 } else {
792 const latestShells = yield* Effect.forEach(latest, (entry) =>
793 projections.getThreadShell(entry.threadId),
794 );
795 const latestGroup = latestShells.filter((shell) => shell !== null);
796 const latestOwner = worktreeOwner(latestGroup);
797 if (
798 latestGroup.length !== group.length ||
799 latestOwner?.id !== thread.id ||
800 latestOwner?.branch !== thread.branch ||
801 latestGroup.some((shell) => {
802 const previous = group.find((member) => member.id === shell.id);
803 return (
804 previous === undefined ||
805 shell.branch !== thread.branch ||
806 !Equal.equals(shell.settledAt, previous.settledAt) ||
807 (shell.settledAt !== null &&
808 !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
809 !storageCleanupThreadIdle(shell, now) ||
810 path.resolve(shell.worktreePath!) !== worktreePath ||
811 storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
812 );
813 })
814 )
815 return "thread activity or shared worktree changed since check";
816 }
817 // Sessions can outlive their run and can be shared across app threads.
818 const sessionRows = yield* sql<{ payload_json: string }>`
819 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
820 WHERE status != 'stopped'
821 `;
822 const sessions = yield* Effect.forEach(sessionRows, (row) =>
823 decodeCleanupSession(row.payload_json),
824 );
825 // A stored session can stay ready after its runtime was released,
826 // for example once every thread detached; only a live one holds it.
827 for (const session of sessions) {
828 const cwd = path.resolve(session.cwd);
829 if (
830 (cwd === worktreePath || inside(worktreePath, cwd)) &&
831 (yield* providerSessions.isLive(session.id))
832 )
833 return "provider session is still open";
834 }
835 return null;
836 });
837 const blocked = yield* blockedSinceCheck();
838 if (blocked !== null) return keep(blocked);
839 const bytes = yield* measureWorktree(worktreePath);
840 const blockedWhileMeasuring = yield* blockedSinceCheck();
841 if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring);
842 if (yield* branchChanged(worktreePath, thread.branch))
843 return keep("repository or branch changed since check");
844 if (
845 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
846 head.commitSha
847 )
848 return keep("commit changed since check");
849 const finalChanges = yield* localChangesReason(worktreePath, settings);
850 if (finalChanges !== null) return keep(finalChanges);
851 const current = resolveWorktreeCleanup(
852 yield* settingsService.getSettings,
853 thread.projectId,
854 );
855 if (
856 Object.keys(settings).some(
857 (key) =>
858 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
859 )
860 )
861 return keep("settings changed since check");
862 // Clean only untracked files; Git must still refuse removal if a tracked
863 // edit arrives after our last status check.
864 if (settings.worktreeKeepWhen === "tracked-changes")
865 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
866 yield* cleanupGit(
867 project.workspaceRoot,
868 ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", "--", worktreePath],
869 "git worktree remove",
870 );
871 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
872 yield* gitManager.invalidateStatus(project.workspaceRoot);
873 // Preserve branch and path: ProviderTurnStartService recreates the checkout
874 // from that branch when the thread is resumed.
875 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
876 }).pipe(
877 (effect) => withWorkspaceLease(worktreePath, effect),
878 Effect.catch((error) =>
879 Effect.gen(function* () {
880 entries.push({
881 ...entry,
882 outcome: "failed",
883 reason: cleanupFailureReason(error),
884 });
885 yield* Effect.logWarning("storage cleanup failed for worktree", {
886 threadId: thread.id,
887 error,
888 });
889 }),
890 ),
891 );
892 }
893 yield* reportOrphanWorktrees(
894 roots,
895 yield* projectStore.list({ includeDeleted: true }),
896 entries,
897 );
898 });
899
900 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
901 root: string,
902 days: number | null,
903 now: number,
904 rotatedLogs: boolean,
905 removed: { files: number; bytes: number },
906 ) {
907 if (days === null || !(yield* fs.exists(root))) return removed;
908 const realRoot = yield* fs.realPath(root);
909 if (realRoot !== path.resolve(root)) return removed;
910 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
911 directory: string,
912 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
913 for (const name of yield* fs.readDirectory(directory)) {
914 const target = path.join(directory, name);
915 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
916 const stat = yield* fs.stat(target);
917 if (stat.type === "Directory" && rotatedLogs) {
918 yield* visit(target);
919 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
920 const modified = Option.getOrNull(stat.mtime);
921 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
922 const current = (yield* settingsService.getSettings).storageCleanup;
923 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
924 return;
925 yield* fs.remove(target);
926 removed.files++;
927 removed.bytes += Number(stat.size);
928 }
929 }
930 }
931 });
932 yield* visit(realRoot);
933 return removed;
934 });
935
936 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
937 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
938 trigger: StorageCleanupReport["trigger"],
939 ) {
940 const now = yield* Clock.currentTimeMillis;
941 const serverSettings = yield* settingsService.getSettings;
942 const settings = serverSettings.storageCleanup;
943 const entries: StorageCleanupReportEntry[] = [];
944 yield* cleanWorktrees(serverSettings, now, entries).pipe(
945 Effect.catch((error) =>
946 Effect.gen(function* () {
947 entries.push({
948 kind: "worktree",
949 outcome: "failed",
950 reason: cleanupFailureReason(error),
951 path: null,
952 projectPath: null,
953 threadId: null,
954 threadTitle: null,
955 bytes: null,
956 files: null,
957 });
958 yield* Effect.logWarning("worktree cleanup failed", { error });
959 }),
960 ),
961 );
962 for (const category of [
963 {
964 kind: "browser-artifacts" as const,
965 root: config.browserArtifactsDir,
966 days: settings.browserArtifactsAfterDays,
967 label: "browser artifacts",
968 },
969 {
970 kind: "logs" as const,
971 root: config.logsDir,
972 days: settings.logsAfterDays,
973 label: "rotated logs",
974 },
975 ]) {
976 if (category.days === null) continue;
977 const removed = { files: 0, bytes: 0 };
978 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
979 Effect.map(({ files, bytes }) =>
980 entries.push({
981 kind: category.kind,
982 outcome: files > 0 ? "removed" : "kept",
983 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
984 path: null,
985 projectPath: null,
986 threadId: null,
987 threadTitle: null,
988 bytes: files > 0 ? bytes : null,
989 files: files > 0 ? files : null,
990 }),
991 ),
992 Effect.catch((error) =>
993 Effect.gen(function* () {
994 entries.push({
995 kind: category.kind,
996 outcome: "failed",
997 reason: cleanupFailureReason(error),
998 path: null,
999 projectPath: null,
1000 threadId: null,
1001 threadTitle: null,
1002 bytes: removed.files > 0 ? removed.bytes : null,
1003 files: removed.files > 0 ? removed.files : null,
1004 });
1005 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
1006 }),
1007 ),
1008 );
1009 }
1010 const counts = { removed: 0, kept: 0, failed: 0 };
1011 let bytesFreed = 0;
1012 for (const entry of entries) {
1013 counts[entry.outcome]++;
1014 if (entry.outcome !== "kept") bytesFreed += entry.bytes ?? 0;
1015 }
1016 const priority = (entry: StorageCleanupReportEntry) =>
1017 entry.outcome === "failed"
1018 ? 0
1019 : entry.outcome === "removed"
1020 ? 1
1021 : entry.kind === "worktree" && entry.threadId === null
1022 ? 2
1023 : 3;
1024 const latestReport: StorageCleanupReport = {
1025 trigger,
1026 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
1027 finishedAt: DateTime.formatIso(yield* DateTime.now),
1028 entries: entries.sort((a, b) => priority(a) - priority(b)).slice(0, REPORT_ENTRY_LIMIT),
1029 counts,
1030 bytesFreed,
1031 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
1032 };
1033 yield* SubscriptionRef.set(reportRef, latestReport);
1034 return latestReport;
1035 });
1036 const automaticSweepQueued = yield* Ref.make(false);
1037 const worker = yield* makeDrainableWorker(
1038 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
1039 (completion === undefined ? Ref.set(automaticSweepQueued, false) : Effect.void).pipe(
1040 Effect.andThen(sweep(completion === undefined ? "automatic" : "manual")),
1041 Effect.exit,
1042 Effect.flatMap((exit) =>
1043 completion === undefined
1044 ? exit.pipe(
1045 Effect.asVoid,
1046 Effect.catchCause((cause) =>
1047 Effect.logWarning("storage cleanup failed", { cause }),
1048 ),
1049 )
1050 : Deferred.done(completion, exit).pipe(Effect.asVoid),
1051 ),
1052 ),
1053 );
1054 const requestSweep = Ref.getAndSet(automaticSweepQueued, true).pipe(
1055 Effect.flatMap((queued) => (queued ? Effect.void : worker.enqueue(undefined))),
1056 );
1057 const runNow = Effect.gen(function* () {
1058 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
1059 yield* worker.enqueue(completion);
1060 return yield* Deferred.await(completion);
1061 });
1062
1063 const start = Effect.fn("StorageCleanup.start")(function* () {
1064 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
1065 Effect.sync(() => {
1066 if (event.type === "snapshot") {
1067 liveTerminals.clear();
1068 for (const terminal of event.terminals) noteTerminal(terminal);
1069 } else if (event.type === "upsert") {
1070 noteTerminal(event.terminal);
1071 } else {
1072 const threadTerminals = liveTerminals.get(event.threadId);
1073 threadTerminals?.delete(event.terminalId);
1074 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
1075 }
1076 }),
1077 );
1078 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1079 const changes = yield* settingsService.subscribeChanges;
1080 const events = engine.streamDomainEvents;
1081 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
1082 yield* forkParked(
1083 requestSweep.pipe(
1084 Effect.andThen(worker.drain),
1085 Effect.repeat(Schedule.spaced("1 hour")),
1086 Effect.asVoid,
1087 ),
1088 );
1089 yield* forkParked(
1090 Stream.runForEach(changes, (settings) => {
1091 if (
1092 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
1093 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
1094 sameProjectWorktreePolicies(settings, lastSettings)
1095 )
1096 return Effect.void;
1097 lastSettings = settings;
1098 return requestSweep;
1099 }),
1100 );
1101 yield* forkParked(
1102 Stream.runForEach(events, (event) =>
1103 (event.type === "thread.deleted" ||
1104 (event.type === "provider-session.updated" &&
1105 (event.payload.status === "stopped" || event.payload.status === "error"))) &&
1106 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
1107 ? requestSweep
1108 : Effect.void,
1109 ).pipe(
1110 Effect.catchCause((cause) =>
1111 Effect.logWarning("Storage cleanup event stream failed", { cause }),
1112 ),
1113 ),
1114 );
1115 });
1116 yield* start();
1117 return StorageCleanup.of({
1118 runNow,
1119 latestReport: SubscriptionRef.get(reportRef),
1120 reports: SubscriptionRef.changes(reportRef),
1121 drain: worker.drain,
1122 });
1123});
1124
1125export const layer = Layer.effect(StorageCleanup, make);