Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

storageCleanup.ts

1,120 lines45.5 KB

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);
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 );
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 );
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 );
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 );
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;
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 );
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 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 defaultBranches = new Map<string, string | null>();
596 const groups = Map.groupBy(
597 snapshot.threads.filter((thread) => thread.worktreePath !== null),
598 (thread) => path.resolve(thread.worktreePath!),
599 );
600 const candidates = [
601 ...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!),
602 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
603 ];
604 for (const thread of candidates) {
605 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
606 if (!worktreeCleanupEnabled(settings)) continue;
607 const worktreePath = path.resolve(thread.worktreePath!);
608 const group = groups.get(worktreePath) ?? [];
609 const activityAt = Math.max(...group.map(storageCleanupActivityAt));
610 const deleted = "workspaceRoot" in thread;
611 const project = deleted
612 ? { workspaceRoot: thread.workspaceRoot }
613 : snapshot.projects.find((entry) => entry.id === thread.projectId);
614 const entry: StorageCleanupReportEntry = {
615 kind: "worktree",
616 outcome: "kept",
617 reason: "",
618 path: worktreePath,
619 threadId: thread.id,
620 threadTitle: thread.title,
621 bytes: null,
622 files: null,
623 };
624 const keep = (reason: string) => entries.push({ ...entry, reason: sentence(reason) });
625 yield* Effect.gen(function* () {
626 if (!(yield* fs.exists(worktreePath))) return;
627 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
628 if (group.length > 1 && worktreeOwner(group) === undefined)
629 return keep(`shared by ${group.length} threads`);
630 if (project === undefined) return keep("project is unavailable");
631 if (
632 thread.branch === null ||
633 (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
634 )
635 return keep("thread is running or has pending work");
636 if (group.some((member) => member.branch !== thread.branch))
637 return keep("a subagent thread's branch differs from this worktree's branch");
638 if (hasTerminal(worktreePath)) return keep("open terminal");
639 // Roots are canonical, so compare canonical paths. A symlinked parent
640 // (a linked drive) is fine; a symlinked worktree directory is not.
641 const realPath = yield* fs.realPath(worktreePath);
642 const realParent = yield* fs.realPath(path.dirname(worktreePath));
643 if (realPath !== path.join(realParent, path.basename(worktreePath)))
644 return keep("worktree is a symbolic link");
645 if (!roots.some((root) => inside(root, realPath)))
646 return keep("outside the managed worktree folder");
647 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
648 return keep("contains a project checkout");
649 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
650 return keep("not a linked worktree");
651 if (yield* branchChanged(worktreePath, thread.branch))
652 return keep("repository or branch changed");
653 const changes = yield* localChangesReason(worktreePath, settings);
654 if (changes !== null) return keep(changes);
655 if (
656 !deleted &&
657 group.some(
658 (member) =>
659 member.settledAt !== null &&
660 now - Math.max(DateTime.toEpochMillis(member.updatedAt), activityAt) <
661 SETTLE_SCRIPT_GRACE_MS,
662 )
663 )
664 return keep("settled moments ago");
665 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
666 const old =
667 !deleted &&
668 settings.worktreeAfterDays !== null &&
669 activityAt < now - settings.worktreeAfterDays * DAY_MS;
670 const settledFor =
671 deleted || thread.settledAt === null
672 ? null
673 : now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
674 const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
675 const settled =
676 settledFor !== null &&
677 settings.worktreeSettledAfterDays !== null &&
678 settledFor >= settings.worktreeSettledAfterDays * DAY_MS;
679 let eligible = deleted || old || settled;
680 let removalReason = deleted
681 ? "thread was deleted"
682 : old
683 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
684 : `settled for ${settledDays} days`;
685 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
686 const repositoryCwd = path.resolve(project.workspaceRoot);
687 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
688 const defaultBranchKey = `${repositoryCwd}\0${remote}`;
689 let branch = defaultBranches.get(defaultBranchKey);
690 if (branch === undefined) {
691 branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
692 // Without a local HEAD ref, only the remote can identify its default;
693 // a conventional name may be a feature branch.
694 if (branch === null) {
695 branch = yield* git
696 .execute({
697 operation: "StorageCleanup.resolveDefaultBranch",
698 cwd: repositoryCwd,
699 args: ["ls-remote", "--symref", "--", remote, "HEAD"],
700 timeoutMs: 20_000,
701 })
702 .pipe(
703 Effect.map(
704 (result) =>
705 /^ref: refs\/heads\/(.+)\tHEAD\r?$/m.exec(result.stdout)?.[1] ?? null,
706 ),
707 Effect.orElseSucceed(() => null),
708 );
709 }
710 defaultBranches.set(defaultBranchKey, branch);
711 }
712 if (branch === null) return keep("default branch is unavailable");
713 const defaultRef = `refs/remotes/${remote}/${branch}`;
714 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
715 if (!refreshed.has(defaultRef)) {
716 yield* git.fetchRemoteTrackingBranch({
717 cwd: repositoryCwd,
718 remoteName: remote,
719 remoteBranch: branch,
720 });
721 refreshed.add(defaultRef);
722 refreshedDefaultRefs.set(repositoryCwd, refreshed);
723 }
724 const base = yield* git.resolveCommit({
725 cwd: worktreePath,
726 revision: defaultRef,
727 });
728 const ancestor = yield* git.execute({
729 operation: "StorageCleanup.integratedBranch",
730 cwd: worktreePath,
731 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
732 allowNonZeroExit: true,
733 });
734 const integrated = ancestor.exitCode === 0;
735 eligible = integrated && settings.worktreeUnchanged;
736 if (eligible) removalReason = "no commits beyond the default branch";
737 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
738 const pullRequest = yield* gitManager.branchPullRequest(
739 { cwd: worktreePath, branch: thread.branch },
740 { refresh: true },
741 );
742 eligible = storageCleanupPullRequestMerged(pullRequest, {
743 branch: thread.branch,
744 defaultBranch: branch,
745 headSha: head.commitSha,
746 integrated,
747 });
748 if (eligible) removalReason = "pull request was merged";
749 }
750 }
751 if (!eligible)
752 return keep(
753 !deleted && settings.worktreeAfterDays !== null
754 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
755 : settings.worktreeSettledAfterDays !== null
756 ? settledFor === null
757 ? "not settled"
758 : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days`
759 : settings.worktreeOnMerge
760 ? "not merged"
761 : "has commits beyond the default branch",
762 );
763 // Threads, queued deletion work and provider sessions as they are now, so a
764 // queued turn, resumed session or new thread sharing this path cancels
765 // the removal. Read only this path's threads: a full snapshot per
766 // worktree takes seconds on large databases.
767 const blockedSinceCheck = Effect.fnUntraced(function* () {
768 const latestProjects = yield* projectStore.listShells();
769 if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects]))
770 return "contains a project checkout";
771 const latest = (yield* projections.getThreadWorktreePaths({
772 includeArchived: true,
773 })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath);
774 if (hasTerminal(worktreePath)) return "open terminal";
775 if (deleted) {
776 if (
777 latest.length > 0 ||
778 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
779 .worktreeOnDelete
780 )
781 return "thread or cleanup settings changed since check";
782 // V2 deletion queues durable cleanup. Do not remove its checkout until
783 // every effect has finished successfully or was explicitly cancelled.
784 const pendingCleanup = yield* sql`
785 SELECT 1 FROM orchestration_v2_effect_outbox
786 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
787 `;
788 if (pendingCleanup.length > 0) return "thread deletion is still pending";
789 } else {
790 const latestShells = yield* Effect.forEach(latest, (entry) =>
791 projections.getThreadShell(entry.threadId),
792 );
793 const latestGroup = latestShells.filter((shell) => shell !== null);
794 const latestOwner = worktreeOwner(latestGroup);
795 if (
796 latestGroup.length !== group.length ||
797 latestOwner?.id !== thread.id ||
798 latestOwner?.branch !== thread.branch ||
799 latestGroup.some((shell) => {
800 const previous = group.find((member) => member.id === shell.id);
801 return (
802 previous === undefined ||
803 shell.branch !== thread.branch ||
804 !Equal.equals(shell.settledAt, previous.settledAt) ||
805 (shell.settledAt !== null &&
806 !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
807 !storageCleanupThreadIdle(shell, now) ||
808 path.resolve(shell.worktreePath!) !== worktreePath ||
809 storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
810 );
811 })
812 )
813 return "thread activity or shared worktree changed since check";
814 }
815 // Sessions can outlive their run and can be shared across app threads.
816 const sessionRows = yield* sql<{ payload_json: string }>`
817 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
818 WHERE status != 'stopped'
819 `;
820 const sessions = yield* Effect.forEach(sessionRows, (row) =>
821 decodeCleanupSession(row.payload_json),
822 );
823 // A stored session can stay ready after its runtime was released,
824 // for example once every thread detached; only a live one holds it.
825 for (const session of sessions) {
826 const cwd = path.resolve(session.cwd);
827 if (
828 (cwd === worktreePath || inside(worktreePath, cwd)) &&
829 (yield* providerSessions.isLive(session.id))
830 )
831 return "provider session is still open";
832 }
833 return null;
834 });
835 const blocked = yield* blockedSinceCheck();
836 if (blocked !== null) return keep(blocked);
837 const bytes = yield* measureWorktree(worktreePath);
838 const blockedWhileMeasuring = yield* blockedSinceCheck();
839 if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring);
840 if (yield* branchChanged(worktreePath, thread.branch))
841 return keep("repository or branch changed since check");
842 if (
843 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
844 head.commitSha
845 )
846 return keep("commit changed since check");
847 const finalChanges = yield* localChangesReason(worktreePath, settings);
848 if (finalChanges !== null) return keep(finalChanges);
849 const current = resolveWorktreeCleanup(
850 yield* settingsService.getSettings,
851 thread.projectId,
852 );
853 if (
854 Object.keys(settings).some(
855 (key) =>
856 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
857 )
858 )
859 return keep("settings changed since check");
860 // Clean only untracked files; Git must still refuse removal if a tracked
861 // edit arrives after our last status check.
862 if (settings.worktreeKeepWhen === "tracked-changes")
863 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
864 yield* cleanupGit(
865 project.workspaceRoot,
866 ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", "--", worktreePath],
867 "git worktree remove",
868 );
869 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
870 yield* gitManager.invalidateStatus(project.workspaceRoot);
871 // Preserve branch and path: ProviderTurnStartService recreates the checkout
872 // from that branch when the thread is resumed.
873 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
874 }).pipe(
875 (effect) => withWorkspaceLease(worktreePath, effect),
876 Effect.catch((error) =>
877 Effect.gen(function* () {
878 entries.push({
879 ...entry,
880 outcome: "failed",
881 reason: cleanupFailureReason(error),
882 });
883 yield* Effect.logWarning("storage cleanup failed for worktree", {
884 threadId: thread.id,
885 error,
886 });
887 }),
888 ),
889 );
890 }
891 yield* reportOrphanWorktrees(
892 roots,
893 yield* projectStore.list({ includeDeleted: true }),
894 entries,
895 );
896 });
897​
898 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
899 root: string,
900 days: number | null,
901 now: number,
902 rotatedLogs: boolean,
903 removed: { files: number; bytes: number },
904 ) {
905 if (days === null || !(yield* fs.exists(root))) return removed;
906 const realRoot = yield* fs.realPath(root);
907 if (realRoot !== path.resolve(root)) return removed;
908 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
909 directory: string,
910 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
911 for (const name of yield* fs.readDirectory(directory)) {
912 const target = path.join(directory, name);
913 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
914 const stat = yield* fs.stat(target);
915 if (stat.type === "Directory" && rotatedLogs) {
916 yield* visit(target);
917 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
918 const modified = Option.getOrNull(stat.mtime);
919 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
920 const current = (yield* settingsService.getSettings).storageCleanup;
921 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
922 return;
923 yield* fs.remove(target);
924 removed.files++;
925 removed.bytes += Number(stat.size);
926 }
927 }
928 }
929 });
930 yield* visit(realRoot);
931 return removed;
932 });
933​
934 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
935 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
936 trigger: StorageCleanupReport["trigger"],
937 ) {
938 const now = yield* Clock.currentTimeMillis;
939 const serverSettings = yield* settingsService.getSettings;
940 const settings = serverSettings.storageCleanup;
941 const entries: StorageCleanupReportEntry[] = [];
942 yield* cleanWorktrees(serverSettings, now, entries).pipe(
943 Effect.catch((error) =>
944 Effect.gen(function* () {
945 entries.push({
946 kind: "worktree",
947 outcome: "failed",
948 reason: cleanupFailureReason(error),
949 path: null,
950 threadId: null,
951 threadTitle: null,
952 bytes: null,
953 files: null,
954 });
955 yield* Effect.logWarning("worktree cleanup failed", { error });
956 }),
957 ),
958 );
959 for (const category of [
960 {
961 kind: "browser-artifacts" as const,
962 root: config.browserArtifactsDir,
963 days: settings.browserArtifactsAfterDays,
964 label: "browser artifacts",
965 },
966 {
967 kind: "logs" as const,
968 root: config.logsDir,
969 days: settings.logsAfterDays,
970 label: "rotated logs",
971 },
972 ]) {
973 if (category.days === null) continue;
974 const removed = { files: 0, bytes: 0 };
975 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
976 Effect.map(({ files, bytes }) =>
977 entries.push({
978 kind: category.kind,
979 outcome: files > 0 ? "removed" : "kept",
980 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
981 path: null,
982 threadId: null,
983 threadTitle: null,
984 bytes: files > 0 ? bytes : null,
985 files: files > 0 ? files : null,
986 }),
987 ),
988 Effect.catch((error) =>
989 Effect.gen(function* () {
990 entries.push({
991 kind: category.kind,
992 outcome: "failed",
993 reason: cleanupFailureReason(error),
994 path: null,
995 threadId: null,
996 threadTitle: null,
997 bytes: removed.files > 0 ? removed.bytes : null,
998 files: removed.files > 0 ? removed.files : null,
999 });
1000 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
1001 }),
1002 ),
1003 );
1005 const counts = { removed: 0, kept: 0, failed: 0 };
1006 let bytesFreed = 0;
1007 for (const entry of entries) {
1008 counts[entry.outcome]++;
1009 if (entry.outcome !== "kept") bytesFreed += entry.bytes ?? 0;
1011 const priority = (entry: StorageCleanupReportEntry) =>
1012 entry.outcome === "failed"
1013 ? 0
1014 : entry.outcome === "removed"
1015 ? 1
1016 : entry.kind === "worktree" && entry.threadId === null
1017 ? 2
1018 : 3;
1019 const latestReport: StorageCleanupReport = {
1020 trigger,
1021 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
1022 finishedAt: DateTime.formatIso(yield* DateTime.now),
1023 entries: entries.sort((a, b) => priority(a) - priority(b)).slice(0, REPORT_ENTRY_LIMIT),
1024 counts,
1025 bytesFreed,
1026 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
1027 };
1028 yield* SubscriptionRef.set(reportRef, latestReport);
1029 return latestReport;
1030 });
1031 const automaticSweepQueued = yield* Ref.make(false);
1032 const worker = yield* makeDrainableWorker(
1033 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
1034 (completion === undefined ? Ref.set(automaticSweepQueued, false) : Effect.void).pipe(
1035 Effect.andThen(sweep(completion === undefined ? "automatic" : "manual")),
1036 Effect.exit,
1037 Effect.flatMap((exit) =>
1038 completion === undefined
1039 ? exit.pipe(
1040 Effect.asVoid,
1041 Effect.catchCause((cause) =>
1042 Effect.logWarning("storage cleanup failed", { cause }),
1043 ),
1045 : Deferred.done(completion, exit).pipe(Effect.asVoid),
1046 ),
1047 ),
1048 );
1049 const requestSweep = Ref.getAndSet(automaticSweepQueued, true).pipe(
1050 Effect.flatMap((queued) => (queued ? Effect.void : worker.enqueue(undefined))),
1051 );
1052 const runNow = Effect.gen(function* () {
1053 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
1054 yield* worker.enqueue(completion);
1055 return yield* Deferred.await(completion);
1056 });
1057​
1058 const start = Effect.fn("StorageCleanup.start")(function* () {
1059 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
1060 Effect.sync(() => {
1061 if (event.type === "snapshot") {
1062 liveTerminals.clear();
1063 for (const terminal of event.terminals) noteTerminal(terminal);
1064 } else if (event.type === "upsert") {
1065 noteTerminal(event.terminal);
1066 } else {
1067 const threadTerminals = liveTerminals.get(event.threadId);
1068 threadTerminals?.delete(event.terminalId);
1069 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
1071 }),
1072 );
1073 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1074 const changes = yield* settingsService.subscribeChanges;
1075 const events = engine.streamDomainEvents;
1076 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
1077 yield* forkParked(
1078 requestSweep.pipe(
1079 Effect.andThen(worker.drain),
1080 Effect.repeat(Schedule.spaced("1 hour")),
1081 Effect.asVoid,
1082 ),
1083 );
1084 yield* forkParked(
1085 Stream.runForEach(changes, (settings) => {
1086 if (
1087 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
1088 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
1089 sameProjectWorktreePolicies(settings, lastSettings)
1091 return Effect.void;
1092 lastSettings = settings;
1093 return requestSweep;
1094 }),
1095 );
1096 yield* forkParked(
1097 Stream.runForEach(events, (event) =>
1098 (event.type === "thread.deleted" ||
1099 (event.type === "provider-session.updated" &&
1100 (event.payload.status === "stopped" || event.payload.status === "error"))) &&
1101 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
1102 ? requestSweep
1103 : Effect.void,
1104 ).pipe(
1105 Effect.catchCause((cause) =>
1106 Effect.logWarning("Storage cleanup event stream failed", { cause }),
1107 ),
1108 ),
1109 );
1110 });
1111 yield* start();
1112 return StorageCleanup.of({
1113 runNow,
1114 latestReport: SubscriptionRef.get(reportRef),
1115 reports: SubscriptionRef.changes(reportRef),
1116 drain: worker.drain,
1117 });
1118});
1119​
1120export const layer = Layer.effect(StorageCleanup, make);