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))
709 return { waiting: false, kept: [] };
710 let waiting = false;
711 const kept: string[] = [];
712 const roots: Array<string> = [];
713 for (const directory of managedWorktreesDirectories(
714 serverSettings,
715 config.worktreesDir,
716 path,
717 yield* HostProcess.HomeDirectory,
718 )) {
719 const root = yield* fs.exists(directory).pipe(
720 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
721 Effect.orElseSucceed(() => null),
722 );
723 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
724 }
725 const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
726 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
727 FROM orchestration_v2_projection_threads t
728 JOIN projection_projects p ON p.project_id = t.project_id
729 WHERE t.deleted_at IS NOT NULL
730 `.pipe(NodeSqliteClient.readOnly);
731 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
732 decodeCleanupThread(row.payload_json).pipe(
733 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
734 ),
735 )).filter((thread) => thread.worktreePath !== null && thread.branch !== null);
736 const snapshot = yield* readThreads();
737 const refreshedDefaultRefs = new Map<string, Set<string>>();
738 const defaultBranches = new Map<string, string | null>();
739 const groups = Map.groupBy(
740 snapshot.threads.filter((thread) => thread.worktreePath !== null),
741 (thread) => path.resolve(thread.worktreePath!),
742 );
743 const deletedByPath = Map.groupBy(deletedThreads, (thread) =>
744 path.resolve(thread.worktreePath!),
745 );
746 const candidates = [
747 ...[...groups].map(
748 ([worktreePath, group]) =>
749 // A deleted thread still owns the worktree its remaining subagents share,
750 // but only deletion cleanup acts on it; otherwise the live rules apply.
751 deletedByPath
752 .get(worktreePath)
753 ?.find(
754 (deleted) =>
755 resolveWorktreeCleanup(serverSettings, deleted.projectId).worktreeOnDelete &&
756 worktreeOwner([deleted, ...group]) === deleted,
757 ) ??
758 worktreeOwner(group) ??
759 group[0]!,
760 ),
761 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
762 ];
763 for (const thread of candidates) {
764 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
765 if (!worktreeCleanupEnabled(settings)) continue;
766 const worktreePath = path.resolve(thread.worktreePath!);
767 const group = groups.get(worktreePath) ?? [];
768 const activityAt = Math.max(...group.map(storageCleanupActivityAt));
769 const deleted = "workspaceRoot" in thread;
770 const members = deleted ? [thread, ...group] : group;
771 const project = deleted
772 ? { workspaceRoot: thread.workspaceRoot }
773 : snapshot.projects.find((entry) => entry.id === thread.projectId);
774 const entry: StorageCleanupReportEntry = {
775 kind: "worktree",
776 outcome: "kept",
777 reason: "",
778 path: worktreePath,
779 projectPath: project?.workspaceRoot ?? null,
780 threadId: thread.id,
781 threadTitle: thread.title,
782 bytes: null,
783 files: null,
784 };
785 const keep = (reason: string) => {
786 if (deleted && settings.worktreeOnDelete) kept.push(worktreePath);
787 entries.push({ ...entry, reason: sentence(reason) });
788 };
789 // Reasons a provider session stop or finished deletion work can clear.
790 const waitForStop = (reason: string) => {
791 if (deleted && settings.worktreeOnDelete) waiting = true;
792 return reason;
793 };
794 yield* Effect.gen(function* () {
795 if (!(yield* fs.exists(worktreePath))) return;
796 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
797 if (members.length > 1 && worktreeOwner(members) === undefined)
798 return keep(`shared by ${members.length} threads`);
799 if (project === undefined) return keep("project is unavailable");
800 if (
801 thread.branch === null ||
802 !group.every((member) => storageCleanupThreadIdle(member, now))
803 )
804 return keep(waitForStop("thread is running or has pending work"));
805 if (group.some((member) => member.branch !== thread.branch))
806 return keep("a subagent thread's branch differs from this worktree's branch");
807 if (hasTerminal(worktreePath)) return keep(waitForStop("open terminal"));
808 // Compare canonical roots while allowing symlinked parents, never symlinked worktree directories.
809 const realPath = yield* fs.realPath(worktreePath);
810 const realParent = yield* fs.realPath(path.dirname(worktreePath));
811 if (realPath !== path.join(realParent, path.basename(worktreePath)))
812 return keep("worktree is a symbolic link");
813 if (!roots.some((root) => inside(root, realPath)))
814 return keep("outside the managed worktree folder");
815 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
816 return keep("contains a project checkout");
817 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
818 return keep("not a linked worktree");
819 if (yield* branchChanged(worktreePath, thread.branch))
820 return keep("repository or branch changed");
821 const changes = yield* localChangesReason(worktreePath, settings);
822 if (changes !== null) return keep(changes);
823 if (
824 group.some(
825 (member) =>
826 member.settledAt !== null &&
827 now - Math.max(DateTime.toEpochMillis(member.updatedAt), activityAt) <
828 SETTLE_SCRIPT_GRACE_MS,
829 )
830 )
831 return keep(waitForStop("settled moments ago"));
832 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
833 const old =
834 !deleted &&
835 settings.worktreeAfterDays !== null &&
836 activityAt < now - settings.worktreeAfterDays * DAY_MS;
837 const settledFor =
838 deleted || thread.settledAt === null
839 ? null
840 : now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
841 const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
842 const settled =
843 settledFor !== null &&
844 settings.worktreeSettledAfterDays !== null &&
845 settledFor >= settings.worktreeSettledAfterDays * DAY_MS;
846 let eligible = deleted || old || settled;
847 let removalReason = deleted
848 ? "thread was deleted"
849 : old
850 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
851 : `settled for ${settledDays} days`;
852 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
853 const repositoryCwd = path.resolve(project.workspaceRoot);
854 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
855 const defaultBranchKey = `${repositoryCwd}\0${remote}`;
856 let branch = defaultBranches.get(defaultBranchKey);
857 if (branch === undefined) {
858 branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
859 // Without a local HEAD ref, only the remote can identify its default;
860 // a conventional name may be a feature branch.
861 if (branch === null) {
862 branch = yield* git
863 .execute({
864 operation: "StorageCleanup.resolveDefaultBranch",
865 cwd: repositoryCwd,
866 args: ["ls-remote", "--symref", "--", remote, "HEAD"],
867 timeoutMs: 20_000,
868 })
869 .pipe(
870 Effect.map(
871 (result) =>
872 /^ref: refs\/heads\/(.+)\tHEAD\r?$/m.exec(result.stdout)?.[1] ?? null,
873 ),
874 Effect.orElseSucceed(() => null),
875 );
876 }
877 defaultBranches.set(defaultBranchKey, branch);
878 }
879 if (branch === null) return keep("default branch is unavailable");
880 const defaultRef = `refs/remotes/${remote}/${branch}`;
881 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
882 if (!refreshed.has(defaultRef)) {
883 yield* git.fetchRemoteTrackingBranch({
884 cwd: repositoryCwd,
885 remoteName: remote,
886 remoteBranch: branch,
887 });
888 refreshed.add(defaultRef);
889 refreshedDefaultRefs.set(repositoryCwd, refreshed);
890 }
891 const base = yield* git.resolveCommit({
892 cwd: worktreePath,
893 revision: defaultRef,
894 });
895 const ancestor = yield* git.execute({
896 operation: "StorageCleanup.integratedBranch",
897 cwd: worktreePath,
898 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
899 allowNonZeroExit: true,
900 });
901 const integrated = ancestor.exitCode === 0;
902 eligible = integrated && settings.worktreeUnchanged;
903 if (eligible) removalReason = "no commits beyond the default branch";
904 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
905 const pullRequest = yield* gitManager.branchPullRequest(
906 { cwd: worktreePath, branch: thread.branch },
907 { refresh: true },
908 );
909 eligible = storageCleanupPullRequestMerged(pullRequest, {
910 branch: thread.branch,
911 defaultBranch: branch,
912 headSha: head.commitSha,
913 integrated,
914 });
915 if (eligible) removalReason = "pull request was merged";
916 }
917 }
918 if (!eligible)
919 return keep(
920 !deleted && settings.worktreeAfterDays !== null
921 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
922 : settings.worktreeSettledAfterDays !== null
923 ? settledFor === null
924 ? "not settled"
925 : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days`
926 : settings.worktreeOnMerge
927 ? "not merged"
928 : "has commits beyond the default branch",
929 );
930 // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds.
931 const blockedSinceCheck = Effect.fnUntraced(function* () {
932 const latestProjects = yield* projectStore.listShells();
933 if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects]))
934 return "contains a project checkout";
935 const latest = (yield* projections.getThreadWorktreePaths({
936 includeArchived: true,
937 })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath);
938 if (hasTerminal(worktreePath)) return waitForStop("open terminal");
939 if (deleted) {
940 if (
941 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
942 .worktreeOnDelete
943 )
944 return "thread or cleanup settings changed since check";
945 // Durable deletion cleanup must succeed or be explicitly cancelled before removing its checkout.
946 const pendingCleanup = yield* sql<{ status: string }>`
947 SELECT status FROM orchestration_v2_effect_outbox
948 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled')
949 `.pipe(NodeSqliteClient.readOnly);
950 // Failed effects never retry, so only running work can finish and free the path.
951 if (pendingCleanup.some((row) => row.status !== "failed"))
952 return waitForStop("thread deletion is still pending");
953 if (pendingCleanup.length > 0) return "thread deletion is still pending";
954 }
955 const latestShells = yield* Effect.forEach(latest, (entry) =>
956 projections.getThreadShell(entry.threadId),
957 );
958 const latestGroup = latestShells.filter((shell) => shell !== null);
959 const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup);
960 if (
961 latestGroup.length !== group.length ||
962 latestOwner?.id !== thread.id ||
963 latestOwner?.branch !== thread.branch ||
964 latestGroup.some((shell) => {
965 const previous = group.find((member) => member.id === shell.id);
966 return (
967 previous === undefined ||
968 shell.branch !== thread.branch ||
969 !Equal.equals(shell.settledAt, previous.settledAt) ||
970 (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
971 !storageCleanupThreadIdle(shell, now) ||
972 path.resolve(shell.worktreePath!) !== worktreePath ||
973 storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
974 );
975 })
976 )
977 return waitForStop("thread activity or shared worktree changed since check");
978 // Sessions can outlive their run and can be shared across app threads.
979 const sessionRows = yield* sql<{ payload_json: string }>`
980 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
981 WHERE status != 'stopped'
982 `.pipe(NodeSqliteClient.readOnly);
983 const sessions = yield* Effect.forEach(sessionRows, (row) =>
984 decodeCleanupSession(row.payload_json),
985 );
986 // Ready persisted sessions may have released their runtime; only live sessions protect the path.
987 for (const session of sessions) {
988 const cwd = path.resolve(session.cwd);
989 if (
990 (cwd === worktreePath || inside(worktreePath, cwd)) &&
991 (yield* providerSessions.isLive(session.id))
992 )
993 return waitForStop("provider session is still open");
994 }
995 return null;
996 });
997 const blocked = yield* blockedSinceCheck();
998 if (blocked !== null) return keep(blocked);
999 const bytes = yield* measureWorktree(worktreePath);
1000 const blockedWhileMeasuring = yield* blockedSinceCheck();
1001 if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring);
1002 if (yield* branchChanged(worktreePath, thread.branch))
1003 return keep("repository or branch changed since check");
1004 if (
1005 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
1006 head.commitSha
1007 )
1008 return keep("commit changed since check");
1009 const finalChanges = yield* localChangesReason(worktreePath, settings);
1010 if (finalChanges !== null) return keep(finalChanges);
1011 const current = resolveWorktreeCleanup(
1012 yield* settingsService.getSettings,
1013 thread.projectId,
1014 );
1015 if (
1016 Object.keys(settings).some(
1017 (key) =>
1018 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
1019 )
1020 )
1021 return keep("settings changed since check");
1022 // Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check.
1023 if (settings.worktreeKeepWhen === "tracked-changes")
1024 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
1025 const submodules = yield* submoduleRemoval(worktreePath, settings);
1026 if (submodules.reason !== null) return keep(submodules.reason);
1027 if (submodules.force) {
1028 const changes = yield* localChangesReason(worktreePath, settings);
1029 if (changes !== null) return keep(changes);
1030 }
1031 yield* removeLinkedWorktree({
1032 operation: "StorageCleanup.cleanupGit",
1033 cwd: project.workspaceRoot,
1034 worktreePath,
1035 // Git requires force for submodules; recursive checks above cannot make removal atomic.
1036 force: submodules.force,
1037 execute: git.execute,
1038 run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"),
1039 });
1040 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
1041 yield* gitManager.invalidateStatus(project.workspaceRoot);
1042 // Preserve branch/path so ProviderTurnStartService can recreate the checkout on resume.
1043 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
1044 }).pipe(
1045 (effect) => withWorkspaceLease(worktreePath, effect),
1046 Effect.catch((error) =>
1047 Effect.gen(function* () {
1048 entries.push({
1049 ...entry,
1050 outcome: "failed",
1051 reason: cleanupFailureReason(error),
1052 });
1053 if (deleted && settings.worktreeOnDelete) kept.push(worktreePath);
1054 yield* Effect.logWarning("storage cleanup failed for worktree", {
1055 threadId: thread.id,
1056 error,
1057 });
1058 }),
1059 ),
1060 );
1061 }
1062 yield* reportOrphanWorktrees(
1063 roots,
1064 yield* projectStore.list({ includeDeleted: true }),
1065 entries,
1066 );
1067 return { waiting, kept };
1068 });
1069
1070 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
1071 root: string,
1072 days: number | null,
1073 now: number,
1074 rotatedLogs: boolean,
1075 removed: { files: number; bytes: number },
1076 ) {
1077 if (days === null || !(yield* fs.exists(root))) return removed;
1078 // A symlinked parent (a linked T3 home) is fine; a symlinked folder is not.
1079 const realRoot = yield* fs.realPath(root);
1080 const realParent = yield* fs.realPath(path.dirname(root));
1081 if (realRoot !== path.join(realParent, path.basename(root))) return removed;
1082 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
1083 directory: string,
1084 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
1085 for (const name of yield* fs.readDirectory(directory)) {
1086 const target = path.join(directory, name);
1087 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
1088 const stat = yield* fs.stat(target);
1089 if (stat.type === "Directory" && rotatedLogs) {
1090 yield* visit(target);
1091 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
1092 const modified = Option.getOrNull(stat.mtime);
1093 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
1094 const current = (yield* settingsService.getSettings).storageCleanup;
1095 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
1096 return;
1097 yield* fs.remove(target);
1098 removed.files++;
1099 removed.bytes += Number(stat.size);
1100 }
1101 }
1102 }
1103 });
1104 yield* visit(realRoot);
1105 return removed;
1106 });
1107
1108 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
1109 // Only deleted threads' worktrees wait on session stops: any stop while one waits, or a stop inside one kept for another reason.
1110 // A deletion stays pending until a sweep that started after it finishes.
1111 let deletedWorktreeWaits = true;
1112 let keptDeletedWorktrees: ReadonlyArray<string> = [];
1113 let deletions = 0;
1114 let sweptDeletions = 0;
1115 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
1116 trigger: StorageCleanupReport["trigger"],
1117 ) {
1118 const deletionsAtStart = deletions;
1119 const now = yield* Clock.currentTimeMillis;
1120 const serverSettings = yield* settingsService.getSettings;
1121 const settings = serverSettings.storageCleanup;
1122 const entries: StorageCleanupReportEntry[] = [];
1123 const deletedWorktrees = yield* cleanWorktrees(serverSettings, now, entries).pipe(
1124 Effect.catch((error) =>
1125 Effect.gen(function* () {
1126 entries.push({
1127 kind: "worktree",
1128 outcome: "failed",
1129 reason: cleanupFailureReason(error),
1130 path: null,
1131 projectPath: null,
1132 threadId: null,
1133 threadTitle: null,
1134 bytes: null,
1135 files: null,
1136 });
1137 yield* Effect.logWarning("worktree cleanup failed", { error });
1138 return { waiting: true, kept: [] };
1139 }),
1140 ),
1141 );
1142 deletedWorktreeWaits = deletedWorktrees.waiting;
1143 keptDeletedWorktrees = deletedWorktrees.kept;
1144 sweptDeletions = deletionsAtStart;
1145 for (const category of [
1146 {
1147 kind: "browser-artifacts" as const,
1148 root: config.browserArtifactsDir,
1149 days: settings.browserArtifactsAfterDays,
1150 label: "browser artifacts",
1151 },
1152 {
1153 kind: "logs" as const,
1154 root: config.logsDir,
1155 days: settings.logsAfterDays,
1156 label: "rotated logs",
1157 },
1158 ]) {
1159 if (category.days === null) continue;
1160 const removed = { files: 0, bytes: 0 };
1161 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
1162 Effect.map(({ files, bytes }) =>
1163 entries.push({
1164 kind: category.kind,
1165 outcome: files > 0 ? "removed" : "kept",
1166 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
1167 path: null,
1168 projectPath: null,
1169 threadId: null,
1170 threadTitle: null,
1171 bytes: files > 0 ? bytes : null,
1172 files: files > 0 ? files : null,
1173 }),
1174 ),
1175 Effect.catch((error) =>
1176 Effect.gen(function* () {
1177 entries.push({
1178 kind: category.kind,
1179 outcome: "failed",
1180 reason: cleanupFailureReason(error),
1181 path: null,
1182 projectPath: null,
1183 threadId: null,
1184 threadTitle: null,
1185 bytes: removed.files > 0 ? removed.bytes : null,
1186 files: removed.files > 0 ? removed.files : null,
1187 });
1188 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
1189 }),
1190 ),
1191 );
1192 }
1193 const counts = { removed: 0, kept: 0, failed: 0 };
1194 let bytesFreed = 0;
1195 for (const entry of entries) {
1196 counts[entry.outcome]++;
1197 if (entry.outcome !== "kept") bytesFreed += entry.bytes ?? 0;
1198 }
1199 const priority = (entry: StorageCleanupReportEntry) =>
1200 entry.outcome === "failed"
1201 ? 0
1202 : entry.outcome === "removed"
1203 ? 1
1204 : entry.kind === "worktree" && entry.threadId === null
1205 ? 2
1206 : 3;
1207 const latestReport: StorageCleanupReport = {
1208 trigger,
1209 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
1210 finishedAt: DateTime.formatIso(yield* DateTime.now),
1211 entries: entries.sort((a, b) => priority(a) - priority(b)).slice(0, REPORT_ENTRY_LIMIT),
1212 counts,
1213 bytesFreed,
1214 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
1215 };
1216 yield* SubscriptionRef.set(reportRef, latestReport);
1217 return latestReport;
1218 });
1219 const automaticSweepQueued = yield* Ref.make(false);
1220 const worker = yield* makeDrainableWorker(
1221 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
1222 (completion === undefined ? Ref.set(automaticSweepQueued, false) : Effect.void).pipe(
1223 Effect.andThen(sweep(completion === undefined ? "automatic" : "manual")),
1224 Effect.exit,
1225 Effect.flatMap((exit) =>
1226 completion === undefined
1227 ? exit.pipe(
1228 Effect.asVoid,
1229 Effect.catchCause((cause) =>
1230 Effect.logWarning("storage cleanup failed", { cause }),
1231 ),
1232 )
1233 : Deferred.done(completion, exit).pipe(Effect.asVoid),
1234 ),
1235 ),
1236 );
1237 const requestSweep = Ref.getAndSet(automaticSweepQueued, true).pipe(
1238 Effect.flatMap((queued) => (queued ? Effect.void : worker.enqueue(undefined))),
1239 );
1240 const runNow = Effect.gen(function* () {
1241 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
1242 yield* worker.enqueue(completion);
1243 return yield* Deferred.await(completion);
1244 });
1245
1246 const start = Effect.fn("StorageCleanup.start")(function* () {
1247 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
1248 Effect.sync(() => {
1249 if (event.type === "snapshot") {
1250 liveTerminals.clear();
1251 for (const terminal of event.terminals) noteTerminal(terminal);
1252 } else if (event.type === "upsert") {
1253 noteTerminal(event.terminal);
1254 } else {
1255 const threadTerminals = liveTerminals.get(event.threadId);
1256 threadTerminals?.delete(event.terminalId);
1257 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
1258 }
1259 }),
1260 );
1261 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1262 const changes = yield* settingsService.subscribeChanges;
1263 const events = engine.streamDomainEvents;
1264 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
1265 yield* forkParked(
1266 requestSweep.pipe(
1267 Effect.andThen(worker.drain),
1268 Effect.repeat(Schedule.spaced("1 hour")),
1269 Effect.asVoid,
1270 ),
1271 );
1272 yield* forkParked(
1273 Stream.runForEach(changes, (settings) => {
1274 if (
1275 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
1276 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
1277 sameProjectWorktreePolicies(settings, lastSettings)
1278 )
1279 return Effect.void;
1280 lastSettings = settings;
1281 return requestSweep;
1282 }),
1283 );
1284 yield* forkParked(
1285 Stream.runForEach(events, (event) => {
1286 if (event.type === "thread.deleted") deletions++;
1287 else if (
1288 event.type !== "provider-session.updated" ||
1289 (event.payload.status !== "stopped" && event.payload.status !== "error")
1290 )
1291 return Effect.void;
1292 else if (!deletedWorktreeWaits && deletions === sweptDeletions) {
1293 const cwd = pathKey(event.payload.cwd);
1294 if (
1295 !keptDeletedWorktrees.some(
1296 (worktreePath) => pathKey(worktreePath) === cwd || inside(worktreePath, cwd),
1297 )
1298 )
1299 return Effect.void;
1300 }
1301 return anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
1302 ? requestSweep
1303 : Effect.void;
1304 }).pipe(
1305 Effect.catchCause((cause) =>
1306 Effect.logWarning("Storage cleanup event stream failed", { cause }),
1307 ),
1308 ),
1309 );
1310 });
1311 yield* start();
1312 return StorageCleanup.of({
1313 runNow,
1314 latestReport: SubscriptionRef.get(reportRef),
1315 reports: SubscriptionRef.changes(reportRef),
1316 drain: worker.drain,
1317 });
1318});
1319
1320export const layer = Layer.effect(StorageCleanup, make);