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