# How the Forge Sandbox Feature Creates Isolated Git Worktrees for Safe Experimentation

> Forge's sandbox feature isolates Git worktrees for safe experimentation. Effortlessly test code changes outside your main repository without risk. Discover risk-free development.

- Repository: [Forge Code/forgecode](https://github.com/antinomyhq/forgecode)
- Tags: internals
- Published: 2026-04-08

---

**The Forge sandbox feature creates dedicated Git worktrees outside the main repository directory, allowing developers to experiment with code changes in complete isolation without affecting the primary working tree.**

The **Forge sandbox feature** in the antinomyhq/forgecode repository provides a robust mechanism for safe code experimentation by leveraging Git worktrees. This implementation automatically manages isolated development environments through a simple CLI flag or programmatic API, ensuring that experimental changes remain completely separate from your main codebase. The core logic resides in [`crates/forge_main/src/sandbox.rs`](https://github.com/antinomyhq/forgecode/blob/main/crates/forge_main/src/sandbox.rs) and is invoked from the CLI entry point in [`crates/forge_main/src/main.rs`](https://github.com/antinomyhq/forgecode/blob/main/crates/forge_main/src/main.rs).

## How Forge Creates Isolated Git Worktrees

The sandbox implementation follows a six-step process to establish isolated environments while maintaining Git integrity.

### Validating Repository Context

Before creating any worktree, Forge confirms it is operating within a valid Git repository. The system executes `git rev-parse --is-inside-work-tree` and aborts immediately if the check fails. This validation occurs in [`crates/forge_main/src/sandbox.rs`](https://github.com/antinomyhq/forgecode/blob/main/crates/forge_main/src/sandbox.rs) at lines 21-31, ensuring that all subsequent Git operations target a legitimate repository structure.

### Determining Worktree Placement策略

Once validated, Forge determines the repository root using `git rev-parse --show-toplevel`, returning the absolute path of the top-level directory (lines 33-46). The implementation places the new worktree as a sibling directory to the repository root rather than nesting it inside. This placement strategy uses the parent folder of the repo root, with the user-supplied sandbox name (e.g., `my-sandbox`) becoming a standalone directory adjacent to the main project (lines 50-57).

### Branch Detection and Creation

The system intelligently handles branch management when creating worktrees. First, it checks whether a branch with the sandbox name already exists using `git rev-parse --verify refs/heads/<name>` (lines 89-96). 

If the branch does **not** exist, Forge executes `git worktree add -b <name> <path>` to create a new branch from the current `HEAD`. If the branch **does** exist, it uses `git worktree add <path> <name>` to check out the existing branch into the new directory (lines 97-116). This dual-path approach ensures developers can resume work on existing experimental branches or start fresh from the current state.

### Reusing Existing Sandbox Directories

Forge optimizes for repeat usage by detecting existing worktrees. If the target directory already exists and contains a `.git` file pointing to a valid worktree, the function reuses the existing environment and returns its canonical path (lines 58-81). This prevents redundant creation overhead and preserves previous experimental state. The final canonical path is returned to the caller as a `PathBuf` (lines 124-138).

## Why Isolated Git Worktrees Enable Safe Experimentation

The **Forge sandbox feature** delivers five critical benefits for experimental development:

- **Isolation**: Each sandbox maintains its own checkout and `HEAD`. Commits, rebases, or resets inside the sandbox never affect the primary working tree, preventing accidental contamination of stable code.
- **Speed**: Because `git worktree` shares the same object database as the main repository, creation is instantaneous and disk-space usage remains minimal compared to full repository clones.
- **Safety**: Developers can execute risky refactorings, run destructive scripts, or test experimental branches without risking the main repo or triggering accidental pushes to production branches.
- **Convenient CLI**: The `--sandbox <name>` flag automates all setup steps, enabling single-command initialization of experimental environments.
- **Reusability**: Existing sandbox directories are automatically detected and reused, eliminating setup overhead while preserving previous experimental context.

## Implementing the Sandbox in Your Workflow

You can leverage the Forge sandbox through both programmatic Rust APIs and command-line interfaces.

### Programmatic API Usage

Access the sandbox functionality directly in Rust applications:

```rust
use forge_main::Sandbox;

fn main() -> anyhow::Result<()> {
    // Create (or reuse) a sandbox named "experiment"
    let worktree_path = Sandbox::new("experiment").create()?;
    println!("Sandbox worktree at: {}", worktree_path.display());

    // You can now `cd` into `worktree_path` and run any git commands
    Ok(())
}

```

### Command-Line Initialization

Create isolated worktrees using the CLI flag:

```bash

# CLI usage – create an isolated worktree called "temp-run"

forge --sandbox temp-run

# Forge will print:

#   Worktree [Created]  /path/to/parent/temp-run

# The current directory for the session is now that worktree.

```

### Working Within the Isolated Environment

Once created, the sandbox functions as a completely independent Git repository:

```bash

# Run a command inside the sandbox without affecting the main repo

cd /path/to/parent/temp-run
git status          # Shows the sandbox's clean state

# … make experimental commits …

git log             # Only shows commits on the sandbox branch

```

## Summary

- The **Forge sandbox feature** creates isolated Git worktrees in sibling directories to the main repository, ensuring physical and logical separation.
- Implementation in [`crates/forge_main/src/sandbox.rs`](https://github.com/antinomyhq/forgecode/blob/main/crates/forge_main/src/sandbox.rs) handles repository validation, branch detection, and intelligent reuse of existing worktrees.
- Worktrees share the main repository's object database, providing instant creation with minimal disk overhead.
- The `--sandbox` CLI flag and `Sandbox` Rust API provide ergonomic interfaces for experimental development.
- Existing sandboxes are automatically detected and reused, preserving experimental state between sessions.

## Frequently Asked Questions

### What happens if I create a sandbox that already exists?

If the target directory already exists and contains a valid `.git` file pointing to a worktree, Forge automatically reuses the existing environment according to the logic in [`crates/forge_main/src/sandbox.rs`](https://github.com/antinomyhq/forgecode/blob/main/crates/forge_main/src/sandbox.rs) (lines 58-81). The function returns the canonical path to the existing worktree without attempting recreation, preserving any previous experimental changes.

### Does using the Forge sandbox feature consume additional disk space?

No, sandbox worktrees share the same Git object database as the main repository. Only the working tree files and branch metadata require additional space, making sandboxes significantly more storage-efficient than full repository clones while providing complete isolation for experimentation.

### Can I push changes from a sandbox back to the main repository?

Yes, because the sandbox is a legitimate Git worktree connected to the same remote. You can commit changes within the sandbox and push them to remote branches. However, the sandbox's isolated nature ensures these operations do not interfere with the main working tree's state until you explicitly choose to integrate changes.

### How does the sandbox feature handle non-Git directories?

Forge validates the repository context before proceeding. If you attempt to create a sandbox outside a Git repository, the system executes `git rev-parse --is-inside-work-tree` and aborts with an error (sandbox.rs lines 21-31). This ensures the sandbox feature only operates within valid Git repositories.