Sandboxing and Isolation
Git worktrees, containers, and other isolation patterns for safe agent execution
Overview
Permissions tell the agent what it can do. Hooks validate each action in context. But even with both layers in place, the question remains: what happens when something slips through? A well-crafted command might pass every check and still produce an unintended result. A valid edit might introduce a subtle bug that cascades through the codebase.
Sandboxing and isolation solve this by ensuring that the agent works in a contained environment where mistakes are cheap to reverse. Instead of trying to prevent every possible error, you make errors recoverable. This is the third pillar of agent safety: not stopping all mistakes, but limiting their blast radius.
The Isolation Spectrum
Isolation techniques range from lightweight to heavy, each offering a different trade-off between safety and overhead.
Isolation spectrum from lightweight to heavy: Lightweight (Git Worktree, Git Branch), Medium (Virtual Environment, Namespace Isolation), and Heavy (Docker Container, VM/Sandbox). Each level provides progressively more isolation.
For most development workflows, git worktrees provide the best balance of safety and convenience. Containers add stronger isolation for CI/CD and untrusted execution scenarios.
Git Worktrees: The Agent's Sandbox
A git worktree creates a separate working directory linked to the same repository. The agent works in this isolated copy while your main working directory remains untouched. If the agent's changes are good, you merge them. If not, you delete the worktree and move on.
Git worktree isolation: a Git Repository contains the Main Worktree (developer's working directory on the main branch) and an Agent Worktree (.claude/worktrees/feature-x on branch agent/feature-x), both sharing the same .git history. The developer works in the main worktree while the AI agent works in the agent worktree, with changes flowing through PR/review.
Why Worktrees Work Well for Agents
- Shared history: The worktree has access to the full git history, so the agent can reference commits, diffs, and branches
- Separate filesystem: Files modified in the worktree do not appear in your main working directory
- Branch isolation: The agent works on its own branch, so even if it commits, your branch is unaffected
- Cheap to create and destroy: Creating a worktree takes milliseconds and uses minimal disk space (git uses hard links)
- Standard git workflow: Merging from a worktree uses the same PR/review process as any other branch
Creating and Managing Worktrees
The Worktree Workflow
The standard agent-in-worktree workflow follows these steps:
- Create a worktree on a new branch
- Start the agent session pointing at the worktree directory
- Let the agent work autonomously within the isolated copy
- Review the agent's changes via
git diffor a pull request - Merge good changes, discard bad ones
- Remove the worktree
Container Isolation
For stronger isolation, especially in CI/CD environments, Docker containers provide a fully sandboxed execution environment. The agent runs inside a container with controlled access to the filesystem, network, and system resources.
Container isolation: the host machine contains a Docker container running the AI Agent with a mounted repository (read-write). The git repository on the host is volume-mounted into the container. Network access from the container is blocked.
Why Containers Add Safety
- Filesystem isolation: The agent can only access mounted directories, not the full host filesystem
- Network control: You can block or restrict network access, preventing the agent from reaching external services
- Process isolation: Processes inside the container cannot affect host processes
- Resource limits: CPU and memory caps prevent runaway processes
- Disposable: Destroy the container after each session -- no state leaks between runs
A Container Configuration for Agent Work
Key security features in this configuration:
network_mode: "none"prevents all network access -- no calling external APIs, no installing packages from the internetcap_drop: ALLremoves Linux capabilities, preventing privilege escalationread_only: truemakes the root filesystem immutable -- only the mounted workspace is writable- Resource limits prevent the agent from consuming all host resources
Combining Worktrees and Containers
The most robust isolation combines both approaches: the agent works in a git worktree (for branch isolation) mounted inside a Docker container (for system isolation).
Combined worktree and container isolation: the host machine has a main worktree for the developer. Inside a Docker container, a git worktree contains the AI agent working on project files on an isolated branch. Changes flow from the worktree through a git push to a Pull Request, which is reviewed before merging into the main worktree.
This double layer means:
- Git isolation: Changes are on a separate branch; your main branch is untouched
- System isolation: The agent cannot access host resources, network, or filesystem outside the mount
- Review gate: Changes flow through a pull request before reaching the main branch
The Review-Gate Pattern
Isolation is most effective when paired with a review gate -- a mandatory human review step between the agent's work and its integration into the main codebase.
Review-gate workflow: the agent works in isolation, commits to a branch, and a PR is created automatically. A human reviews the PR and either approves it (merge to main), requests changes (agent revises and recommits), or rejects it (branch deleted).
The review gate is what makes isolation practical for teams. The agent works with full autonomy inside its sandbox, maximizing speed and throughput. But no changes reach the main branch without a human looking at them.
Choosing Your Isolation Strategy
The right isolation strategy depends on your risk tolerance and workflow.
Worktree only -- best for trusted local development. The agent works on a separate branch in a worktree. Changes are reviewed via diff or PR. Good for teams that trust the agent but want an easy undo path.
Container only -- best for CI/CD pipelines and batch operations. The agent runs in a disposable container with controlled resources and no network. Changes are committed and pushed from within the container.
Worktree plus container -- best for high-security environments and untrusted tasks. Maximum isolation with a standard review workflow. Use this when the agent is working with sensitive code or when mistakes are expensive.
No isolation -- appropriate only when permissions and hooks are robust, the agent is in default (ask-first) mode, and the developer is actively watching the session. Even then, working on a feature branch is recommended.
Principle: The more autonomous the agent, the stronger the isolation should be. If you reduce human oversight, compensate with stronger containment.
Practical Considerations
Worktree Cleanup
Worktrees accumulate if not cleaned up. Add a script or hook to remove stale worktrees.
Container Performance
Running an agent inside a container adds overhead for file I/O due to volume mounting. Mitigate this by:
- Using named volumes instead of bind mounts on Linux
- Keeping the mounted workspace as small as possible (mount only the project, not the entire home directory)
- Using the
:delegatedmount flag on macOS for write-heavy workloads
Credential Management
When using containers, the agent may need credentials (for git, for package registries). Never bake credentials into images. Instead:
- Mount credentials as read-only files
- Use short-lived tokens that expire after the session
- Inject credentials via environment variables at runtime, not at build time
Summary
Sandboxing and isolation are the third pillar of agent safety, complementing permissions and hooks. Git worktrees provide lightweight branch isolation where the agent works on a separate copy of the codebase. Docker containers add system-level isolation by controlling filesystem, network, and process access. The most robust approach combines both: a worktree inside a container with a mandatory review gate before any changes reach the main branch. The core principle is the disposable environment -- make the agent's workspace cheap to create and destroy so that mistakes are always recoverable. In the final lesson of this module, we will bring all three pillars together into a complete safety framework configuration.