MCPcopy Create free account
hub / github.com/AnukarOP/claude-code-leaked / createAgentWorktree

Function createAgentWorktree

source code/utils/worktree.ts:904–954  ·  view source on GitHub ↗
(slug: string)

Source from the content-addressed store, hash-verified

902 * Falls back to hook-based creation if not in a git repository.
903 */
904export async function createAgentWorktree(slug: string): Promise<{
905 worktreePath: string
906 worktreeBranch?: string
907 headCommit?: string
908 gitRoot?: string
909 hookBased?: boolean
910}> {
911 validateWorktreeSlug(slug)
912
913 // Try hook-based worktree creation first (allows user-configured VCS)
914 if (hasWorktreeCreateHook()) {
915 const hookResult = await executeWorktreeCreateHook(slug)
916 logForDebugging(
917 `Created hook-based agent worktree at: ${hookResult.worktreePath}`,
918 )
919
920 return { worktreePath: hookResult.worktreePath, hookBased: true }
921 }
922
923 // Fall back to git worktree
924 // findCanonicalGitRoot (not findGitRoot) so agent worktrees always land in
925 // the main repo's .claude/worktrees/ even when spawned from inside a session
926 // worktree — otherwise they nest at <worktree>/.claude/worktrees/ and the
927 // periodic cleanup (which scans the canonical root) never finds them.
928 const gitRoot = findCanonicalGitRoot(getCwd())
929 if (!gitRoot) {
930 throw new Error(
931 'Cannot create agent worktree: not in a git repository and no WorktreeCreate hooks are configured. ' +
932 'Configure WorktreeCreate/WorktreeRemove hooks in settings.json to use worktree isolation with other VCS systems.',
933 )
934 }
935
936 const { worktreePath, worktreeBranch, headCommit, existed } =
937 await getOrCreateWorktree(gitRoot, slug)
938
939 if (!existed) {
940 logForDebugging(
941 `Created agent worktree at: ${worktreePath} on branch: ${worktreeBranch}`,
942 )
943 await performPostCreationSetup(gitRoot, worktreePath)
944 } else {
945 // Bump mtime so the periodic stale-worktree cleanup doesn't consider this
946 // worktree stale — the fast-resume path is read-only and leaves the original
947 // creation-time mtime intact, which can be past the 30-day cutoff.
948 const now = new Date()
949 await utimes(worktreePath, now, now)
950 logForDebugging(`Resuming existing agent worktree at: ${worktreePath}`)
951 }
952
953 return { worktreePath, worktreeBranch, headCommit, gitRoot }
954}
955
956/**
957 * Remove a worktree created by createAgentWorktree.

Callers 2

callFunction · 0.85
runBridgeLoopFunction · 0.85

Calls 7

validateWorktreeSlugFunction · 0.85
hasWorktreeCreateHookFunction · 0.85
logForDebuggingFunction · 0.85
getCwdFunction · 0.85
getOrCreateWorktreeFunction · 0.85
performPostCreationSetupFunction · 0.85

Tested by

no test coverage detected