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

storageCleanup.ts

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