All Articles Claude Code

Creating Experimentation Worktrees Without Polluting Main

You have an idea. It's bold. It might be brilliant, or it might be a dead end. The problem?

You have an idea. It’s bold. It might be brilliant, or it might be a dead end. The problem? If you try it on your main branch, you might leave a trail of messy commits, broken tests, and reverted changes. Your git history becomes a graveyard of half-baked experiments.

But what if you could sandbox your experiments? Work in complete isolation, try crazy ideas, and decide later whether to bring them back or throw them away?

That’s what experimentation worktrees do. They’re your playground. Your main branch stays pristine. You stay sane.

The Problem: Why Experiments Pollute Main

Let’s be honest. When you’re experimenting, your workflow looks like this: try approach A, realize it doesn’t work, revert, try approach B, add a console.log to debug, remove it, push to main (oops), revert, fix unrelated bug, commit to main anyway.

Your main branch is now littered with “revert commit X” and “fix: removed debug code.” Your team sees this noise when they review history. New developers are confused about what the “real” changes are.

The traditional solution is to use feature branches, but they have problems too: you still feel pressure to keep your local main clean, switching branches means IDE confusion, and you can’t easily run two experimental approaches in parallel.

The deeper issue is psychological. When you’re on a feature branch, you know it’ll eventually be code-reviewed and merged into main. This creates subtle pressure to keep things tidy. Even if you’re exploring, you’re exploring with training wheels. You don’t fully commit to the wild ideas because part of you is already thinking about the eventual PR.

Real experimentation needs a different mindset. You need to be willing to completely redesign a system, try an approach that might sound crazy, leave debug code around for days, refactor the same function five times. You need a space where “messy” is not just acceptable—it’s expected.

Experimentation worktrees solve this perfectly. You create a disposable worktree, make a mess, and decide what to keep later. Your mind is free to explore because you know this isn’t going to main unless you deliberately decide it should.

Another problem with traditional workflows: they serialize your experiments. You’re on branch A, working. You need to compare with branch B. You switch branches. Your IDE reloads files. Cached build artifacts become invalid. If you had node_modules installed per-branch, they get swapped out. You lose your flow. Compare that to worktrees: you have three terminal windows, each with its own directory, each with its own node_modules, build system, LSP instance. No interference. You can work on three approaches genuinely simultaneously, testing each in parallel, comparing results side-by-side.

The Risk of Experiments Polluting Shared Context

In traditional development, the pressure to keep branches clean creates a subtle problem. Developers working on features avoid large-scale refactors because they’ll “complicate the PR.” They avoid trying radically different approaches because they might “mess up the history.” They avoid experimenting with speculative ideas because “we already agreed on the approach.”

This pressure toward premature commitment closes off the space for creative problem-solving. Organizations that enforce strict commit message conventions and code review standards end up with clean git histories but mediocre solutions. They’re not exploring alternatives; they’re optimizing the first idea they had.

Worktrees solve this by separating the space of creativity from the space of production. Your experimental branch can have terrible commit messages, messy code, reverted changes, debug logging left everywhere. None of that matters because it’s not in main. When you’re happy with the results, you can clean it up for the merge. But during exploration, you’re freed from the pressure to keep things tidy.

This psychological difference is profound. Teams with worktrees explore more. They try ideas that seem risky. They refactor aggressively. They discover better solutions because they’re not constrained by the pressure to maintain clean history during experimentation.

Creating Your First Experimentation Worktree

Let’s say you want to explore a new approach to error handling. First, make sure your main branch is clean. Now create an experimentation worktree:

git worktree add ../myproject-exp-error-handling -b exp/error-handling-prototype

This creates a new isolated directory with a fresh branch. Your main is untouched back in your original location. The worktree is a sibling directory to your main project. When you list directories, you’ll see:

myproject/                    (your main, original directory)
myproject-exp-error-handling/ (your experiment, new directory)

Each has its own git index, own working directory, own npm/bundler artifacts. They’re completely independent. If you break something in the experiment, main doesn’t even know. If you change a dependency in the experiment, your main’s node_modules is unaffected.

The exp/ prefix on the branch name is a convention. It signals to anyone reading your branches: “this is an experiment, temporary, not for production.” You could also use experiment/, scratch/, or whatever convention makes sense to your team. The important part is consistency—when you see that prefix, you know it’s disposable.

The worktree exists as long as you want it. Minutes, hours, days, weeks. You can leave it sitting around for months if you’re working on a long-term exploration. Or you can create and destroy them rapidly while trying different approaches.

Understanding What Happens at the Git Level

When you create a worktree, git creates a new branch and a new working directory. Internally, git links them together so it knows they’re part of the same repository. This is cleaner than the old worktree approach (using git branch to create separate clones). Modern git worktrees are fully integrated.

Working in Your Experiment

Now you’re free to experiment wildly. Make changes, break things, try three different approaches. Commit as you go. Don’t worry about commit messages or history. This is temporary.

Here’s the mental freedom this creates: You can refactor a function five times in five different commits, and none of it matters. You can add debug logging everywhere. You can change configuration files, add temporary dependencies, modify database schemas. No one is watching. No one will judge your commit history. You’re exploring.

The commits are for your own tracking. “Approach 1: error handling at the adapter layer” (commit 1). “Approach 2: error handling at the controller layer” (commit 2). “Comparing both approaches” (commit 3). These aren’t production commits—they’re exploration breadcrumbs. Later, when you’ve decided what works, you can clean them up into a coherent story.

You now have a branch with multiple commits of pure experimentation. Your main branch has none of this noise. It stays clean. It stays deployable. It stays ready for your team to work on.

Running Tests and Validating Experiments

Before you decide to keep or discard your experiment, validate it. Run your full test suite. If tests fail, debug and iterate within the worktree. No risk—your main branch doesn’t even know any of this happened.

cd ../myproject-exp-error-handling
npm test
npm run build
npm start &
# Now test in browser

You can also run your application and manually test. In your browser, try workflows that your changes affect. All of this in your isolated worktree. If something breaks catastrophically, you delete the worktree and start fresh. No damage to main.

This is where the real experimentation happens. You have an idea, you implement it, you test it. Quick feedback loops. You try approach A, see it doesn’t perform well, revert those commits, try approach B. All in the same worktree. All without touching main.

Comparing Experimental Results

Let’s say you want to compare your experimental approach with the current approach in main. Use git diff main..HEAD to show all changes. You can now decide: is the experiment clearly better? Is it experimental but promising? Is it a dead end?

# See all changes in your experiment
git diff main..HEAD

# Or compare specific files
git diff main -- src/error-handler.ts

# See commit history in your experiment
git log main..HEAD --oneline

The beauty: you’re deciding based on code quality, performance, and maintainability. That’s what matters. You have evidence. You ran the tests. You tested manually. You can see the exact code changes. Then you make a decision from a position of knowledge, not guessing.

Keeping or Discarding Your Experiment

If your experiment is solid and you want to bring it into main, you have options. You can merge the entire branch, keeping all the experimental commits in the history. Or you can squash all commits into one clean commit that says “Implement new error handling approach.” Or you can cherry-pick specific commits that represent the cleanest ideas.

# Option 1: Merge as-is
git checkout main
git merge exp/error-handling-prototype

# Option 2: Squash to one commit
git merge --squash exp/error-handling-prototype
git commit -m "Implement new error handling approach"

# Option 3: Rebase and clean up commits
git checkout exp/error-handling-prototype
git rebase -i main  # Interactive rebase to clean up commits
git checkout main
git merge exp/error-handling-prototype

After merging, clean up the worktree:

# Remove the worktree
git worktree remove ../myproject-exp-error-handling

# Delete the branch
git branch -d exp/error-handling-prototype

Your main branch now has the experimental code, merged cleanly. Future developers reading the history see a coherent feature, not all the exploratory messiness.

Maybe the experiment is good but not ready for main yet. Just leave the worktree in place. Later, when you’re ready, pick up where you left off. You can continue working in that worktree, making more commits, testing more thoroughly. Worktrees have no expiration date.

Sometimes it happens: the idea didn’t work out. Delete the worktree:

git worktree remove ../myproject-exp-error-handling
git branch -d exp/error-handling-prototype

The branch still exists in git (actually, with the -d flag, we deleted it). The working directory is gone. You’re not carrying around experimental code you don’t need. The exploration taught you something, and that knowledge remains. The code? Gone. And that’s fine.

Managing Multiple Experiments

You might want to explore multiple approaches simultaneously. Each one gets its own worktree:

# Experiment 1: Error handling approach A
git worktree add ../exp-error-a -b exp/error-handling-approach-a

# Experiment 2: Error handling approach B
git worktree add ../exp-error-b -b exp/error-handling-approach-b

# Experiment 3: Error handling approach C
git worktree add ../exp-error-c -b exp/error-handling-approach-c

Now you have three parallel experiments:

project/        (main, clean)
exp-error-a/    (approach A, testing)
exp-error-b/    (approach B, testing)
exp-error-c/    (approach C, testing)

You can work in three terminal windows. In one, you’re implementing approach A. In another, you’re running tests on approach B. In the third, you’re benchmarking approach C. When all three are ready, you compare them side-by-side and decide which is best.

This is impossible with feature branches. You’d switch between branches constantly. With worktrees, everything runs simultaneously. No context switching. No friction.

The comparison at the end is what makes this powerful:

  • Approach A: 15% performance improvement, requires refactoring three modules
  • Approach B: 8% improvement, simpler implementation, easier to maintain
  • Approach C: 25% improvement, requires complete redesign, high risk

You can see the tradeoffs clearly. Then you can make an informed decision. Maybe approach B is the winner because the tradeoff between simplicity and performance is worth it. Maybe C is worth the risk. Or maybe none of them are worth merging, and the learning itself is the value.

Recording Experiment Outcomes and Building Knowledge

Before you delete a failed experiment, document what you learned. Create an EXPERIMENTS.md file in your project and add notes about what you tried, what happened, and what you learned.

# Experiments Log

## Error Handling Refactor (2024-Q1)

### Approach A: Adapter-layer error handling

- Branch: exp/error-handling-approach-a
- Status: REJECTED
- Performance: 15% improvement
- Reason: Required refactoring three modules, high risk for edge cases
- Learning: Adapter layer interception is too coarse-grained

### Approach B: Middleware-based error handling

- Branch: exp/error-handling-approach-b
- Status: MERGED
- Performance: 8% improvement
- Reason: Simpler implementation, lower maintenance burden
- Learning: Middleware layer is the right abstraction for cross-cutting concerns

### Approach C: Complete redesign

- Branch: exp/error-handling-approach-c
- Status: ARCHIVED
- Performance: 25% improvement
- Reason: Redesign too large in scope, not worth current disruption
- Learning: Possible future optimization, revisit when doing major refactor

This becomes tribal knowledge. Future developers (including future you) know what’s been tried and why. They don’t repeat failed experiments. They understand the architectural constraints because they see why past approaches didn’t work.

The deepest benefit of this approach—and of worktrees themselves—isn’t technical. It’s cultural. When your tool makes experimentation frictionless, people experiment more. Instead of carefully planning a big refactor, they try three approaches and pick the best. Instead of debating optimizations, they implement both and measure. Instead of arguing about architecture, they prototype different approaches.

This is how better decisions get made. Not through debate, but through evidence. Worktrees are the tool that makes gathering evidence low-cost. And when evidence is cheap to gather, teams gravitate toward evidence-based decision making.

Over time, this creates a culture of pragmatism. Less “this is the best way because I said so,” more “let’s see which actually works.” Less design by committee, more design by experimentation. Better outcomes.

Practical Workflow: Claude Code + Experimentation Worktrees

Here’s how you might use this with Claude Code: “I want to explore three different approaches to caching. Create three worktrees, implement each approach, run benchmarks, and let me know which is fastest.”

Claude can:

  1. Create three worktrees with different branches
  2. Implement approach A, B, C in each
  3. Run benchmarks in each worktree
  4. Report back with results
  5. Clean up the two losing approaches
  6. Merge the winner into main

All while your main branch stays pristine.

Why Traditional Branching Isn’t Enough

You might be thinking: “Isn’t this just feature branches? What’s different?” Good question. Feature branches are fine for short-lived, focused work. But they have real limitations for experimental work.

When you’re on a feature branch, you still have the psychological pressure to keep it “production-ready.” You’re aware that eventually this will be reviewed and merged, so you subconsciously write cleaner code and better commit messages. That’s actually a limitation when you’re exploring wildly different approaches. You want the freedom to try something weird, break it, revert parts, try again.

Feature branches also create IDE and tooling friction. You switch branches and suddenly your IDE has old type definitions cached, your build artifacts are stale, your LSP is confused. Worktrees avoid this entirely—they’re separate directories with their own node_modules, build artifacts, LSP instances, everything.

Most importantly, worktrees let you work on multiple experiments simultaneously. You have three terminal windows open, one for each worktree, testing three approaches in parallel. With feature branches, you keep switching back and forth, killing your flow.

The Mental Model of Experimentation

Worktrees work because they match how creative people actually think. You have a main branch (the stable baseline), and you have sandboxes (safe places to mess around). When you’re in a sandbox, you don’t have to worry about the baseline. You can make ridiculous changes without impacting anything else.

This is why it’s so powerful for complex experiments. Let’s say you’re rearchitecting a major system. This isn’t a two-hour task. It might take days of exploration. With worktrees, you can:

  1. Create a worktree: git worktree add ../project-exp-v2-arch -b exp/v2-architecture
  2. Spend a full day exploring the new architecture
  3. Run tests, manual testing, benchmarks
  4. Compare carefully with main
  5. If it’s looking good, work on the next phase in the same worktree
  6. Eventually either merge it (as one big clean commit or a series of logical commits) or discard it

Meanwhile, your main branch receives regular updates from your team. Your experiment stays on its own timeline.

Conflict Resolution in Experiments

What happens when your team modifies files you also modified in your experiment? Git handles this gracefully. You can rebase your experiment branch onto main frequently to stay relatively up-to-date, resolving conflicts as you go. Or you can leave it isolated until you’re ready to merge, then do a big rebase-and-merge.

The key advantage over feature branches: you’re not blocking other people’s work. Your experiment doesn’t delay anyone’s merge to main. Your team can ship features while you’re exploring.

Automating Experiment Management

As you get more comfortable with worktrees, you might build tooling around them. A simple script could create a new experimentation worktree with the right naming convention and branch name. Another script could list all active experiments and their branch age. Dangerous but powerful: a script that cleans up experiments older than 30 days.

Claude Code can help automate this. You could have a /start-experiment command that creates a worktree with proper scaffolding. When you’re done, /finish-experiment either merges or cleans up.

Multi-Person Experimentation

Worktrees aren’t just for solo exploration. Your entire team can run parallel experiments. One person exploring a new framework, another refactoring the database layer, another experimenting with a different authentication system. They’re not stepping on each other’s toes. They can compare results when done and decide together what to merge.

This is particularly powerful for architectural decisions. Instead of endless debates about “should we use approach A or B?”, you say “let’s implement both and see.” Two days later you have working prototypes to evaluate. The decision becomes obvious when you can see actual code, performance, and complexity.

The Cleanup Problem

One challenge: you’ll end up with old experiment worktrees taking up disk space. Remember that git worktree list shows all of them. Periodically, review and clean up experiments you’re done with.

# List all worktrees
git worktree list

# Remove a worktree and its branch
git worktree remove ../project-exp-failed-approach
git branch -D exp/failed-approach

Make this part of your regular maintenance. Once a month, audit your experiments.

Scaling Experiments Across Teams

In larger organizations, you might have a shared “experiments” branch where multiple teams contribute exploratory work. This becomes a proving ground for ideas before they reach production. An optional feature? Test it in an experiment branch. An architectural pattern someone invented? Validate it in parallel with production work.

Git worktrees scale to this. You might have:

  • A main branch (production-ready)
  • An experiments branch (active research)
  • Individual worktrees for specific team members exploring specific ideas

All running simultaneously, with clear merging paths. The team knows which code is stable, which is experimental, which is validated.

The real power emerges when multiple teams use this pattern simultaneously. Team A is exploring a new database optimization. Team B is prototyping a different authentication system. Team C is validating a microservices refactor. Each team has its own worktree. Each worktree is independent. There’s zero coordination overhead. Teams finish their explorations, decide independently whether the work is production-ready, and if so, merge into main. If not, the worktree stays archived as documentation of what was tried and why it didn’t work out. This is how organizations scale thoughtful experimentation without creating bureaucracy around decision-making.

The Organizational Psychology of Worktrees

There’s a psychological dimension to worktrees that deserves examination. When developers know they’re working in an isolated sandbox that won’t touch main, their behavior changes. They’re willing to try wilder ideas. They’re willing to refactor aggressively. They’re willing to experiment with architectures that might not work because the cost of failure is localized—it doesn’t pollute the codebase everyone else is building on.

This psychological safety is worth understanding. In a feature-branch workflow, developers subconsciously keep the branch “clean” and “production-ready,” even during exploration. They’re aware it will be code-reviewed and merged. This creates subtle pressure toward conservative decisions. But in a worktree, your experimentation doesn’t have to look good. It doesn’t have to follow conventions. It can be messy, chaotic, and iterative. This freedom leads to more creative problem-solving.

Organizations that embrace worktrees see a culture shift. From “we carefully plan changes” to “we try approaches and learn from them.” From “we debate the best design” to “we prototype both and compare.” This is the difference between design-by-analysis and design-by-experiment. Experiment-driven organizations move faster because they spend less time in theoretical debate and more time gathering concrete evidence.

The cost is real—you’re running multiple experimental codebases in parallel, using more disk space, potentially wasting developer time on approaches that don’t work out. But the benefit is profound: your best ideas aren’t the ones you thought of first. They’re the ones you discovered through exploring multiple paths.

The Philosophy: Embrace Exploration

The fundamental insight is this: experimentation should be cheap. If it’s expensive (takes a lot of setup, creates a lot of noise, blocks other work), people don’t do it. They stick with what they know. But if it’s cheap, people explore naturally. Worktrees make exploration cheap.

This leads to better code, better architecture, better decisions. You’re not guessing—you’re trying. You’re not debating—you’re comparing. You’re not committing to the first idea—you’re confident enough to test alternatives.

The teams that ship better products aren’t the ones that guess best. They’re the ones that experiment most efficiently. They try ideas quickly, gather evidence, decide based on reality. Worktrees are the tool that makes that possible.

When you make exploration costless, exploration becomes normal. And exploration drives innovation.


-iNet

Free Discovery Call

Start With a Conversation, Not a Commitment

Every engagement begins with a free 30-minute discovery call. We'll map what's slowing your business down and tell you exactly what we'd fix first – no pitch deck, no obligation.