Official References: Git Worktree Documentation · Gemini CLI Trusted Folders
Why Use Git Worktrees with Gemini?
Gemini CLI modifies local files and executes commands directly. If you switch branches via git checkout or git stash while the AI is performing a long-running task, the context can break or work-in-progress modifications might collide.
By using Git Worktrees, you create independent directories for each task, gaining:
- Safe Independence: Work in your own directory while the AI modifies code in another.
- Context Isolation: Maintain separate
GEMINI.mdor local memories for each worktree. - Immediate Parallel Testing: Run tests for different branch versions simultaneously in different terminals.
Practical Worktree Workflow
1. Create a New Worktree
Leave your current main branch as is and create an independent folder for a new feature.
# Run from ~/workspace/project-main
git worktree add ../project-feature-x feature-x-branchNow ../project-feature-x contains the source code and node_modules environment completely independent of main.
2. Start Gemini CLI Session
Start Gemini CLI in the worktree directory. Gemini is safe here as it only reads files within that folder.
cd ../project-feature-x
gemini3. Execute and Verify Tasks
Have Gemini implement the feature. While it works, you can continue other tasks or code reviews in the original main directory.
4. Complete and Clean Up
Once finished, commit your changes and remove the worktree.
# After completing the task
git add .
git commit -m "feat: add feature X using Gemini CLI"
git push origin feature-x-branch
# Remove the worktree
cd ../project-main
git worktree remove ../project-feature-xTips for Gemini + Worktree
- Leverage
GEMINI.md: Create a temporaryGEMINI.mdin the specific worktree directory to specify task-specific goals and constraints. This guides the AI without affecting themainbranch. - Trusted Folders: Ensure the new worktree directory is registered as a trusted folder in Gemini CLI via the
/trustcommand. - Shared Module Management: If
node_modulesis too large, use a package manager that shares packages across worktrees (like pnpm or yarn berry).
Cautions
- DB and External State: While source code is isolated, local databases or shared environment variables might not be. Be cautious when the AI modifies DB schemas.
- Untracked Files: Be careful not to lose uncommitted files when removing a worktree.
Next to Read
- Safety mechanisms to prevent AI errors: Trusted Folders, Sandboxing, and Restore
- Automation in headless mode: Headless Automation