MCPcopy Create free account
hub / github.com/Noumena-Network/code / cleanupStaleAgentWorktrees

Function cleanupStaleAgentWorktrees

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

Source from the content-addressed store, hash-verified

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

Callers 1

Calls 7

getCwdFunction · 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