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

storageCleanup.ts

1,301 lines53.8 KB

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