> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/ComposioHQ/agent-orchestrator/llms.txt
> Use this file to discover all available pages before exploring further.

# Worktree Plugin

> Workspace plugin that uses git worktrees for efficient workspace isolation

# Worktree Plugin

The worktree plugin provides workspace isolation using git worktrees, enabling multiple parallel agent sessions to work on different branches without duplicating the entire repository.

## Overview

Git worktrees allow you to check out multiple branches from the same repository simultaneously. This plugin creates isolated workspaces for each agent session by leveraging worktrees, which share the git object database but have separate working directories.

<Note>
  Worktrees are ideal when you want fast workspace creation with minimal disk usage, as they share the git object database with the main repository.
</Note>

## Configuration

Configure the worktree plugin in your `agent-orchestrator.yaml`:

```yaml theme={null}
plugins:
  workspace:
    name: worktree
    config:
      worktreeDir: ~/my-worktrees  # Optional: defaults to ~/.worktrees
```

### Configuration Options

<ParamField path="worktreeDir" type="string" default="~/.worktrees">
  Base directory where worktrees will be created. Path supports `~` expansion for home directory.

  Worktrees are organized as: `{worktreeDir}/{projectId}/{sessionId}/`
</ParamField>

## How It Works

1. **Create Workspace**: Creates a new git worktree from the specified branch
2. **Fetch Latest**: Fetches the latest changes from `origin` before creating the worktree
3. **Branch Creation**: Creates a new feature branch based on the project's default branch
4. **Symlink Support**: Can symlink shared resources (e.g., `node_modules`, `.env`) from the main repository
5. **Post-Create Hooks**: Runs custom setup commands after workspace creation

## Usage Example

```yaml theme={null}
projects:
  - id: my-app
    path: ~/repos/my-app
    repo: owner/my-app
    defaultBranch: main
    symlinks:
      - node_modules  # Share node_modules to save disk space
      - .env.local    # Share environment config
    postCreate:
      - pnpm install  # Install dependencies after worktree creation
```

## Requirements

<Warning>
  The worktree plugin requires:

  * Git 2.5 or later (for worktree support)
  * A git repository with a remote named `origin`
  * Write access to the worktree base directory
</Warning>

### Path Segment Safety

Project IDs and session IDs must contain only safe characters: `a-z`, `A-Z`, `0-9`, `_`, `-`

This prevents directory traversal attacks and ensures filesystem compatibility.

## Features

### Workspace Lifecycle

**Create**

* Fetches latest from remote (fails silently if offline)
* Creates worktree with new branch from `origin/{defaultBranch}`
* Handles branch name conflicts gracefully
* Creates symlinks for shared resources
* Runs post-create hooks

**Destroy**

* Removes worktree using `git worktree remove --force`
* Falls back to manual directory deletion if git command fails
* Does NOT delete branches (prevents accidental deletion of pre-existing branches)

**List**

* Lists all worktrees for a project using `git worktree list --porcelain`
* Returns workspace info including path, branch, session ID

**Exists**

* Checks if workspace path exists and is a valid git working tree
* Uses `git rev-parse --is-inside-work-tree`

**Restore**

* Recreates a workspace after it was destroyed or corrupted
* Prunes stale worktree entries
* Fetches latest from remote
* Creates worktree on existing or new branch

### Symlink Support

<Info>
  Symlinks allow sharing large directories like `node_modules` or `vendor` across worktrees, saving disk space and installation time.
</Info>

Symlinks are created from the main repository to the worktree. They must be relative paths without `..` segments for security.

```yaml theme={null}
projects:
  - id: my-app
    path: ~/repos/my-app
    symlinks:
      - node_modules      # Share dependencies
      - .next/cache       # Share Next.js cache
      - vendor            # Share PHP vendor directory
```

### Post-Create Hooks

Run custom commands after workspace creation:

```yaml theme={null}
projects:
  - id: my-app
    path: ~/repos/my-app
    postCreate:
      - pnpm install
      - pnpm build
      - cp .env.example .env
```

<Warning>
  Post-create commands run with full shell privileges. Only use commands from trusted configuration.
</Warning>

## Troubleshooting

<Accordion title="Error: Branch already exists">
  The plugin handles this automatically by creating the worktree and checking out the existing branch.

  If checkout fails, it removes the orphaned worktree and throws an error.
</Accordion>

<Accordion title="Error: Invalid projectId or sessionId">
  Project IDs and session IDs must match the pattern: `/^[a-zA-Z0-9_-]+$/`

  Use only letters, numbers, hyphens, and underscores.
</Accordion>

<Accordion title="Symlink targets are missing">
  Symlinks are created from `{mainRepoPath}/{symlinkPath}` to `{worktreePath}/{symlinkPath}`.

  If the source doesn't exist, the symlink is skipped silently.
</Accordion>

<Accordion title="Worktree cleanup failed">
  If `git worktree remove` fails, the plugin falls back to `rmSync` to forcefully delete the directory.

  Stale worktree entries can be cleaned up with:

  ```bash theme={null}
  git worktree prune
  ```
</Accordion>

<Accordion title="Fetch fails (offline mode)">
  The plugin catches fetch errors and continues. Worktrees can be created offline using cached refs.

  If you need the latest changes, ensure network connectivity before creating workspaces.
</Accordion>

## Advanced Configuration

### Custom Worktree Directory Structure

Worktrees are organized by project and session:

```
~/.worktrees/
  my-app/
    session-123/  # Worktree for session-123
    session-456/  # Worktree for session-456
  another-app/
    session-789/
```

This structure allows multiple projects and multiple sessions per project.

### Comparison with Clone Plugin

| Feature | Worktree | Clone |
| - | - | - |
| Disk usage | Low (shared objects) | High (full copy) |
| Creation speed | Fast | Slower |
| Independence | Shared git database | Fully independent |
| Use case | Parallel branches | Isolated experiments |

## Security Considerations

<Warning>
  * Path segments are validated to prevent directory traversal
  * Symlinks are validated to ensure they stay within the workspace
  * Post-create commands run with shell privileges (trusted config only)
</Warning>

## Source Code

Source: `packages/plugins/workspace-worktree/src/index.ts`


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.