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

storageCleanup.ts

1,255 lines51.5 KB

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