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

storageCleanup.ts

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