Open History to see the last commit
1import type {
2 OrchestrationThreadShell,
3 ProjectId,
4 ServerSettings,
5 ServerSettingsError,
6 TerminalSummary,
7 WorktreeCleanupRules,
8} from "@t3tools/contracts";
9import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
10import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11import * as Cause from "effect/Cause";
12import * as Clock from "effect/Clock";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Equal from "effect/Equal";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import type { PlatformError } from "effect/PlatformError";
22import * as Schedule from "effect/Schedule";
23import type * as Scope from "effect/Scope";
24import * as Stream from "effect/Stream";
25
26import * as ServerConfig from "./config.ts";
27import * as GitManager from "./git/GitManager.ts";
28import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
29import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
30import * as ThreadDeletionReactor from "./orchestration/Services/ThreadDeletionReactor.ts";
31import * as ProviderService from "./provider/Services/ProviderService.ts";
32import { threadHasQueuedTurnStart } from "./orchestration/ThreadSettlementPolicy.ts";
33import { forkParked } from "./serverActivation.ts";
34import * as Settings from "./serverSettings.ts";
35import * as TerminalManager from "./terminal/Manager.ts";
36import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
37import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
38
39export class StorageCleanup extends Context.Service<
40 StorageCleanup,
41 {
42 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
43 readonly drain: Effect.Effect<void>;
44 }
45>()("t3/storageCleanup") {}
46
47const DAY_MS = 86_400_000;
48
49const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) =>
50 rules.worktreeAfterDays !== null ||
51 rules.worktreeOnMerge ||
52 rules.worktreeOnDelete ||
53 rules.worktreeUnchanged;
54
55function anyWorktreePolicy(
56 settings: ServerSettings,
57 predicate: (rules: WorktreeCleanupRules) => boolean,
58): boolean {
59 return (
60 predicate(resolveWorktreeCleanup(settings, null)) ||
61 Object.keys(settings.projectSettingsOverrides).some((projectId) =>
62 predicate(resolveWorktreeCleanup(settings, projectId as ProjectId)),
63 )
64 );
65}
66
67function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings): boolean {
68 return [
69 ...new Set([
70 ...Object.keys(left.projectSettingsOverrides),
71 ...Object.keys(right.projectSettingsOverrides),
72 ]),
73 ].every((projectId) =>
74 Equal.equals(
75 left.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
76 right.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
77 ),
78 );
79}
80
81/** Live sessions keep their cwd even when no turn is currently running. */
82function storageCleanupThreadIdle(thread: OrchestrationThreadShell, now: number): boolean {
83 return (
84 thread.branch !== null &&
85 thread.worktreePath !== null &&
86 (thread.session === null || thread.session.status === "stopped") &&
87 thread.latestTurn?.state !== "running" &&
88 thread.backgroundLiveness == null &&
89 !thread.hasPendingApprovals &&
90 !thread.hasPendingUserInput &&
91 !threadHasQueuedTurnStart(thread, DateTime.formatIso(DateTime.makeUnsafe(now)))
92 );
93}
94
95/** PR metadata refreshes must not reset the inactivity clock. */
96function storageCleanupActivityAt(thread: OrchestrationThreadShell): number {
97 return Math.max(
98 ...[
99 thread.createdAt,
100 thread.latestUserMessageAt,
101 thread.latestTurn?.requestedAt,
102 thread.latestTurn?.startedAt,
103 thread.latestTurn?.completedAt,
104 ].flatMap((value) => (value == null ? [] : [Date.parse(value)])),
105 );
106}
107
108export const make = Effect.gen(function* () {
109 const config = yield* ServerConfig.ServerConfig;
110 const settingsService = yield* Settings.ServerSettingsService;
111 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
112 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
113 const threadDeletion = yield* ThreadDeletionReactor.ThreadDeletionReactor;
114 const providers = yield* ProviderService.ProviderService;
115 const git = yield* GitVcsDriver.GitVcsDriver;
116 const gitManager = yield* GitManager.GitManager;
117 const terminals = yield* TerminalManager.TerminalManager;
118 const fs = yield* FileSystem.FileSystem;
119 const path = yield* Path.Path;
120 const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
121 const noteTerminal = (terminal: TerminalSummary) => {
122 const threadTerminals =
123 liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
124 threadTerminals.set(terminal.terminalId, terminal);
125 liveTerminals.set(terminal.threadId, threadTerminals);
126 };
127
128 const inside = (root: string, target: string) => {
129 const relative = path.relative(root, target);
130 return (
131 relative !== "" &&
132 relative !== ".." &&
133 !relative.startsWith(`..${path.sep}`) &&
134 !path.isAbsolute(relative)
135 );
136 };
137 const hasTerminal = (worktreePath: string) =>
138 [...liveTerminals.values()]
139 .flatMap((entries) => [...entries.values()])
140 .some((terminal) => {
141 if (terminal.status !== "starting" && terminal.status !== "running") return false;
142 const cwd = path.resolve(terminal.cwd);
143 return (
144 (terminal.worktreePath !== null &&
145 path.resolve(terminal.worktreePath) === worktreePath) ||
146 cwd === worktreePath ||
147 inside(worktreePath, cwd)
148 );
149 });
150
151 const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {
152 const active = yield* snapshots.getShellSnapshot();
153 const archived = yield* snapshots.getArchivedShellSnapshot();
154 return { projects: active.projects, threads: [...active.threads, ...archived.threads] };
155 });
156
157 // Local threads under another project need not have a worktreePath of their own.
158 const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* (
159 worktreePath: string,
160 projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
161 ) {
162 for (const project of projects) {
163 const projectPath = path.resolve(project.workspaceRoot);
164 if (projectPath === worktreePath || inside(worktreePath, projectPath)) return true;
165 const realPath = yield* fs
166 .realPath(projectPath)
167 .pipe(Effect.orElseSucceed(() => projectPath));
168 if (realPath === worktreePath || inside(worktreePath, realPath)) return true;
169 }
170 return false;
171 });
172
173 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
174 serverSettings: ServerSettings,
175 now: number,
176 ) {
177 if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
178 if (!(yield* fs.exists(config.worktreesDir))) return;
179 const hasDeleteRule = anyWorktreePolicy(serverSettings, (rules) => rules.worktreeOnDelete);
180 const deletedThreads = hasDeleteRule
181 ? (yield* snapshots.getDeletedWorktreeThreads()).filter(
182 (thread) => resolveWorktreeCleanup(serverSettings, thread.projectId).worktreeOnDelete,
183 )
184 : [];
185 if (deletedThreads.length > 0) {
186 // Read tombstones before taking this fence. A later deletion waits for the
187 // next sweep; every captured deletion must finish stopping its resources.
188 const { snapshotSequence } = yield* snapshots.getSnapshotSequence();
189 yield* threadDeletion.drainThrough(snapshotSequence);
190 }
191 const snapshot = yield* readThreads();
192 const root = yield* fs.realPath(config.worktreesDir);
193 const refreshedDefaultRefs = new Map<string, Set<string>>();
194 const groups = Map.groupBy(
195 snapshot.threads.filter((thread) => thread.worktreePath !== null),
196 (thread) => path.resolve(thread.worktreePath!),
197 );
198 const candidates = [
199 ...[...groups.values()].flatMap((group) => (group.length === 1 ? [group[0]!] : [])),
200 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath))),
201 ];
202 for (const thread of candidates) {
203 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
204 if (!worktreeCleanupEnabled(settings)) continue;
205 const worktreePath = path.resolve(thread.worktreePath!);
206 const deleted = "deletedAt" in thread;
207 const project = deleted
208 ? { workspaceRoot: thread.workspaceRoot }
209 : snapshot.projects.find((entry) => entry.id === thread.projectId);
210 if (
211 project === undefined ||
212 (!deleted && !storageCleanupThreadIdle(thread, now)) ||
213 hasTerminal(worktreePath)
214 )
215 continue;
216 yield* Effect.gen(function* () {
217 if (!inside(root, worktreePath) || !(yield* fs.exists(worktreePath))) return;
218 if ((yield* fs.realPath(worktreePath)) !== worktreePath) return;
219 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) return;
220 // A linked worktree has a .git file. Never remove a main checkout.
221 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") return;
222 const status = yield* git.statusDetailsLocal(worktreePath);
223 if (!status.isRepo || status.branch !== thread.branch || status.hasWorkingTreeChanges)
224 return;
225 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
226 const ignored = yield* git.execute({
227 operation: "StorageCleanup.ignoredFiles",
228 cwd: worktreePath,
229 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
230 maxOutputBytes: 64 * 1024,
231 });
232 // Ignored files can contain secrets or local datasets. Dependency installs
233 // are reproducible; every other ignored path prevents automatic removal.
234 if (
235 ignored.stdoutTruncated ||
236 ignored.stdout
237 .split("\0")
238 .some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))
239 )
240 return;
241 const old =
242 !deleted &&
243 settings.worktreeAfterDays !== null &&
244 storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
245 let eligible = deleted || old;
246 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
247 const repositoryCwd = path.resolve(project.workspaceRoot);
248 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
249 const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
250 if (branch === null) return;
251 const defaultRef = `refs/remotes/${remote}/${branch}`;
252 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
253 if (!refreshed.has(defaultRef)) {
254 yield* git.fetchRemoteTrackingBranch({
255 cwd: repositoryCwd,
256 remoteName: remote,
257 remoteBranch: branch,
258 });
259 refreshed.add(defaultRef);
260 refreshedDefaultRefs.set(repositoryCwd, refreshed);
261 }
262 const base = yield* git.resolveCommit({
263 cwd: worktreePath,
264 revision: defaultRef,
265 });
266 const ancestor = yield* git.execute({
267 operation: "StorageCleanup.integratedBranch",
268 cwd: worktreePath,
269 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
270 allowNonZeroExit: true,
271 });
272 if (ancestor.exitCode !== 0) return;
273 eligible = settings.worktreeUnchanged;
274 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
275 const pullRequest = yield* gitManager.branchPullRequest(
276 { cwd: worktreePath, branch: thread.branch },
277 { refresh: true },
278 );
279 eligible = pullRequest?.state === "merged";
280 }
281 }
282 if (!eligible) return;
283 // Re-read after Git/host calls so a queued turn, resumed session or new
284 // thread sharing this path cancels the removal.
285 const latestSnapshot = yield* readThreads();
286 if (yield* containsProjectRoot(worktreePath, [project, ...latestSnapshot.projects])) return;
287 const latest = latestSnapshot.threads.filter(
288 (entry) =>
289 entry.worktreePath !== null && path.resolve(entry.worktreePath) === worktreePath,
290 );
291 if (hasTerminal(worktreePath)) return;
292 if (deleted) {
293 if (
294 latest.length > 0 ||
295 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
296 .worktreeOnDelete
297 )
298 return;
299 // A failed session stop is logged by the deletion reactor. Its drain
300 // alone is not proof that a provider released this checkout.
301 if (
302 (yield* providers.listSessions()).some(
303 (session) =>
304 session.status !== "closed" &&
305 (session.threadId === thread.id ||
306 (session.cwd !== undefined &&
307 (path.resolve(session.cwd) === worktreePath ||
308 inside(worktreePath, path.resolve(session.cwd))))),
309 )
310 )
311 return;
312 } else if (
313 latest.length !== 1 ||
314 latest[0]!.id !== thread.id ||
315 !storageCleanupThreadIdle(latest[0]!, now) ||
316 storageCleanupActivityAt(latest[0]!) !== storageCleanupActivityAt(thread)
317 )
318 return;
319 const finalStatus = yield* git.statusDetailsLocal(worktreePath);
320 if (
321 !finalStatus.isRepo ||
322 finalStatus.branch !== thread.branch ||
323 finalStatus.hasWorkingTreeChanges
324 )
325 return;
326 if (
327 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
328 head.commitSha
329 )
330 return;
331 const finalIgnored = yield* git.execute({
332 operation: "StorageCleanup.ignoredFiles",
333 cwd: worktreePath,
334 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
335 maxOutputBytes: 64 * 1024,
336 });
337 if (
338 finalIgnored.stdoutTruncated ||
339 finalIgnored.stdout
340 .split("\0")
341 .some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))
342 )
343 return;
344 const current = resolveWorktreeCleanup(
345 yield* settingsService.getSettings,
346 thread.projectId,
347 );
348 if (
349 Object.keys(settings).some(
350 (key) =>
351 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
352 )
353 )
354 return;
355 yield* git.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath, force: false });
356 yield* gitManager.invalidateStatus(project.workspaceRoot);
357 // Preserve branch and path: ProviderCommandReactor recreates the checkout
358 // from that branch when the thread is resumed.
359 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
360 }).pipe(
361 (effect) => withWorkspaceLease(worktreePath, effect),
362 Effect.catch((error) =>
363 Effect.logDebug("storage cleanup skipped worktree", { threadId: thread.id, error }),
364 ),
365 );
366 }
367 });
368
369 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
370 root: string,
371 days: number | null,
372 now: number,
373 rotatedLogs: boolean,
374 ) {
375 if (days === null || !(yield* fs.exists(root))) return;
376 const realRoot = yield* fs.realPath(root);
377 if (realRoot !== path.resolve(root)) return;
378 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
379 directory: string,
380 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
381 for (const name of yield* fs.readDirectory(directory)) {
382 const target = path.join(directory, name);
383 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
384 const stat = yield* fs.stat(target);
385 if (stat.type === "Directory" && rotatedLogs) {
386 yield* visit(target);
387 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
388 const modified = Option.getOrNull(stat.mtime);
389 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
390 const current = (yield* settingsService.getSettings).storageCleanup;
391 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
392 return;
393 yield* fs.remove(target);
394 }
395 }
396 }
397 });
398 yield* visit(realRoot);
399 });
400
401 const sweep = Effect.fn("StorageCleanup.sweep")(function* () {
402 const serverSettings = yield* settingsService.getSettings;
403 const settings = serverSettings.storageCleanup;
404 const now = yield* Clock.currentTimeMillis;
405 yield* cleanWorktrees(serverSettings, now).pipe(
406 Effect.catch((error) => Effect.logWarning("worktree cleanup failed", { error })),
407 );
408 yield* cleanFiles(
409 config.browserArtifactsDir,
410 settings.browserArtifactsAfterDays,
411 now,
412 false,
413 ).pipe(
414 Effect.catch((error) => Effect.logWarning("browser artifact cleanup failed", { error })),
415 );
416 yield* cleanFiles(config.logsDir, settings.logsAfterDays, now, true).pipe(
417 Effect.catch((error) => Effect.logWarning("rotated log cleanup failed", { error })),
418 );
419 });
420 const worker = yield* makeDrainableWorker(() =>
421 sweep().pipe(
422 Effect.catchCause((cause) =>
423 Cause.hasInterruptsOnly(cause)
424 ? Effect.failCause(cause)
425 : Effect.logWarning("storage cleanup failed", { cause }),
426 ),
427 ),
428 );
429
430 const start = Effect.fn("StorageCleanup.start")(function* () {
431 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
432 Effect.sync(() => {
433 if (event.type === "snapshot") {
434 liveTerminals.clear();
435 for (const terminal of event.terminals) noteTerminal(terminal);
436 } else if (event.type === "upsert") {
437 noteTerminal(event.terminal);
438 } else {
439 const threadTerminals = liveTerminals.get(event.threadId);
440 threadTerminals?.delete(event.terminalId);
441 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
442 }
443 }),
444 );
445 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
446 const changes = yield* settingsService.subscribeChanges;
447 const events = yield* engine.subscribeDomainEvents;
448 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
449 yield* forkParked(
450 worker
451 .enqueue(undefined)
452 .pipe(
453 Effect.andThen(worker.drain),
454 Effect.repeat(Schedule.spaced("1 hour")),
455 Effect.asVoid,
456 ),
457 );
458 yield* forkParked(
459 Stream.runForEach(changes, (settings) => {
460 if (
461 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
462 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
463 sameProjectWorktreePolicies(settings, lastSettings)
464 )
465 return Effect.void;
466 lastSettings = settings;
467 return worker.enqueue(undefined);
468 }),
469 );
470 yield* forkParked(
471 Stream.runForEach(events, (event) =>
472 event.type === "thread.deleted" &&
473 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
474 ? worker.enqueue(undefined)
475 : Effect.void,
476 ),
477 );
478 });
479 return { start, drain: worker.drain } satisfies StorageCleanup["Service"];
480});
481
482export const layer = Layer.effect(StorageCleanup, make);