# How Cloudflare OS Manages Agent Code State with Worktree Sessions

> Discover how Cloudflare OS uses worktree sessions to manage agent code state, ensuring isolated and persistent Git repository views for secure code execution.

- Repository: [Cloudflare/cloudflare-os](https://github.com/cloudflare/cloudflare-os)
- Tags: internals
- Published: 2026-09-05

---

**Cloudflare OS manages agent code state through temporary worktree sessions that provide isolated, mutable views of Git repositories during `executeCode` calls, persisting changes only upon explicit commit.**

Cloudflare OS gives agents programmable access to Git-tracked file trees through a specialized **worktree session** abstraction. These sessions exist only for the duration of a single execution turn, ensuring that file system operations remain isolated while leveraging underlying Git plumbing for version control.

## What Are Worktree Sessions?

A worktree session represents a mutable view of a Git repository that agents manipulate through RPC calls. When an agent invokes `createWorktree`, the overseer instantiates a **`WorktreeSessionImpl`** class that implements the `Worktree` interface defined in [`worktree-binding.d.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/worktree-binding.d.ts). This session acts as the RPC target backing the worktree binding exposed to agent code.

The session is minted per execution, meaning each `executeCode` call receives a fresh session object. All file-tool operations—`readFile`, `writeFile`, `deleteFile`, and `listFiles`—resolve through a **`WorktreeTurnAccess`** object that tracks in-memory overlays and deletions separately from the immutable Git store.

## Inside WorktreeSessionImpl

The core implementation resides in [`packages/workshop-backend/src/worktree-session.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-backend/src/worktree-session.ts), where the class manages three critical pieces of state: the pin base, the HEAD commit, and the overlay buffer.

### Session Initialization

When the overseer creates a new session, it calls the constructor at lines 60-63:

```ts
new WorktreeSessionImpl(host, worktreeId, turn, initiator)

```

The `host` parameter supplies a **`WorkspaceGitCache`** and **`GitStore`**, along with a **`WorktreeRecordView`** containing the latest explicit commit (`headCommit`). The `turn` parameter provides the execution context that records all buffered changes.

### Pin Base Resolution

Each turn maintains a **pin**—the commit that serves as the foundation for the current overlay. The private `#pinBase()` method (lines 66-73) retrieves this commit via `turn.getPinBase(worktreeId)`. All read and write operations calculate their results relative to this base commit, ensuring that agents see a consistent snapshot even if the underlying repository advances.

### HEAD Tracking

The visible **HEAD** of the worktree represents the most recent explicit commit. The `#head()` method (lines 75-80) first checks for a buffered head stored in the current turn, then falls back to the registry record returned by `host.getWorktreeRecord`. This two-tier lookup allows the session to reflect durable commits while accounting for in-flight changes.

## State Management Flow

Cloudflare OS manages agent code state through a seven-step lifecycle that separates temporary overlays from durable Git history.

### 1. Create the Worktree Session

The overseer registers the worktree binding type in [`overseer.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/overseer.ts) and instantiates `WorktreeSessionImpl` when an agent calls `createWorktree`. The resulting binding exposes a `bindingName` that agents use to access the worktree within their code environment, while the actual `worktreeId` remains internal to the system.

### 2. Initialize the Overlay

`WorktreeTurnAccess` maintains two in-memory maps: `overlayFiles` (path-to-content mappings) and `removedPaths` (deleted file tracking). When agents read files, the system checks these maps first before falling back to the base commit via `gitCache`.

### 3. Perform File Operations

File modifications build **`FileChange`** objects. The `writeFile` method creates diffs for existing files or whole-file `set` operations for new files, appending these to the turn via `turn.appendChange()`. The `diff` method (lines 18-75) computes unified diffs between the current overlay plus removals and a target commit, defaulting to the session's HEAD.

### 4. Commit Changes

When agents call `commit(message)`, the session bundles overlay changes and deletions into a changes map and invokes `gitStore.writeChangedFilesAsCommit`. This creates a new commit with the previous explicit head as parent. The turn records this via `turn.appendCommit()`, but the durable worktree record updates only at the step barrier, guaranteeing **atomic visibility**.

### 5. Terminate the Session

When `executeCode` completes, the session discards its overlay and buffered head. The next execution creates a fresh session that reads the latest worktree record, including any commits made in previous turns.

## Practical Implementation

Agents interact with worktree sessions through the `Worktree` interface during `executeCode` blocks:

```ts
// Create a worktree from a known commit
const { worktreeId, bindingName } = await agent.createWorktree({
  title: "My sandbox",
  commitId: "a1b2c3d4…",                 // base commit OID
  bindingName: "myRepo"
});

// Use the binding inside executeCode
await agent.executeCode(async (myRepo: Worktree) => {
  // Read a file from the base commit
  const readMe = await myRepo.readFile("README.md");

  // Edit a file – changes stay in‑memory until you commit
  await myRepo.writeFile("README.md", readMe + "\nAdded by the agent");

  // See a diff against the current HEAD
  console.log(await myRepo.diff());

  // Persist the edit
  const newCommit = await myRepo.commit("Update README");
  console.log("New commit:", newCommit);
});

```

Subsequent executions see the committed state automatically:

```ts
// Subsequent execution sees the committed state
await agent.executeCode(async (myRepo: Worktree) => {
  // The file now contains the new content
  const updated = await myRepo.readFile("README.md");
  console.log(updated);
});

```

## Summary

- **Worktree sessions** in Cloudflare OS provide temporary, isolated Git views that exist only during `executeCode` calls according to the cloudflare/cloudflare-os source code.
- The **`WorktreeSessionImpl`** class in [`packages/workshop-backend/src/worktree-session.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-backend/src/worktree-session.ts) manages state through a pin base, HEAD tracking, and in-memory overlays.
- **`WorktreeTurnAccess`** buffers all file modifications in memory, keeping the immutable Git plumbing separate from active edits.
- Changes persist only after explicit `commit()` calls, which create new commits via `gitStore.writeChangedFilesAsCommit` and update the durable record at step barriers.
- Each execution receives a fresh session reading from the latest worktree registry, ensuring strong consistency between agent turns.

## Frequently Asked Questions

### What happens to uncommitted changes when executeCode ends?

Uncommitted changes are discarded when the worktree session terminates. The overlay maps (`overlayFiles` and `removedPaths`) and buffered head exist only within the `WorktreeTurnAccess` object tied to the current turn. When the execution ends, the next session initializes fresh from the durable worktree record, seeing only explicitly committed history.

### How does the pin base differ from HEAD?

The **pin base** represents the commit against which the current turn's overlay is calculated, retrieved via `turn.getPinBase(worktreeId)`. The **HEAD** represents the most recent explicit commit in the worktree history, which may advance when agents call `commit()`. While the pin remains stable during a single execution to provide a consistent view, HEAD updates to reflect newly created commits.

### Is the worktree state shared between different agent executions?

Yes, but only through durable Git commits. Each `executeCode` call receives a fresh `WorktreeSessionImpl` instance, but these sessions initialize from the same underlying `WorktreeRecordView` stored in the overseer's registry. When one execution commits changes, those commits become part of the shared history that subsequent sessions read via `host.getWorktreeRecord()`. However, in-flight overlays are never shared between concurrent or sequential executions.

### Where is the Worktree interface defined?

The `Worktree` RPC interface is declared in [`packages/workshop-backend/src/worktree-binding.d.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-backend/src/worktree-binding.d.ts). This TypeScript declaration file specifies the methods available to agents, including `readFile`, `writeFile`, `deleteFile`, `listFiles`, `grep`, `commit`, and `diff`. The `WorktreeSessionImpl` class implements this interface to provide the actual RPC target backing each worktree binding.