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