> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_10_snapshot_and_file_system/10.4_worktree_management.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 10.4 Worktree Management

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Date Generated**: 2026-02-17

***

In software development, you often need to handle multiple tasks simultaneously -- you might be developing a new feature when you suddenly need to switch to another branch to fix an urgent bug. The traditional approach is `git stash` or `git checkout`, but these operations interrupt your current workflow. Git Worktree provides a more elegant solution: creating multiple independent working directories within the same Git repository, each corresponding to a different branch, without interfering with one another.

OpenCode's Worktree module integrates this Git feature into the AI coding assistant, enabling multiple Agent instances to work in parallel on different branches of the same project -- for example, one Agent developing a new feature on the main branch while another Agent fixes a bug in a separate Worktree.

> **Extended Explanation: What Is Git Worktree?**
>
> Git Worktree is a feature introduced in Git 2.5. Normally, a Git repository has only one working directory (Working Tree), which is where you typically edit code. Git Worktree allows you to "split" multiple working directories from the same repository, each checking out a different branch.
>
> ```bash
> # Create a new worktree, checking out the feature-x branch
> git worktree add ../my-project-feature-x feature-x
>
> # Now ../my-project-feature-x/ is a completely independent working directory
> # Modifying files here does not affect the main working directory
> ```
>
> All Worktrees share the same `.git` database (objects, refs, etc.), so creating a Worktree consumes almost no additional disk space. However, each Worktree has its own independent staging area (index) and working directory, and can independently perform `add`, `commit`, `checkout`, and other operations.
>
> **Key limitation**: The same branch cannot be checked out by two Worktrees simultaneously.

## 10.4.1 Data Model

The Worktree module is defined in `worktree/index.ts`, using the TypeScript Namespace pattern. The core data structure is `Worktree.Info`:

```typescript
// worktree/index.ts
export const Info = z
  .object({
    name: z.string(),       // Worktree name, e.g. "brave-cabin"
    branch: z.string(),     // Git branch name, e.g. "opencode/brave-cabin"
    directory: z.string(),  // Absolute path to the Worktree
  })
  .meta({ ref: "Worktree" })
```

The three operations each have corresponding input types:

| Operation | Input Type    | Key Fields                                                         |
| --------- | ------------- | ------------------------------------------------------------------ |
| Create    | `CreateInput` | `name?` (optional name), `startCommand?` (optional startup script) |
| Remove    | `RemoveInput` | `directory` (path of the Worktree to remove)                       |
| Reset     | `ResetInput`  | `directory` (path of the Worktree to reset)                        |

The module also defines two events for notifying external consumers of Worktree lifecycle changes:

```typescript
export const Event = {
  Ready: BusEvent.define("worktree.ready", z.object({
    name: z.string(),
    branch: z.string(),
  })),
  Failed: BusEvent.define("worktree.failed", z.object({
    message: z.string(),
  })),
}
```

## 10.4.2 Worktree Creation Flow

Creating a Worktree is the most complex operation. The implementation of `Worktree.create()` can be divided into a **synchronous phase** and an **asynchronous phase** -- this is an important design decision.

### Synchronous Phase: Fast Return

```typescript
export const create = fn(CreateInput.optional(), async (input) => {
  // 1. Pre-check: only Git projects support Worktrees
  if (Instance.project.vcs !== "git") {
    throw new NotGitError({ message: "Worktrees are only supported for git projects" })
  }

  // 2. Determine the Worktree storage root directory
  const root = path.join(Global.Path.data, "worktree", Instance.project.id)
  // Typical path: ~/.local/share/opencode/worktree/<project-id>/
  await fs.mkdir(root, { recursive: true })

  // 3. Generate a unique name
  const base = input?.name ? slug(input.name) : ""
  const info = await candidate(root, base || undefined)

  // 4. Create the Git Worktree (without checking out files)
  const created = await $`git worktree add --no-checkout -b ${info.branch} ${info.directory}`
    .quiet().nothrow().cwd(Instance.worktree)

  if (created.exitCode !== 0) {
    throw new CreateFailedError({
      message: errorText(created) || "Failed to create git worktree"
    })
  }

  // 5. Register the new Worktree as a project Sandbox
  await Project.addSandbox(Instance.project.id, info.directory).catch(() => undefined)

  // 6. Asynchronous initialization (see below)
  setTimeout(() => { /* ... */ }, 0)

  // 7. Immediately return Worktree information
  return info
})
```

Note that step 4 uses the `--no-checkout` flag -- this means the Worktree directory is created empty after this step. The actual file checkout happens in the asynchronous phase. The benefit of this design is: **the create operation appears "instant" to the caller**, allowing the user to immediately obtain the Worktree metadata while the time-consuming file checkout and initialization proceed in the background.

### Name Generation Strategy

Worktree names are generated using an interesting "adjective-noun" combination approach:

```typescript
const ADJECTIVES = [
  "brave", "calm", "clever", "cosmic", "crisp", "curious",
  "eager", "gentle", "glowing", "happy", /* ... 30 total */
] as const

const NOUNS = [
  "cabin", "cactus", "canyon", "circuit", "comet", "eagle",
  "engine", "falcon", "forest", "garden", /* ... 32 total */
] as const

function randomName() {
  return `${pick(ADJECTIVES)}-${pick(NOUNS)}`
  // e.g.: "stellar-rocket", "curious-falcon", "gentle-meadow"
}
```

30 x 32 = 960 combinations, sufficient to avoid name collisions within a single project. The `candidate()` function also checks two conditions after generating a name:

1. **Directory does not exist**: Ensures it won't overwrite an existing Worktree.
2. **Branch does not exist**: Ensures the `opencode/<name>` branch name is available.

If either condition is not met, it retries up to 26 times. If the user provides a custom name, it first attempts to use that name, and only appends a random suffix upon failure:

```typescript
async function candidate(root: string, base?: string) {
  for (const attempt of Array.from({ length: 26 }, (_, i) => i)) {
    const name = base
      ? (attempt === 0 ? base : `${base}-${randomName()}`)
      : randomName()
    const branch = `opencode/${name}`
    const directory = path.join(root, name)

    if (await exists(directory)) continue

    const ref = `refs/heads/${branch}`
    const branchCheck = await $`git show-ref --verify --quiet ${ref}`
      .quiet().nothrow().cwd(Instance.worktree)
    if (branchCheck.exitCode === 0) continue

    return Info.parse({ name, branch, directory })
  }
  throw new NameGenerationFailedError({
    message: "Failed to generate a unique worktree name"
  })
}
```

### Asynchronous Phase: Background Initialization

After the create operation returns, a `setTimeout` callback begins executing the actual initialization work on the next tick of the event loop:

```typescript
setTimeout(() => {
  const start = async () => {
    // 1. Check out files
    const populated = await $`git reset --hard`
      .quiet().nothrow().cwd(info.directory)
    if (populated.exitCode !== 0) {
      // Emit failure event
      GlobalBus.emit("event", {
        directory: info.directory,
        payload: { type: Event.Failed.type, properties: { message } },
      })
      return
    }

    // 2. Bootstrap Instance context
    const booted = await Instance.provide({
      directory: info.directory,
      init: InstanceBootstrap,
      fn: () => undefined,
    }).then(() => true).catch(() => false)
    if (!booted) return

    // 3. Emit ready event
    GlobalBus.emit("event", {
      directory: info.directory,
      payload: {
        type: Event.Ready.type,
        properties: { name: info.name, branch: info.branch },
      },
    })

    // 4. Execute startup scripts
    await runStartScripts(info.directory, { projectID, extra })
  }
  void start().catch(/* ... */)
}, 0)
```

Initialization proceeds in four steps:

1. **`git reset --hard`**: Populates the empty directory created with `--no-checkout` into a complete working directory.
2. **`Instance.provide()`**: Initializes OpenCode's Instance context (configuration, storage, event bus, etc.) for the new Worktree directory, making it a workspace capable of independently running an Agent.
3. **Emit `Ready` event**: Notifies all listeners via `GlobalBus` that the Worktree is ready.
4. **Execute startup scripts**: First executes project-level `start` commands (e.g., `npm install`), then executes any additional startup commands provided by the user.

## 10.4.3 Worktree Removal

The removal operation needs to handle three scenarios: the Worktree exists normally, the Worktree has been deregistered from Git but the directory still exists, and the Worktree does not exist at all.

```typescript
export const remove = fn(RemoveInput, async (input) => {
  // 1. Normalize the path (resolve symlinks, unify case)
  const directory = await canonical(input.directory)

  // 2. Parse the `git worktree list --porcelain` output
  const list = await $`git worktree list --porcelain`
    .quiet().nothrow().cwd(Instance.worktree)
  // Output format:
  // worktree /path/to/worktree
  // branch refs/heads/opencode/brave-cabin
  //
  // worktree /path/to/another
  // branch refs/heads/opencode/clever-rocket

  // 3. Find the matching entry in the list
  const entry = /* ... match by canonical path ... */

  // 4. If not found in Git but directory exists, delete the directory directly
  if (!entry?.path) {
    const directoryExists = await exists(directory)
    if (directoryExists) {
      await fs.rm(directory, { recursive: true, force: true })
    }
    return true
  }

  // 5. Use Git command to formally remove the Worktree
  await $`git worktree remove --force ${entry.path}`
    .quiet().nothrow().cwd(Instance.worktree)

  // 6. Delete the associated branch
  const branch = entry.branch?.replace(/^refs\/heads\//, "")
  if (branch) {
    await $`git branch -D ${branch}`
      .quiet().nothrow().cwd(Instance.worktree)
  }

  return true
})
```

The `--force` flag ensures the Worktree can be deleted even if it contains uncommitted changes. Branch cleanup is necessary because the `-b` flag was used during creation to create a new branch, and these branches are no longer needed after the Worktree is removed.

### Path Normalization

Path comparison is a detail that's easy to get wrong in Worktree management. The `canonical()` function ensures path consistency:

```typescript
async function canonical(input: string) {
  const abs = path.resolve(input)              // Convert to absolute path
  const real = await fs.realpath(abs).catch(() => abs)  // Resolve symlinks
  const normalized = path.normalize(real)      // Normalize separators
  return process.platform === "win32"
    ? normalized.toLowerCase()                 // Windows paths are case-insensitive
    : normalized
}
```

This function handles three common path inconsistency issues: relative paths, symbolic links, and case differences on Windows.

## 10.4.4 Worktree Reset

The reset operation restores a Worktree to the latest state of the remote default branch -- essentially "tearing down and rebuilding this workspace." This is a complex multi-step process:

```typescript
export const reset = fn(ResetInput, async (input) => {
  // 1. Safety check: do not allow resetting the primary workspace
  const directory = await canonical(input.directory)
  const primary = await canonical(Instance.worktree)
  if (directory === primary) {
    throw new ResetFailedError({ message: "Cannot reset the primary workspace" })
  }

  // 2. Determine the reset target (remote default branch > main > master)
  const target = remoteBranch
    ? `${remote}/${remoteBranch}`  // Prefer remote HEAD
    : localBranch                  // Fall back to local main/master

  // 3. If there's a remote branch, fetch the latest code first
  if (remoteBranch) {
    await $`git fetch ${remote} ${remoteBranch}`.cwd(Instance.worktree)
  }

  // 4. Hard reset to the target
  await $`git reset --hard ${target}`.cwd(worktreePath)

  // 5. Deep cleanup
  const clean = await sweep(worktreePath)  // git clean -ffdx + fallback strategy

  // 6. Recursively reset submodules
  await $`git submodule update --init --recursive --force`.cwd(worktreePath)
  await $`git submodule foreach --recursive git reset --hard`.cwd(worktreePath)
  await $`git submodule foreach --recursive git clean -fdx`.cwd(worktreePath)

  // 7. Verify cleanup results
  const status = await $`git status --porcelain=v1`.cwd(worktreePath)
  const dirty = outputText(status.stdout)
  if (dirty) {
    throw new ResetFailedError({
      message: `Worktree reset left local changes:\n${dirty}`
    })
  }

  // 8. Re-execute startup scripts
  queueStartScripts(worktreePath, { projectID })
  return true
})
```

### Default Branch Detection

The logic for determining "which branch to reset to" uses an interesting multi-level fallback strategy:

```
1. Detect remote (prefer origin, then the sole remote, then upstream)
2. Read remote HEAD reference (git symbolic-ref refs/remotes/origin/HEAD)
3. If remote HEAD is unavailable, check if a local main branch exists
4. Fall back to the master branch
5. If none of the above are found, throw an error
```

This multi-level fallback ensures correct operation across various Git repository configurations.

### Deep Cleanup Strategy

The `sweep()` function handles edge cases where `git clean` might fail:

```typescript
async function sweep(root: string) {
  // First attempt at git clean
  const first = await $`git clean -ffdx`.quiet().nothrow().cwd(root)
  if (first.exitCode === 0) return first

  // Parse failure information to find files that couldn't be deleted
  const entries = failed(first)
  if (!entries.length) return first

  // Manually delete problematic files
  await prune(root, entries)

  // Second attempt
  return $`git clean -ffdx`.quiet().nothrow().cwd(root)
}
```

`git clean -ffdx` uses all "force" options (`-ff` for force delete, `-d` to include directories, `-x` to include gitignored files), but on some platforms (especially Windows) it may still fail due to file locks and other reasons. `sweep()` parses Git's error output, extracts the list of "failed to remove" files, manually deletes them via Node.js's `fs.rm()`, and retries.

## 10.4.5 Integration with the Instance System

Worktree is tightly integrated with the Instance system introduced in Chapter 3. Each Worktree is an independent Instance context:

```
Primary workspace (/path/to/project/)
├── Instance A (directory=/path/to/project/, worktree=/path/to/project/)
│   ├── Its own Session
│   ├── Its own Tool registry
│   └── Its own event bus
│
Worktree storage (~/.local/share/opencode/worktree/<project-id>/)
├── brave-cabin/
│   └── Instance B (directory=.../brave-cabin/, worktree=/path/to/project/)
│       ├── Independent Session
│       └── Independent Tool registry
└── clever-rocket/
    └── Instance C (directory=.../clever-rocket/, worktree=/path/to/project/)
        └── ...
```

Note the distinction between `directory` and `worktree`:

* **`directory`**: The Instance's working directory -- for a Worktree, this is the Worktree's own path.
* **`worktree`**: The Git repository's root working tree -- all Instances share the same value (the main project directory).

This distinction is important because Git operations (such as `git worktree add`) need to be executed in the main working tree, while file operations are performed in each Instance's respective `directory`.

## 10.4.6 HTTP API

Worktree operations are exposed as HTTP APIs through the Server's experimental routes:

```typescript
// server/routes/experimental.ts
app.post("/worktree", async (c) => {
  return c.json(await Worktree.create(await c.req.json()))
})

app.get("/worktree", async (c) => {
  return c.json(await Project.sandboxes())
})

app.delete("/worktree", async (c) => {
  return c.json(await Worktree.remove(await c.req.json()))
})

app.post("/worktree/reset", async (c) => {
  return c.json(await Worktree.reset(await c.req.json()))
})
```

These APIs enable Web UIs and IDE extensions to manage Worktrees as well, not just the CLI.

## 10.4.7 Error Handling System

The Worktree module defines six named error types, each corresponding to a specific failure scenario:

```typescript
export const NotGitError = NamedError.create("WorktreeNotGitError", ...)
export const NameGenerationFailedError = NamedError.create("WorktreeNameGenerationFailedError", ...)
export const CreateFailedError = NamedError.create("WorktreeCreateFailedError", ...)
export const StartCommandFailedError = NamedError.create("WorktreeStartCommandFailedError", ...)
export const RemoveFailedError = NamedError.create("WorktreeRemoveFailedError", ...)
export const ResetFailedError = NamedError.create("WorktreeResetFailedError", ...)
```

These errors are created using the `NamedError.create()` factory function, and each error carries a structured `message` field. At the Server layer, these errors are caught by middleware and converted into HTTP 400 responses with human-readable error messages.

## 10.4.8 Summary

The Worktree module demonstrates several design patterns worth learning:

1. **Asynchronous initialization**: `create()` immediately returns metadata, while the time-consuming initialization completes in the background. The event system (`Event.Ready` / `Event.Failed`) notifies the caller of the final result. This three-phase pattern of "fast response + background processing + event notification" is very common in interactive applications.
2. **Defensive path handling**: The `canonical()` function uniformly handles relative paths, symbolic links, and platform differences, avoiding match failures caused by inconsistent path formats.
3. **Progressive fault tolerance**: The `sweep()` function first tries the standard approach, then parses error information and takes remedial action upon failure, and finally retries. This "attempt -> diagnose -> fix -> retry" pattern is very practical when dealing with system-level operations.
4. **Multi-level fallback**: Default branch detection uses a fallback chain of `remote HEAD -> main -> master`, ensuring correct operation across various repository configurations.
5. **Human-friendly naming system**: Using adjective-noun combinations to generate human-readable names is much easier to remember and communicate than UUIDs or hashes.
