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

storageCleanup.ts

862 lines34.4 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 // Whether cwd stopped being a checkout of this branch. Two small Git reads,
275 // since every worktree in a sweep is asked; statusDetailsLocal also diffs and
276 // counts.
277 const branchChanged = Effect.fn("StorageCleanup.branchChanged")(function* (
278 cwd: string,
279 branch: string | null,
280 ) {
281 const failure = (detail: string) =>
282 new GitCommandError({
283 operation: "StorageCleanup.branchChanged",
284 command: "git",
285 cwd,
286 detail,
287 });
288 // Null when cwd is not a repository, or is gone. Git's own messages are
289 // matched, so they must not be translated.
290 const read = Effect.fnUntraced(function* (args: string[], allowedExitCode?: number) {
291 const result = yield* git
292 .execute({
293 operation: "StorageCleanup.branchChanged",
294 cwd,
295 args,
296 env: { LC_ALL: "C" },
297 allowNonZeroExit: true,
298 })
299 .pipe(
300 Effect.catch((error) =>
301 Effect.flatMap(fs.exists(cwd), (exists) =>
302 exists ? Effect.fail(error) : Effect.succeed(null),
303 ),
304 ),
305 );
306 if (result === null) return null;
307 if (result.exitCode === 0 || result.exitCode === allowedExitCode) return result;
308 if (result.stderr.toLowerCase().includes("not a git repository")) return null;
309 return yield* failure(
310 result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
311 );
312 });
313 const index = yield* read(["rev-parse", "--git-path", "index"]);
314 if (index === null) return true;
315 // Another Git process is writing to this checkout.
316 if (yield* fs.exists(`${path.resolve(cwd, index.stdout.trim())}.lock`))
317 return yield* failure(
318 "Git index is locked. Status will resume when the index lock is removed.",
319 );
320 // Exits 1 for a detached HEAD. Reads the full ref name, which is never
321 // shortened to "heads/<branch>" when a tag shares the branch name.
322 const head = yield* read(["symbolic-ref", "--quiet", "HEAD"], 1);
323 if (head === null) return true;
324 const ref = head.exitCode === 0 ? head.stdout.trim() : "";
325 const name = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length).trim() : null;
326 // Status output writes a detached HEAD as "(detached)", so a branch named
327 // with a leading "(" has always been read as one.
328 return (name?.startsWith("(") ? null : name) !== branch;
329 });
330​
331 const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* (
332 cwd: string,
333 rules: WorktreeCleanupRules,
334 ) {
335 const status = yield* git.execute({
336 operation: "StorageCleanup.localChanges",
337 cwd,
338 args: [
339 "status",
340 "--porcelain=v1",
341 "-z",
342 "--ignore-submodules=none",
343 rules.worktreeKeepWhen === "tracked-changes"
344 ? "--untracked-files=no"
345 : "--untracked-files=all",
346 ],
347 maxOutputBytes: 64 * 1024,
348 });
349 if (status.stdoutTruncated) return "local changes exceed the inspection limit";
350 const records = status.stdout.split("\0").filter(Boolean);
351 let count = 0;
352 for (let i = 0; i < records.length; i++) {
353 count++;
354 if (/^[RC]|^.[RC]/.test(records[i]!)) i++;
355 }
356 if (count > 0) return `has uncommitted changes (${count} ${count === 1 ? "file" : "files"})`;
357 if (rules.worktreeKeepWhen !== "any-local-files") return null;
358 const ignored = yield* git.execute({
359 operation: "StorageCleanup.ignoredFiles",
360 cwd,
361 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
362 maxOutputBytes: 64 * 1024,
363 });
364 if (ignored.stdoutTruncated) return "ignored files exceed the inspection limit";
365 const file = ignored.stdout
366 .split("\0")
367 .find((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry));
368 return file === undefined ? null : `has ignored files (${file})`;
369 });
370​
371 const cleanupGit = Effect.fn("StorageCleanup.cleanupGit")(function* (
372 cwd: string,
373 args: string[],
374 command: string,
375 ) {
376 const result = yield* git.execute({
377 operation: "StorageCleanup.cleanupGit",
378 cwd,
379 args,
380 allowNonZeroExit: true,
381 timeoutMs: 300_000,
382 });
383 if (result.exitCode !== 0)
384 return yield* Effect.fail(
385 new GitCommandError({
386 operation: "StorageCleanup.cleanupGit",
387 command,
388 cwd,
389 detail: result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
390 }),
391 );
392 });
393​
394 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
395 serverSettings: ServerSettings,
396 now: number,
397 entries: StorageCleanupReportEntry[],
398 ) {
399 const roots: Array<string> = [];
400 for (const directory of managedWorktreesDirectories(
401 serverSettings,
402 config.worktreesDir,
403 path,
404 yield* HostProcess.HomeDirectory,
405 )) {
406 // An unmounted drive only skips its own worktrees.
407 const root = yield* fs.exists(directory).pipe(
408 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
409 Effect.orElseSucceed(() => null),
410 );
411 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
412 }
413 const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
414 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
415 FROM orchestration_v2_projection_threads t
416 JOIN projection_projects p ON p.project_id = t.project_id
417 WHERE t.deleted_at IS NOT NULL
418 `;
419 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
420 decodeCleanupThread(row.payload_json).pipe(
421 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
422 ),
423 )).filter((thread) => thread.worktreePath !== null && thread.branch !== null);
424 const snapshot = yield* readThreads();
425 const refreshedDefaultRefs = new Map<string, Set<string>>();
426 const groups = Map.groupBy(
427 snapshot.threads.filter((thread) => thread.worktreePath !== null),
428 (thread) => path.resolve(thread.worktreePath!),
429 );
430 const candidates = [
431 ...[...groups.values()].map((group) => group[0]!),
432 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
433 ];
434 for (const thread of candidates) {
435 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
436 if (!worktreeCleanupEnabled(settings)) continue;
437 const worktreePath = path.resolve(thread.worktreePath!);
438 const deleted = "workspaceRoot" in thread;
439 const project = deleted
440 ? { workspaceRoot: thread.workspaceRoot }
441 : snapshot.projects.find((entry) => entry.id === thread.projectId);
442 const entry: StorageCleanupReportEntry = {
443 kind: "worktree",
444 outcome: "kept",
445 reason: "",
446 path: worktreePath,
447 threadId: thread.id,
448 threadTitle: thread.title,
449 bytes: null,
450 files: null,
451 };
452 const keep = (reason: string) => entries.push({ ...entry, reason: sentence(reason) });
453 yield* Effect.gen(function* () {
454 if (!(yield* fs.exists(worktreePath))) return;
455 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
456 const shared = groups.get(worktreePath)?.length ?? 0;
457 if (shared > 1) return keep(`shared by ${shared} threads`);
458 if (project === undefined) return keep("project is unavailable");
459 if (!deleted && !storageCleanupThreadIdle(thread, now))
460 return keep("thread is running or has pending work");
461 if (hasTerminal(worktreePath)) return keep("open terminal");
462 // Roots are canonical, so compare canonical paths. A symlinked parent
463 // (a linked drive) is fine; a symlinked worktree directory is not.
464 const realPath = yield* fs.realPath(worktreePath);
465 const realParent = yield* fs.realPath(path.dirname(worktreePath));
466 if (realPath !== path.join(realParent, path.basename(worktreePath)))
467 return keep("worktree is a symbolic link");
468 if (!roots.some((root) => inside(root, realPath)))
469 return keep("outside the managed worktree folder");
470 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
471 return keep("contains a project checkout");
472 // A linked worktree has a .git file. Never remove a main checkout.
473 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
474 return keep("not a linked worktree");
475 if (yield* branchChanged(worktreePath, thread.branch))
476 return keep("repository or branch changed");
477 const changes = yield* localChangesReason(worktreePath, settings);
478 if (changes !== null) return keep(changes);
479 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
480 const old =
481 !deleted &&
482 settings.worktreeAfterDays !== null &&
483 storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
484 let eligible = deleted || old;
485 let removalReason = deleted
486 ? "thread was deleted"
487 : `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days`;
488 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
489 const repositoryCwd = path.resolve(project.workspaceRoot);
490 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
491 const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
492 if (branch === null) return keep("default branch is unavailable");
493 const defaultRef = `refs/remotes/${remote}/${branch}`;
494 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
495 if (!refreshed.has(defaultRef)) {
496 yield* git.fetchRemoteTrackingBranch({
497 cwd: repositoryCwd,
498 remoteName: remote,
499 remoteBranch: branch,
500 });
501 refreshed.add(defaultRef);
502 refreshedDefaultRefs.set(repositoryCwd, refreshed);
503 }
504 const base = yield* git.resolveCommit({
505 cwd: worktreePath,
506 revision: defaultRef,
507 });
508 const ancestor = yield* git.execute({
509 operation: "StorageCleanup.integratedBranch",
510 cwd: worktreePath,
511 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
512 allowNonZeroExit: true,
513 });
514 const integrated = ancestor.exitCode === 0;
515 eligible = integrated && settings.worktreeUnchanged;
516 if (eligible) removalReason = "no commits beyond the default branch";
517 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
518 const pullRequest = yield* gitManager.branchPullRequest(
519 { cwd: worktreePath, branch: thread.branch },
520 { refresh: true },
521 );
522 eligible = storageCleanupPullRequestMerged(pullRequest, {
523 branch: thread.branch,
524 defaultBranch: branch,
525 headSha: head.commitSha,
526 integrated,
527 });
528 if (eligible) removalReason = "pull request was merged";
529 }
530 }
531 if (!eligible)
532 return keep(
533 !deleted && settings.worktreeAfterDays !== null
534 ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} of ${settings.worktreeAfterDays} days`
535 : settings.worktreeOnMerge
536 ? "not merged"
537 : "has commits beyond the default branch",
538 );
539 // Threads, queued deletion work and provider sessions as they are now, so a
540 // queued turn, resumed session or new thread sharing this path cancels
541 // the removal.
542 const blockedSinceCheck = Effect.fnUntraced(function* () {
543 const latestSnapshot = yield* readThreads();
544 if (yield* containsProjectRoot(worktreePath, [project, ...latestSnapshot.projects]))
545 return "contains a project checkout";
546 const latest = latestSnapshot.threads.filter(
547 (entry) =>
548 entry.worktreePath !== null && path.resolve(entry.worktreePath) === worktreePath,
549 );
550 if (hasTerminal(worktreePath)) return "open terminal";
551 if (deleted) {
552 if (
553 latest.length > 0 ||
554 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
555 .worktreeOnDelete
556 )
557 return "thread or cleanup settings changed since check";
558 // V2 deletion queues durable cleanup. Do not remove its checkout until
559 // every effect has finished successfully or was explicitly cancelled.
560 const pendingCleanup = yield* sql`
561 SELECT 1 FROM orchestration_v2_effect_outbox
562 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
563 `;
564 if (pendingCleanup.length > 0) return "thread deletion is still pending";
565 } else if (
566 latest.length !== 1 ||
567 latest[0]!.id !== thread.id ||
568 !storageCleanupThreadIdle(latest[0]!, now) ||
569 storageCleanupActivityAt(latest[0]!) !== storageCleanupActivityAt(thread)
570 )
571 return "thread activity or shared worktree changed since check";
572 // Sessions can outlive their run and can be shared across app threads.
573 const sessionRows = yield* sql<{ payload_json: string }>`
574 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
575 WHERE status != 'stopped'
576 `;
577 const sessions = yield* Effect.forEach(sessionRows, (row) =>
578 decodeCleanupSession(row.payload_json),
579 );
580 if (
581 sessions.some((session) => {
582 const cwd = path.resolve(session.cwd);
583 return cwd === worktreePath || inside(worktreePath, cwd);
584 })
585 )
586 return "provider session is still open";
587 return null;
588 });
589 // Most cancelled removals are caught here, before the worktree is walked.
590 const blocked = yield* blockedSinceCheck();
591 if (blocked !== null) return keep(blocked);
592 const bytes = yield* measureWorktree(worktreePath);
593 // The walk can take a while; ask again for anything that started during it.
594 const blockedWhileMeasuring = yield* blockedSinceCheck();
595 if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring);
596 if (yield* branchChanged(worktreePath, thread.branch))
597 return keep("repository or branch changed since check");
598 if (
599 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
600 head.commitSha
601 )
602 return keep("commit changed since check");
603 const finalChanges = yield* localChangesReason(worktreePath, settings);
604 if (finalChanges !== null) return keep(finalChanges);
605 const current = resolveWorktreeCleanup(
606 yield* settingsService.getSettings,
607 thread.projectId,
608 );
609 if (
610 Object.keys(settings).some(
611 (key) =>
612 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
613 )
614 )
615 return keep("settings changed since check");
616 // Clean only untracked files; Git must still refuse removal if a tracked
617 // edit arrives after our last status check.
618 if (settings.worktreeKeepWhen === "tracked-changes")
619 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
620 yield* cleanupGit(
621 project.workspaceRoot,
622 ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", worktreePath],
623 "git worktree remove",
624 );
625 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
626 yield* gitManager.invalidateStatus(project.workspaceRoot);
627 // Preserve branch and path: ProviderTurnStartService recreates the checkout
628 // from that branch when the thread is resumed.
629 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
630 }).pipe(
631 (effect) => withWorkspaceLease(worktreePath, effect),
632 Effect.catch((error) =>
633 Effect.gen(function* () {
634 entries.push({
635 ...entry,
636 outcome: "failed",
637 reason: cleanupFailureReason(error),
638 });
639 yield* Effect.logWarning("storage cleanup failed for worktree", {
640 threadId: thread.id,
641 error,
642 });
643 }),
644 ),
645 );
646 }
647 });
648​
649 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
650 root: string,
651 days: number | null,
652 now: number,
653 rotatedLogs: boolean,
654 // Owned by the caller so files removed before a failure still count.
655 removed: { files: number; bytes: number },
656 ) {
657 if (days === null || !(yield* fs.exists(root))) return removed;
658 const realRoot = yield* fs.realPath(root);
659 if (realRoot !== path.resolve(root)) return removed;
660 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
661 directory: string,
662 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
663 for (const name of yield* fs.readDirectory(directory)) {
664 const target = path.join(directory, name);
665 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
666 const stat = yield* fs.stat(target);
667 if (stat.type === "Directory" && rotatedLogs) {
668 yield* visit(target);
669 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
670 const modified = Option.getOrNull(stat.mtime);
671 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
672 const current = (yield* settingsService.getSettings).storageCleanup;
673 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
674 return;
675 yield* fs.remove(target);
676 removed.files++;
677 removed.bytes += Number(stat.size);
678 }
679 }
680 }
681 });
682 yield* visit(realRoot);
683 return removed;
684 });
685​
686 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
687 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
688 trigger: StorageCleanupReport["trigger"],
689 ) {
690 const now = yield* Clock.currentTimeMillis;
691 const serverSettings = yield* settingsService.getSettings;
692 const settings = serverSettings.storageCleanup;
693 const entries: StorageCleanupReportEntry[] = [];
694 yield* cleanWorktrees(serverSettings, now, entries).pipe(
695 Effect.catch((error) =>
696 Effect.gen(function* () {
697 entries.push({
698 kind: "worktree",
699 outcome: "failed",
700 reason: cleanupFailureReason(error),
701 path: null,
702 threadId: null,
703 threadTitle: null,
704 bytes: null,
705 files: null,
706 });
707 yield* Effect.logWarning("worktree cleanup failed", { error });
708 }),
709 ),
710 );
711 for (const category of [
712 {
713 kind: "browser-artifacts" as const,
714 root: config.browserArtifactsDir,
715 days: settings.browserArtifactsAfterDays,
716 label: "browser artifacts",
717 },
718 {
719 kind: "logs" as const,
720 root: config.logsDir,
721 days: settings.logsAfterDays,
722 label: "rotated logs",
723 },
724 ]) {
725 if (category.days === null) continue;
726 const removed = { files: 0, bytes: 0 };
727 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
728 Effect.map(({ files, bytes }) =>
729 entries.push({
730 kind: category.kind,
731 outcome: files > 0 ? "removed" : "kept",
732 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
733 path: null,
734 threadId: null,
735 threadTitle: null,
736 bytes: files > 0 ? bytes : null,
737 files: files > 0 ? files : null,
738 }),
739 ),
740 Effect.catch((error) =>
741 Effect.gen(function* () {
742 entries.push({
743 kind: category.kind,
744 outcome: "failed",
745 reason: cleanupFailureReason(error),
746 path: null,
747 threadId: null,
748 threadTitle: null,
749 bytes: removed.files > 0 ? removed.bytes : null,
750 files: removed.files > 0 ? removed.files : null,
751 });
752 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
753 }),
754 ),
755 );
756 }
757 const counts = { removed: 0, kept: 0, failed: 0 };
758 let bytesFreed = 0;
759 for (const entry of entries) {
760 counts[entry.outcome]++;
761 bytesFreed += entry.bytes ?? 0;
762 }
763 const priority = { failed: 0, removed: 1, kept: 2 };
764 const latestReport: StorageCleanupReport = {
765 trigger,
766 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
767 finishedAt: DateTime.formatIso(yield* DateTime.now),
768 entries: entries
769 .sort((a, b) => priority[a.outcome] - priority[b.outcome])
770 .slice(0, REPORT_ENTRY_LIMIT),
771 counts,
772 bytesFreed,
773 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
774 };
775 yield* SubscriptionRef.set(reportRef, latestReport);
776 return latestReport;
777 });
778 const worker = yield* makeDrainableWorker(
779 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
780 sweep(completion === undefined ? "automatic" : "manual").pipe(
781 Effect.exit,
782 Effect.flatMap((exit) =>
783 completion === undefined
784 ? exit.pipe(
785 Effect.asVoid,
786 Effect.catchCause((cause) =>
787 Effect.logWarning("storage cleanup failed", { cause }),
788 ),
789 )
790 : Deferred.done(completion, exit).pipe(Effect.asVoid),
791 ),
792 ),
793 );
794 const runNow = Effect.gen(function* () {
795 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
796 yield* worker.enqueue(completion);
797 return yield* Deferred.await(completion);
798 });
799​
800 const start = Effect.fn("StorageCleanup.start")(function* () {
801 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
802 Effect.sync(() => {
803 if (event.type === "snapshot") {
804 liveTerminals.clear();
805 for (const terminal of event.terminals) noteTerminal(terminal);
806 } else if (event.type === "upsert") {
807 noteTerminal(event.terminal);
808 } else {
809 const threadTerminals = liveTerminals.get(event.threadId);
810 threadTerminals?.delete(event.terminalId);
811 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
812 }
813 }),
814 );
815 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
816 const changes = yield* settingsService.subscribeChanges;
817 const events = engine.streamDomainEvents;
818 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
819 yield* forkParked(
820 worker
821 .enqueue(undefined)
822 .pipe(
823 Effect.andThen(worker.drain),
824 Effect.repeat(Schedule.spaced("1 hour")),
825 Effect.asVoid,
826 ),
827 );
828 yield* forkParked(
829 Stream.runForEach(changes, (settings) => {
830 if (
831 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
832 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
833 sameProjectWorktreePolicies(settings, lastSettings)
834 )
835 return Effect.void;
836 lastSettings = settings;
837 return worker.enqueue(undefined);
838 }),
839 );
840 yield* forkParked(
841 Stream.runForEach(events, (event) =>
842 (event.type === "thread.deleted" || event.type === "provider-session.updated") &&
843 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
844 ? worker.enqueue(undefined)
845 : Effect.void,
846 ).pipe(
847 Effect.catchCause((cause) =>
848 Effect.logWarning("Storage cleanup event stream failed", { cause }),
849 ),
850 ),
851 );
852 });
853 yield* start();
854 return StorageCleanup.of({
855 runNow,
856 latestReport: SubscriptionRef.get(reportRef),
857 reports: SubscriptionRef.changes(reportRef),
858 drain: worker.drain,
859 });
860});
861​
862export const layer = Layer.effect(StorageCleanup, make);