# Agent worktrees

An agent changes the user's real repository in an isolated directory, around `git worktree add` and `remove`. A worktree belongs to one conversation branch, or to one sub-agent run; the other branches keep working in the checkout.

## Tools

| Tool | Parameters | Effect |
| --- | --- | --- |
| `worktree_create` | `source_repo`, `branch_name`, `base_ref` = `HEAD`, `label`, `pr` | Creates and binds as the active worktree of the turn's branch |
| `worktree_merge` | `worktree_id`, `strategy` = `ff-only` (or `squash`, `no-ff`, `auto`), `delete_branch` = false | Merges into `source_repo`, removes the directory, keeps the branch |
| `worktree_discard` | `worktree_id`, `force` = false, `delete_branch` = true | Removes without merging; the record stays |
| `worktree_keep` | `worktree_id` | Detaches; directory and branch stay for the user |
| `worktree_list` | `status_filter`, `scope` = `session` | Lists records |
| `agent` | `isolation` = `"worktree"` | The spawned sub-agent runs in a worktree of its own (see [Branches and sub-agents](#branches)) |

Of these, only discard asks for approval. Tools return one text line, or `[tool error] code: detail`. The WebSocket offers `session_worktrees`, `create_branch_worktree`, list, get, merge, discard and keep (`ws_actions/worktree.py`). No switch tool: one active worktree per branch, and more only through sub-agents and jobs.

## States

| From | Event | To | On disk |
| --- | --- | --- | --- |
| `active` | Merge begins (`git merge` runs, gating concurrent merges) | `committing` | Unchanged |
| `committing` | Success | `merged` | Directory removed, branch kept unless asked |
| `committing` | `merge_conflict`, `not_fast_forward`, `merge_failed` | `active`, with `error` | Directory kept for inspection; a conflicting merge is aborted in `source_repo`, so the checkout is never left mid-merge |
| `active`, `errored` | Discard | `discarded` | Directory removed, branch deleted by default |
| `active`, `errored` | Keep | `kept` | Untouched; the user takes over |
| `active`, `committing` | Reserved: the state machine allows it, no current path writes it | `errored` | Unchanged; can return to `active` |

Merged, discarded and kept are terminal. Illegal transitions raise. Merge and discard on a dirty tree refuse `worktree_dirty`, unless `force` on discard or `commit_pending` on merge, which commits everything in the worktree first. The agent's tool never sets `commit_pending`; the Merge button does, because the person asked to merge what the worktree holds. Discard has no backup.

| Merge | Git | When |
| --- | --- | --- |
| `ff-only` | `merge --ff-only` | Default; else `not_fast_forward` |
| `squash` | `merge --squash`, then a generic commit | Many exploratory commits |
| `no-ff` | Always a merge commit | Preserve history |
| `auto` | `ff-only` when `source_repo`'s HEAD is an ancestor of the branch, else `no-ff` | The Merge button: the checkout may have moved on while the branch worked |

## Record

| Field | Value |
| --- | --- |
| `id` | `wt_` + 12 hex |
| `source_repo`, `worktree_path`, `branch_name`, `base_ref` | `worktree_path` is `<state>/worktrees/<id>-<slug>`; branch defaults to `op/wt/<slug>-<id6>` |
| `status`, `created_at`, `completed_at` | Timestamps are unix |
| `parent_session`, `parent_job` | Owning session and bound job |
| `parent_branch` | The conversation branch whose turns run here; empty for a conversation-wide worktree. A sub-agent's worktree carries the branch that spawned it beside `parent_job` |
| `base_sha` | The commit the worktree started from; "what changed" is measured from it after the checkout moves |
| `ephemeral` | Made for one isolated sub-agent run; removed when the run ends with nothing changed |
| `merge_strategy`, `merge_sha`, `files_changed`, `error` | Outcome |
| `pr_number` | Set for a PR worktree |
| `include_synced`, `include_failed` | `.worktreeinclude` results |

Stored in `<state>/worktrees.json`. Not cleaned up when a session closes.

## Where tools run

The `_current_worktree_path` context variable (`state/worktree/context.py`) carries the path; no tool has a cwd argument. `worktree_create` binds it for the rest of its own turn. Each turn binds the first of these (`turn_context.py`, `runtime_location_for`):

1. The worktree of the job it runs for.
2. The worktree of its own branch (`req.branch_id`; without one, the selected branch, `store.current_branch_for`).
3. A conversation-wide worktree.
4. The project folder.

| Tool | Behaviour |
| --- | --- |
| bash | Starts at the worktree each time, in a fresh subprocess. `cd ..` can leave: a default location, not a sandbox. Hard isolation is the docker backend |
| read, write, edit, list, apply_patch (`path_resolve.py`) | Relative paths resolve against the worktree. An absolute path outside gets an `[outside worktree]` warning and is not blocked |
| glob, grep | No `path` searches the worktree; a relative one resolves inside it (`resolve_root`) |
| Dispatch path check (`_host/execution.py`) | Read and write paths are anchored to the worktree before the sandbox check, so the check looks at the file the tool opens |
| terminal_use | Its `workdir` is relative to the worktree |
| Runtime subprocess (`--cd`) | Prefers the worktree over the session workdir |
| System prompt (`environment_block`) | Names the worktree, its source checkout and branch, and says earlier paths name the same files by relative path and to re-read before editing |

**Why this design**

| Topic | Reason |
| --- | --- |
| One binding for every tool | Claude Code's tools all read the session cwd that `EnterWorktreeTool` moves; none takes a folder argument. Before, glob and grep searched the default workdir and list and apply_patch refused relative paths, so a branch could write a file in its worktree and not find it again |
| Re-read notice | Follows Claude Code's `buildWorktreeNotice`: inherited context names files in the checkout, and a worktree started from a commit lacks the checkout's uncommitted edits |

## Branches and sub-agents

| Who | How it starts | How it ends |
| --- | --- | --- |
| A conversation branch | The input box's worktree chip, Own worktree (`create_branch_worktree`), or `worktree_create` on that branch. The branch's next turn runs there | Merge, Squash, Keep as a git branch or Discard on the chip; the agent's own merge and discard tools |
| A sub-agent | `agent(isolation="worktree")`: a worktree of the repository of the folder the calling turn works in, with `parent_job`, the calling branch and `ephemeral` | No changes: removed when the run ends (sync result, or the job's terminal projection). Changes: the result names the worktree for `worktree_merge`; the chip lists it under Sub-agent worktrees |

A branch made from an isolated branch by edit, retry or fork starts in the checkout: one worktree serves one branch, so two parallel branches never share a working tree. A sub-agent of a branch that runs in a worktree gets a worktree of that worktree and merges back into it. A cancelled job still discards its worktree with `force`.

**Why this design**

| Topic | Reason |
| --- | --- |
| Opt-in, per branch or sub-agent | Claude Code: the checkout is the default; isolation is chosen per agent (`isolation: "worktree"`), and an untouched worktree is removed when the agent ends. Worktrees are per branch here because branches run in parallel. A background sub-agent whose tools can write gets one by default in a git repository, since two writers in one folder corrupt each other's edits; a foreground or read-only one shares the checkout ([Agent settings](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collaboration.html#agent-settings)) |
| Created for the next turn | Codex accepts `--worktree` only for a new session or a fork, never for a resumed one. A branch is the fork, so its worktree applies from its next turn, never under a running one |
| A git branch, not a patch | Maka leases a worktree per child session and returns a patch artifact; a patch drops the commits and needs its own apply step. A git branch merged by git keeps both |
| Start from a commit | Grok Build copies the checkout's uncommitted files into the new worktree. Copying half-finished edits into parallel branches makes both merges conflict, so the worktree starts from a commit and the turn re-reads |

## In the app

| Where | What |
| --- | --- |
| Input box, environment row (`worktree-chip.tsx`) | A chip beside the environment chip: Checkout, or the worktree's branch with its changed-file count. Its menu chooses Checkout or Own worktree, and for an open worktree offers Merge into checkout, Squash into one commit, Keep as a git branch and Discard. Discard opens the confirmation dialog. Shown once the conversation's folder is in a git repository, or while any worktree of the branch is open. Merge, keep and discard wait while the branch is running |
| Transcript (`worktree-branch-marker.tsx`) | One line at the top of the branch: where it runs and how many files changed, or that its worktree was merged, kept or discarded |
| Activity (`running-panel.tsx`) | The changed-file count of the branch's worktree, in the tip of its main agent's glyph on the work chart |

All three read one copy of the conversation's worktrees (`lib/worktrees/session-worktrees.ts`), re-read on every `worktree_status` broadcast.

**Why this design**

| Topic | Reason |
| --- | --- |
| In the input box | Codex puts the Local / Worktree choice where the person decides where the next turn runs. The chip reuses the environment chip's control and menu instead of a new panel |
| Merge on the same chip | The chip names the worktree, so its actions sit there. Discard alone asks first: it deletes work |
| Marker on the branch | The transcript line reuses the sub-agent branch strip, so a branch says where it ran wherever it is read |

## Choosing the repository

1. The `source_repo` argument.
2. The conversation's project folder (the selected Project).
3. The configured default folder: `OPENPROGRAM_WORKDIR`, then `default_workdir`.

Never the worker's own cwd: that is wherever the worker started, a checkout of OpenProgram under a test run, and an installed app has no checkout. An `isolation="worktree"` sub-agent uses the same chain after the turn's own worktree.

None found: `source_repo_not_resolved`. OpenProgram never runs `git init` for the user. A dirty source repository is fine: the worktree starts from `base_ref`. Function forms hold only parameters; the Project stays the source.

## Isolation and commits

- Neither `source_repo` nor the worktree may sit under `<state>/projects`, the session store: `worktree_in_sessions_dir`.
- Discard leaves `source_repo`'s HEAD and working tree untouched.
- A kept branch is never deleted.
- The agent commits through bash, so it writes the message. Only the person's Merge commits pending work, with a generic message.
- File diffs are git's job; tool results enter context as usual.

## Jobs and sessions

| Scenario | Flow | Outcome |
| --- | --- | --- |
| One change | create, edit, test, commit, merge | `merged` |
| Failed attempt | create, discard (`force`), create, merge | One `discarded`, one `merged`; one active per branch at a time |
| Plan agent, three jobs | One worktree per job; the plan agent activates none, lists them, merges one | Others discarded; a later merge may need another strategy if HEAD moved |
| User takes over | `worktree_keep`; later turns return to the source repository | `kept` |

A job cancel discards its worktree with `force=True` (`jobs/runner/projection.py`); any other end removes an ephemeral worktree that holds nothing. A completed job never auto-merges. Light jobs need no worktree. Worktree tools are synchronous git calls; git's own lock serialises concurrent adds.

## From a pull request

`pr` accepts `123`, `#123` or a GitHub PR URL (`state/worktree/pr_ref.py`) and ignores `branch_name` and `base_ref`.

1. `gh pr view <n> --json headRefName,headRepositoryOwner,isCrossRepository`.
2. Fetch: same repository `git fetch origin <headRefName>:<ref>`; fork `git fetch origin pull/<n>/head:<ref>`, so no remote is registered.
3. Normal `git worktree add` on branch `op/wt/pr-<n>-<id6>`; the throwaway ref is deleted.

## .worktreeinclude

`git worktree add` checks out tracked files only, so `.env` and local overrides are missing. Patterns in `source_repo/.worktreeinclude` name untracked files to copy, right after the add, in `create_worktree` (`include_sync.py`), the one point every creation path shares.

| Pattern | Meaning |
| --- | --- |
| `#…`, blank | Ignored |
| `*`, `?`, `[...]` | Globs |
| No `/` | Basename anywhere |
| Contains `/` | Anchored to the repository root |
| Trailing `/` | Directory and contents |
| `!`, `**` | Not supported |

**Copy semantics**

- Candidates: `git ls-files --others`, without `--exclude-standard`, so ignored files appear.
- An existing destination is left alone. Symlinks stay links. Permissions are preserved (`shutil.copy2`).
- One failure does not stop the rest; both lists reach the record and the tool's return.
- No file: no git calls.
- Matching is `fnmatch` and `pathlib`: git has no include-filter plumbing, `core.excludesFile` injection is refused here, and `pathspec` is not a base dependency.

## Errors

| Code | What happened, what to do |
| --- | --- |
| `not_a_git_repo` | Not a repository; run `git init` first |
| `source_repo_not_resolved` | Pass an absolute path or set the workdir |
| `already_active` | Merge, discard or keep the active one first |
| `worktree_dirty` | Commit or stash, or discard with `force` |
| `not_fast_forward` | Rebase or use another strategy |
| `merge_conflict`, `merge_failed` | Resolve in the worktree with edit and bash, retry |
| `worktree_in_sessions_dir` | Choose a repository outside the session store |
| `worktree_exists` | Path or branch taken; pass another label or `branch_name` |
| `invalid_branch_name`, `invalid_base_ref` | Empty, NUL, or starting with `-` |
| `pr_ref_error` | `pr` did not parse; `gh_not_found`, `gh_not_authenticated`, or `gh` failed. Never falls back to `base_ref` |
| `pr_worktree_exists` | Names the open worktree for this PR |

A missing `base_ref` passes through git's stderr.

## Out of scope

Remote push (use bash), cherry-pick or rebase between worktrees, a conflict-resolution UI, worktrees across repositories, backup before discard, chroot or namespace sandboxing.

## Implementation status

| Designed, not built | Intended |
| --- | --- |
| After keep | An Open in editor item for a kept worktree |
| DAG markers and `worktree_id` on tool items | Create, merge, discard and keep as marker nodes in context commits; a badge on tool calls. The transcript line and the Activity tag mark the branch today |
| Running state per branch | The chip holds merge and discard while the conversation's shown branch runs; another branch's run does not hold it, and a merge does not check whether a sub-agent is still writing in its worktree |
| Uncommitted edits into a new worktree | Not copied (Grok Build does); the turn re-reads |
| `outside_worktree` metadata | Only the tool warning exists today |
| Missing-directory detection | `worktree_list` marks a vanished path `discarded`; after a restart, still-active ones become `kept` |

Manager, store, tools, branch and job binding, every file tool, the chip, the transcript line, the Activity tag and the sub-agent isolation are in code. `tests/component/core/test_worktree_branch_e2e.py` drives them against a real temporary repository.

[Async job lifecycle](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/async-job-lifecycle.html)
