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

storageCleanup.ts

797 lines31.5 KB

1import {
2 GitCommandError,
3 OrchestrationV2AppThreadJson,
4 OrchestrationV2ProviderSessionJson,
5} from "@t3tools/contracts";
6import * as Schema from "effect/Schema";
7import * as SqlClient from "effect/sql/SqlClient";
8import type {
9 OrchestrationV2ThreadShell,
10 ProjectId,
11 ServerSettings,
12 ServerSettingsError,
13 TerminalSummary,
14 WorktreeCleanupRules,
15 StorageCleanupReport,
16 StorageCleanupReportEntry,
17} from "@t3tools/contracts";
18import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
19import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
20import * as Context from "effect/Context";
21import * as Deferred from "effect/Deferred";
22import * as Layer from "effect/Layer";
23import * as Clock from "effect/Clock";
24import * as DateTime from "effect/DateTime";
25import * as Effect from "effect/Effect";
26import * as Equal from "effect/Equal";
27import * as FileSystem from "effect/FileSystem";
28import * as Option from "effect/Option";
29import * as Path from "effect/Path";
30import type { PlatformError } from "effect/PlatformError";
31import * as Schedule from "effect/Schedule";
32import * as Stream from "effect/Stream";
33import * as SubscriptionRef from "effect/SubscriptionRef";
34​
35import * as ServerConfig from "./config.ts";
36import * as GitManager from "./git/GitManager.ts";
37import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
38import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
39import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
40import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts";
41import { forkParked } from "./serverActivation.ts";
42import * as Settings from "./serverSettings.ts";
43import * as TerminalManager from "./terminal/Manager.ts";
44import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";
45import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
46import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
47import * as HostProcess from "@t3tools/shared/HostProcess";
48​
49const decodeCleanupThread = Schema.decodeUnknownEffect(
50 Schema.fromJsonString(OrchestrationV2AppThreadJson),
51);
52const decodeCleanupSession = Schema.decodeUnknownEffect(
53 Schema.fromJsonString(OrchestrationV2ProviderSessionJson),
54);
55​
56const DAY_MS = 86_400_000;
57​
58const sentence = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
59const REPORT_ENTRY_LIMIT = 200;
60const isGitCommandError = Schema.is(GitCommandError);
61​
62function cleanupFailureReason(error: { readonly message: string }) {
63 return isGitCommandError(error)
64 ? `${error.command}: ${error.detail.split(/\r?\n/)[0]}${error.reason ? ` (${error.reason})` : ""}`
65 : (error.message.split(/\r?\n/)[0] ?? error.message);
67​
68const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) =>
69 rules.worktreeAfterDays !== null ||
70 rules.worktreeOnMerge ||
71 rules.worktreeOnDelete ||
72 rules.worktreeUnchanged;
73​
74function anyWorktreePolicy(
75 settings: ServerSettings,
76 predicate: (rules: WorktreeCleanupRules) => boolean,
77): boolean {
78 return (
79 predicate(resolveWorktreeCleanup(settings, null)) ||
80 Object.keys(settings.projectSettingsOverrides).some((projectId) =>
81 predicate(resolveWorktreeCleanup(settings, projectId as ProjectId)),
82 )
83 );
85​
86function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings): boolean {
87 return [
88 ...new Set([
89 ...Object.keys(left.projectSettingsOverrides),
90 ...Object.keys(right.projectSettingsOverrides),
91 ]),
92 ].every((projectId) =>
93 Equal.equals(
94 left.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
95 right.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
96 ),
97 );
99​
100/** Live sessions keep their cwd even when no turn is currently running. */
101export function storageCleanupThreadIdle(thread: OrchestrationV2ThreadShell, now: number): boolean {
102 return (
103 thread.branch !== null &&
104 thread.worktreePath !== null &&
105 thread.activeRunId === null &&
106 (thread.status === "idle" ||
107 thread.status === "completed" ||
108 thread.status === "interrupted" ||
109 thread.status === "failed" ||
110 thread.status === "cancelled" ||
111 thread.status === "rolled_back") &&
112 (thread.pendingBackgroundTasks?.length ?? 0) === 0 &&
113 thread.pendingRuntimeRequest === null &&
114 !threadHasQueuedTurnStart(thread, now)
115 );
117​
118/** PR metadata refreshes must not reset the inactivity clock. */
119export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): number {
120 return Math.max(
121 ...[
122 thread.createdAt,
123 thread.latestUserMessageAt,
124 thread.latestRunRequestedAt,
125 thread.latestRunStartedAt,
126 thread.latestRunCompletedAt,
127 ].flatMap((value) => (value == null ? [] : [DateTime.toEpochMillis(value)])),
128 );
130​
131/**
132 * Whether the host's pull request proves this worktree's head was merged. A
133 * squash or rebase merge leaves the head outside the default branch, so the
134 * merged pull request then has to name this exact commit.
135 */
136export function storageCleanupPullRequestMerged(
137 pullRequest: Pick<
138 GitManager.GitBranchPullRequest,
139 "state" | "headRef" | "baseRef" | "headSha"
140 > | null,
141 worktree: {
142 readonly branch: string;
143 readonly defaultBranch: string;
144 readonly headSha: string;
145 readonly integrated: boolean;
146 },
147): boolean {
148 return (
149 pullRequest?.state === "merged" &&
150 (worktree.integrated ||
151 (pullRequest.headRef === worktree.branch &&
152 pullRequest.baseRef === worktree.defaultBranch &&
153 pullRequest.headSha === worktree.headSha))
154 );
156​
157export class StorageCleanup extends Context.Service<
158 StorageCleanup,
159 {
160 readonly runNow: Effect.Effect<StorageCleanupReport, ServerSettingsError>;
161 readonly latestReport: Effect.Effect<StorageCleanupReport | null>;
162 readonly reports: Stream.Stream<StorageCleanupReport | null>;
163 readonly drain: Effect.Effect<void>;
164 }
165>()("t3/storageCleanup") {}
166​
167const make = Effect.gen(function* () {
168 const config = yield* ServerConfig.ServerConfig;
169 const settingsService = yield* Settings.ServerSettingsService;
170 const projectStore = yield* ProjectStore.ProjectStoreV2;
171 const engine = yield* Orchestrator.OrchestratorV2;
172 const projections = yield* ProjectionStore.ProjectionStoreV2;
173 const sql = yield* SqlClient.SqlClient;
174 const git = yield* GitVcsDriver.GitVcsDriver;
175 const gitManager = yield* GitManager.GitManager;
176 const terminals = yield* TerminalManager.TerminalManager;
177 const fs = yield* FileSystem.FileSystem;
178 const path = yield* Path.Path;
179 const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
180 const noteTerminal = (terminal: TerminalSummary) => {
181 const threadTerminals =
182 liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
183 threadTerminals.set(terminal.terminalId, terminal);
184 liveTerminals.set(terminal.threadId, threadTerminals);
185 };
186​
187 const inside = (root: string, target: string) => {
188 const relative = path.relative(root, target);
189 return (
190 relative !== "" &&
191 relative !== ".." &&
192 !relative.startsWith(`..${path.sep}`) &&
193 !path.isAbsolute(relative)
194 );
195 };
196 const hasTerminal = (worktreePath: string) =>
197 [...liveTerminals.values()]
198 .flatMap((entries) => [...entries.values()])
199 .some((terminal) => {
200 if (terminal.status !== "starting" && terminal.status !== "running") return false;
201 const cwd = path.resolve(terminal.cwd);
202 return (
203 (terminal.worktreePath !== null &&
204 path.resolve(terminal.worktreePath) === worktreePath) ||
205 cwd === worktreePath ||
206 inside(worktreePath, cwd)
207 );
208 });
209​
210 const measureWorktree = (worktreePath: string) =>
211 Effect.gen(function* () {
212 const root = yield* fs.realPath(worktreePath);
213 const pending = [root];
214 let entries = 1;
215 let bytes = 0;
216 while (pending.length > 0) {
217 const target = pending.pop()!;
218 // Effect's stat follows links. Probe with readLink first to get lstat
219 // semantics, including skipping dangling links and directory links.
220 const isLink = yield* fs.readLink(target).pipe(
221 Effect.as(true),
222 Effect.catchIf(
223 (error) =>
224 error.cause instanceof Error &&
225 "code" in error.cause &&
226 error.cause.code === "EINVAL",
227 () => Effect.succeed(false),
228 ),
229 );
230 if (isLink) continue;
231 if ((yield* fs.realPath(target)) !== target) return null;
232 const stat = yield* fs.stat(target);
233 if (stat.type === "File") bytes += Number(stat.size);
234 else if (stat.type === "Directory") {
235 const names = yield* fs.readDirectory(target);
236 entries += names.length;
237 if (entries > 2_000_000) return null;
238 for (const name of names) {
239 const child = path.join(target, name);
240 if (!inside(root, child)) return null;
241 pending.push(child);
242 }
243 }
244 }
245 return bytes;
246 }).pipe(
247 Effect.timeout("30 seconds"),
248 Effect.orElseSucceed(() => null),
249 );
250​
251 const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {
252 const active = yield* projections.getShellSnapshot();
253 const archived = yield* projections.getShellSnapshot({ location: "archive" });
254 const projects = yield* projectStore.listShells();
255 return { projects, threads: [...active.threads, ...archived.threads] };
256 });
257​
258 // Local threads under another project need not have a worktreePath of their own.
259 const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* (
260 worktreePath: string,
261 projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
262 ) {
263 for (const project of projects) {
264 const projectPath = path.resolve(project.workspaceRoot);
265 if (projectPath === worktreePath || inside(worktreePath, projectPath)) return true;
266 const realPath = yield* fs
267 .realPath(projectPath)
268 .pipe(Effect.orElseSucceed(() => projectPath));
269 if (realPath === worktreePath || inside(worktreePath, realPath)) return true;
270 }
271 return false;
272 });
273​
274 const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* (
275 cwd: string,
276 rules: WorktreeCleanupRules,
277 ) {
278 const status = yield* git.execute({
279 operation: "StorageCleanup.localChanges",
280 cwd,
281 args: [
282 "status",
283 "--porcelain=v1",
284 "-z",
285 "--ignore-submodules=none",
286 rules.worktreeKeepWhen === "tracked-changes"
287 ? "--untracked-files=no"
288 : "--untracked-files=all",
289 ],
290 maxOutputBytes: 64 * 1024,
291 });
292 if (status.stdoutTruncated) return "local changes exceed the inspection limit";
293 const records = status.stdout.split("\0").filter(Boolean);
294 let count = 0;
295 for (let i = 0; i < records.length; i++) {
296 count++;
297 if (/^[RC]|^.[RC]/.test(records[i]!)) i++;
298 }
299 if (count > 0) return `has uncommitted changes (${count} ${count === 1 ? "file" : "files"})`;
300 if (rules.worktreeKeepWhen !== "any-local-files") return null;
301 const ignored = yield* git.execute({
302 operation: "StorageCleanup.ignoredFiles",
303 cwd,
304 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
305 maxOutputBytes: 64 * 1024,
306 });
307 if (ignored.stdoutTruncated) return "ignored files exceed the inspection limit";
308 const file = ignored.stdout
309 .split("\0")
310 .find((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry));
311 return file === undefined ? null : `has ignored files (${file})`;
312 });
313​
314 const cleanupGit = Effect.fn("StorageCleanup.cleanupGit")(function* (
315 cwd: string,
316 args: string[],
317 command: string,
318 ) {
319 const result = yield* git.execute({
320 operation: "StorageCleanup.cleanupGit",
321 cwd,
322 args,
323 allowNonZeroExit: true,
324 timeoutMs: 300_000,
325 });
326 if (result.exitCode !== 0)
327 return yield* Effect.fail(
328 new GitCommandError({
329 operation: "StorageCleanup.cleanupGit",
330 command,
331 cwd,
332 detail: result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
333 }),
334 );
335 });
336​
337 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
338 serverSettings: ServerSettings,
339 now: number,
340 entries: StorageCleanupReportEntry[],
341 ) {
342 const roots: Array<string> = [];
343 for (const directory of managedWorktreesDirectories(
344 serverSettings,
345 config.worktreesDir,
346 path,
347 yield* HostProcess.HomeDirectory,
348 )) {
349 // An unmounted drive only skips its own worktrees.
350 const root = yield* fs.exists(directory).pipe(
351 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
352 Effect.orElseSucceed(() => null),
353 );
354 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
355 }
356 const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
357 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
358 FROM orchestration_v2_projection_threads t
359 JOIN projection_projects p ON p.project_id = t.project_id
360 WHERE t.deleted_at IS NOT NULL
361 `;
362 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
363 decodeCleanupThread(row.payload_json).pipe(
364 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
365 ),
366 )).filter((thread) => thread.worktreePath !== null && thread.branch !== null);
367 const snapshot = yield* readThreads();
368 const refreshedDefaultRefs = new Map<string, Set<string>>();
369 const groups = Map.groupBy(
370 snapshot.threads.filter((thread) => thread.worktreePath !== null),
371 (thread) => path.resolve(thread.worktreePath!),
372 );
373 const candidates = [
374 ...[...groups.values()].map((group) => group[0]!),
375 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
376 ];
377 for (const thread of candidates) {
378 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
379 if (!worktreeCleanupEnabled(settings)) continue;
380 const worktreePath = path.resolve(thread.worktreePath!);
381 const deleted = "workspaceRoot" in thread;
382 const project = deleted
383 ? { workspaceRoot: thread.workspaceRoot }
384 : snapshot.projects.find((entry) => entry.id === thread.projectId);
385 const entry: StorageCleanupReportEntry = {
386 kind: "worktree",
387 outcome: "kept",
388 reason: "",
389 path: worktreePath,
390 threadId: thread.id,
391 threadTitle: thread.title,
392 bytes: null,
393 files: null,
394 };
395 const keep = (reason: string) => entries.push({ ...entry, reason: sentence(reason) });
396 yield* Effect.gen(function* () {
397 if (!(yield* fs.exists(worktreePath))) return;
398 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
399 const shared = groups.get(worktreePath)?.length ?? 0;
400 if (shared > 1) return keep(`shared by ${shared} threads`);
401 if (project === undefined) return keep("project is unavailable");
402 if (!deleted && !storageCleanupThreadIdle(thread, now))
403 return keep("thread is running or has pending work");
404 if (hasTerminal(worktreePath)) return keep("open terminal");
405 // Roots are canonical, so compare canonical paths. A symlinked parent
406 // (a linked drive) is fine; a symlinked worktree directory is not.
407 const realPath = yield* fs.realPath(worktreePath);
408 const realParent = yield* fs.realPath(path.dirname(worktreePath));
409 if (realPath !== path.join(realParent, path.basename(worktreePath)))
410 return keep("worktree is a symbolic link");
411 if (!roots.some((root) => inside(root, realPath)))
412 return keep("outside the managed worktree folder");
413 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
414 return keep("contains a project checkout");
415 // A linked worktree has a .git file. Never remove a main checkout.
416 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
417 return keep("not a linked worktree");
418 const status = yield* git.statusDetailsLocal(worktreePath);
419 if (!status.isRepo || status.branch !== thread.branch)
420 return keep("repository or branch changed");
421 const changes = yield* localChangesReason(worktreePath, settings);
422 if (changes !== null) return keep(changes);
423 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
424 const old =
425 !deleted &&
426 settings.worktreeAfterDays !== null &&
427 storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
428 let eligible = deleted || old;
429 let removalReason = deleted
430 ? "thread was deleted"
431 : `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days`;
432 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
433 const repositoryCwd = path.resolve(project.workspaceRoot);
434 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
435 const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
436 if (branch === null) return keep("default branch is unavailable");
437 const defaultRef = `refs/remotes/${remote}/${branch}`;
438 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
439 if (!refreshed.has(defaultRef)) {
440 yield* git.fetchRemoteTrackingBranch({
441 cwd: repositoryCwd,
442 remoteName: remote,
443 remoteBranch: branch,
444 });
445 refreshed.add(defaultRef);
446 refreshedDefaultRefs.set(repositoryCwd, refreshed);
447 }
448 const base = yield* git.resolveCommit({
449 cwd: worktreePath,
450 revision: defaultRef,
451 });
452 const ancestor = yield* git.execute({
453 operation: "StorageCleanup.integratedBranch",
454 cwd: worktreePath,
455 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
456 allowNonZeroExit: true,
457 });
458 const integrated = ancestor.exitCode === 0;
459 eligible = integrated && settings.worktreeUnchanged;
460 if (eligible) removalReason = "no commits beyond the default branch";
461 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
462 const pullRequest = yield* gitManager.branchPullRequest(
463 { cwd: worktreePath, branch: thread.branch },
464 { refresh: true },
465 );
466 eligible = storageCleanupPullRequestMerged(pullRequest, {
467 branch: thread.branch,
468 defaultBranch: branch,
469 headSha: head.commitSha,
470 integrated,
471 });
472 if (eligible) removalReason = "pull request was merged";
473 }
474 }
475 if (!eligible)
476 return keep(
477 !deleted && settings.worktreeAfterDays !== null
478 ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} of ${settings.worktreeAfterDays} days`
479 : settings.worktreeOnMerge
480 ? "not merged"
481 : "has commits beyond the default branch",
482 );
483 const bytes = yield* measureWorktree(worktreePath);
484 // Re-read after Git/host calls and size measurement so a queued turn,
485 // resumed session or new thread sharing this path cancels the removal.
486 const latestSnapshot = yield* readThreads();
487 if (yield* containsProjectRoot(worktreePath, [project, ...latestSnapshot.projects]))
488 return keep("contains a project checkout");
489 const latest = latestSnapshot.threads.filter(
490 (entry) =>
491 entry.worktreePath !== null && path.resolve(entry.worktreePath) === worktreePath,
492 );
493 if (hasTerminal(worktreePath)) return keep("open terminal");
494 if (deleted) {
495 if (
496 latest.length > 0 ||
497 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
498 .worktreeOnDelete
499 )
500 return keep("thread or cleanup settings changed since check");
501 // V2 deletion queues durable cleanup. Do not remove its checkout until
502 // every effect has finished successfully or was explicitly cancelled.
503 const pendingCleanup = yield* sql`
504 SELECT 1 FROM orchestration_v2_effect_outbox
505 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
506 `;
507 if (pendingCleanup.length > 0) return keep("thread deletion is still pending");
508 } else if (
509 latest.length !== 1 ||
510 latest[0]!.id !== thread.id ||
511 !storageCleanupThreadIdle(latest[0]!, now) ||
512 storageCleanupActivityAt(latest[0]!) !== storageCleanupActivityAt(thread)
513 )
514 return keep("thread activity or shared worktree changed since check");
515 // Sessions can outlive their run and can be shared across app threads.
516 const sessionRows = yield* sql<{ payload_json: string }>`
517 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
518 WHERE status != 'stopped'
519 `;
520 const sessions = yield* Effect.forEach(sessionRows, (row) =>
521 decodeCleanupSession(row.payload_json),
522 );
523 if (
524 sessions.some((session) => {
525 const cwd = path.resolve(session.cwd);
526 return cwd === worktreePath || inside(worktreePath, cwd);
527 })
528 )
529 return keep("provider session is still open");
530 const finalStatus = yield* git.statusDetailsLocal(worktreePath);
531 if (!finalStatus.isRepo || finalStatus.branch !== thread.branch)
532 return keep("repository or branch changed since check");
533 if (
534 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
535 head.commitSha
536 )
537 return keep("commit changed since check");
538 const finalChanges = yield* localChangesReason(worktreePath, settings);
539 if (finalChanges !== null) return keep(finalChanges);
540 const current = resolveWorktreeCleanup(
541 yield* settingsService.getSettings,
542 thread.projectId,
543 );
544 if (
545 Object.keys(settings).some(
546 (key) =>
547 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
548 )
549 )
550 return keep("settings changed since check");
551 // Clean only untracked files; Git must still refuse removal if a tracked
552 // edit arrives after our last status check.
553 if (settings.worktreeKeepWhen === "tracked-changes")
554 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
555 yield* cleanupGit(
556 project.workspaceRoot,
557 ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", worktreePath],
558 "git worktree remove",
559 );
560 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
561 yield* gitManager.invalidateStatus(project.workspaceRoot);
562 // Preserve branch and path: ProviderTurnStartService recreates the checkout
563 // from that branch when the thread is resumed.
564 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
565 }).pipe(
566 (effect) => withWorkspaceLease(worktreePath, effect),
567 Effect.catch((error) =>
568 Effect.gen(function* () {
569 entries.push({
570 ...entry,
571 outcome: "failed",
572 reason: cleanupFailureReason(error),
573 });
574 yield* Effect.logWarning("storage cleanup failed for worktree", {
575 threadId: thread.id,
576 error,
577 });
578 }),
579 ),
580 );
581 }
582 });
583​
584 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
585 root: string,
586 days: number | null,
587 now: number,
588 rotatedLogs: boolean,
589 // Owned by the caller so files removed before a failure still count.
590 removed: { files: number; bytes: number },
591 ) {
592 if (days === null || !(yield* fs.exists(root))) return removed;
593 const realRoot = yield* fs.realPath(root);
594 if (realRoot !== path.resolve(root)) return removed;
595 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
596 directory: string,
597 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
598 for (const name of yield* fs.readDirectory(directory)) {
599 const target = path.join(directory, name);
600 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
601 const stat = yield* fs.stat(target);
602 if (stat.type === "Directory" && rotatedLogs) {
603 yield* visit(target);
604 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
605 const modified = Option.getOrNull(stat.mtime);
606 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
607 const current = (yield* settingsService.getSettings).storageCleanup;
608 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
609 return;
610 yield* fs.remove(target);
611 removed.files++;
612 removed.bytes += Number(stat.size);
613 }
614 }
615 }
616 });
617 yield* visit(realRoot);
618 return removed;
619 });
620​
621 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
622 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
623 trigger: StorageCleanupReport["trigger"],
624 ) {
625 const now = yield* Clock.currentTimeMillis;
626 const serverSettings = yield* settingsService.getSettings;
627 const settings = serverSettings.storageCleanup;
628 const entries: StorageCleanupReportEntry[] = [];
629 yield* cleanWorktrees(serverSettings, now, entries).pipe(
630 Effect.catch((error) =>
631 Effect.gen(function* () {
632 entries.push({
633 kind: "worktree",
634 outcome: "failed",
635 reason: cleanupFailureReason(error),
636 path: null,
637 threadId: null,
638 threadTitle: null,
639 bytes: null,
640 files: null,
641 });
642 yield* Effect.logWarning("worktree cleanup failed", { error });
643 }),
644 ),
645 );
646 for (const category of [
647 {
648 kind: "browser-artifacts" as const,
649 root: config.browserArtifactsDir,
650 days: settings.browserArtifactsAfterDays,
651 label: "browser artifacts",
652 },
653 {
654 kind: "logs" as const,
655 root: config.logsDir,
656 days: settings.logsAfterDays,
657 label: "rotated logs",
658 },
659 ]) {
660 if (category.days === null) continue;
661 const removed = { files: 0, bytes: 0 };
662 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
663 Effect.map(({ files, bytes }) =>
664 entries.push({
665 kind: category.kind,
666 outcome: files > 0 ? "removed" : "kept",
667 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
668 path: null,
669 threadId: null,
670 threadTitle: null,
671 bytes: files > 0 ? bytes : null,
672 files: files > 0 ? files : null,
673 }),
674 ),
675 Effect.catch((error) =>
676 Effect.gen(function* () {
677 entries.push({
678 kind: category.kind,
679 outcome: "failed",
680 reason: cleanupFailureReason(error),
681 path: null,
682 threadId: null,
683 threadTitle: null,
684 bytes: removed.files > 0 ? removed.bytes : null,
685 files: removed.files > 0 ? removed.files : null,
686 });
687 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
688 }),
689 ),
690 );
691 }
692 const counts = { removed: 0, kept: 0, failed: 0 };
693 let bytesFreed = 0;
694 for (const entry of entries) {
695 counts[entry.outcome]++;
696 bytesFreed += entry.bytes ?? 0;
697 }
698 const priority = { failed: 0, removed: 1, kept: 2 };
699 const latestReport: StorageCleanupReport = {
700 trigger,
701 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
702 finishedAt: DateTime.formatIso(yield* DateTime.now),
703 entries: entries
704 .sort((a, b) => priority[a.outcome] - priority[b.outcome])
705 .slice(0, REPORT_ENTRY_LIMIT),
706 counts,
707 bytesFreed,
708 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
709 };
710 yield* SubscriptionRef.set(reportRef, latestReport);
711 return latestReport;
712 });
713 const worker = yield* makeDrainableWorker(
714 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
715 sweep(completion === undefined ? "automatic" : "manual").pipe(
716 Effect.exit,
717 Effect.flatMap((exit) =>
718 completion === undefined
719 ? exit.pipe(
720 Effect.asVoid,
721 Effect.catchCause((cause) =>
722 Effect.logWarning("storage cleanup failed", { cause }),
723 ),
724 )
725 : Deferred.done(completion, exit).pipe(Effect.asVoid),
726 ),
727 ),
728 );
729 const runNow = Effect.gen(function* () {
730 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
731 yield* worker.enqueue(completion);
732 return yield* Deferred.await(completion);
733 });
734​
735 const start = Effect.fn("StorageCleanup.start")(function* () {
736 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
737 Effect.sync(() => {
738 if (event.type === "snapshot") {
739 liveTerminals.clear();
740 for (const terminal of event.terminals) noteTerminal(terminal);
741 } else if (event.type === "upsert") {
742 noteTerminal(event.terminal);
743 } else {
744 const threadTerminals = liveTerminals.get(event.threadId);
745 threadTerminals?.delete(event.terminalId);
746 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
747 }
748 }),
749 );
750 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
751 const changes = yield* settingsService.subscribeChanges;
752 const events = engine.streamDomainEvents;
753 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
754 yield* forkParked(
755 worker
756 .enqueue(undefined)
757 .pipe(
758 Effect.andThen(worker.drain),
759 Effect.repeat(Schedule.spaced("1 hour")),
760 Effect.asVoid,
761 ),
762 );
763 yield* forkParked(
764 Stream.runForEach(changes, (settings) => {
765 if (
766 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
767 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
768 sameProjectWorktreePolicies(settings, lastSettings)
769 )
770 return Effect.void;
771 lastSettings = settings;
772 return worker.enqueue(undefined);
773 }),
774 );
775 yield* forkParked(
776 Stream.runForEach(events, (event) =>
777 (event.type === "thread.deleted" || event.type === "provider-session.updated") &&
778 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
779 ? worker.enqueue(undefined)
780 : Effect.void,
781 ).pipe(
782 Effect.catchCause((cause) =>
783 Effect.logWarning("Storage cleanup event stream failed", { cause }),
784 ),
785 ),
786 );
787 });
788 yield* start();
789 return StorageCleanup.of({
790 runNow,
791 latestReport: SubscriptionRef.get(reportRef),
792 reports: SubscriptionRef.changes(reportRef),
793 drain: worker.drain,
794 });
795});
796​
797export const layer = Layer.effect(StorageCleanup, make);