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

storageCleanup.ts

1,284 lines52.8 KB

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