Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

storageCleanup.ts

1,361 lines56.6 KB

1import {
2 GitCommandError,
3 OrchestrationV2AppThreadJson,
4 OrchestrationV2ProviderSessionJson,
5} from "@t3tools/contracts";
6import * as Schema from "effect/Schema";
7import * as SqlClient from "effect/sql/SqlClient";
8import type {
9 OrchestrationV2ThreadShell,
10 ProjectId,
11 ServerSettings,
12 ServerSettingsError,
13 TerminalSummary,
14 WorktreeCleanupRules,
15 StorageCleanupReport,
16 StorageCleanupReportEntry,
17} from "@t3tools/contracts";
18import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
19import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
20import * as Context from "effect/Context";
21import * as Deferred from "effect/Deferred";
22import * as Layer from "effect/Layer";
23import * as Clock from "effect/Clock";
24import * as DateTime from "effect/DateTime";
25import * as Effect from "effect/Effect";
26import * as Equal from "effect/Equal";
27import * as FileSystem from "effect/FileSystem";
28import * as Option from "effect/Option";
29import * as Path from "effect/Path";
30import * as Ref from "effect/Ref";
31import type { PlatformError } from "effect/PlatformError";
32import * as Schedule from "effect/Schedule";
33import * as Stream from "effect/Stream";
34import * as SubscriptionRef from "effect/SubscriptionRef";
35import { parse as parseYaml } from "yaml";
36​
37import * as ServerConfig from "./config.ts";
38import * as GitManager from "./git/GitManager.ts";
39import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
40import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
41import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
42import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
43import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts";
44import { forkParked } from "./serverActivation.ts";
45import * as Settings from "./serverSettings.ts";
46import * as TerminalManager from "./terminal/Manager.ts";
47import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";
48import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
49import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";
50import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
51import * as HostProcess from "@t3tools/shared/HostProcess";
52import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
53import { isNetworkPath } from "@t3tools/shared/path";
54​
55const decodeCleanupThread = Schema.decodeUnknownEffect(
56 Schema.fromJsonString(OrchestrationV2AppThreadJson),
57);
58const decodeCleanupSession = Schema.decodeUnknownEffect(
59 Schema.fromJsonString(OrchestrationV2ProviderSessionJson),
60);
61// pnpm 11 writes this file as JSON, older versions as YAML.
62const decodePnpmModulesManifest = Schema.decodeUnknownEffect(
63 Schema.Struct({
64 storeDir: Schema.String,
65 virtualStoreDir: Schema.optional(Schema.String),
66 }),
67);
68​
69const DAY_MS = 86_400_000;
70// Give settle scripts time to open terminals that protect the worktree.
71const SETTLE_SCRIPT_GRACE_MS = 60_000;
72// Worktree creation can precede its thread row, including review-guide checkouts.
73const ORPHAN_WORKTREE_GRACE_MS = 60 * 60 * 1_000;
74​
75const sentence = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
76const REPORT_ENTRY_LIMIT = 200;
77const isGitCommandError = Schema.is(GitCommandError);
78​
79function cleanupFailureReason(error: { readonly message: string }) {
80 return isGitCommandError(error)
81 ? `${error.command}: ${error.detail.split(/\r?\n/)[0]}${error.reason ? ` (${error.reason})` : ""}`
82 : (error.message.split(/\r?\n/)[0] ?? error.message);
84​
85const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) =>
86 rules.worktreeAfterDays !== null ||
87 rules.worktreeSettledAfterDays !== null ||
88 rules.worktreeOnMerge ||
89 rules.worktreeOnDelete ||
90 rules.worktreeUnchanged;
91​
92function anyWorktreePolicy(
93 settings: ServerSettings,
94 predicate: (rules: WorktreeCleanupRules) => boolean,
95): boolean {
96 return (
97 predicate(resolveWorktreeCleanup(settings, null)) ||
98 Object.keys(settings.projectSettingsOverrides).some((projectId) =>
99 predicate(resolveWorktreeCleanup(settings, projectId as ProjectId)),
100 )
101 );
103​
104function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings): boolean {
105 return [
106 ...new Set([
107 ...Object.keys(left.projectSettingsOverrides),
108 ...Object.keys(right.projectSettingsOverrides),
109 ]),
110 ].every((projectId) =>
111 Equal.equals(
112 left.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
113 right.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
114 ),
115 );
117​
118type LimitRecoverySettings = Pick<
119 ServerSettings,
120 "autoResumeLimitedThreads" | "snoozeLimitedThreads"
121>;
122​
123export function storageCleanupThreadIdle(
124 thread: OrchestrationV2ThreadShell,
125 now: number,
126 settings: LimitRecoverySettings,
127): boolean {
128 return (
129 thread.worktreePath !== null &&
130 thread.activeRunId === null &&
131 (thread.status === "idle" ||
132 thread.status === "completed" ||
133 thread.status === "interrupted" ||
134 thread.status === "failed" ||
135 thread.status === "cancelled" ||
136 thread.status === "rolled_back") &&
137 (thread.pendingBackgroundTasks?.length ?? 0) === 0 &&
138 thread.pendingRuntimeRequest === null &&
139 !threadHasQueuedTurnStart(thread, now) &&
140 !heldForLimitRecovery(thread, now, settings)
141 );
143​
144// A run held for its usage-limit reset has its work still ahead of it, and a
145// fresh worktree would otherwise look unchanged and be removed before it runs.
146function heldForLimitRecovery(
147 thread: OrchestrationV2ThreadShell,
148 now: number,
149 settings: LimitRecoverySettings,
150): boolean {
151 if (
152 thread.status !== "failed" ||
153 thread.lastErrorClass !== "usage_limit" ||
154 !thread.usageLimitResetAt ||
155 thread.archivedAt !== null ||
156 thread.settledOverride === "settled"
157 )
158 return false;
159 const resetMs = Date.parse(thread.usageLimitResetAt);
160 const recovery = thread.limitRecovery;
161 if (recovery?.runId === thread.latestRunId && recovery.resetAt === thread.usageLimitResetAt)
162 // An auto-resume holds until its continuation replaces the failed run.
163 return recovery.autoResume || (recovery.snooze === true && resetMs > now);
164 // The recovery worker arms this failure on a later tick; hold it until then.
165 // Like the worker, skip a reset that had already passed when the run ended.
166 if (
167 !Number.isFinite(resetMs) ||
168 resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt)
169 )
170 return false;
171 return settings.autoResumeLimitedThreads || (settings.snoozeLimitedThreads && resetMs > now);
173​
174/** PR metadata refreshes must not reset the inactivity clock. */
175export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): number {
176 return Math.max(
177 ...[
178 thread.createdAt,
179 thread.latestUserMessageAt,
180 thread.latestRunRequestedAt,
181 thread.latestRunStartedAt,
182 thread.latestRunCompletedAt,
183 ].flatMap((value) => (value == null ? [] : [DateTime.toEpochMillis(value)])),
184 );
186​
187/** Only a complete subagent or side chat chain within this worktree shares ownership. */
188function worktreeOwner<T extends Pick<OrchestrationV2ThreadShell, "id" | "lineage">>(
189 threads: ReadonlyArray<T>,
190) {
191 if (threads.length === 1) return threads[0];
192 const byId = new Map(threads.map((thread) => [thread.id, thread]));
193 const tops = threads.filter((thread) => !byId.has(thread.lineage.parentThreadId!));
194 if (tops.length !== 1) return undefined;
195 const owner = tops[0]!;
196 for (const thread of threads) {
197 let current = thread;
198 const seen = new Set<string>();
199 while (current.id !== owner.id) {
200 if (
201 seen.has(current.id) ||
202 (current.lineage.relationshipToParent !== "subagent" &&
203 current.lineage.sideChat !== true) ||
204 current.lineage.rootThreadId !== owner.lineage.rootThreadId
205 )
206 return undefined;
207 seen.add(current.id);
208 const parent = byId.get(current.lineage.parentThreadId!);
209 if (parent === undefined) return undefined;
210 current = parent;
211 }
212 }
213 return owner;
215​
216/** Squash/rebase merges require the merged PR to name this exact head commit. */
217export function storageCleanupPullRequestMerged(
218 pullRequest: Pick<
219 GitManager.GitBranchPullRequest,
220 "state" | "headRef" | "baseRef" | "headSha"
221 > | null,
222 worktree: {
223 readonly branch: string;
224 readonly defaultBranch: string;
225 readonly headSha: string;
226 readonly integrated: boolean;
227 },
228): boolean {
229 return (
230 pullRequest?.state === "merged" &&
231 (worktree.integrated ||
232 (pullRequest.headRef === worktree.branch &&
233 pullRequest.baseRef === worktree.defaultBranch &&
234 pullRequest.headSha === worktree.headSha))
235 );
237​
238export class StorageCleanup extends Context.Service<
239 StorageCleanup,
240 {
241 readonly runNow: Effect.Effect<StorageCleanupReport, ServerSettingsError>;
242 readonly latestReport: Effect.Effect<StorageCleanupReport | null>;
243 readonly reports: Stream.Stream<StorageCleanupReport | null>;
244 readonly drain: Effect.Effect<void>;
245 }
246>()("t3/storageCleanup") {}
247​
248const make = Effect.gen(function* () {
249 const config = yield* ServerConfig.ServerConfig;
250 const settingsService = yield* Settings.ServerSettingsService;
251 const projectStore = yield* ProjectStore.ProjectStoreV2;
252 const engine = yield* Orchestrator.OrchestratorV2;
253 const projections = yield* ProjectionStore.ProjectionStoreV2;
254 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
255 const sql = yield* SqlClient.SqlClient;
256 const git = yield* GitVcsDriver.GitVcsDriver;
257 const gitManager = yield* GitManager.GitManager;
258 const terminals = yield* TerminalManager.TerminalManager;
259 const fs = yield* FileSystem.FileSystem;
260 const path = yield* Path.Path;
261 const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
262 const orphanSizes = new Map<string, number | null>();
263 const noteTerminal = (terminal: TerminalSummary) => {
264 const threadTerminals =
265 liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
266 threadTerminals.set(terminal.terminalId, terminal);
267 liveTerminals.set(terminal.threadId, threadTerminals);
268 };
269​
270 const isWindows = yield* HostProcess.isWindows;
271 const pathKey = (target: string) => {
272 const resolved = path.resolve(target);
273 return isWindows ? resolved.toLowerCase() : resolved;
274 };
275 const inside = (root: string, target: string) => {
276 const relative = path.relative(pathKey(root), pathKey(target));
277 return (
278 relative !== "" &&
279 relative !== ".." &&
280 !relative.startsWith(`..${path.sep}`) &&
281 !path.isAbsolute(relative)
282 );
283 };
284 const hasTerminal = (worktreePath: string) =>
285 [...liveTerminals.values()]
286 .flatMap((entries) => [...entries.values()])
287 .some((terminal) => {
288 if (terminal.status !== "starting" && terminal.status !== "running") return false;
289 const cwd = path.resolve(terminal.cwd);
290 return (
291 (terminal.worktreePath !== null &&
292 pathKey(terminal.worktreePath) === pathKey(worktreePath)) ||
293 pathKey(cwd) === pathKey(worktreePath) ||
294 inside(worktreePath, cwd)
295 );
296 });
297​
298 // pnpm imports packages by clone or reflink when its store shares a device
299 // with the worktree. Those files have one link but share blocks with the
300 // store, so removing them frees almost nothing. A store on another device
301 // forces real copies, which still count.
302 const sharedPnpmVirtualStore = Effect.fnUntraced(
303 function* (root: string) {
304 const nodeModules = path.join(root, "node_modules");
305 const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml"));
306 const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text)));
307 // An agent can write this manifest, and statting a network path makes
308 // Windows sign in to its host with the user's NTLM credentials.
309 if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) {
310 return null;
311 }
312 const virtualStore = path.resolve(nodeModules, manifest.virtualStoreDir ?? ".pnpm");
313 const [store, virtual] = yield* Effect.all([
314 fs.stat(manifest.storeDir),
315 fs.stat(virtualStore),
316 ]);
317 return store.dev === virtual.dev ? virtualStore : null;
318 },
319 Effect.orElseSucceed(() => null),
320 );
321​
322 const measureWorktree = Effect.fn("storageCleanup.measureWorktree")(
323 function* (worktreePath: string) {
324 const root = yield* fs.realPath(worktreePath);
325 const skipped = yield* sharedPnpmVirtualStore(root);
326 const pending = [root];
327 let entries = 1;
328 let bytes = 0;
329 while (pending.length > 0) {
330 const target = pending.pop()!;
331 if (target === skipped) continue;
332 // Effect's stat follows links. Probe with readLink first to get lstat
333 // semantics, including skipping dangling links and directory links.
334 const isLink = yield* fs.readLink(target).pipe(
335 Effect.as(true),
336 Effect.catchIf(
337 (error) =>
338 error.cause instanceof Error &&
339 "code" in error.cause &&
340 error.cause.code === "EINVAL",
341 () => Effect.succeed(false),
342 ),
343 );
344 if (isLink) continue;
345 if ((yield* fs.realPath(target)) !== target) return null;
346 const stat = yield* fs.stat(target);
347 if (stat.type === "File") {
348 // Removing a shared hardlink leaves its blocks allocated.
349 if (Option.getOrElse(stat.nlink, () => 1n) !== 1n) continue;
350 bytes += Option.match(stat.blocks, {
351 onNone: () => Number(stat.size),
352 onSome: (blocks) => Number(blocks * 512n),
353 });
354 } else if (stat.type === "Directory") {
355 const names = yield* fs.readDirectory(target);
356 entries += names.length;
357 if (entries > 2_000_000) return null;
358 for (const name of names) {
359 const child = path.join(target, name);
360 if (!inside(root, child)) return null;
361 pending.push(child);
362 }
363 }
364 }
365 return bytes;
366 },
367 Effect.timeout("30 seconds"),
368 Effect.orElseSucceed(() => null),
369 );
370​
371 // Large snapshots take seconds; use the reader worker instead of blocking the event loop.
372 const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {
373 const snapshot = yield* projections.getShellSnapshot().pipe(NodeSqliteClient.readOnly);
374 const projects = yield* projectStore.listShells();
375 return { projects, threads: [...snapshot.threads, ...snapshot.archivedThreads] };
376 });
377​
378 const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* (
379 worktreePath: string,
380 projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
381 ) {
382 for (const project of projects) {
383 const projectPath = path.resolve(project.workspaceRoot);
384 if (pathKey(projectPath) === pathKey(worktreePath) || inside(worktreePath, projectPath))
385 return true;
386 const realPath = yield* fs
387 .realPath(projectPath)
388 .pipe(Effect.orElseSucceed(() => projectPath));
389 if (pathKey(realPath) === pathKey(worktreePath) || inside(worktreePath, realPath))
390 return true;
391 }
392 return false;
393 });
394​
395 const reportOrphanWorktrees = Effect.fn("StorageCleanup.reportOrphanWorktrees")(function* (
396 roots: ReadonlyArray<string>,
397 projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
398 entries: StorageCleanupReportEntry[],
399 ) {
400 const rows = yield* sql<{ worktreePath: string }>`
401 SELECT DISTINCT json_extract(payload_json, '$.worktreePath') AS "worktreePath"
402 FROM orchestration_v2_projection_threads
403 WHERE json_extract(payload_json, '$.worktreePath') IS NOT NULL
404 `.pipe(NodeSqliteClient.readOnly);
405 const referenced = new Set<string>();
406 for (const row of rows) {
407 const resolved = path.resolve(row.worktreePath);
408 referenced.add(pathKey(resolved));
409 referenced.add(
410 pathKey(yield* fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved))),
411 );
412 }
413 const referencedAncestors = new Set<string>();
414 for (let ancestor of referenced) {
415 while (roots.some((root) => inside(root, ancestor))) {
416 ancestor = pathKey(path.dirname(ancestor));
417 referencedAncestors.add(ancestor);
418 }
419 }
420 const projectRoots = (yield* Effect.forEach(
421 yield* Effect.filter(projects, (project) =>
422 fs.exists(path.resolve(project.workspaceRoot)).pipe(Effect.orElseSucceed(() => true)),
423 ),
424 (project) => {
425 const resolved = path.resolve(project.workspaceRoot);
426 return fs.realPath(resolved).pipe(
427 Effect.orElseSucceed(() => resolved),
428 Effect.map((realPath) => [resolved, realPath]),
429 );
430 },
431 )).flat();
432 const inProject = (target: string, managedRoot: string) =>
433 projectRoots.some(
434 (root) =>
435 !inside(root, managedRoot) && (pathKey(root) === pathKey(target) || inside(root, target)),
436 );
437 const directories = Effect.fnUntraced(function* (parent: string, managedRoot: string) {
438 if (inProject(parent, managedRoot)) return [];
439 const result: string[] = [];
440 for (const name of yield* fs.readDirectory(parent).pipe(Effect.orElseSucceed(() => []))) {
441 const target = path.join(parent, name);
442 if (!inside(parent, target) || inProject(target, managedRoot)) continue;
443 const directory = yield* Effect.gen(function* () {
444 if (pathKey(yield* fs.realPath(target)) !== pathKey(target)) return false;
445 return (yield* fs.stat(target)).type === "Directory";
446 }).pipe(Effect.orElseSucceed(() => false));
447 if (directory) result.push(target);
448 }
449 return result;
450 });
451 // Let the first walk time out and cache unmeasurable folders; later walks share the remaining budget.
452 const now = yield* Clock.currentTimeMillis;
453 const measurementDeadline = now + 30_000;
454 let firstMeasurement = true;
455 const reported = new Set<string>();
456 const report = Effect.fnUntraced(
457 function* (worktreePath: string) {
458 const key = pathKey(worktreePath);
459 if (
460 reported.has(key) ||
461 referenced.has(key) ||
462 referencedAncestors.has(key) ||
463 projectRoots.some((root) => pathKey(root) === key || inside(worktreePath, root))
464 )
465 return;
466 const modified = Option.getOrNull((yield* fs.stat(worktreePath)).mtime);
467 if (modified !== null && modified.getTime() > now - ORPHAN_WORKTREE_GRACE_MS) return;
468 const gitPath = path.join(worktreePath, ".git");
469 const linked = (yield* fs.exists(gitPath)) && (yield* fs.stat(gitPath)).type === "File";
470 reported.add(key);
471 const remaining = measurementDeadline - (yield* Clock.currentTimeMillis);
472 if (!orphanSizes.has(key) && (firstMeasurement || remaining > 0)) {
473 const measured = yield* measureWorktree(worktreePath).pipe(
474 firstMeasurement ? Effect.asSome : Effect.timeoutOption(remaining),
475 );
476 firstMeasurement = false;
477 if (Option.isSome(measured)) orphanSizes.set(key, measured.value);
478 }
479 const bytes = orphanSizes.get(key) ?? null;
480 entries.push({
481 kind: "worktree",
482 outcome: "kept",
483 reason: linked
484 ? "No thread uses this worktree"
485 : "No thread uses this folder, and it isn't a git worktree",
486 path: worktreePath,
487 projectPath: null,
488 threadId: null,
489 threadTitle: null,
490 bytes,
491 files: null,
492 });
493 },
494 Effect.orElseSucceed(() => undefined),
495 );
496 for (const root of roots) {
497 // Worktrees can be <root>/<repository>/<branch> or explicitly <root>/<name>.
498 for (const projectDirectory of yield* directories(root, root)) {
499 yield* Effect.gen(function* () {
500 if (referenced.has(pathKey(projectDirectory))) return;
501 const gitPath = path.join(projectDirectory, ".git");
502 if (yield* fs.exists(gitPath)) {
503 if ((yield* fs.stat(gitPath)).type === "File") yield* report(projectDirectory);
504 return;
505 }
506 for (const worktreePath of yield* directories(projectDirectory, root)) {
507 yield* report(worktreePath);
508 }
509 }).pipe(Effect.orElseSucceed(() => undefined));
510 }
511 }
512 for (const key of orphanSizes.keys()) {
513 if (!reported.has(key)) orphanSizes.delete(key);
514 }
515 });
516​
517 // Use two small Git reads: statusDetailsLocal also diffs and counts for every worktree.
518 const branchChanged = Effect.fn("StorageCleanup.branchChanged")(function* (
519 cwd: string,
520 branch: string | null,
521 ) {
522 const failure = (detail: string) =>
523 new GitCommandError({
524 operation: "StorageCleanup.branchChanged",
525 command: "git",
526 cwd,
527 detail,
528 });
529 // Return null for missing/non-repository cwd; force untranslated git diagnostics for matching.
530 const read = Effect.fnUntraced(function* (args: string[], allowedExitCode?: number) {
531 const result = yield* git
532 .execute({
533 operation: "StorageCleanup.branchChanged",
534 cwd,
535 args,
536 env: { LC_ALL: "C" },
537 allowNonZeroExit: true,
538 })
539 .pipe(
540 Effect.catch((error) =>
541 Effect.flatMap(fs.exists(cwd), (exists) =>
542 exists ? Effect.fail(error) : Effect.succeed(null),
543 ),
544 ),
545 );
546 if (result === null) return null;
547 if (result.exitCode === 0 || result.exitCode === allowedExitCode) return result;
548 if (result.stderr.toLowerCase().includes("not a git repository")) return null;
549 return yield* failure(
550 result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
551 );
552 });
553 const index = yield* read(["rev-parse", "--git-path", "index"]);
554 if (index === null) return true;
555 if (yield* fs.exists(`${path.resolve(cwd, index.stdout.trim())}.lock`))
556 return yield* failure(
557 "Git index is locked. Status will resume when the index lock is removed.",
558 );
559 // Detached HEAD exits 1; full refs avoid shortening when a tag shares the branch name.
560 const head = yield* read(["symbolic-ref", "--quiet", "HEAD"], 1);
561 if (head === null) return true;
562 const ref = head.exitCode === 0 ? head.stdout.trim() : "";
563 const name = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length).trim() : null;
564 return (name?.startsWith("(") ? null : name) !== branch;
565 });
566​
567 const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* (
568 cwd: string,
569 rules: WorktreeCleanupRules,
570 ) {
571 const status = yield* git.execute({
572 operation: "StorageCleanup.localChanges",
573 cwd,
574 args: [
575 "status",
576 "--porcelain=v1",
577 "-z",
578 "--ignore-submodules=none",
579 rules.worktreeKeepWhen === "tracked-changes"
580 ? "--untracked-files=no"
581 : "--untracked-files=all",
582 ],
583 maxOutputBytes: 64 * 1024,
584 });
585 if (status.stdoutTruncated) return "local changes exceed the inspection limit";
586 const records = status.stdout.split("\0").filter(Boolean);
587 let count = 0;
588 for (let i = 0; i < records.length; i++) {
589 count++;
590 if (/^[RC]|^.[RC]/.test(records[i]!)) i++;
591 }
592 if (count > 0) return `has uncommitted changes (${count} ${count === 1 ? "file" : "files"})`;
593 if (rules.worktreeKeepWhen !== "any-local-files") return null;
594 const ignored = yield* git.execute({
595 operation: "StorageCleanup.ignoredFiles",
596 cwd,
597 args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
598 maxOutputBytes: 64 * 1024,
599 });
600 if (ignored.stdoutTruncated) return "ignored files exceed the inspection limit";
601 const file = ignored.stdout
602 .split("\0")
603 .find((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry));
604 return file === undefined ? null : `has ignored files (${file})`;
605 });
606​
607 const submoduleRemoval = Effect.fn("StorageCleanup.submoduleRemoval")(
608 function* (cwd: string, rules: WorktreeCleanupRules) {
609 const inspect = (args: string[], maxOutputBytes = 64 * 1024) =>
610 git.execute({
611 operation: "StorageCleanup.submodules",
612 cwd,
613 args,
614 maxOutputBytes,
615 });
616 const admin = yield* inspect(["rev-parse", "--absolute-git-dir"]);
617 if (admin.stdoutTruncated || admin.stderrTruncated)
618 return { force: false, reason: "submodule inspection exceeded the limit" };
619 const modules = path.join(admin.stdout.replace(/\n$/, ""), "modules");
620 const stored = yield* fs.exists(modules);
621 if (!stored && !(yield* fs.exists(path.join(cwd, ".gitmodules"))))
622 return { force: false, reason: null };
623 const populated = yield* inspect([
624 "submodule",
625 "foreach",
626 "--recursive",
627 "--quiet",
628 'printf "%s\\0" "$toplevel/$sm_path"',
629 ]);
630 if (populated.stdoutTruncated || populated.stderrTruncated)
631 return { force: false, reason: "submodule inspection exceeded the limit" };
632 const paths = populated.stdout.split("\0").filter(Boolean);
633 const pending = [modules];
634 for (const submodule of paths) {
635 const directory = yield* inspect(["-C", submodule, "rev-parse", "--absolute-git-dir"]);
636 if (directory.stdoutTruncated || directory.stderrTruncated)
637 return { force: false, reason: "submodule inspection exceeded the limit" };
638 pending.push(directory.stdout.replace(/\n$/, ""));
639 }
640 const visited = new Set<string>();
641 while (pending.length > 0) {
642 const directory = pending.pop()!;
643 if (!(yield* fs.exists(directory))) continue;
644 const canonical = yield* fs.realPath(directory);
645 if (visited.has(canonical)) continue;
646 visited.add(canonical);
647 if (visited.size > 10_000)
648 return { force: false, reason: "submodule inspection exceeded the limit" };
649 if ((yield* fs.stat(directory)).type !== "Directory")
650 return { force: false, reason: "submodule repository could not be inspected" };
651 if (yield* fs.exists(path.join(directory, "HEAD"))) {
652 const unpushed = yield* inspect([
653 "--git-dir",
654 directory,
655 "--work-tree",
656 cwd,
657 "rev-list",
658 "--max-count=1",
659 "HEAD",
660 "--all",
661 "--reflog",
662 "--not",
663 "--remotes",
664 ]);
665 if (unpushed.stdoutTruncated || unpushed.stderrTruncated)
666 return { force: false, reason: "submodule inspection exceeded the limit" };
667 if (unpushed.stdout.trim() !== "")
668 return { force: false, reason: "submodule has commits not on a remote-tracking ref" };
669 pending.push(path.join(directory, "modules"));
670 } else {
671 for (const name of yield* fs.readDirectory(directory))
672 pending.push(path.join(directory, name));
673 }
674 }
675 // Check files after walking stored history to shorten the gap before forced removal.
676 for (const submodule of paths) {
677 const changes = yield* localChangesReason(submodule, rules);
678 if (changes !== null) return { force: false, reason: `submodule ${changes}` };
679 }
680 const force = stored || paths.length > 0;
681 if (force && rules.worktreeKeepWhen !== "tracked-changes") {
682 const root = yield* fs.realPath(cwd);
683 // Git status and foreach omit files inside deinitialized gitlink directories.
684 const populatedPaths = new Set(paths.map(pathKey));
685 const unchecked: string[] = [];
686 for (const repository of [root, ...paths]) {
687 const index = yield* inspect(
688 ["-C", repository, "ls-files", "--stage", "-z"],
689 16 * 1024 * 1024,
690 );
691 if (index.stdoutTruncated || index.stderrTruncated)
692 return { force: false, reason: "submodule inspection exceeded the limit" };
693 for (const entry of index.stdout.split("\0")) {
694 if (!entry.startsWith("160000 ")) continue;
695 const submodule = path.resolve(repository, entry.slice(entry.indexOf("\t") + 1));
696 if (!inside(root, submodule))
697 return { force: false, reason: "submodules could not be inspected" };
698 if (!populatedPaths.has(pathKey(submodule)) && (yield* fs.exists(submodule)))
699 unchecked.push(submodule);
700 }
701 }
702 let inspected = unchecked.length;
703 while (unchecked.length > 0) {
704 if (inspected > 10_000)
705 return { force: false, reason: "submodule inspection exceeded the limit" };
706 const target = unchecked.pop()!;
707 if (
708 (yield* fs.realPath(target)) !== path.resolve(target) ||
709 (yield* fs.stat(target)).type !== "Directory"
710 )
711 return { force: false, reason: "submodule has local files" };
712 if (path.basename(target) === "node_modules") continue;
713 const names = yield* fs.readDirectory(target);
714 inspected += names.length;
715 for (const name of names) unchecked.push(path.join(target, name));
716 }
717 }
718 return { force, reason: null };
719 },
720 Effect.orElseSucceed(() => ({ force: false, reason: "submodules could not be inspected" })),
721 );
722​
723 const cleanupGit = Effect.fn("StorageCleanup.cleanupGit")(function* (
724 cwd: string,
725 args: string[],
726 command: string,
727 ) {
728 const result = yield* git.execute({
729 operation: "StorageCleanup.cleanupGit",
730 cwd,
731 args,
732 allowNonZeroExit: true,
733 timeoutMs: 300_000,
734 });
735 if (result.exitCode !== 0)
736 return yield* new GitCommandError({
737 operation: "StorageCleanup.cleanupGit",
738 command,
739 cwd,
740 detail: result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed",
741 });
742 });
743​
744 const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
745 serverSettings: ServerSettings,
746 now: number,
747 entries: StorageCleanupReportEntry[],
748 ) {
749 if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled))
750 return { waiting: false, kept: [] };
751 let waiting = false;
752 const kept: string[] = [];
753 const roots: Array<string> = [];
754 for (const directory of managedWorktreesDirectories(
755 serverSettings,
756 config.worktreesDir,
757 path,
758 yield* HostProcess.HomeDirectory,
759 )) {
760 const root = yield* fs.exists(directory).pipe(
761 Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
762 Effect.orElseSucceed(() => null),
763 );
764 if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
765 }
766 const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>`
767 SELECT t.payload_json, p.workspace_root AS "workspaceRoot"
768 FROM orchestration_v2_projection_threads t
769 JOIN projection_projects p ON p.project_id = t.project_id
770 WHERE t.deleted_at IS NOT NULL
771 `.pipe(NodeSqliteClient.readOnly);
772 const deletedThreads = (yield* Effect.forEach(deletedRows, (row) =>
773 decodeCleanupThread(row.payload_json).pipe(
774 Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })),
775 ),
776 )).filter((thread) => thread.worktreePath !== null && thread.branch !== null);
777 const snapshot = yield* readThreads();
778 const refreshedDefaultRefs = new Map<string, Set<string>>();
779 const defaultBranches = new Map<string, string | null>();
780 const groups = Map.groupBy(
781 snapshot.threads.filter((thread) => thread.worktreePath !== null),
782 (thread) => path.resolve(thread.worktreePath!),
783 );
784 const deletedByPath = Map.groupBy(deletedThreads, (thread) =>
785 path.resolve(thread.worktreePath!),
786 );
787 const candidates = [
788 ...[...groups].map(
789 ([worktreePath, group]) =>
790 // A deleted thread still owns the worktree its remaining subagents share,
791 // but only deletion cleanup acts on it; otherwise the live rules apply.
792 deletedByPath
793 .get(worktreePath)
794 ?.find(
795 (deleted) =>
796 resolveWorktreeCleanup(serverSettings, deleted.projectId).worktreeOnDelete &&
797 worktreeOwner([deleted, ...group]) === deleted,
798 ) ??
799 worktreeOwner(group) ??
800 group[0]!,
801 ),
802 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
803 ];
804 for (const thread of candidates) {
805 const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
806 if (!worktreeCleanupEnabled(settings)) continue;
807 const worktreePath = path.resolve(thread.worktreePath!);
808 const group = groups.get(worktreePath) ?? [];
809 const activityAt = Math.max(...group.map(storageCleanupActivityAt));
810 const deleted = "workspaceRoot" in thread;
811 const members = deleted ? [thread, ...group] : group;
812 const project = deleted
813 ? { workspaceRoot: thread.workspaceRoot }
814 : snapshot.projects.find((entry) => entry.id === thread.projectId);
815 const entry: StorageCleanupReportEntry = {
816 kind: "worktree",
817 outcome: "kept",
818 reason: "",
819 path: worktreePath,
820 projectPath: project?.workspaceRoot ?? null,
821 threadId: thread.id,
822 threadTitle: thread.title,
823 bytes: null,
824 files: null,
825 };
826 const keep = (reason: string) => {
827 if (deleted && settings.worktreeOnDelete) kept.push(worktreePath);
828 entries.push({ ...entry, reason: sentence(reason) });
829 };
830 // Reasons a provider session stop or finished deletion work can clear.
831 const waitForStop = (reason: string) => {
832 if (deleted && settings.worktreeOnDelete) waiting = true;
833 return reason;
834 };
835 yield* Effect.gen(function* () {
836 if (!(yield* fs.exists(worktreePath))) return;
837 if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
838 if (members.length > 1 && worktreeOwner(members) === undefined)
839 return keep(`shared by ${members.length} threads`);
840 if (project === undefined) return keep("project is unavailable");
841 if (
842 thread.branch === null ||
843 !group.every((member) => storageCleanupThreadIdle(member, now, serverSettings))
844 )
845 return keep(waitForStop("thread is running or has pending work"));
846 if (group.some((member) => member.branch !== thread.branch))
847 return keep("a subagent thread's branch differs from this worktree's branch");
848 if (hasTerminal(worktreePath)) return keep(waitForStop("open terminal"));
849 // Compare canonical roots while allowing symlinked parents, never symlinked worktree directories.
850 const realPath = yield* fs.realPath(worktreePath);
851 const realParent = yield* fs.realPath(path.dirname(worktreePath));
852 if (realPath !== path.join(realParent, path.basename(worktreePath)))
853 return keep("worktree is a symbolic link");
854 if (!roots.some((root) => inside(root, realPath)))
855 return keep("outside the managed worktree folder");
856 if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects]))
857 return keep("contains a project checkout");
858 if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File")
859 return keep("not a linked worktree");
860 if (yield* branchChanged(worktreePath, thread.branch))
861 return keep("repository or branch changed");
862 const changes = yield* localChangesReason(worktreePath, settings);
863 if (changes !== null) return keep(changes);
864 if (
865 group.some(
866 (member) =>
867 member.settledAt !== null &&
868 now - Math.max(DateTime.toEpochMillis(member.updatedAt), activityAt) <
869 SETTLE_SCRIPT_GRACE_MS,
870 )
871 )
872 return keep(waitForStop("settled moments ago"));
873 const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
874 const old =
875 !deleted &&
876 settings.worktreeAfterDays !== null &&
877 activityAt < now - settings.worktreeAfterDays * DAY_MS;
878 const settledFor =
879 deleted || thread.settledAt === null
880 ? null
881 : now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
882 const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
883 const settled =
884 settledFor !== null &&
885 settings.worktreeSettledAfterDays !== null &&
886 settledFor >= settings.worktreeSettledAfterDays * DAY_MS;
887 let eligible = deleted || old || settled;
888 let removalReason = deleted
889 ? "thread was deleted"
890 : old
891 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
892 : `settled for ${settledDays} days`;
893 if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
894 const repositoryCwd = path.resolve(project.workspaceRoot);
895 const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
896 const defaultBranchKey = `${repositoryCwd}\0${remote}`;
897 let branch = defaultBranches.get(defaultBranchKey);
898 if (branch === undefined) {
899 branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
900 // Without a local HEAD ref, only the remote can identify its default;
901 // a conventional name may be a feature branch.
902 if (branch === null) {
903 branch = yield* git
904 .execute({
905 operation: "StorageCleanup.resolveDefaultBranch",
906 cwd: repositoryCwd,
907 args: ["ls-remote", "--symref", "--", remote, "HEAD"],
908 timeoutMs: 20_000,
909 })
910 .pipe(
911 Effect.map(
912 (result) =>
913 /^ref: refs\/heads\/(.+)\tHEAD\r?$/m.exec(result.stdout)?.[1] ?? null,
914 ),
915 Effect.orElseSucceed(() => null),
916 );
917 }
918 defaultBranches.set(defaultBranchKey, branch);
919 }
920 if (branch === null) return keep("default branch is unavailable");
921 const defaultRef = `refs/remotes/${remote}/${branch}`;
922 const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
923 if (!refreshed.has(defaultRef)) {
924 yield* git.fetchRemoteTrackingBranch({
925 cwd: repositoryCwd,
926 remoteName: remote,
927 remoteBranch: branch,
928 });
929 refreshed.add(defaultRef);
930 refreshedDefaultRefs.set(repositoryCwd, refreshed);
931 }
932 const base = yield* git.resolveCommit({
933 cwd: worktreePath,
934 revision: defaultRef,
935 });
936 const ancestor = yield* git.execute({
937 operation: "StorageCleanup.integratedBranch",
938 cwd: worktreePath,
939 args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
940 allowNonZeroExit: true,
941 });
942 const integrated = ancestor.exitCode === 0;
943 eligible = integrated && settings.worktreeUnchanged;
944 if (eligible) removalReason = "no commits beyond the default branch";
945 if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
946 const pullRequest = yield* gitManager.branchPullRequest(
947 { cwd: worktreePath, branch: thread.branch },
948 { refresh: true },
949 );
950 eligible = storageCleanupPullRequestMerged(pullRequest, {
951 branch: thread.branch,
952 defaultBranch: branch,
953 headSha: head.commitSha,
954 integrated,
955 });
956 if (eligible) removalReason = "pull request was merged";
957 }
958 }
959 if (!eligible)
960 return keep(
961 !deleted && settings.worktreeAfterDays !== null
962 ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
963 : settings.worktreeSettledAfterDays !== null
964 ? settledFor === null
965 ? "not settled"
966 : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days`
967 : settings.worktreeOnMerge
968 ? "not merged"
969 : "has commits beyond the default branch",
970 );
971 // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds.
972 const blockedSinceCheck = Effect.fnUntraced(function* () {
973 const latestProjects = yield* projectStore.listShells();
974 if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects]))
975 return "contains a project checkout";
976 const latest = (yield* projections.getThreadWorktreePaths({
977 includeArchived: true,
978 })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath);
979 if (hasTerminal(worktreePath)) return waitForStop("open terminal");
980 if (deleted) {
981 if (
982 !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
983 .worktreeOnDelete
984 )
985 return "thread or cleanup settings changed since check";
986 // Durable deletion cleanup must succeed or be explicitly cancelled before removing its checkout.
987 const pendingCleanup = yield* sql<{ status: string }>`
988 SELECT status FROM orchestration_v2_effect_outbox
989 WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled')
990 `.pipe(NodeSqliteClient.readOnly);
991 // Failed effects never retry, so only running work can finish and free the path.
992 if (pendingCleanup.some((row) => row.status !== "failed"))
993 return waitForStop("thread deletion is still pending");
994 if (pendingCleanup.length > 0) return "thread deletion is still pending";
995 }
996 const latestShells = yield* Effect.forEach(latest, (entry) =>
997 projections.getThreadShell(entry.threadId),
998 );
999 const latestGroup = latestShells.filter((shell) => shell !== null);
1000 const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup);
1001 if (
1002 latestGroup.length !== group.length ||
1003 latestOwner?.id !== thread.id ||
1004 latestOwner?.branch !== thread.branch ||
1005 latestGroup.some((shell) => {
1006 const previous = group.find((member) => member.id === shell.id);
1007 return (
1008 previous === undefined ||
1009 shell.branch !== thread.branch ||
1010 !Equal.equals(shell.settledAt, previous.settledAt) ||
1011 (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
1012 !storageCleanupThreadIdle(shell, now, serverSettings) ||
1013 path.resolve(shell.worktreePath!) !== worktreePath ||
1014 storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
1015 );
1016 })
1018 return waitForStop("thread activity or shared worktree changed since check");
1019 // Sessions can outlive their run and can be shared across app threads.
1020 const sessionRows = yield* sql<{ payload_json: string }>`
1021 SELECT payload_json FROM orchestration_v2_projection_provider_sessions
1022 WHERE status != 'stopped'
1023 `.pipe(NodeSqliteClient.readOnly);
1024 const sessions = yield* Effect.forEach(sessionRows, (row) =>
1025 decodeCleanupSession(row.payload_json),
1026 );
1027 // Ready persisted sessions may have released their runtime; only live sessions protect the path.
1028 for (const session of sessions) {
1029 const cwd = path.resolve(session.cwd);
1030 if (
1031 (pathKey(cwd) === pathKey(worktreePath) || inside(worktreePath, cwd)) &&
1032 (yield* providerSessions.isLive(session.id))
1034 return waitForStop("provider session is still open");
1036 return null;
1037 });
1038 const blocked = yield* blockedSinceCheck();
1039 if (blocked !== null) return keep(blocked);
1040 const bytes = yield* measureWorktree(worktreePath);
1041 const blockedWhileMeasuring = yield* blockedSinceCheck();
1042 if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring);
1043 if (yield* branchChanged(worktreePath, thread.branch))
1044 return keep("repository or branch changed since check");
1045 if (
1046 (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
1047 head.commitSha
1049 return keep("commit changed since check");
1050 const finalChanges = yield* localChangesReason(worktreePath, settings);
1051 if (finalChanges !== null) return keep(finalChanges);
1052 const currentSettings = yield* settingsService.getSettings;
1053 const current = resolveWorktreeCleanup(currentSettings, thread.projectId);
1054 if (
1055 currentSettings.autoResumeLimitedThreads !== serverSettings.autoResumeLimitedThreads ||
1056 currentSettings.snoozeLimitedThreads !== serverSettings.snoozeLimitedThreads ||
1057 Object.keys(settings).some(
1058 (key) =>
1059 current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
1062 return keep("settings changed since check");
1063 // Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check.
1064 if (settings.worktreeKeepWhen === "tracked-changes")
1065 yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
1066 const submodules = yield* submoduleRemoval(worktreePath, settings);
1067 if (submodules.reason !== null) return keep(submodules.reason);
1068 if (submodules.force) {
1069 const changes = yield* localChangesReason(worktreePath, settings);
1070 if (changes !== null) return keep(changes);
1072 yield* removeLinkedWorktree({
1073 operation: "StorageCleanup.cleanupGit",
1074 cwd: project.workspaceRoot,
1075 worktreePath,
1076 // Git requires force for submodules; recursive checks above cannot make removal atomic.
1077 force: submodules.force,
1078 execute: git.execute,
1079 run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"),
1080 });
1081 entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes });
1082 yield* gitManager.invalidateStatus(project.workspaceRoot);
1083 // Preserve branch/path so ProviderTurnStartService can recreate the checkout on resume.
1084 yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
1085 }).pipe(
1086 (effect) => withWorkspaceLease(worktreePath, effect),
1087 Effect.catch((error) =>
1088 Effect.gen(function* () {
1089 entries.push({
1090 ...entry,
1091 outcome: "failed",
1092 reason: cleanupFailureReason(error),
1093 });
1094 if (deleted && settings.worktreeOnDelete) kept.push(worktreePath);
1095 yield* Effect.logWarning("storage cleanup failed for worktree", {
1096 threadId: thread.id,
1097 error,
1098 });
1099 }),
1100 ),
1101 );
1103 yield* reportOrphanWorktrees(
1104 roots,
1105 yield* projectStore.list({ includeDeleted: true }),
1106 entries,
1107 );
1108 return { waiting, kept };
1109 });
1110​
1111 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
1112 root: string,
1113 days: number | null,
1114 now: number,
1115 rotatedLogs: boolean,
1116 removed: { files: number; bytes: number },
1117 ) {
1118 if (days === null || !(yield* fs.exists(root))) return removed;
1119 // A symlinked parent (a linked T3 home) is fine; a symlinked folder is not.
1120 const realRoot = yield* fs.realPath(root);
1121 const realParent = yield* fs.realPath(path.dirname(root));
1122 if (realRoot !== path.join(realParent, path.basename(root))) return removed;
1123 const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
1124 directory: string,
1125 ): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
1126 for (const name of yield* fs.readDirectory(directory)) {
1127 const target = path.join(directory, name);
1128 if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
1129 const stat = yield* fs.stat(target);
1130 if (stat.type === "Directory" && rotatedLogs) {
1131 yield* visit(target);
1132 } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
1133 const modified = Option.getOrNull(stat.mtime);
1134 if (modified !== null && modified.getTime() < now - days * DAY_MS) {
1135 const current = (yield* settingsService.getSettings).storageCleanup;
1136 if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
1137 return;
1138 yield* fs.remove(target);
1139 removed.files++;
1140 removed.bytes += Number(stat.size);
1144 });
1145 yield* visit(realRoot);
1146 return removed;
1147 });
1148​
1149 const reportRef = yield* SubscriptionRef.make<StorageCleanupReport | null>(null);
1150 // Only deleted threads' worktrees wait on session stops: any stop while one waits, or a stop inside one kept for another reason.
1151 // A deletion stays pending until a sweep that started after it finishes.
1152 let deletedWorktreeWaits = true;
1153 let keptDeletedWorktrees: ReadonlyArray<string> = [];
1154 let deletions = 0;
1155 let sweptDeletions = 0;
1156 const sweep = Effect.fn("StorageCleanup.sweep")(function* (
1157 trigger: StorageCleanupReport["trigger"],
1158 ) {
1159 const deletionsAtStart = deletions;
1160 const now = yield* Clock.currentTimeMillis;
1161 const serverSettings = yield* settingsService.getSettings;
1162 const settings = serverSettings.storageCleanup;
1163 const entries: StorageCleanupReportEntry[] = [];
1164 const deletedWorktrees = yield* cleanWorktrees(serverSettings, now, entries).pipe(
1165 Effect.catch((error) =>
1166 Effect.gen(function* () {
1167 entries.push({
1168 kind: "worktree",
1169 outcome: "failed",
1170 reason: cleanupFailureReason(error),
1171 path: null,
1172 projectPath: null,
1173 threadId: null,
1174 threadTitle: null,
1175 bytes: null,
1176 files: null,
1177 });
1178 yield* Effect.logWarning("worktree cleanup failed", { error });
1179 return { waiting: true, kept: [] };
1180 }),
1181 ),
1182 );
1183 deletedWorktreeWaits = deletedWorktrees.waiting;
1184 keptDeletedWorktrees = deletedWorktrees.kept;
1185 sweptDeletions = deletionsAtStart;
1186 for (const category of [
1188 kind: "browser-artifacts" as const,
1189 root: config.browserArtifactsDir,
1190 days: settings.browserArtifactsAfterDays,
1191 label: "browser artifacts",
1192 },
1194 kind: "logs" as const,
1195 root: config.logsDir,
1196 days: settings.logsAfterDays,
1197 label: "rotated logs",
1198 },
1199 ]) {
1200 if (category.days === null) continue;
1201 const removed = { files: 0, bytes: 0 };
1202 yield* cleanFiles(category.root, category.days, now, category.kind === "logs", removed).pipe(
1203 Effect.map(({ files, bytes }) =>
1204 entries.push({
1205 kind: category.kind,
1206 outcome: files > 0 ? "removed" : "kept",
1207 reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`,
1208 path: null,
1209 projectPath: null,
1210 threadId: null,
1211 threadTitle: null,
1212 bytes: files > 0 ? bytes : null,
1213 files: files > 0 ? files : null,
1214 }),
1215 ),
1216 Effect.catch((error) =>
1217 Effect.gen(function* () {
1218 entries.push({
1219 kind: category.kind,
1220 outcome: "failed",
1221 reason: cleanupFailureReason(error),
1222 path: null,
1223 projectPath: null,
1224 threadId: null,
1225 threadTitle: null,
1226 bytes: removed.files > 0 ? removed.bytes : null,
1227 files: removed.files > 0 ? removed.files : null,
1228 });
1229 yield* Effect.logWarning("storage file cleanup failed", { kind: category.kind, error });
1230 }),
1231 ),
1232 );
1234 const counts = { removed: 0, kept: 0, failed: 0 };
1235 let bytesFreed = 0;
1236 for (const entry of entries) {
1237 counts[entry.outcome]++;
1238 if (entry.outcome !== "kept") bytesFreed += entry.bytes ?? 0;
1240 const priority = (entry: StorageCleanupReportEntry) =>
1241 entry.outcome === "failed"
1242 ? 0
1243 : entry.outcome === "removed"
1244 ? 1
1245 : entry.kind === "worktree" && entry.threadId === null
1246 ? 2
1247 : 3;
1248 const latestReport: StorageCleanupReport = {
1249 trigger,
1250 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
1251 finishedAt: DateTime.formatIso(yield* DateTime.now),
1252 entries: entries.sort((a, b) => priority(a) - priority(b)).slice(0, REPORT_ENTRY_LIMIT),
1253 counts,
1254 bytesFreed,
1255 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
1256 };
1257 yield* SubscriptionRef.set(reportRef, latestReport);
1258 return latestReport;
1259 });
1260 const automaticSweepQueued = yield* Ref.make(false);
1261 const worker = yield* makeDrainableWorker(
1262 (completion: Deferred.Deferred<StorageCleanupReport, ServerSettingsError> | undefined) =>
1263 (completion === undefined ? Ref.set(automaticSweepQueued, false) : Effect.void).pipe(
1264 Effect.andThen(sweep(completion === undefined ? "automatic" : "manual")),
1265 Effect.exit,
1266 Effect.flatMap((exit) =>
1267 completion === undefined
1268 ? exit.pipe(
1269 Effect.asVoid,
1270 Effect.catchCause((cause) =>
1271 Effect.logWarning("storage cleanup failed", { cause }),
1272 ),
1274 : Deferred.done(completion, exit).pipe(Effect.asVoid),
1275 ),
1276 ),
1277 );
1278 const requestSweep = Ref.getAndSet(automaticSweepQueued, true).pipe(
1279 Effect.flatMap((queued) => (queued ? Effect.void : worker.enqueue(undefined))),
1280 );
1281 const runNow = Effect.gen(function* () {
1282 const completion = yield* Deferred.make<StorageCleanupReport, ServerSettingsError>();
1283 yield* worker.enqueue(completion);
1284 return yield* Deferred.await(completion);
1285 });
1286​
1287 const start = Effect.fn("StorageCleanup.start")(function* () {
1288 const unsubscribe = yield* terminals.subscribeMetadata((event) =>
1289 Effect.sync(() => {
1290 if (event.type === "snapshot") {
1291 liveTerminals.clear();
1292 for (const terminal of event.terminals) noteTerminal(terminal);
1293 } else if (event.type === "upsert") {
1294 noteTerminal(event.terminal);
1295 } else {
1296 const threadTerminals = liveTerminals.get(event.threadId);
1297 threadTerminals?.delete(event.terminalId);
1298 if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
1300 }),
1301 );
1302 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1303 const changes = yield* settingsService.subscribeChanges;
1304 const events = engine.streamDomainEvents;
1305 let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
1306 yield* forkParked(
1307 requestSweep.pipe(
1308 Effect.andThen(worker.drain),
1309 Effect.repeat(Schedule.spaced("1 hour")),
1310 Effect.asVoid,
1311 ),
1312 );
1313 yield* forkParked(
1314 Stream.runForEach(changes, (settings) => {
1315 if (
1316 Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
1317 Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
1318 sameProjectWorktreePolicies(settings, lastSettings)
1320 return Effect.void;
1321 lastSettings = settings;
1322 return requestSweep;
1323 }),
1324 );
1325 yield* forkParked(
1326 Stream.runForEach(events, (event) => {
1327 if (event.type === "thread.deleted") deletions++;
1328 else if (
1329 event.type !== "provider-session.updated" ||
1330 (event.payload.status !== "stopped" && event.payload.status !== "error")
1332 return Effect.void;
1333 else if (!deletedWorktreeWaits && deletions === sweptDeletions) {
1334 const cwd = pathKey(event.payload.cwd);
1335 if (
1336 !keptDeletedWorktrees.some(
1337 (worktreePath) => pathKey(worktreePath) === cwd || inside(worktreePath, cwd),
1340 return Effect.void;
1342 return anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
1343 ? requestSweep
1344 : Effect.void;
1345 }).pipe(
1346 Effect.catchCause((cause) =>
1347 Effect.logWarning("Storage cleanup event stream failed", { cause }),
1348 ),
1349 ),
1350 );
1351 });
1352 yield* start();
1353 return StorageCleanup.of({
1354 runNow,
1355 latestReport: SubscriptionRef.get(reportRef),
1356 reports: SubscriptionRef.changes(reportRef),
1357 drain: worker.drain,
1358 });
1359});
1360​
1361export const layer = Layer.effect(StorageCleanup, make);