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

storageCleanup.ts

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