@devries-cameron20 / t3code-1 / commits / fa1184d29e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): report orphaned managed worktrees (#19749)

maria committed Oct 15, 2026 at 23:50 UTC fa1184d29eb0ecad789129118c592d3c8303ee97
5 files changed +781 -15
apps/server/src/storageCleanup.test.ts
+550 -2
@@ -18,6 +18,7 @@ import {
18 type WorktreeKeepWhen,
19 type StorageCleanupSettings,
20 } from "@t3tools/contracts";
21 +import * as HostProcess from "@t3tools/shared/HostProcess";
22 import * as ServerConfig from "./config.ts";
23 import * as StorageCleanup from "./storageCleanup.ts";
24 import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
@@ -265,6 +266,8 @@ const cleanupFixture = (
266 storageCleanup,
267 };
268 let threads = [shell({ branch: "feature", worktreePath: worktree })];
269 + let storedWorktreePaths: string[] = [worktree];
270 + let projectRoots = [repo];
271 let editBeforeRemoval = false;
272 let openSessionCwd: string | null = null;
273 let sessionLive = true;
@@ -291,8 +294,14 @@ const cleanupFixture = (
294 subscribeChanges: Effect.succeed(Stream.empty),
295 } as unknown as Settings.ServerSettingsService["Service"]),
296 Effect.provideService(ProjectStore.ProjectStoreV2, {
297 + list: () => Effect.sync(() => projectRoots.map((workspaceRoot) => ({ workspaceRoot }))),
298 listShells: () =>
295 - Effect.succeed([{ id: ProjectId.make("project-1"), workspaceRoot: repo }]),
299 + Effect.sync(() =>
300 + projectRoots.map((workspaceRoot, index) => ({
301 + id: ProjectId.make(`project-${index + 1}`),
302 + workspaceRoot,
303 + })),
304 + ),
305 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
306 Effect.provideService(ProjectionStore.ProjectionStoreV2, {
307 getShellSnapshot: (input?: { location?: string }) =>
@@ -336,7 +345,12 @@ const cleanupFixture = (
345 }),
346 },
347 ]
339 - : [],
348 + : strings.join("").includes('AS "worktreePath"')
349 + ? [
350 + ...threads.flatMap((thread) => thread.worktreePath ?? []),
351 + ...storedWorktreePaths,
352 + ].map((worktreePath) => ({ worktreePath }))
353 + : [],
354 )) as unknown as SqlClient.SqlClient),
355 Effect.provideService(GitManager.GitManager, {
356 invalidateStatus: () => Effect.void,
@@ -388,6 +402,12 @@ const cleanupFixture = (
402 setThreads: (next: typeof threads) => {
403 threads = next;
404 },
405 + setStoredWorktreePaths: (paths: string[]) => {
406 + storedWorktreePaths = paths;
407 + },
408 + setProjectRoots: (roots: string[]) => {
409 + projectRoots = roots;
410 + },
411 setSessionLive: (live: boolean) => {
412 sessionLive = live;
413 },
@@ -656,7 +676,535 @@ describe("subagent worktree ownership", () => {
676 );
677 });
678
679 +describe("orphan worktree reports", () => {
680 + it.live("keeps orphan results visible when thread results fill the report", () =>
681 + runCleanupTest(
682 + Effect.gen(function* () {
683 + const fixture = yield* cleanupFixture();
684 + fixture.setThreads(
685 + Array.from({ length: 205 }, (_, index) =>
686 + shell({
687 + id: ThreadId.make(`busy-${index}`),
688 + branch: "busy",
689 + worktreePath: `${fixture.config.worktreesDir}/busy-${index}`,
690 + status: "running",
691 + }),
692 + ),
693 + );
694 + for (let index = 0; index < 205; index++) {
695 + yield* fixture.fs.makeDirectory(`${fixture.config.worktreesDir}/busy-${index}`);
696 + }
697 + const orphans = ["one", "two"].map(
698 + (name) => `${fixture.config.worktreesDir}/repository/${name}`,
699 + );
700 + for (const orphan of orphans) {
701 + yield* fixture.fs.makeDirectory(orphan, { recursive: true });
702 + yield* fixture.fs.utimes(orphan, 1, 1);
703 + }
704 + const report = yield* fixture.service.runNow;
705 + expect(report.entries).toHaveLength(200);
706 + expect(
707 + report.entries
708 + .slice(0, 2)
709 + .map((entry) => entry.path)
710 + .sort(),
711 + ).toEqual(orphans);
712 + expect(report.counts).toEqual({ removed: 0, kept: 207, failed: 0 });
713 + expect(report.omittedCount).toBe(7);
714 + }),
715 + ),
716 + );
717 +
718 + it.live.each(["canonical", "win32", "linux"] as const)(
719 + "skips an ancestor of a referenced thread worktree (%s)",
720 + (platform) =>
721 + runCleanupTest(
722 + Effect.gen(function* () {
723 + const fixture = yield* cleanupFixture().pipe(
724 + Effect.provideService(HostProcess.Platform, platform === "win32" ? "win32" : "linux"),
725 + );
726 + fixture.setThreads([]);
727 + const ancestor = `${fixture.config.worktreesDir}/repository/stack`;
728 + const worktree = `${ancestor}/feature`;
729 + yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "nested", worktree]);
730 + const alias = `${fixture.repo}/alias`;
731 + if (platform === "canonical") yield* fixture.fs.symlink(worktree, alias);
732 + fixture.setStoredWorktreePaths([
733 + platform === "canonical"
734 + ? alias
735 + : platform === "win32"
736 + ? worktree.toUpperCase()
737 + : worktree,
738 + ]);
739 + yield* fixture.fs.utimes(ancestor, 1, 1);
740 + expect((yield* fixture.service.runNow).entries).toEqual([]);
741 + expect(yield* fixture.fs.exists(worktree)).toBe(true);
742 + }),
743 + ),
744 + );
745 +
746 + it.live("waits an hour before reporting a folder without a thread row", () =>
747 + runCleanupTest(
748 + Effect.gen(function* () {
749 + const fixture = yield* cleanupFixture();
750 + fixture.setThreads([]);
751 + const folder = `${fixture.config.worktreesDir}/review-guide-123/checkout`;
752 + yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "review", folder]);
753 + expect((yield* fixture.service.runNow).entries).toEqual([]);
754 + yield* fixture.fs.utimes(folder, 1, 1);
755 + expect((yield* fixture.service.runNow).entries).toEqual([
756 + expect.objectContaining({
757 + path: folder,
758 + outcome: "kept",
759 + reason: "No thread uses this worktree",
760 + }),
761 + ]);
762 + expect(yield* fixture.fs.exists(`${folder}/tracked.txt`)).toBe(true);
763 + }),
764 + ),
765 + );
766 +
767 + it.live("continues reporting when a project root cannot be probed", () =>
768 + runCleanupTest(
769 + Effect.gen(function* () {
770 + const fixture = yield* cleanupFixture();
771 + fixture.setThreads([]);
772 + const loop = `${fixture.repo}/loop`;
773 + yield* fixture.fs.symlink(loop, loop);
774 + fixture.setProjectRoots([fixture.repo, loop]);
775 + const orphan = `${fixture.config.worktreesDir}/repository/orphan`;
776 + yield* fixture.fs.makeDirectory(orphan, { recursive: true });
777 + yield* fixture.fs.utimes(orphan, 1, 1);
778 + expect((yield* fixture.service.runNow).entries).toEqual([
779 + expect.objectContaining({ path: orphan, outcome: "kept", bytes: 0 }),
780 + ]);
781 + }),
782 + ),
783 + );
784 +
785 + it.effect.each(["walk-timeout", "sweep-budget"] as const)(
786 + "caches walk timeouts and retries budget-cut orphan sizes (%s)",
787 + (limit) =>
788 + runCleanupTest(
789 + Effect.gen(function* () {
790 + yield* TestClock.setTime(NOW_MS);
791 + const fs = yield* FileSystem.FileSystem;
792 + const measuring = yield* Deferred.make<void>();
793 + let orphan = "";
794 + let walks = 0;
795 + const fixture = yield* cleanupFixture().pipe(
796 + Effect.provideService(FileSystem.FileSystem, {
797 + ...fs,
798 + readDirectory: (directory, options) =>
799 + Effect.gen(function* () {
800 + if (directory.endsWith("/repository") && walks === 0)
801 + yield* TestClock.adjust("1 second");
802 + if (directory === orphan) {
803 + walks++;
804 + if (limit === "walk-timeout" || walks === 1) {
805 + yield* Deferred.succeed(measuring, undefined);
806 + return yield* Effect.never;
807 + }
808 + }
809 + return (yield* fs.readDirectory(directory, options)).sort();
810 + }),
811 + }),
812 + );
813 + fixture.setThreads([]);
814 + orphan = `${fixture.config.worktreesDir}/repository/orphan`;
815 + yield* fs.makeDirectory(orphan, { recursive: true });
816 + yield* fs.writeFileString(`${orphan}/file`, "x");
817 + yield* fs.utimes(orphan, 1, 1);
818 + const later = `${fixture.config.worktreesDir}/repository/z-later`;
819 + yield* fs.makeDirectory(later);
820 + yield* fs.utimes(later, 1, 1);
821 + if (limit === "sweep-budget") {
822 + const first = `${fixture.config.worktreesDir}/repository/a-first`;
823 + yield* fs.makeDirectory(first);
824 + yield* fs.utimes(first, 1, 1);
825 + }
826 + const orphanEntry = (report: StorageCleanupReport) =>
827 + report.entries.find((entry) => entry.path === orphan);
828 + const sweep = yield* fixture.service.runNow.pipe(Effect.forkChild);
829 + yield* Deferred.await(measuring);
830 + yield* TestClock.adjust(limit === "walk-timeout" ? "30 seconds" : "29 seconds");
831 + const firstReport = yield* Fiber.join(sweep);
832 + expect(orphanEntry(firstReport)?.bytes).toBeNull();
833 + expect(firstReport.entries.find((entry) => entry.path === later)?.bytes).toBeNull();
834 + const nextReport = yield* fixture.service.runNow;
835 + expect(orphanEntry(nextReport)?.bytes).toBe(limit === "walk-timeout" ? null : 1);
836 + expect(nextReport.entries.find((entry) => entry.path === later)?.bytes).toBe(0);
837 + yield* fs.writeFileString(`${orphan}/file`, "changed");
838 + expect(orphanEntry(yield* fixture.service.runNow)?.bytes).toBe(
839 + limit === "walk-timeout" ? null : 1,
840 + );
841 + expect(walks).toBe(limit === "walk-timeout" ? 1 : 2);
842 + if (limit === "walk-timeout") return;
843 + fixture.setStoredWorktreePaths([orphan]);
844 + expect(orphanEntry(yield* fixture.service.runNow)).toBeUndefined();
845 + fixture.setStoredWorktreePaths([]);
846 + expect(orphanEntry(yield* fixture.service.runNow)?.bytes).toBe(7);
847 + expect(walks).toBe(3);
848 + }),
849 + ),
850 + );
851 +
852 + it.live.each(["nested", "direct"] as const)(
853 + "reports a linked orphan's size without removing its files (%s)",
854 + (location) =>
855 + runCleanupTest(
856 + Effect.gen(function* () {
857 + const fixture = yield* cleanupFixture();
858 + fixture.setThreads([]);
859 + const orphan = `${fixture.config.worktreesDir}/${location === "nested" ? "repository/" : ""}orphan`;
860 + yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]);
861 + const sizes = yield* Effect.forEach(yield* fixture.fs.readDirectory(orphan), (name) =>
862 + fixture.fs.stat(`${orphan}/${name}`).pipe(Effect.map((stat) => Number(stat.size))),
863 + );
864 + const outside = yield* fixture.fs.makeTempDirectoryScoped();
865 + yield* fixture.fs.writeFileString(`${outside}/external`, "outside data");
866 + yield* fixture.fs.symlink(outside, `${orphan}/linked-directory`);
867 + yield* fixture.fs.symlink(`${outside}/missing`, `${orphan}/dangling-link`);
868 + yield* fixture.fs.utimes(orphan, 1, 1);
869 + const report = yield* fixture.service.runNow;
870 + expect(report.entries).toEqual([
871 + {
872 + kind: "worktree",
873 + outcome: "kept",
874 + reason: "No thread uses this worktree",
875 + path: orphan,
876 + threadId: null,
877 + threadTitle: null,
878 + bytes: sizes.reduce((sum, size) => sum + size, 0),
879 + files: null,
880 + },
881 + ]);
882 + expect(report.bytesFreed).toBe(0);
883 + expect(yield* fixture.fs.readFileString(`${orphan}/tracked.txt`)).toBe("original\n");
884 + expect(yield* fixture.fs.readFileString(`${outside}/external`)).toBe("outside data");
885 + expect(
886 + (yield* fixture.command(orphan, ["rev-parse", "--is-inside-work-tree"])).stdout.trim(),
887 + ).toBe("true");
888 + }),
889 + ),
890 + );
891 +
892 + it.live.each(["active", "outside-active-snapshot"] as const)(
893 + "does not report a folder referenced by a thread (%s)",
894 + (location) =>
895 + runCleanupTest(
896 + Effect.gen(function* () {
897 + const fixture = yield* cleanupFixture();
898 + const worktreePath = `${fixture.config.worktreesDir}/repository/referenced`;
899 + yield* fixture.command(fixture.repo, [
900 + "worktree",
901 + "add",
902 + "-b",
903 + "referenced",
904 + worktreePath,
905 + ]);
906 + fixture.setThreads(
907 + location === "active"
908 + ? [shell({ branch: "referenced", worktreePath, status: "running" })]
909 + : [],
910 + );
911 + if (location !== "active")
912 + fixture.setStoredWorktreePaths([fixture.worktree, worktreePath]);
913 + yield* fixture.fs.utimes(worktreePath, 1, 1);
914 + const report = yield* fixture.service.runNow;
915 + expect(report.entries.filter((entry) => entry.threadId === null)).toEqual([]);
916 + expect(yield* fixture.fs.exists(worktreePath)).toBe(true);
917 + }),
918 + ),
919 + );
920 +
921 + it.live.each(["exact", "nested", "symlink"] as const)(
922 + "does not report a folder containing a project checkout (%s)",
923 + (location) =>
924 + runCleanupTest(
925 + Effect.gen(function* () {
926 + const fixture = yield* cleanupFixture();
927 + fixture.setThreads([]);
928 + const worktreePath = `${fixture.config.worktreesDir}/repository/project-checkout`;
929 + yield* fixture.fs.makeDirectory(`${worktreePath}/nested`, { recursive: true });
930 + const alias = `${fixture.repo}/alias`;
931 + if (location === "symlink") yield* fixture.fs.symlink(`${worktreePath}/nested`, alias);
932 + fixture.setProjectRoots([
933 + fixture.repo,
934 + location === "exact"
935 + ? worktreePath
936 + : location === "nested"
937 + ? `${worktreePath}/nested`
938 + : alias,
939 + ]);
940 + yield* fixture.fs.utimes(worktreePath, 1, 1);
941 + expect((yield* fixture.service.runNow).entries).toEqual([]);
942 + expect(yield* fixture.fs.exists(worktreePath)).toBe(true);
943 + }),
944 + ),
945 + );
946 +
947 + it.live.each(["exact", "contains", "symlink"] as const)(
948 + "does not report project internals under a custom managed root (%s)",
949 + (location) =>
950 + runCleanupTest(
951 + Effect.gen(function* () {
952 + const fixture = yield* cleanupFixture();
953 + fixture.setThreads([]);
954 + const source = `${fixture.repo}/src`;
955 + yield* fixture.fs.makeDirectory(`${source}/nested/deep`, { recursive: true });
956 + const alias = `${fixture.config.worktreesDir}/project-alias`;
957 + if (location === "symlink") {
958 + yield* fixture.fs.symlink(fixture.repo, alias);
959 + fixture.setProjectRoots([alias]);
960 + }
961 + if (location === "contains") fixture.setProjectRoots([fixture.repo, `${source}/nested`]);
962 + fixture.setSettings({
963 + worktreesDirectory: location === "contains" ? source : fixture.repo,
964 + });
965 + expect((yield* fixture.service.runNow).entries).toEqual([]);
966 + expect(yield* fixture.fs.exists(`${source}/nested/deep`)).toBe(true);
967 + }),
968 + ),
969 + );
970 +
971 + it.live.each(["direct", "symlink"] as const)(
972 + "reports an orphan under a managed root inside a project (%s)",
973 + (location) =>
974 + runCleanupTest(
975 + Effect.gen(function* () {
976 + const fs = yield* FileSystem.FileSystem;
977 + const walked: string[] = [];
978 + const fixture = yield* cleanupFixture().pipe(
979 + Effect.provideService(FileSystem.FileSystem, {
980 + ...fs,
981 + readDirectory: (directory, options) => {
982 + walked.push(directory);
983 + return fs.readDirectory(directory, options);
984 + },
985 + }),
986 + );
987 + fixture.setThreads([]);
988 + const root = `${fixture.repo}/.worktrees`;
989 + const orphan = `${root}/repository/orphan`;
990 + const source = `${fixture.repo}/src`;
991 + yield* fs.makeDirectory(`${source}/nested/deep`, { recursive: true });
992 + yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]);
993 + if (location === "symlink") {
994 + const alias = `${fixture.config.worktreesDir}/project-alias`;
995 + yield* fs.symlink(fixture.repo, alias);
996 + fixture.setProjectRoots([alias]);
997 + }
998 + fixture.setSettings({ worktreesDirectory: root });
999 + yield* fs.utimes(orphan, 1, 1);
1000 + const report = yield* fixture.service.runNow;
1001 + expect(report.entries).toEqual([
1002 + expect.objectContaining({
1003 + path: orphan,
1004 + outcome: "kept",
1005 + reason: "No thread uses this worktree",
1006 + }),
1007 + ]);
1008 + expect(walked.some((directory) => directory.startsWith(source))).toBe(false);
1009 + expect(yield* fs.readFileString(`${orphan}/tracked.txt`)).toBe("original\n");
1010 + }),
1011 + ),
1012 + );
1013 +
1014 + it.live("reports an orphan containing a removed project checkout", () =>
1015 + runCleanupTest(
1016 + Effect.gen(function* () {
1017 + const fixture = yield* cleanupFixture();
1018 + fixture.setThreads([]);
1019 + const orphan = `${fixture.config.worktreesDir}/repository/orphan`;
1020 + const removed = `${orphan}/removed-checkout`;
1021 + yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]);
1022 + yield* fixture.fs.makeDirectory(removed);
1023 + yield* fixture.fs.remove(removed, { recursive: true });
1024 + fixture.setProjectRoots([fixture.repo, removed]);
1025 + yield* fixture.fs.utimes(orphan, 1, 1);
1026 + const report = yield* fixture.service.runNow;
1027 + expect(report.entries).toEqual([
1028 + expect.objectContaining({
1029 + path: orphan,
1030 + outcome: "kept",
1031 + reason: "No thread uses this worktree",
1032 + }),
1033 + ]);
1034 + expect(yield* fixture.fs.readFileString(`${orphan}/tracked.txt`)).toBe("original\n");
1035 + }),
1036 + ),
1037 + );
1038 +
1039 + it.live("skips project workspace internals while reporting a real orphan sibling", () =>
1040 + runCleanupTest(
1041 + Effect.gen(function* () {
1042 + const fixture = yield* cleanupFixture();
1043 + fixture.setThreads([]);
1044 + const project = `${fixture.config.worktreesDir}/project-checkout`;
1045 + const orphan = `${fixture.config.worktreesDir}/repository/orphan`;
1046 + yield* fixture.fs.makeDirectory(`${project}/src/nested`, { recursive: true });
1047 + yield* fixture.fs.makeDirectory(orphan, { recursive: true });
1048 + yield* fixture.fs.writeFileString(`${orphan}/file`, "x");
1049 + fixture.setProjectRoots([fixture.repo, project]);
1050 + yield* fixture.fs.utimes(orphan, 1, 1);
1051 + const report = yield* fixture.service.runNow;
1052 + expect(report.entries).toEqual([
1053 + expect.objectContaining({ path: orphan, outcome: "kept", bytes: 1 }),
1054 + ]);
1055 + expect(yield* fixture.fs.exists(`${project}/src/nested`)).toBe(true);
1056 + expect(yield* fixture.fs.exists(orphan)).toBe(true);
1057 + }),
1058 + ),
1059 + );
1060 +
1061 + it.live("skips symbolic links at both directory levels and disabled cleanup", () =>
1062 + runCleanupTest(
1063 + Effect.gen(function* () {
1064 + const fixture = yield* cleanupFixture();
1065 + fixture.setThreads([]);
1066 + const outside = yield* fixture.fs.makeTempDirectoryScoped();
1067 + yield* fixture.fs.makeDirectory(`${outside}/checkout`);
1068 + const projectDirectory = `${fixture.config.worktreesDir}/repository`;
1069 + yield* fixture.fs.makeDirectory(projectDirectory);
1070 + yield* fixture.fs.symlink(outside, `${fixture.config.worktreesDir}/linked-project`);
1071 + yield* fixture.fs.symlink(`${outside}/checkout`, `${projectDirectory}/linked-checkout`);
1072 + yield* fixture.fs.symlink(`${outside}/missing`, `${projectDirectory}/dangling-link`);
1073 + expect((yield* fixture.service.runNow).entries).toEqual([]);
1074 + const orphan = `${projectDirectory}/orphan`;
1075 + yield* fixture.fs.makeDirectory(orphan);
1076 + fixture.disable();
1077 + expect((yield* fixture.service.runNow).entries).toEqual([]);
1078 + expect(yield* fixture.fs.exists(orphan)).toBe(true);
1079 + }),
1080 + ),
1081 + );
1082 +
1083 + it.live("reports ordinary folders with an honest reason and keeps their files", () =>
1084 + runCleanupTest(
1085 + Effect.gen(function* () {
1086 + const fixture = yield* cleanupFixture();
1087 + fixture.setThreads([]);
1088 + const folder = `${fixture.config.worktreesDir}/repository/leftover`;
1089 + yield* fixture.fs.makeDirectory(folder, { recursive: true });
1090 + yield* fixture.fs.writeFileString(`${folder}/payload`, "leftover data");
1091 + yield* fixture.fs.utimes(folder, 1, 1);
1092 + const report = yield* fixture.service.runNow;
1093 + expect(report.entries).toEqual([
1094 + expect.objectContaining({
1095 + path: folder,
1096 + outcome: "kept",
1097 + bytes: 13,
1098 + reason: "No thread uses this folder, and it isn't a git worktree",
1099 + }),
1100 + ]);
1101 + expect(report.bytesFreed).toBe(0);
1102 + expect(yield* fixture.fs.readFileString(`${folder}/payload`)).toBe("leftover data");
1103 + }),
1104 + ),
1105 + );
1106 +
1107 + it.live("continues after an inaccessible directory's git probe", (context) =>
1108 + runCleanupTest(
1109 + Effect.gen(function* () {
1110 + if ((yield* HostProcess.isWindows) || (yield* HostProcess.UserId) === 0)
1111 + return context.skip();
1112 + const fixture = yield* cleanupFixture();
1113 + fixture.setThreads([]);
1114 + const blocked = `${fixture.config.worktreesDir}/a-inaccessible`;
1115 + const orphan = `${fixture.config.worktreesDir}/z-repository/orphan`;
1116 + yield* fixture.fs.makeDirectory(blocked);
1117 + yield* fixture.fs.makeDirectory(orphan, { recursive: true });
1118 + yield* fixture.fs.writeFileString(`${orphan}/file`, "x");
1119 + yield* fixture.fs.chmod(blocked, 0);
1120 + yield* fixture.fs.utimes(orphan, 1, 1);
1121 + const report = yield* fixture.service.runNow.pipe(
1122 + Effect.ensuring(fixture.fs.chmod(blocked, 0o700).pipe(Effect.orDie)),
1123 + );
1124 + expect(report.entries).toEqual([
1125 + expect.objectContaining({ path: orphan, outcome: "kept", bytes: 1 }),
1126 + ]);
1127 + expect(yield* fixture.fs.exists(orphan)).toBe(true);
1128 + }),
1129 + ),
1130 + );
1131 +
1132 + it.live.each(["win32", "linux"] as const)(
1133 + "compares thread paths with host casing rules and excludes existing projects (%s)",
1134 + (platform) =>
1135 + runCleanupTest(
1136 + Effect.gen(function* () {
1137 + const fixture = yield* cleanupFixture().pipe(
1138 + Effect.provideService(HostProcess.Platform, platform),
1139 + );
1140 + fixture.setThreads([]);
1141 + const parent = `${fixture.config.worktreesDir}/repository`;
1142 + const referenced = `${parent}/Referenced`;
1143 + const project = `${parent}/Project`;
1144 + const nested = `${parent}/Nested`;
1145 + for (const folder of [referenced, project, nested]) {
1146 + yield* fixture.fs.makeDirectory(`${folder}/child`, { recursive: true });
1147 + yield* fixture.fs.utimes(folder, 1, 1);
1148 + }
1149 + fixture.setStoredWorktreePaths([fixture.worktree, referenced.toUpperCase()]);
1150 + fixture.setProjectRoots([fixture.repo, project, `${nested}/child`]);
1151 + const report = yield* fixture.service.runNow;
1152 + expect(report.entries.map((entry) => entry.path).sort()).toEqual(
1153 + platform === "win32" ? [] : [referenced],
1154 + );
1155 + }),
1156 + ),
1157 + );
1158 +
1159 + it.live("caps orphan entries while preserving kept totals", () =>
1160 + runCleanupTest(
1161 + Effect.gen(function* () {
1162 + const fixture = yield* cleanupFixture();
1163 + fixture.setThreads([]);
1164 + for (let i = 0; i < 205; i++) {
1165 + const orphan = `${fixture.config.worktreesDir}/repository/orphan-${i}`;
1166 + yield* fixture.fs.makeDirectory(orphan, { recursive: true });
1167 + yield* fixture.fs.writeFileString(`${orphan}/file`, "x");
1168 + yield* fixture.fs.utimes(orphan, 1, 1);
1169 + }
1170 + const report = yield* fixture.service.runNow;
1171 + expect(report.entries).toHaveLength(200);
1172 + expect(report.entries.every((entry) => entry.bytes === 1)).toBe(true);
1173 + expect(report.omittedCount).toBe(5);
1174 + expect(report.counts).toEqual({ removed: 0, kept: 205, failed: 0 });
1175 + expect(report.bytesFreed).toBe(0);
1176 + }),
1177 + ),
1178 + );
1179 +});
1180 +
1181 describe("storage cleanup reports and local file policies", () => {
1182 + it.live.each(["before-check", "while-measuring"] as const)(
1183 + "keeps a worktree protected by a missing project root (%s)",
1184 + (timing) =>
1185 + runCleanupTest(
1186 + Effect.gen(function* () {
1187 + const fixture = yield* pausedMeasurementFixture();
1188 + if (timing === "before-check")
1189 + fixture.setProjectRoots([fixture.repo, `${fixture.worktree}/removed-checkout`]);
1190 + const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild);
1191 + if (timing === "while-measuring") {
1192 + yield* Deferred.await(fixture.measuring);
1193 + fixture.setProjectRoots([fixture.repo, `${fixture.worktree}/removed-checkout`]);
1194 + }
1195 + yield* Deferred.succeed(fixture.resume, undefined);
1196 + const report = yield* Fiber.join(cleanup);
1197 + expect(report.entries[0]).toMatchObject({
1198 + outcome: "kept",
1199 + reason: "Contains a project checkout",
1200 + });
1201 + expect(yield* fixture.fs.readFileString(`${fixture.worktree}/tracked.txt`)).toBe(
1202 + "original\n",
1203 + );
1204 + }),
1205 + ),
1206 + );
1207 +
1208 it.live("measures nested regular files without following symlinks", () =>
1209 runCleanupTest(
1210 Effect.gen(function* () {
apps/server/src/storageCleanup.ts
+153 -8
@@ -60,6 +60,8 @@ const DAY_MS = 86_400_000;
60 // After a settle, the project's settle script needs time to open its
61 // terminal, which then protects the worktree.
62 const SETTLE_SCRIPT_GRACE_MS = 60_000;
63 +// Worktree creation can precede its thread row, including review-guide checkouts.
64 +const ORPHAN_WORKTREE_GRACE_MS = 60 * 60 * 1_000;
65
66 const sentence = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
67 const REPORT_ENTRY_LIMIT = 200;
@@ -210,6 +212,7 @@ const make = Effect.gen(function* () {
212 const fs = yield* FileSystem.FileSystem;
213 const path = yield* Path.Path;
214 const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
215 + const orphanSizes = new Map<string, number | null>();
216 const noteTerminal = (terminal: TerminalSummary) => {
217 const threadTerminals =
218 liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
@@ -217,8 +220,13 @@ const make = Effect.gen(function* () {
220 liveTerminals.set(terminal.threadId, threadTerminals);
221 };
222
223 + const isWindows = yield* HostProcess.isWindows;
224 + const pathKey = (target: string) => {
225 + const resolved = path.resolve(target);
226 + return isWindows ? resolved.toLowerCase() : resolved;
227 + };
228 const inside = (root: string, target: string) => {
221 - const relative = path.relative(root, target);
229 + const relative = path.relative(pathKey(root), pathKey(target));
230 return (
231 relative !== "" &&
232 relative !== ".." &&
@@ -300,15 +308,141 @@ const make = Effect.gen(function* () {
308 ) {
309 for (const project of projects) {
310 const projectPath = path.resolve(project.workspaceRoot);
303 - if (projectPath === worktreePath || inside(worktreePath, projectPath)) return true;
311 + if (pathKey(projectPath) === pathKey(worktreePath) || inside(worktreePath, projectPath))
312 + return true;
313 const realPath = yield* fs
314 .realPath(projectPath)
315 .pipe(Effect.orElseSucceed(() => projectPath));
307 - if (realPath === worktreePath || inside(worktreePath, realPath)) return true;
316 + if (pathKey(realPath) === pathKey(worktreePath) || inside(worktreePath, realPath))
317 + return true;
318 }
319 return false;
320 });
321
322 + const reportOrphanWorktrees = Effect.fn("StorageCleanup.reportOrphanWorktrees")(function* (
323 + roots: ReadonlyArray<string>,
324 + projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
325 + entries: StorageCleanupReportEntry[],
326 + ) {
327 + // Include deleted and archived threads, even those without a branch or project.
328 + const rows = yield* sql<{ worktreePath: string }>`
329 + SELECT DISTINCT json_extract(payload_json, '$.worktreePath') AS "worktreePath"
330 + FROM orchestration_v2_projection_threads
331 + WHERE json_extract(payload_json, '$.worktreePath') IS NOT NULL
332 + `.pipe(NodeSqliteClient.readOnly);
333 + const referenced = new Set<string>();
334 + for (const row of rows) {
335 + const resolved = path.resolve(row.worktreePath);
336 + referenced.add(pathKey(resolved));
337 + referenced.add(
338 + pathKey(yield* fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved))),
339 + );
340 + }
341 + const referencedAncestors = new Set<string>();
342 + for (let ancestor of referenced) {
343 + while (roots.some((root) => inside(root, ancestor))) {
344 + ancestor = pathKey(path.dirname(ancestor));
345 + referencedAncestors.add(ancestor);
346 + }
347 + }
348 + const projectRoots = (yield* Effect.forEach(
349 + yield* Effect.filter(projects, (project) =>
350 + fs.exists(path.resolve(project.workspaceRoot)).pipe(Effect.orElseSucceed(() => true)),
351 + ),
352 + (project) => {
353 + const resolved = path.resolve(project.workspaceRoot);
354 + return fs.realPath(resolved).pipe(
355 + Effect.orElseSucceed(() => resolved),
356 + Effect.map((realPath) => [resolved, realPath]),
357 + );
358 + },
359 + )).flat();
360 + const inProject = (target: string, managedRoot: string) =>
361 + projectRoots.some(
362 + (root) =>
363 + !inside(root, managedRoot) && (pathKey(root) === pathKey(target) || inside(root, target)),
364 + );
365 + const directories = Effect.fnUntraced(function* (parent: string, managedRoot: string) {
366 + if (inProject(parent, managedRoot)) return [];
367 + const result: string[] = [];
368 + for (const name of yield* fs.readDirectory(parent).pipe(Effect.orElseSucceed(() => []))) {
369 + const target = path.join(parent, name);
370 + if (!inside(parent, target) || inProject(target, managedRoot)) continue;
371 + const directory = yield* Effect.gen(function* () {
372 + if (pathKey(yield* fs.realPath(target)) !== pathKey(target)) return false;
373 + return (yield* fs.stat(target)).type === "Directory";
374 + }).pipe(Effect.orElseSucceed(() => false));
375 + if (directory) result.push(target);
376 + }
377 + return result;
378 + });
379 + // Let the first walk reach its own limit so unmeasurable folders get cached.
380 + // Later walks share the remaining sweep budget.
381 + // Unmeasured folders still appear with an unknown size.
382 + const now = yield* Clock.currentTimeMillis;
383 + const measurementDeadline = now + 30_000;
384 + let firstMeasurement = true;
385 + const reported = new Set<string>();
386 + const report = Effect.fnUntraced(
387 + function* (worktreePath: string) {
388 + const key = pathKey(worktreePath);
389 + if (
390 + reported.has(key) ||
391 + referenced.has(key) ||
392 + referencedAncestors.has(key) ||
393 + projectRoots.some((root) => pathKey(root) === key || inside(worktreePath, root))
394 + )
395 + return;
396 + const modified = Option.getOrNull((yield* fs.stat(worktreePath)).mtime);
397 + if (modified !== null && modified.getTime() > now - ORPHAN_WORKTREE_GRACE_MS) return;
398 + const gitPath = path.join(worktreePath, ".git");
399 + const linked = (yield* fs.exists(gitPath)) && (yield* fs.stat(gitPath)).type === "File";
400 + reported.add(key);
401 + const remaining = measurementDeadline - (yield* Clock.currentTimeMillis);
402 + if (!orphanSizes.has(key) && (firstMeasurement || remaining > 0)) {
403 + const measured = yield* measureWorktree(worktreePath).pipe(
404 + firstMeasurement ? Effect.map(Option.some) : Effect.timeoutOption(remaining),
405 + );
406 + firstMeasurement = false;
407 + if (Option.isSome(measured)) orphanSizes.set(key, measured.value);
408 + }
409 + const bytes = orphanSizes.get(key) ?? null;
410 + entries.push({
411 + kind: "worktree",
412 + outcome: "kept",
413 + reason: linked
414 + ? "No thread uses this worktree"
415 + : "No thread uses this folder, and it isn't a git worktree",
416 + path: worktreePath,
417 + threadId: null,
418 + threadTitle: null,
419 + bytes,
420 + files: null,
421 + });
422 + },
423 + Effect.orElseSucceed(() => undefined),
424 + );
425 + for (const root of roots) {
426 + // Worktrees can be <root>/<repository>/<branch> or explicitly <root>/<name>.
427 + for (const projectDirectory of yield* directories(root, root)) {
428 + yield* Effect.gen(function* () {
429 + if (referenced.has(pathKey(projectDirectory))) return;
430 + const gitPath = path.join(projectDirectory, ".git");
431 + if (yield* fs.exists(gitPath)) {
432 + if ((yield* fs.stat(gitPath)).type === "File") yield* report(projectDirectory);
433 + return;
434 + }
435 + for (const worktreePath of yield* directories(projectDirectory, root)) {
436 + yield* report(worktreePath);
437 + }
438 + }).pipe(Effect.orElseSucceed(() => undefined));
439 + }
440 + }
441 + for (const key of orphanSizes.keys()) {
442 + if (!reported.has(key)) orphanSizes.delete(key);
443 + }
444 + });
445 +
446 // Whether cwd stopped being a checkout of this branch. Two small Git reads,
447 // since every worktree in a sweep is asked; statusDetailsLocal also diffs and
448 // counts.
@@ -434,6 +568,7 @@ const make = Effect.gen(function* () {
568 now: number,
569 entries: StorageCleanupReportEntry[],
570 ) {
571 + if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
572 const roots: Array<string> = [];
573 for (const directory of managedWorktreesDirectories(
574 serverSettings,
@@ -739,6 +874,11 @@ const make = Effect.gen(function* () {
874 ),
875 );
876 }
877 + yield* reportOrphanWorktrees(
878 + roots,
879 + yield* projectStore.list({ includeDeleted: true }),
880 + entries,
881 + );
882 });
883
884 const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
@@ -853,16 +993,21 @@ const make = Effect.gen(function* () {
993 let bytesFreed = 0;
994 for (const entry of entries) {
995 counts[entry.outcome]++;
856 - bytesFreed += entry.bytes ?? 0;
996 + if (entry.outcome !== "kept") bytesFreed += entry.bytes ?? 0;
997 }
858 - const priority = { failed: 0, removed: 1, kept: 2 };
998 + const priority = (entry: StorageCleanupReportEntry) =>
999 + entry.outcome === "failed"
1000 + ? 0
1001 + : entry.outcome === "removed"
1002 + ? 1
1003 + : entry.kind === "worktree" && entry.threadId === null
1004 + ? 2
1005 + : 3;
1006 const latestReport: StorageCleanupReport = {
1007 trigger,
1008 startedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
1009 finishedAt: DateTime.formatIso(yield* DateTime.now),
863 - entries: entries
864 - .sort((a, b) => priority[a.outcome] - priority[b.outcome])
865 - .slice(0, REPORT_ENTRY_LIMIT),
1010 + entries: entries.sort((a, b) => priority(a) - priority(b)).slice(0, REPORT_ENTRY_LIMIT),
1011 counts,
1012 bytesFreed,
1013 omittedCount: Math.max(0, entries.length - REPORT_ENTRY_LIMIT),
apps/web/src/components/settings/StorageSettings.test.tsx
+72 -3
@@ -1,6 +1,11 @@
1 // @vitest-environment jsdom
2 import { RegistryProvider } from "@effect/atom-react";
3 -import { DEFAULT_SERVER_SETTINGS, ProjectId, type StorageCleanupReport } from "@t3tools/contracts";
3 +import {
4 + DEFAULT_SERVER_SETTINGS,
5 + ProjectId,
6 + ThreadId,
7 + type StorageCleanupReport,
8 +} from "@t3tools/contracts";
9 import { act, type ReactNode } from "react";
10 import { createRoot, type Root } from "react-dom/client";
11 import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
@@ -8,11 +13,12 @@ import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
13 const state = vi.hoisted(() => ({
14 settings: {} as typeof DEFAULT_SERVER_SETTINGS,
15 run: vi.fn(),
16 + report: null as StorageCleanupReport | null,
17 }));
18
19 vi.mock("../../state/server", async () => {
20 const { Atom } = await import("effect/reactivity");
15 - const report = Atom.make({ _tag: "Success", value: null, waiting: false });
21 + const report = Atom.make(() => ({ _tag: "Success", value: state.report, waiting: false }));
22 const allowed = Atom.make(true);
23 return {
24 serverEnvironment: {
@@ -56,14 +62,25 @@ vi.mock("./useScopedSettings", () => ({
62 vi.mock("./settingsLayout", () => ({
63 SettingsPageContainer: ({ children }: { children: ReactNode }) => children,
64 SettingsSection: ({ children }: { children: ReactNode }) => children,
59 - SettingsRow: ({ description, control }: { description: ReactNode; control: ReactNode }) => (
65 + SettingsRow: ({
66 + title,
67 + description,
68 + control,
69 + }: {
70 + title: ReactNode;
71 + description: ReactNode;
72 + control: ReactNode;
73 + }) => (
74 <div>
75 + <h3>{title}</h3>
76 {description}
77 {control}
78 </div>
79 ),
80 SettingResetButton: () => null,
81 useRelativeTimeTick: () => undefined,
82 + useSettingsSearchTargetId: () => null,
83 + useSettingsSearchTarget: () => undefined,
84 }));
85 vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
86
@@ -88,6 +105,7 @@ beforeEach(() => {
105 },
106 projectSettingsOverrides: {},
107 };
108 + state.report = null;
109 state.run.mockReset();
110 container = document.createElement("div");
111 document.body.append(container);
@@ -166,3 +184,54 @@ it("keeps cleanup disabled when settled retention and all other rules are off",
184 await act(async () => button.click());
185 expect(state.run).not.toHaveBeenCalled();
186 });
187 +
188 +it("shows an orphan's full path and size while keeping thread row titles unchanged", async () => {
189 + state.settings = {
190 + ...state.settings,
191 + storageCleanup: { ...state.settings.storageCleanup, worktreeSettledAfterDays: 0 },
192 + };
193 + state.report = {
194 + trigger: "manual",
195 + startedAt: "2026-10-14T12:00:00.000Z",
196 + finishedAt: "2026-10-14T12:00:01.000Z",
197 + entries: [
198 + {
199 + kind: "worktree",
200 + outcome: "kept",
201 + path: "/worktrees/repo/orphan",
202 + threadId: null,
203 + threadTitle: null,
204 + reason: "No thread uses this folder, and it isn't a git worktree",
205 + bytes: 6600000,
206 + files: null,
207 + },
208 + {
209 + kind: "worktree",
210 + outcome: "kept",
211 + path: "/worktrees/repo/thread-checkout",
212 + threadId: ThreadId.make("thread"),
213 + threadTitle: "Thread title",
214 + reason: "Thread is running or has pending work",
215 + bytes: null,
216 + files: null,
217 + },
218 + ],
219 + counts: { removed: 0, kept: 2, failed: 0 },
220 + omittedCount: 0,
221 + bytesFreed: 0,
222 + };
223 + await render();
224 + const lastRun = Array.from(container.querySelectorAll("button")).find((button) =>
225 + button.textContent?.includes("Last run"),
226 + )!;
227 + await act(async () => lastRun.click());
228 + const titles = Array.from(container.querySelectorAll("h3"), (heading) => heading.textContent);
229 + expect(titles).toContain("/worktrees/repo/orphan");
230 + expect(titles).toContain("thread-checkout");
231 + expect(titles).not.toContain("/worktrees/repo/thread-checkout");
232 + expect(container.textContent).toContain(
233 + "No thread uses this folder, and it isn't a git worktree",
234 + );
235 + expect(container.textContent).toContain("6.29 MB");
236 + expect(container.textContent).toContain("0 B recovered.");
237 +});
apps/web/src/components/settings/StorageSettings.tsx
+5 -2
@@ -198,7 +198,9 @@ function CleanupResults({
198 {report.entries.map((entry, index) => {
199 const name =
200 entry.kind === "worktree"
201 - ? (entry.path?.split(/[\\/]/).findLast(Boolean) ?? "Worktrees")
201 + ? ((entry.threadId === null
202 + ? entry.path
203 + : entry.path?.split(/[\\/]/).findLast(Boolean)) ?? "Worktrees")
204 : entry.kind === "logs"
205 ? "Rotated logs"
206 : "Browser artifacts";
@@ -215,7 +217,8 @@ function CleanupResults({
217 </span>
218 }
219 control={
218 - entry.outcome === "removed" && (
220 + (entry.outcome === "removed" ||
221 + (entry.outcome === "kept" && entry.bytes !== null)) && (
222 <span className="text-xs text-muted-foreground">
223 {[
224 entry.kind !== "worktree" && entry.files !== null
docs/user/project-settings.md
+1
@@ -168,6 +168,7 @@ Existing prompts for deleting a worktree manually remain available when this pol
168
169 Choose **Delete now** to run the enabled rules immediately. The latest results show which
170 worktrees were removed or kept and why, plus any failures.
171 +Results also list folders in the worktree folder that no thread uses, with their sizes; cleanup never removes them, so remove them manually if you want.
172
173 Browser captures and rotated logs have separate retention periods. Expired capture links stop
174 working. Current logs, message attachments, and browser profiles are kept.