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