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