---
name: codemode-how-to-git
description: 'Hand a branch of work to a separate session in its own checkout, keeping the current checkout untouched. Use for a long refactor, a risky migration, or parallel features that touch the same files; not for parallel work on one branch.'
---

# Worktree sessions

In code mode the `worktrees` namespace creates a git worktree and starts a Po
session inside it: call `discover({ namespace: 'worktrees' })` for the types,
then `exec`. Without code mode use `run_worktree` for checkout management.
The new session appears nested under the current one in the SESSIONS rail, so a
parent can hand off a branch of work and keep its own checkout untouched.

New worktrees live outside the repository, under `git/worktrees` in the admitted
Po home. Use the path on the record: an imported checkout
stays in its original directory.

## When to use it

Use a worktree when work needs its own branch **and** its own checkout at the
same time: a long refactor you want to leave half-finished, a risky migration,
or two features that touch the same files.

Do not reach for it to parallelise work that shares a branch. Two sessions on
one branch in two checkouts will fight, and git refuses the second worktree.

A new checkout has no installed dependencies unless `.po/worktree.yaml` defines
`setup`. If it does, check the child session's `worktree-setup` runner before
building. A retained checkout after a setup failure is not a reason to spawn again:
read `record.setupStage` first. `failed` or `unconfirmed` means inspect that
child, not spawn a second one.

## Sparse checkouts

Use `worktrees.profiles()` to discover the repository's checkout profiles. Pass
`sparseProfile` to `spawn` to select files, not `profile` or `selection.profile`.
For example, use `{ branch: 'wt/fix-web', sparseProfile: 'web' }` if `web` is
listed. `full` means the whole repository. When the workspace configures a
default profile, spawn is restricted to that default; otherwise any listed profile
works. Omit `sparseProfile` to use the default, or ordinary Git or Rift when no
default is configured. Spawn the narrow profile and `expand` it later rather than
asking for a wider one.

When more files are needed, use `worktrees.expand(id, ['apps/mobile'])` instead
of creating another checkout. Folders must be repository-relative and cannot
overlap an exclusion. Use `worktrees.reapply(id)` to read the updated profile
at HEAD without dropping earlier expansions. For repositories not initialized
for per-worktree config, stop and ask the owner to run the explicit `sparo init`
step in the package README. Do not change shared Git config on their behalf.

## Isolated workflow runs

`startWorkflow` exists only in code mode; `run_worktree` has no equivalent.
Use `worktrees.startWorkflow` instead of `spawn` followed by a separate workflow
launch when a repository workflow needs its own checkout. List workflows from
the repository root with `workflow.list()`. Use the definition's repository-relative
path as `key`, including any folders. Do not use an absolute path or a stored
library workflow. The workspace needs Workflow and a remote-tracking base. The
new checkout branches from that base, but the run uses your session's own copy of
the definition, so an uncommitted or unpushed workflow still runs; files it reads
at runtime come from the new checkout. `branch` must be a new branch name. The
launcher does not run the regular checkout `setup`; preparation belongs to the
workflow. Pass string `inputs`, not environment, target sessions or allocations.

```ts
const launch = await worktrees.startWorkflow({
  key: 'automations/check.workflow.yml', // use the path for your repository
  attemptId: 'check-change-42',
  inputs: { component: 'web' },
});
```

Optional `branch` and `sparseProfile` select the checkout. Save the `attemptId`
and reuse it with **the same arguments** when checking the same launch. A
`pending` admission is not a lost run. `registered` includes a `runId`, not
proof that the workflow finished. If an outcome is unknown, inspect the child
and the saved attempt; do not change the ID to try again. Successful work may
be closed non-forcibly after its checkout and delivery are verified. The branch
stays. Failed, dirty or unverified work is kept for inspection.

## Calling it

`discover({ namespace: 'worktrees' })` lists every method. Records come back as
objects, so filter them in the script rather than reading printed text. `spawn`
can be slow: pass a larger `timeoutMs` to `exec`. `branch` must be a new branch;
ask the person to open an existing branch from the New Session dialog.
Operations on one worktree take its short `id`, never its path or branch. Each
listed record carries a `relationship` relative to the calling session: `parent`
means you created the worktree, `child` means you are its worktree session, and
`other` means neither. To report to your parent from a nested worktree, use your
own record with relationship `child`, not the record for your parent's worktree.
Use `parent` records to contact your own children. These labels do not grant
permission to send, merge, or close another session's worktree.

Subagents may only call `list`, `status`, `profiles` and `prune({ dryRun: true })`;
the rest refuse with `main_agent_only`. Report back to the main agent instead.

`send` delivers between a worktree session and its parent. A `spawn`
`task` is the first message to the new session. Both use durable Session delivery
when available. A delivery error after the worktree is created does not remove
the worktree. Do not spawn it again to retry the task.

If admission requires recovery, call `messages` from the **recipient** session
with the worktree id to retrieve the persisted text. Do not resend automatically.
If admission merely timed out, delivery may still be pending: check the delivery
id in the sender's outbox or call `messages` from the recipient before deciding
whether to resend. A timeout does not prove the message was lost. If persistence
itself failed, inspect the worktree and sender outbox before using `send` again.

## What it refuses, and why

- **`close` on a dirty tree.** It names the uncommitted files and stops.
  Pass `{ force: true }` only after reading that list. The files are gone after.
- **`merge` when the parent checkout is dirty.** The merge lands in the parent,
  so uncommitted edits there would be folded into a merge commit nobody meant to
  make. Commit or stash first.
- **`spawn` on a branch that already exists.** Pick another branch name, or ask
  the person to open the existing branch from the New Session dialog.
- **`close` of your own worktree while your parent is live.** Only the parent
  closes it. Report with `network.send` and let the parent decide.
- **`merge` that conflicts.** It fails with `merge_conflict` and the conflicted
  files, and leaves this checkout mid-merge. Resolve them and commit, or run
  `git merge --abort`. Do not spawn or merge again until the checkout is clean.
- **`prune` never deletes a worktree holding uncommitted work**, and never
  touches a directory this tool did not create. It reports those instead.

Run `prune` with `{ dryRun: true }` first. The plan tells you exactly what would be
removed, forgotten, and left alone.

## When the person is asked

`discover` marks `close` and `prune` as needing the person, but most calls do not
ask. A clean `close` of a worktree you created, a dry run, and a prune with an
empty plan run at once. The person is asked only for `close` with
`{ force: true }`, a `close` that stops a live session you neither run nor
created, and a non-dry-run `prune` that removes or forgets something. The call
waits for the decision; `exec` moves to the background after 30 seconds, so keep
other authorized work going. A refusal means nothing ran.

`approval_stale` means the worktree or plan changed after the person approved,
and nothing ran. Read `status` or a dry-run plan again and repeat the same call.
Never pass the `expected*` or `approvalPreview` fields yourself; the gate sets them.

## Notes

- A worktree session is a peer, not a subagent. It has its own context and its
  own turn loop. When it goes idle it reports to its parent once with
  `network.send({ to: parent, text, terminal: true, outcome })`, where `outcome`
  is `'done'`, `'blocked'`, `'failed'` or `'cancelled'`. Never report `done` for blocked or
  failed work. `worktrees.send` stays for progress updates using the worktree's `id` (`worktreeId`), which is distinct from `network`'s `sessionId` and send budget. See @skill:codemode-how-to-network and @skill:codemode-how-to-session for peer messaging and coordinator starts.
- Closing the parent does not close its worktree sessions. They keep running and
  stay in the rail.
- `spawn` needs the cockpit running, because the cockpit owns session
  lifecycle. Without it the call rejects with a message rather than half-creating anything.
