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