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