> 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_03_overall_architecture_design/3.3_multi-project_and_multi-worktree_support.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 3.3 Multi-Project and Multi-Worktree Support

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

***

## 3.3.1 Overview of the `project/` Module

One of OpenCode's design goals is to **allow a single Server instance to simultaneously serve multiple projects and different worktrees**. This requirement gave rise to the design of the `project/` module.

The `project/` module contains five files:

| File           | Responsibility                                                                               |
| -------------- | -------------------------------------------------------------------------------------------- |
| `instance.ts`  | Instance management -- creation, retrieval, and disposal of project instances                |
| `project.ts`   | Project information -- identifying a project's VCS type and structure                        |
| `state.ts`     | State management -- directory-isolated state storage                                         |
| `vcs.ts`       | Version control -- Git operation wrappers                                                    |
| `bootstrap.ts` | Initialization bootstrapping -- the startup flow when a project is opened for the first time |

## 3.3.2 The `Instance.state()` Pattern -- Implementing Instance-Level State Isolation

In Section 2.3.3, we introduced the `Instance.state()` pattern. Here we analyze it further from the multi-project perspective.

**Problem scenario**: Suppose a user uses the OpenCode Server to manage two projects simultaneously:

```
Project A: /home/user/project-a (Python project)
Project B: /home/user/project-b (TypeScript project)
```

The Session module, Tool module, Config module, and others each have their own state. If two projects shared the same state, confusion would ensue -- Project A's configuration might affect Project B.

**Solution**: `State.create()` implements state storage isolated by key (typically the project directory path):

```typescript
// Core logic of state.ts (simplified)
export namespace State {
  const stores = new Map<string, Map<string, any>>()

  export function create<S>(
    getKey: () => string,    // Typically () => Instance.directory
    init: () => S,           // Initialization function
    dispose?: (s: S) => Promise<void>
  ): () => S {
    const id = Symbol()      // Each state has a unique identifier
    return () => {
      const key = getKey()   // Get the current project directory
      let store = stores.get(key)
      if (!store) {
        store = new Map()
        stores.set(key, store)
      }
      if (!store.has(id)) {
        store.set(id, init()) // Lazy initialization
      }
      return store.get(id)
    }
  }
}
```

This way, when code runs in the context of Project A, `state()` returns Project A's state; when running in the context of Project B, it returns Project B's state. The two are completely isolated.

```
             +-- state() --> Project A's Bus subscription list
Instance A --+
             +-- state() --> Project A's Config

             +-- state() --> Project B's Bus subscription list
Instance B --+
             +-- state() --> Project B's Config
```

## 3.3.3 State Management in Multi-Project Concurrent Scenarios

**Instance lifecycle**:

```
create (first access)
    |
    v
provide (set context, execute business logic)
    |  Can be called concurrently by multiple requests
    |  Each request executes within a context.provide() wrapper
    v
dispose (clean up resources)
    |
    +-- State.dispose(directory)   Clean up all Instance States
    +-- cache.delete(directory)    Remove from cache
    +-- GlobalBus.emit("disposed") Notify the global event bus
```

**Concurrency safety**:

`Instance.provide()` uses a `cache` Map to ensure that only one instance is created per directory:

```typescript
let existing = cache.get(input.directory)
if (!existing) {
  existing = iife(async () => {
    // Create new instance
  })
  cache.set(input.directory, existing)
}
```

Using a Promise as the cache value here is a clever design -- even if multiple requests arrive simultaneously, `cache.set()` will only execute once, and subsequent requests will await the same Promise's resolution. This achieves thread safety without using locks (in JavaScript's single-threaded event loop, this approach is safe).

**Instance disposal**:

The `Instance.disposeAll()` method cleans up all instances and is typically called when the Server shuts down:

```typescript
async disposeAll() {
  const entries = [...cache.entries()]
  for (const [key, value] of entries) {
    const ctx = await value.catch(() => undefined)
    if (!ctx) { cache.delete(key); continue }
    await context.provide(ctx, async () => {
      await Instance.dispose()
    })
  }
}
```

Note that it wraps each instance's disposal operation with `context.provide()`, ensuring that cleanup logic executes in the correct context. This is the consistency guarantee of the Instance State pattern -- **all access to Instance State must occur within the correct Instance context**.
