Open History to see the last commit
1import {
2 OrchestrationV2AppThreadJson,
3 OrchestrationV2ProviderSessionJson,
4} from "@t3tools/contracts";
5import * as Schema from "effect/Schema";
6import * as SqlClient from "effect/sql/SqlClient";
7import type {
8 OrchestrationV2ThreadShell,
9 ProjectId,
10 ServerSettings,
11 ServerSettingsError,
12 TerminalSummary,
13 WorktreeCleanupRules,
14} from "@t3tools/contracts";
15import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
16import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
17import * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Equal from "effect/Equal";
22import * as FileSystem from "effect/FileSystem";
23import * as Option from "effect/Option";
24import * as Path from "effect/Path";
25import type { PlatformError } from "effect/PlatformError";
26import * as Schedule from "effect/Schedule";
27import * as Stream from "effect/Stream";
28
29import * as ServerConfig from "./config.ts";
30import * as GitManager from "./git/GitManager.ts";
31import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
32import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
33import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
34import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts";
35import { forkParked } from "./serverActivation.ts";
36import * as Settings from "./serverSettings.ts";
37import * as TerminalManager from "./terminal/Manager.ts";
38import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";
39import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
40import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
41
42const decodeCleanupThread = Schema.decodeUnknownEffect(
43 Schema.fromJsonString(OrchestrationV2AppThreadJson),
44);
45const decodeCleanupSession = Schema.decodeUnknownEffect(
46 Schema.fromJsonString(OrchestrationV2ProviderSessionJson),
47);
48
49const DAY_MS = 86_400_000;
50
51const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) =>
52 rules.worktreeAfterDays !== null ||
53 rules.worktreeOnMerge ||
54 rules.worktreeOnDelete ||
55 rules.worktreeUnchanged;
56
57function anyWorktreePolicy(
58 settings: ServerSettings,
59 predicate: (rules: WorktreeCleanupRules) => boolean,
60): boolean {
61 return (
62 predicate(resolveWorktreeCleanup(settings, null)) ||
63 Object.keys(settings.projectSettingsOverrides).some((projectId) =>
64 predicate(resolveWorktreeCleanup(settings, projectId as ProjectId)),
65 )
66 );
67}
68
69function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings): boolean {
70 return [
71 ...new Set([
72 ...Object.keys(left.projectSettingsOverrides),
73 ...Object.keys(right.projectSettingsOverrides),
74 ]),
75 ].every((projectId) =>
76 Equal.equals(
77 left.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
78 right.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
79 ),
80 );
81}
82
83/** Live sessions keep their cwd even when no turn is currently running. */
84export function storageCleanupThreadIdle(thread: OrchestrationV2ThreadShell, now: number): boolean {
85 return (
86 thread.branch !== null &&
87 thread.worktreePath !== null &&
88 thread.activeRunId === null &&
89 (thread.status === "idle" ||
90 thread.status === "completed" ||
91 thread.status === "interrupted" ||
92 thread.status === "failed" ||
93 thread.status === "cancelled" ||
94 thread.status === "rolled_back") &&
95 (thread.pendingBackgroundTasks?.length ?? 0) === 0 &&
96 thread.pendingRuntimeRequest === null &&
97 !threadHasQueuedTurnStart(thread, now)
98 );
99}
100
101/** PR metadata refreshes must not reset the inactivity clock. */
102export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): number {
103 return Math.max(
104 ...[
105 thread.createdAt,
106 thread.latestUserMessageAt,
107 thread.latestRunRequestedAt,
108 thread.latestRunStartedAt,
109 thread.latestRunCompletedAt,
110 ].flatMap((value) => (value == null ? [] : [DateTime.toEpochMillis(value)])),
111 );
112}
113
114/**
115 * Whether the host's pull request proves this worktree's head was merged. A
116 * squash or rebase merge leaves the head outside the default branch, so the
117 * merged pull request then has to name this exact commit.
118 */
119export function storageCleanupPullRequestMerged(
120 pullRequest: Pick<
121 GitManager.GitBranchPullRequest,
122 "state" | "headRef" | "baseRef" | "headSha"
123 > | null,
124 worktree: {
125 readonly branch: string;
126 readonly defaultBranch: string;
127 readonly headSha: string;
128 readonly integrated: boolean;
129 },
130): boolean {
131 return (
132 pullRequest?.state === "merged" &&
133 (worktree.integrated ||
134 (pullRequest.headRef === worktree.branch &&
135 pullRequest.baseRef === worktree.defaultBranch &&
136 pullRequest.headSha === worktree.headSha))
137 );
138}
139
140export const make = Effect.gen(function* () {
141 const config = yield* ServerConfig.ServerConfig;
142 const settingsService = yield* Settings.ServerSettingsService;
143 const projectStore = yield* ProjectStore.ProjectStoreV2;
144 const engine = yield* Orchestrator.OrchestratorV2;
145 const projections = yield* ProjectionStore.ProjectionStoreV2;
146 const sql = yield* SqlClient.SqlClient;
147 const git = yield* GitVcsDriver.GitVcsDriver;
148 const gitManager = yield* GitManager.GitManager;
149 const terminals = yield* TerminalManager.TerminalManager;
150 const fs = yield* FileSystem.FileSystem;
151 const path = yield* Path.Path;
152 const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
153 const noteTerminal = (terminal: TerminalSummary) => {
154 const threadTerminals =
155 liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
156 threadTerminals.set(terminal.terminalId, terminal);
157 liveTerminals.set(terminal.threadId, threadTerminals);
158 };
159
160 const inside = (root: string, target: string) => {
161 const relative = path.relative(root, target);
162 return (
163 relative !== "" &&
164 relative !== ".." &&
165 !relative.startsWith(`..${path.sep}`) &&
166 !path.isAbsolute(relative)
167 );
168 };
169 const hasTerminal = (worktreePath: string) =>
170 [...liveTerminals.values()]
171 .flatMap((entries) => [...entries.values()])
172 .some((terminal) => {
173 if (terminal.status !== "starting" && terminal.status !== "running") return false;
174 const cwd = path.resolve(terminal.cwd);
175 return (
176 (terminal.worktreePath !== null &&
177 path.resolve(terminal.worktreePath) === worktreePath) ||
178 cwd === worktreePath ||
179 inside(worktreePath, cwd)
180 );
181 });
182
183 const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {
184 const active = yield* projections.getShellSnapshot();
185 const archived = yield* projections.getShellSnapshot({ location: "archive" });
186 const projects = yield* projectStore.listShells();
187 return { projects, threads: [...active.threads, ...archived.threads] };
188 });
189
190 // Local threads under another project need not have a worktreePath of their own.
191 const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* (
192 worktreePath: string,
193 projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
194 ) {
195 for (const project of projects) {
196 const projectPath = path.resolve(project.workspaceRoot);
197 if (projectPath === worktreePath || inside(worktreePath, projectPath)) return true;
198 const realPath = yield* fs
199 .realPath(projectPath)
200 .pipe(Effect.orElseSucceed(() => projectPath));
201 if (realPath === worktreePath || inside(worktreePath, realPath)) return true;
202 }
203 return false;
204 });
205
206 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
207 serverSettings: ServerSettings,
208 now: number,
209 ) {
210 if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
211 const roots: Array<string> = [];
212 for (const directory of managedWorktreesDirectories(
213 serverSettings,
214 config.worktreesDir,
215 path,
216 )) {
217 // An unmounted drive only skips its own worktrees.
218 const root = yield* fs.exists(directory).pipe(
219 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
220 Effect.orElseSucceed(() => null),
221 );
222 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
223 }
224 if (roots.length === 0) return;
225 const hasDeleteRule = anyWorktreePolicy(serverSettings, (rules) => rules.worktreeOnDelete);
226 const deletedRows = hasDeleteRule
227 ? yield* sql<{ payload_json: string; workspaceRoot: string }>`
228 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
229 FROM orchestration_v2_projection_threads t
230 JOIN projection_projects p ON p.project_id = t.project_id
231 WHERE t.deleted_at IS NOT NULL
232 `
233 : [];
234 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
235 decodeCleanupThread(row.payload_json).pipe(
236 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
237 ),
238 )).filter(
239 (thread) =>
240 thread.worktreePath !== null &&
241 thread.branch !== null &&
242 resolveWorktreeCleanup(serverSettings, thread.projectId).worktreeOnDelete,
243 );
244 const snapshot = yield* readThreads();
245 const refreshedDefaultRefs = new Map<string, Set<string>>();
246 const groups = Map.groupBy(
247 snapshot.threads.filter((thread) => thread.worktreePath !== null),
248 (thread) => path.resolve(thread.worktreePath!),
249 );
250 const candidates = [
251 ...[...groups.values()].flatMap((group) => (group.length === 1 ? [group[0]!] : [])),
252 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
253 ];
254 for (const thread of candidates) {
255 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
256 if (!worktreeCleanupEnabled(settings)) continue;
257 const worktreePath = path.resolve(thread.worktreePath!);
258 const deleted = "workspaceRoot" in thread;
259 const project = deleted
260 ? { workspaceRoot: thread.workspaceRoot }
261 : snapshot.projects.find((entry) => entry.id === thread.projectId);
262 if (
263 project === undefined ||
264 (!deleted && !storageCleanupThreadIdle(thread, now)) ||
265 hasTerminal(worktreePath)
266 )
267 continue;
268 yield* Effect.gen(function* () {
269 if (!(yield* fs.exists(worktreePath))) return;
270 // Roots are canonical, so compare canonical paths. A symlinked parent
271 // (a linked drive) is fine; a symlinked worktree directory is not.
272 const realPath = yield* fs.realPath(worktreePath);
273 const realParent = yield* fs.realPath(path.dirname(worktreePath));
274 if (realPath !== path.join(realParent, path.basename(worktreePath))) return;
275 if (!roots.some((root) => inside(root, realPath))) return;
276 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) return;
277 // A linked worktree has a .git file. Never remove a main checkout.
278 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") return;
279 const status = yield* git.statusDetailsLocal(worktreePath);
280 if (!status.isRepo || status.branch !== thread.branch || status.hasWorkingTreeChanges)
281 return;
282 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
283 const ignored = yield* git.execute({
284 operation: "StorageCleanup.ignoredFiles",
285 cwd: worktreePath,
286 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
287 maxOutputBytes: 64 * 1024,
288 });
289 // Ignored files can contain secrets or local datasets. Dependency installs
290 // are reproducible; every other ignored path prevents automatic removal.
291 if (
292 ignored.stdoutTruncated ||
293 ignored.stdout
294 .split("\0")
295 .some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))
296 )
297 return;
298 const old =
299 !deleted &&
300 settings.worktreeAfterDays !== null &&
301 storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
302 let eligible = deleted || old;
303 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
304 const repositoryCwd = path.resolve(project.workspaceRoot);
305 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
306 const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
307 if (branch === null) return;
308 const defaultRef = `refs/remotes/${remote}/${branch}`;
309 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
310 if (!refreshed.has(defaultRef)) {
311 yield* git.fetchRemoteTrackingBranch({
312 cwd: repositoryCwd,
313 remoteName: remote,
314 remoteBranch: branch,
315 });
316 refreshed.add(defaultRef);
317 refreshedDefaultRefs.set(repositoryCwd, refreshed);
318 }
319 const base = yield* git.resolveCommit({
320 cwd: worktreePath,
321 revision: defaultRef,
322 });
323 const ancestor = yield* git.execute({
324 operation: "StorageCleanup.integratedBranch",
325 cwd: worktreePath,
326 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
327 allowNonZeroExit: true,
328 });
329 const integrated = ancestor.exitCode === 0;
330 eligible = integrated && settings.worktreeUnchanged;
331 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
332 const pullRequest = yield* gitManager.branchPullRequest(
333 { cwd: worktreePath, branch: thread.branch },
334 { refresh: true },
335 );
336 eligible = storageCleanupPullRequestMerged(pullRequest, {
337 branch: thread.branch,
338 defaultBranch: branch,
339 headSha: head.commitSha,
340 integrated,
341 });
342 }
343 }
344 if (!eligible) return;
345 // Re-read after Git/host calls so a queued turn, resumed session or new
346 // thread sharing this path cancels the removal.
347 const latestSnapshot = yield* readThreads();
348 if (yield* containsProjectRoot(worktreePath, [project, ...latestSnapshot.projects])) return;
349 const latest = latestSnapshot.threads.filter(
350 (entry) =>
351 entry.worktreePath !== null && path.resolve(entry.worktreePath) === worktreePath,
352 );
353 if (hasTerminal(worktreePath)) return;
354 if (deleted) {
355 if (
356 latest.length > 0 ||
357 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
358 .worktreeOnDelete
359 )
360 return;
361 // V2 deletion queues durable cleanup. Do not remove its checkout until
362 // every effect has finished successfully or was explicitly cancelled.
363 const pendingCleanup = yield* sql`
364 SELECT 1 FROM orchestration_v2_effect_outbox
365 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1
366 `;
367 if (pendingCleanup.length > 0) return;
368 } else if (
369 latest.length !== 1 ||
370 latest[0]!.id !== thread.id ||
371 !storageCleanupThreadIdle(latest[0]!, now) ||
372 storageCleanupActivityAt(latest[0]!) !== storageCleanupActivityAt(thread)
373 )
374 return;
375 // Sessions can outlive their run and can be shared across app threads.
376 const sessionRows = yield* sql<{ payload_json: string }>`
377 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
378 WHERE status != 'stopped'
379 `;
380 const sessions = yield* Effect.forEach(sessionRows, (row) =>
381 decodeCleanupSession(row.payload_json),
382 );
383 if (
384 sessions.some((session) => {
385 const cwd = path.resolve(session.cwd);
386 return cwd === worktreePath || inside(worktreePath, cwd);
387 })
388 )
389 return;
390 const finalStatus = yield* git.statusDetailsLocal(worktreePath);
391 if (
392 !finalStatus.isRepo ||
393 finalStatus.branch !== thread.branch ||
394 finalStatus.hasWorkingTreeChanges
395 )
396 return;
397 if (
398 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
399 head.commitSha
400 )
401 return;
402 const finalIgnored = yield* git.execute({
403 operation: "StorageCleanup.ignoredFiles",
404 cwd: worktreePath,
405 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
406 maxOutputBytes: 64 * 1024,
407 });
408 if (
409 finalIgnored.stdoutTruncated ||
410 finalIgnored.stdout
411 .split("\0")
412 .some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))
413 )
414 return;
415 const current = resolveWorktreeCleanup(
416 yield* settingsService.getSettings,
417 thread.projectId,
418 );
419 if (
420 Object.keys(settings).some(
421 (key) =>
422 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
423 )
424 )
425 return;
426 yield* git.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath, force: false });
427 yield* gitManager.invalidateStatus(project.workspaceRoot);
428 // Preserve branch and path: ProviderTurnStartService recreates the checkout
429 // from that branch when the thread is resumed.
430 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
431 }).pipe(
432 (effect) => withWorkspaceLease(worktreePath, effect),
433 Effect.catch((error) =>
434 Effect.logDebug("storage cleanup skipped worktree", { threadId: thread.id, error }),
435 ),
436 );
437 }
438 });
439
440 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
441 root: string,
442 days: number | null,
443 now: number,
444 rotatedLogs: boolean,
445 ) {
446 if (days === null || !(yield* fs.exists(root))) return;
447 const realRoot = yield* fs.realPath(root);
448 if (realRoot !== path.resolve(root)) return;
449 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
450 directory: string,
451 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
452 for (const name of yield* fs.readDirectory(directory)) {
453 const target = path.join(directory, name);
454 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
455 const stat = yield* fs.stat(target);
456 if (stat.type === "Directory" && rotatedLogs) {
457 yield* visit(target);
458 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
459 const modified = Option.getOrNull(stat.mtime);
460 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
461 const current = (yield* settingsService.getSettings).storageCleanup;
462 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
463 return;
464 yield* fs.remove(target);
465 }
466 }
467 }
468 });
469 yield* visit(realRoot);
470 });
471
472 const sweep = Effect.fn("StorageCleanup.sweep")(function* () {
473 const serverSettings = yield* settingsService.getSettings;
474 const settings = serverSettings.storageCleanup;
475 const now = yield* Clock.currentTimeMillis;
476 yield* cleanWorktrees(serverSettings, now).pipe(
477 Effect.catch((error) => Effect.logWarning("worktree cleanup failed", { error })),
478 );
479 yield* cleanFiles(
480 config.browserArtifactsDir,
481 settings.browserArtifactsAfterDays,
482 now,
483 false,
484 ).pipe(
485 Effect.catch((error) => Effect.logWarning("browser artifact cleanup failed", { error })),
486 );
487 yield* cleanFiles(config.logsDir, settings.logsAfterDays, now, true).pipe(
488 Effect.catch((error) => Effect.logWarning("rotated log cleanup failed", { error })),
489 );
490 });
491 const worker = yield* makeDrainableWorker(() =>
492 sweep().pipe(
493 Effect.catchCauseIf(
494 (cause) => !Cause.hasInterruptsOnly(cause),
495 (cause) => Effect.logWarning("storage cleanup failed", { cause }),
496 ),
497 ),
498 );
499
500 const start = Effect.fn("StorageCleanup.start")(function* () {
501 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
502 Effect.sync(() => {
503 if (event.type === "snapshot") {
504 liveTerminals.clear();
505 for (const terminal of event.terminals) noteTerminal(terminal);
506 } else if (event.type === "upsert") {
507 noteTerminal(event.terminal);
508 } else {
509 const threadTerminals = liveTerminals.get(event.threadId);
510 threadTerminals?.delete(event.terminalId);
511 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
512 }
513 }),
514 );
515 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
516 const changes = yield* settingsService.subscribeChanges;
517 const events = engine.streamDomainEvents;
518 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
519 yield* forkParked(
520 worker
521 .enqueue(undefined)
522 .pipe(
523 Effect.andThen(worker.drain),
524 Effect.repeat(Schedule.spaced("1 hour")),
525 Effect.asVoid,
526 ),
527 );
528 yield* forkParked(
529 Stream.runForEach(changes, (settings) => {
530 if (
531 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
532 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
533 sameProjectWorktreePolicies(settings, lastSettings)
534 )
535 return Effect.void;
536 lastSettings = settings;
537 return worker.enqueue(undefined);
538 }),
539 );
540 yield* forkParked(
541 Stream.runForEach(events, (event) =>
542 (event.type === "thread.deleted" || event.type === "provider-session.updated") &&
543 anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
544 ? worker.enqueue(undefined)
545 : Effect.void,
546 ).pipe(
547 Effect.catchCause((cause) =>
548 Effect.logWarning("Storage cleanup event stream failed", { cause }),
549 ),
550 ),
551 );
552 });
553 return { start, drain: worker.drain };
554});