OpenProgram Docs

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

ToolParametersEffect
worktree_createsource_repo, branch_name, base_ref = HEAD, label, prCreates and binds as the active worktree of the turn's branch
worktree_mergeworktree_id, strategy = ff-only (or squash, no-ff, auto), delete_branch = falseMerges into source_repo, removes the directory, keeps the branch
worktree_discardworktree_id, force = false, delete_branch = trueRemoves without merging; the record stays
worktree_keepworktree_idDetaches; directory and branch stay for the user
worktree_liststatus_filter, scope = sessionLists records
agentisolation = "worktree"The spawned sub-agent runs in a worktree of its own (see Branches and sub-agents)

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

FromEventToOn disk
activeMerge begins (git merge runs, gating concurrent merges)committingUnchanged
committingSuccessmergedDirectory removed, branch kept unless asked
committingmerge_conflict, not_fast_forward, merge_failedactive, with errorDirectory kept for inspection; a conflicting merge is aborted in source_repo, so the checkout is never left mid-merge
active, erroredDiscarddiscardedDirectory removed, branch deleted by default
active, erroredKeepkeptUntouched; the user takes over
active, committingReserved: the state machine allows it, no current path writes iterroredUnchanged; 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.

MergeGitWhen
ff-onlymerge --ff-onlyDefault; else not_fast_forward
squashmerge --squash, then a generic commitMany exploratory commits
no-ffAlways a merge commitPreserve history
autoff-only when source_repo's HEAD is an ancestor of the branch, else no-ffThe Merge button: the checkout may have moved on while the branch worked

Record

FieldValue
idwt_ + 12 hex
source_repo, worktree_path, branch_name, base_refworktree_path is <state>/worktrees/<id>-<slug>; branch defaults to op/wt/<slug>-<id6>
status, created_at, completed_atTimestamps are unix
parent_session, parent_jobOwning session and bound job
parent_branchThe 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_shaThe commit the worktree started from; "what changed" is measured from it after the checkout moves
ephemeralMade for one isolated sub-agent run; removed when the run ends with nothing changed
merge_strategy, merge_sha, files_changed, errorOutcome
pr_numberSet 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.
ToolBehaviour
bashStarts 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, grepNo 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_useIts 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
TopicReason
One binding for every toolClaude 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 noticeFollows 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

WhoHow it startsHow it ends
A conversation branchThe input box's worktree chip, Own worktree (create_branch_worktree), or worktree_create on that branch. The branch's next turn runs thereMerge, Squash, Keep as a git branch or Discard on the chip; the agent's own merge and discard tools
A sub-agentagent(isolation="worktree"): a worktree of the repository of the folder the calling turn works in, with parent_job, the calling branch and ephemeralNo 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
TopicReason
Opt-in, per branch or sub-agentClaude 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)
Created for the next turnCodex 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 patchMaka 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 commitGrok 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

WhereWhat
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
TopicReason
In the input boxCodex 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 chipThe chip names the worktree, so its actions sit there. Discard alone asks first: it deletes work
Marker on the branchThe 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

ScenarioFlowOutcome
One changecreate, edit, test, commit, mergemerged
Failed attemptcreate, discard (force), create, mergeOne discarded, one merged; one active per branch at a time
Plan agent, three jobsOne worktree per job; the plan agent activates none, lists them, merges oneOthers discarded; a later merge may need another strategy if HEAD moved
User takes overworktree_keep; later turns return to the source repositorykept

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.

PatternMeaning
#…, blankIgnored
*, ?, [...]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

CodeWhat happened, what to do
not_a_git_repoNot a repository; run git init first
source_repo_not_resolvedPass an absolute path or set the workdir
already_activeMerge, discard or keep the active one first
worktree_dirtyCommit or stash, or discard with force
not_fast_forwardRebase or use another strategy
merge_conflict, merge_failedResolve in the worktree with edit and bash, retry
worktree_in_sessions_dirChoose a repository outside the session store
worktree_existsPath or branch taken; pass another label or branch_name
invalid_branch_name, invalid_base_refEmpty, NUL, or starting with -
pr_ref_errorpr did not parse; gh_not_found, gh_not_authenticated, or gh failed. Never falls back to base_ref
pr_worktree_existsNames 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 builtIntended
After keepAn Open in editor item for a kept worktree
DAG markers and worktree_id on tool itemsCreate, 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 branchThe 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 worktreeNot copied (Grok Build does); the turn re-reads
outside_worktree metadataOnly the tool warning exists today
Missing-directory detectionworktree_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

Last updated · 2026-11-25