MCPcopy Create free account
hub / github.com/claude-code-best/claude-code / cleanupStaleAgentWorktrees

Function cleanupStaleAgentWorktrees

src/utils/worktree.ts:1060–1138  ·  view source on GitHub ↗
(
  cutoffDate: Date,
)

Source from the content-addressed store, hash-verified

1058 * dir), it's left in place — a later readdir finding it stale again is harmless.
1059 */
1060export async function cleanupStaleAgentWorktrees(
1061 cutoffDate: Date,
1062): Promise<number> {
1063 const gitRoot = findCanonicalGitRoot(getCwd())
1064 if (!gitRoot) {
1065 return 0
1066 }
1067
1068 const dir = worktreesDir(gitRoot)
1069 let entries: string[]
1070 try {
1071 entries = await readdir(dir)
1072 } catch {
1073 return 0
1074 }
1075
1076 const cutoffMs = cutoffDate.getTime()
1077 const currentPath = currentWorktreeSession?.worktreePath
1078 let removed = 0
1079
1080 for (const slug of entries) {
1081 if (!EPHEMERAL_WORKTREE_PATTERNS.some(p => p.test(slug))) {
1082 continue
1083 }
1084
1085 const worktreePath = join(dir, slug)
1086 if (currentPath === worktreePath) {
1087 continue
1088 }
1089
1090 let mtimeMs: number
1091 try {
1092 mtimeMs = (await stat(worktreePath)).mtimeMs
1093 } catch {
1094 continue
1095 }
1096 if (mtimeMs >= cutoffMs) {
1097 continue
1098 }
1099
1100 // Both checks must succeed with empty output. Non-zero exit (corrupted
1101 // worktree, git not recognizing it, etc.) means skip — we don't know
1102 // what's in there.
1103 const [status, unpushed] = await Promise.all([
1104 execFileNoThrowWithCwd(
1105 gitExe(),
1106 ['--no-optional-locks', 'status', '--porcelain', '-uno'],
1107 { cwd: worktreePath },
1108 ),
1109 execFileNoThrowWithCwd(
1110 gitExe(),
1111 ['rev-list', '--max-count=1', 'HEAD', '--not', '--remotes'],
1112 { cwd: worktreePath },
1113 ),
1114 ])
1115 if (status.code !== 0 || status.stdout.trim().length > 0) {
1116 continue
1117 }

Callers 1

Calls 8

getCwdFunction · 0.85
worktreesDirFunction · 0.85
readdirFunction · 0.85
statFunction · 0.85
execFileNoThrowWithCwdFunction · 0.85
removeAgentWorktreeFunction · 0.85
worktreeBranchNameFunction · 0.85
logForDebuggingFunction · 0.70

Tested by

no test coverage detected