Stop Letting AI Agents Destroy Your Git History: Use agent-worktree
Stop Letting AI Agents Destroy Your Git History: Use agent-worktree
Your AI coding agent just force-pushed to main. Again.
You've been there. You fire up Claude, Cursor, or your custom Codex setup to "quickly fix that bug." Thirty minutes later, your repository looks like a tornado hit it—half-committed experiments, mysterious merge conflicts, and somehow three branches named fix-thing-2-final-REALLY. The agent worked in your actual working directory, polluted your stash, and now you're spending Friday evening untangling Git spaghetti instead of shipping code.
Here's the brutal truth: AI agents are chaos engines without proper isolation. They don't care about your carefully maintained branch strategy. They don't know (or care) that you're in the middle of your own feature work. They just execute—and leave you holding the merge conflict bag.
What if you could spin up a completely isolated Git environment for every agent session? What if cleanup happened automatically when the agent finished? What if parallel agents could run simultaneously without stepping on each other's digital toes?
Enter agent-worktree—the Git worktree workflow tool that transforms AI coding agents from repo-wrecking liabilities into precision development instruments. This isn't just another Git wrapper. It's a fundamental reimagining of how AI agents should interact with your codebase.
What is agent-worktree?
agent-worktree is a purpose-built CLI tool created by nekocode that supercharges Git's native worktree feature for the AI coding era. While Git worktrees have existed since 2015, they've remained an underutilized power-user feature—powerful but clunky, with none of the workflow automation modern development demands.
nekocode recognized a critical gap: AI coding agents need ephemeral, isolated environments that mirror production code without risk of contamination. Traditional approaches—Docker containers, temporary clones, or naive branch switching—introduce unacceptable latency, complexity, or state pollution. agent-worktree bridges this gap with a zero-overhead abstraction that makes worktree creation, agent execution, and cleanup as seamless as running a single command.
The tool has gained rapid traction in the AI engineering community precisely because it solves a problem that's exploding in severity. As teams deploy multiple agents simultaneously—Claude for refactoring, Codex for tests, custom agents for documentation—the "isolated environment" problem scales from inconvenience to blocking operational crisis. agent-worktree transforms this chaos into structured, reproducible, and automatically managed parallel development.
At its core, agent-worktree treats each AI agent session as a transaction: create isolated context → execute agent → evaluate result → merge or discard. This transactional model eliminates the cognitive overhead of manual worktree management while preserving Git's integrity guarantees. The result? You get the power of parallel development without the paralysis of parallel complexity.
Key Features That Change Everything
True Parallel Execution Without Interference
agent-worktree leverages Git's native worktree mechanism to create linked working directories that share the same object database but maintain independent HEAD states, index files, and working trees. Unlike git clone --shared, there's no repository duplication—just instantaneous, zero-copy environment provisioning. Run Claude on your authentication refactor while Codex handles API documentation updates, both operating against the same commit graph without any possibility of cross-contamination.
Snap Mode: The "Use and Discard" Revolution
The killer feature. Snap mode (wt new -s) creates a worktree, drops the agent into it, and automatically handles the entire lifecycle. When the agent exits—cleanly, crashed, or Ctrl+C'd—agent-worktree evaluates the state and presents intelligent next actions. No changes? Auto-cleanup. Only commits? One-key merge. Uncommitted work? Reopen the agent or handle manually. This isn't just convenience; it's operational safety for unattended agent runs.
Intelligent Base Branch Management
Every worktree remembers its origin. agent-worktree tracks base branches per-worktree, enabling context-aware merges that default to your starting point—not arbitrary trunk assumptions. The wt merge command automatically targets your base branch, with sensible fallbacks and explicit overrides when history diverges. No more "wait, what was I branching from?" moments.
Configurable Automation Hooks
Define post_create, pre_merge, and post_merge hooks in TOML configuration. Automatically install dependencies when spawning worktrees. Run your test suite before allowing merges. Trigger deployments after successful integration. These hooks execute with clear trust boundaries and documented working directory semantics—post_create runs in the new worktree, merge hooks run at worktree root.
Smart File Replication
The copy_files configuration uses gitignore-style patterns to propagate essential non-tracked files—.env files, local secrets, tool configurations—into new worktrees automatically. No manual setup, no "it works on my machine because I forgot I had that file." Patterns are validated for repository containment, preventing path traversal attacks.
Shell Integration That Actually Works
Auto-detected setup for bash, zsh, fish, and PowerShell. The wt command becomes a natural extension of your shell, with wt cd providing seamless navigation between worktrees and back to your main repository. This isn't aliased complexity—it's first-class shell citizenship.
Use Cases Where agent-worktree Dominates
Multi-Agent Feature Development
Your team runs three Claude instances simultaneously: one refactoring legacy authentication, one implementing OAuth2, one writing comprehensive tests. Without isolation, they'd conflict on shared files, corrupt each other's state, or require serialized execution that stretches a day's work into a week. With agent-worktree, each agent gets its own linked working directory. They execute in parallel, commit independently, and merge through a controlled, reviewable process. Development velocity scales linearly with agent count, not logarithmically.
Ephemeral Experimentation
"What if we tried rewriting the data layer in Rust?" Traditional approach: create branch, switch context, pollute your working directory, maybe forget to clean up. agent-worktree approach: wt new rust-experiment -s claude. The agent explores, commits findings, exits. You review, merge or discard, and the environment vanishes. Experiments become cheap, safe, and automatically catalogued—no branch graveyards, no stale worktrees consuming disk space.
CI/CD Agent Workers
Automated systems running AI agents for code review, dependency updates, or documentation generation need hermetic, reproducible environments. agent-worktree's snap mode with automatic cleanup ensures that each CI job starts pristine and leaves no residue. The wt clean --dry-run command lets you preview and purge stale worktrees, while wt clean automatically removes worktrees with no diff from their base—self-maintaining infrastructure.
Safe Production Hotfixes
Critical bug in production, but your working directory is mid-feature and uncommittable. wt new hotfix-PROD-911 --base main creates an instant clean slate from your release branch. Apply the fix, test, merge with wt merge --into main -d. Your experimental work remains untouched, the hotfix ships, and the temporary environment self-destructs. Crisis response without context destruction.
Step-by-Step Installation & Setup Guide
Getting agent-worktree operational takes under two minutes. Here's the complete flow:
Global Installation via npm
# Install the CLI globally
npm install -g agent-worktree
This provides the wt command system-wide. The package includes automatic shell integration detection.
Shell Integration Setup
# Auto-detect and install shell hooks
wt setup
# Or explicitly target your shell
wt setup --shell zsh
Supported shells: bash, zsh, fish, PowerShell. The integration enables wt cd navigation and environment awareness.
Project Initialization
# Navigate to your project
cd ~/projects/my-api
# Initialize agent-worktree configuration
wt init
# Or with explicit preferences
wt init --trunk main --merge-strategy squash --sync-strategy rebase
This creates .agent-worktree.toml in your project root. The trunk setting auto-detects if omitted, but explicit configuration prevents ambiguity.
Update Management
# Self-update to latest version
wt update
Critical Windows Note:
wt updatereinstalls the npm package, which fails if anywtprocess holds the.exelock. Close all shells runningwtbefore updating—this is a Windows file system limitation, not an agent-worktree bug.
Environment Variable Configuration
# Override default storage location (~/.agent-worktree)
export AGENT_WORKTREE_DIR=/data/agent-worktree
Useful for shared development servers or when home directory quotas restrict storage.
Verification
wt status # Should show "Not in a worktree" when in main repo
wt ls # Empty list for fresh projects
REAL Code Examples from the Repository
Let's examine actual patterns from the agent-worktree documentation, with detailed explanations of the mechanics at work.
Example 1: Basic Worktree Creation and Lifecycle
# Create a worktree from current branch (random name generated if omitted)
wt new feature-x
# ... develop inside the worktree, make commits ...
# Merge back to the base branch you were on when creating
wt merge # Preserves worktree for further work
# Or merge and immediately clean up
wt merge -d # Deletes worktree after successful merge
What's happening under the hood? wt new feature-x invokes git worktree add with agent-worktree's metadata tracking. It creates {branch_name}.toml metadata and a linked working directory under ~/.agent-worktree/workspaces/{project}/. The base branch is recorded at creation time, making wt merge context-aware. The -d flag triggers post-merge cleanup—no manual git worktree remove needed.
Example 2: Snap Mode for AI Agent Execution
# Snap mode with random branch name—perfect for one-off agent tasks
wt new -s claude
# Snap mode with explicit branch naming
wt new fix-bug -s codex
# Snap mode with agent arguments (note the quoting!)
wt new -s "claude --dangerously-skip-permissions"
Critical implementation detail: The -s flag takes a single token. Without quotes, your shell splits claude --dangerously-skip-permissions into separate arguments, handing --dangerously-skip-permissions to wt new instead of the agent. The quotes ensure proper argument passing.
The snap mode lifecycle executes as follows:
Create worktree → Enter directory → Execute agent command → Agent exits
↓
State evaluation:
No changes? → Automatic cleanup
Only commits? → Prompt: [m] Merge or [q] Exit
Uncommitted work? → Prompt: [r] Reopen agent or [q] Exit manually
Safety guard: Nested snap is explicitly refused. Running wt new -s from inside an existing worktree exits with error—you must wt cd back to the main repository first. This prevents the confusion of agent-spawning-agents with tangled working directory chains.
Example 3: Configuration-Driven Automation
Global configuration (~/.agent-worktree/config.toml):
[general]
merge_strategy = "squash" # Default: squash merges for clean history
sync_strategy = "rebase" # Default: rebase for linear history
# Files to copy into every new worktree (gitignore-style patterns)
copy_files = [".env", ".env.*"]
[hooks]
# Runs in the new worktree immediately after creation
post_create = ["pnpm install"]
# Runs at worktree root before merge; merge blocked on failure
pre_merge = ["pnpm test", "pnpm lint"]
# Runs after successful merge
post_merge = []
Project-specific override (.agent-worktree.toml in repository root):
[general]
trunk = "main" # This project uses 'main', not auto-detect
merge_strategy = "merge" # Override: full merge commits, not squash
sync_strategy = "merge" # Override: merge instead of rebase
copy_files = ["*.secret.*"] # Appended to global copy_files list
[hooks]
# Replaces global post_create hooks entirely for this project
post_create = ["pnpm install"]
Security note on hooks: These execute via sh -c (or cmd /C on Windows) with no sandboxing or timeout. The documentation explicitly warns: treat .agent-worktree.toml like any committed shell script. Only execute hooks from repositories you'd directly run with bash. This is a trust boundary, not a vulnerability—agent-worktree correctly delegates security to your existing repository trust model.
Example 4: Workflow Navigation and Inspection
# List all worktrees with base branch context
wt ls
# Show full filesystem paths for each worktree
wt ls -l
# Switch to another worktree's directory
wt cd feature-y
# Return to main repository root
wt cd
# Check current context and any in-progress operations
wt status
The wt status command is particularly valuable—it reports not just your current worktree, but in-progress wt sync operations with recovery hints. If a rebase or merge sync was interrupted, wt status tells you exactly how to --continue or --abort.
Example 5: Cleanup and Maintenance
# Preview what would be cleaned (dry run)
wt clean --dry-run
# Remove worktrees with no diff from their base branch
# Dirty worktrees are always skipped for safety
wt clean
# Force remove a worktree even with uncommitted changes
wt rm -f emergency-fix
The wt clean logic is defensively designed: it falls back to trunk when base branch detection fails, and never destroys work with uncommitted changes. This prevents the catastrophic data loss that makes developers fear automated cleanup tools.
Advanced Usage & Best Practices
Optimize Agent Concurrency with Naming Conventions
Establish branch prefixes that signal intent: agent/claude/, agent/codex/, agent/experiment/. Combined with wt ls, this creates instant visual scanning of which agents own which worktrees. Use wt mv to rename worktrees when experiments evolve beyond their original purpose.
Leverage Hook Dependencies for Hermetic Builds
Structure post_create hooks to fail fast: dependency installation first, then validation that the environment matches expected state. This catches "works on my machine" issues at worktree creation, not during critical merge operations.
Master the Sync Conflict Recovery Flow
wt sync # Start rebase from base branch
# ... conflicts occur ...
# Edit files, stage resolutions
git add .
wt sync --continue # Resume the sync operation
# Or abandon entirely
wt sync --abort
The wt sync --continue and --abort flags mirror Git's rebase/merge semantics but with agent-worktree's metadata awareness. This is essential for long-running agent work that may need base branch updates mid-development.
Configure copy_files Defensively
The copy_files patterns support full gitignore syntax, but with enforced repository containment. Use this for .env.local, tool configurations, or IDE settings that agents need but shouldn't commit. Never include absolute paths or parent directory traversal—agent-worktree rejects these at parse time.
Comparison with Alternatives
| Approach | Isolation Level | Setup Time | Cleanup | Parallel Agents | Agent Integration |
|---|---|---|---|---|---|
| agent-worktree | Full (linked worktrees) | <1 second | Automatic | Native | Purpose-built |
Manual git worktree |
Full | ~30 seconds | Manual | Possible | None |
git clone --shared |
Full | 10-60 seconds | Manual | Possible | None |
| Docker containers | Complete OS isolation | 30-300 seconds | Container lifecycle | Complex networking | Requires volume mounts |
Branch switching (git checkout) |
None (shared working tree) | Instant | N/A | Impossible | None |
| Stash + branch | None (sequential only) | Instant | Manual stash management | Impossible | None |
Why agent-worktree wins: Manual worktree management requires remembering base branches, cleanup procedures, and merge targets—cognitive overhead that explodes with agent count. Docker introduces unacceptable latency for rapid iteration and complicates file system interactions. Branch switching or stashing fundamentally cannot support parallel execution. agent-worktree is the only solution that combines native Git performance with agent-aware automation.
FAQ
Does agent-worktree work with monorepos?
Absolutely. Since worktrees are complete linked copies of the repository, monorepo structure is preserved. Use copy_files to propagate root-level configuration files into worktrees, and configure hooks to run appropriate package manager commands for your workspace.
Can I use agent-worktree without AI agents?
Yes—though it's optimized for agent workflows, any scenario needing ephemeral, isolated Git environments benefits. Manual experimentation, code review environments, and parallel feature development all work seamlessly.
What happens if my agent crashes mid-execution?
Snap mode handles this gracefully. On any agent exit—including crashes and SIGINT (Ctrl+C)—agent-worktree evaluates the worktree state and presents appropriate next actions. Uncommitted work is preserved; you're prompted to reopen the agent or handle manually.
Is Windows fully supported?
Yes, with one documented limitation: wt update requires closing all wt processes first due to Windows file locking behavior. All core functionality—worktree management, snap mode, shell integration—works identically across platforms.
How does agent-worktree handle large repositories?
Performance is essentially identical to native Git worktrees since agent-worktree is a thin orchestration layer. Linked worktrees share the object database, so there's no duplication of Git history. The only disk overhead is working tree files, which you'd have regardless of approach.
Can I customize merge strategies per-worktree?
Global defaults are configured in ~/.agent-worktree/config.toml, with project-level overrides in .agent-worktree.toml. For one-off exceptions, wt merge -s <strategy> and wt merge --into <branch> provide explicit control at invocation time.
What shells are supported for integration?
bash, zsh, fish, and PowerShell are auto-detected and supported. Manual installation for specific shells is available via wt setup --shell <name>.
Conclusion
AI coding agents aren't going away—they're becoming foundational to how software gets built. But unleashing autonomous code generators into your production repository without isolation is like giving a toddler a marker in a white room. The chaos is predictable, expensive, and entirely preventable.
agent-worktree represents the mature, production-ready approach to this challenge. It doesn't fight Git's architecture—it elevates it, adding the workflow intelligence that native worktrees lack and the performance that container-based solutions can't match. The snap mode lifecycle, automatic cleanup, and configurable automation transform agent execution from a manual, error-prone process into a reliable, repeatable system.
If you're running AI agents against real codebases, you need this tool. Not eventually—now. Every un-isolated agent run is technical debt accumulating in your repository's foundation.
Install agent-worktree today, configure your first project with wt init, and experience what parallel, isolated AI development actually feels like. Your future self—reviewing clean merge histories on Monday morning—will thank you.
The repository is at github.com/nekocode/agent-worktree. Star it, install it, and stop letting AI agents wreck your Git history.
Comments (0)
No comments yet. Be the first to share your thoughts!