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