@@ -686,6 +686,51 @@ export class WorktreeManager {
686686 }
687687
688688 async deleteWorktree ( worktreePath : string ) : Promise < void > {
689+ const resolvedWorktreePath = path . resolve ( worktreePath ) ;
690+ const resolvedMainRepoPath = path . resolve ( this . mainRepoPath ) ;
691+
692+ // Safety check 1: Never delete the main repo path
693+ if ( resolvedWorktreePath === resolvedMainRepoPath ) {
694+ const error = new Error (
695+ "Cannot delete worktree: path matches main repo path" ,
696+ ) ;
697+ this . logger . error ( "Safety check failed" , { worktreePath, error } ) ;
698+ throw error ;
699+ }
700+
701+ // Safety check 2: Never delete a parent of the main repo path
702+ if (
703+ resolvedMainRepoPath . startsWith ( resolvedWorktreePath ) &&
704+ resolvedMainRepoPath !== resolvedWorktreePath
705+ ) {
706+ const error = new Error (
707+ "Cannot delete worktree: path is a parent of main repo path" ,
708+ ) ;
709+ this . logger . error ( "Safety check failed" , { worktreePath, error } ) ;
710+ throw error ;
711+ }
712+
713+ // Safety check 3: Check for .git directory (indicates main repo)
714+ try {
715+ const gitPath = path . join ( resolvedWorktreePath , ".git" ) ;
716+ const stat = await fs . stat ( gitPath ) ;
717+ if ( stat . isDirectory ( ) ) {
718+ const error = new Error (
719+ "Cannot delete worktree: path appears to be a main repository (contains .git directory)" ,
720+ ) ;
721+ this . logger . error ( "Safety check failed" , { worktreePath, error } ) ;
722+ throw error ;
723+ }
724+ } catch ( error ) {
725+ // If .git doesn't exist or we can't read it, proceed (unless it was the directory check above)
726+ if (
727+ error instanceof Error &&
728+ error . message . includes ( "Cannot delete worktree" )
729+ ) {
730+ throw error ;
731+ }
732+ }
733+
689734 this . logger . info ( "Deleting worktree" , { worktreePath } ) ;
690735
691736 try {
0 commit comments