Cut a Worktree
Make each Worktree that your Machine needs, with the worktree() Effect.
A Workspace only clones each Repo. The body of the Workspace does a Cut of each Worktree in a state of its own. In this Workflow, a coder Agent works on a new branch. A reviewer reads the coder's commit in a second Worktree, with no branch. Then the Machine removes the review Worktree, and pushes the commit that the reviewer read. Save the file as workflows/fix-a-bug.ts in your Instance:
import { assign } from "xstate";
import { z } from "zod";
import {
agent,
arg,
branchName,
command,
defineEvent,
fail,
isReady,
jr2Setup,
push,
readyOf,
workspace,
worktree,
type Workspaced,
} from "@jr2/orchestrator";
const finished = defineEvent({
name: "finished",
description: "Call this when you committed the fix.",
input: z.object({}),
});
const pass = defineEvent({ name: "pass", description: "Call this when the commit is correct.", input: z.object({}) });
const revise = defineEvent({
name: "revise",
description: "Call this when the commit is not correct. Say what to change.",
input: z.object({ notes: z.string() }),
});
// The run input. `branchName` refuses a name that the cut and the push refuse.
const runInput = z.object({ prompt: z.string(), branch: branchName });
type BodyInput = Workspaced<z.infer<typeof runInput>, "app">;
type Context = BodyInput & { reviewed?: string };
// Your Machine names each folder. So it knows each path before the cut.
const coderTree = (context: BodyInput) => `${context.workspace.repos.app}/fix` as const;
const reviewTree = (context: BodyInput) => `${context.workspace.repos.app}/review` as const;
const cloneTree = (context: BodyInput) => `${context.workspace.repos.app}/default` as const;
const body = jr2Setup({
types: {} as { input: BodyInput; context: Context },
events: [finished, pass, revise],
actors: {
coder: agent({ model: "anthropic/claude-haiku-5-5", instructions: "You fix the bug. You commit the fix." }),
reviewer: agent({
model: "anthropic/claude-haiku-5-5",
workspace: "read",
instructions: "You review one commit. You change nothing.",
}),
// Each run gets a new branch: the cut refuses a branch that exists.
cut: worktree({ expect: "new" }),
// No `--force`: git refuses a Worktree with changes, and the output holds its exit code.
// The state below goes on with either result: a Worktree that stays does no harm here.
remove: command(["git", "worktree", "remove", arg("path")], { timeout: "1m" }),
publish: push({ pin: true }),
fail: fail(),
},
}).createMachine({
id: "fix-a-bug",
context: ({ input }) => input,
on: { "workspace.lost": ".lost", "agent.fault": ".failed" },
initial: "cutting",
states: {
cutting: {
invoke: {
src: "cut",
input: ({ context }) => ({ path: coderTree(context), branch: context.branch }),
// The last arm has no guard: it takes `refused`, `unknown` and each later outcome.
onDone: [{ guard: ({ event }) => isReady(event.output), target: "coding" }, { target: "notCut" }],
},
},
coding: {
invoke: {
src: "coder",
input: ({ context }) => ({ prompt: context.prompt, cwd: coderTree(context), continue: true }),
},
on: { finished: "reading" },
},
// A cut of the same path reads the Worktree. `head` is the tip of the branch, whatever HEAD the coder left.
reading: {
invoke: {
src: "cut",
input: ({ context }) => ({ path: coderTree(context), branch: context.branch }),
onDone: [
{
guard: ({ event }) => isReady(event.output),
target: "detaching",
actions: assign({ reviewed: ({ event }) => readyOf(event.output).head }),
},
{ target: "notCut" },
],
},
},
// Each round forces this folder to the commit, and cleans it.
detaching: {
invoke: {
src: "cut",
input: ({ context }) => ({ path: reviewTree(context), detach: context.reviewed! }),
onDone: [{ guard: ({ event }) => isReady(event.output), target: "reviewing" }, { target: "notCut" }],
},
},
reviewing: {
invoke: {
src: "reviewer",
input: ({ context }) => ({ prompt: `Review ${context.reviewed}.`, cwd: reviewTree(context) }),
},
on: {
pass: "removing",
revise: {
target: "coding",
actions: assign({ prompt: ({ event }) => `Change the fix as the review asks:\n\n${event.notes}` }),
},
},
},
// The clone is not the Worktree that goes, so the command runs there.
removing: {
invoke: {
src: "remove",
input: ({ context }) => ({ path: reviewTree(context), worktree: cloneTree(context) }),
onDone: "publishing",
},
},
// The input names the Worktree and the commit. jr2 reads the branch from the cut of that path.
publishing: {
invoke: {
src: "publish",
input: ({ context }) => ({ worktree: coderTree(context), sha: context.reviewed! }),
onDone: [{ guard: ({ event }) => event.output.outcome === "pushed", target: "done" }, { target: "notPushed" }],
},
},
done: { type: "final" },
notCut: { invoke: { src: "fail", input: { reason: "the Worktree was not cut" } } },
notPushed: { invoke: { src: "fail", input: { reason: "the push did not succeed" } } },
failed: { invoke: { src: "fail", input: { reason: "an Agent's Turn could not go on" } } },
lost: { invoke: { src: "fail", input: { reason: "the Sandbox is gone" } } },
},
});
export const machine = workspace(body, {
input: runInput,
repos: { app: "https://github.com/<you>/app.git" },
});Write your GitHub user name in place of <you>. The Agents use the model of the tab. Push and sign a branch tells how to give the push a credential.
Name the path
The path of a Worktree is exactly /work/<slot>/<name>. <slot> is a Repo Slot. <name> is one folder name that you choose. It is not default, and it starts with neither . nor -. It does not change with the name of the branch.
Make the path from context.workspace.repos, and add as const. Then the compiler can read the slot, and it refuses a slot that the Workspace does not have:
// Your Machine names each folder. So it knows each path before the cut.
const coderTree = (context: BodyInput) => `${context.workspace.repos.app}/fix` as const;
const reviewTree = (context: BodyInput) => `${context.workspace.repos.app}/review` as const;
const cloneTree = (context: BodyInput) => `${context.workspace.repos.app}/default` as const;The check of the compiler is a help. It sees only a literal path under jr2Setup. jr2 also checks each path when the run gets to it.
Cut a branch
Invoke the Effect with { path, branch }. branch is required, unless you give detach. The Machine names the branch, so jr2 never reads it from the folder or from HEAD.
cutting: {
invoke: {
src: "cut",
input: ({ context }) => ({ path: coderTree(context), branch: context.branch }),
// The last arm has no guard: it takes `refused`, `unknown` and each later outcome.
onDone: [{ guard: ({ event }) => isReady(event.output), target: "coding" }, { target: "notCut" }],
},
},The cut fetches, then finds the branch in this order:
- A local branch.
origin/<branch>. The new local branch tracks it.- A new branch, with no upstream. It starts from
from, or from the base of the Binding when the input has nofrom.
The output is ready, refused or unknown. Each Effect outcome is open, so give the last arm of onDone no guard. isReady is the guard for ready.
The field of ready | What it holds |
|---|---|
slot, path | The Repo Slot and the path of the Worktree. |
branch | The branch of the cut, or null for a detached cut. |
head | The tip of the branch, or the commit of a detached cut. It is never HEAD. |
found | How the cut found it: local, remote, none, held, commit or handoff. |
stale | The warning of git when the fetch failed. The cut used what the clone holds. |
held means that a cut made this path before, so the Worktree holds earlier work. No fetch happens, and the cut does not check expect again. Thus a cut of the same path also reads a Worktree:
// A cut of the same path reads the Worktree. `head` is the tip of the branch, whatever HEAD the coder left.
reading: {
invoke: {
src: "cut",
input: ({ context }) => ({ path: coderTree(context), branch: context.branch }),
onDone: [
{
guard: ({ event }) => isReady(event.output),
target: "detaching",
actions: assign({ reviewed: ({ event }) => readyOf(event.output).head }),
},
{ target: "notCut" },
],
},
},readyOf gives the ready output to an action, because xstate does not carry the guard to the action.
Choose what a cut refuses
expect says if the branch can exist. It is an option of worktree(), so a run cannot change it:
worktree(): use a local branch, then a branch of the remote, then make a new branch.worktree({ expect: "new" }): refuse a branch that exists, local or on the remote. Use it for a name that a planner or a run input chooses for new work. A name that collides is then a refusal, and not the branch of a different person. The firstpushof the run to that branch, from any of its Workspaces, checks again that the remote does not hold it. If the remote holds it, the push isrejectedwith the reasonthe remote holds the branch, and its cut had expect: "new", and the remote does not change. If the first push published and jr2 restarted before it kept the answer, the push that goes again isrejectedwith this reason too, although the remote holds the run's own commit.worktree({ expect: "existing" }): refuse a branch that does not exist, and make nothing. Use it when a run must continue a branch that exists.
The example gives the coder a new branch for each run:
// Each run gets a new branch: the cut refuses a branch that exists.
cut: worktree({ expect: "new" }),A pick param or a run input that names a branch can use the schema branchName. It is the rule of the cut and of the push. Thus jr2 refuses a bad name at the Menu or at the door, before the cut.
Read a commit with no branch
Invoke the Effect with { path, detach } to hold one commit, with no branch. The example gives this Worktree to a reviewer. Each cut forces the folder to the commit, and cleans it. Files that a .gitignore ignores stay, so that a reviewer can run the tests. A folder that ignores itself (a Python .venv) stays too, so the reviewer does not install its tools again at each round. Thus a .gitignore that another Agent wrote also keeps its files, and git status does not show them. A .gitattributes that an Agent wrote goes first, so it changes no byte. An ignored AGENTS.md, CLAUDE.md or skill goes, so that the reviewer's system prompt has only what the commit has. A git config, an info/exclude rule or an index that an Agent wrote does not change the files that the cut writes:
// Each round forces this folder to the commit, and cleans it.
detaching: {
invoke: {
src: "cut",
input: ({ context }) => ({ path: reviewTree(context), detach: context.reviewed! }),
onDone: [{ guard: ({ event }) => isReady(event.output), target: "reviewing" }, { target: "notCut" }],
},
},expect applies only to a branch. A slot with expect can thus also make a detached cut, as cut does here. A cut that you lend to a Chart must state expect, so a Chart uses such a slot too.
Take a commit from an enclosing Workspace
In a nested Workspace, invoke the Effect with { path, handoff }. handoff is the ready output of a cut in an enclosing Workspace of the run, which came in through the door. The cut makes a branch Worktree at that commit, and found is handoff, and the slot's expect applies to the branch. jr2 checks the Handoff against the run, and refuses one that the run did not make. Review in a nested Workspace tells how, and gives its rules.
Give the Worktree to each step
Each step names its Worktree by its path:
| The step | The key of its input |
|---|---|
| A Turn | cwd |
A command | worktree |
A push | worktree |
An http Effect with a file | worktree |
Each key is required under Repo Slots. A Turn that wants the folder above the Repo Slots states cwd: "/work". To read a slot that has no Worktree, use /work/<slot>/default. A Workspace with no Repo Slot, and an Agent with workspace: "none", need no cwd.
A Turn of a Working Agent that names a path where no Worktree exists does not start. The Harness refuses it, and the Machine gets agent.fault with the Turn's `cwd` <path> does not exist: cut the Worktree first.
A push has no branch in its input. jr2 finds the cut of that path, and reads the branch there. An Agent can move HEAD, and it cannot change that record:
// The input names the Worktree and the commit. jr2 reads the branch from the cut of that path.
publishing: {
invoke: {
src: "publish",
input: ({ context }) => ({ worktree: coderTree(context), sha: context.reviewed! }),
onDone: [{ guard: ({ event }) => event.output.outcome === "pushed", target: "done" }, { target: "notPushed" }],
},
},Run more than one coder
The author chooses how many Agents work in a Workspace. Agents in one Worktree share git, as people in one checkout do. Give each coder that needs its own branch a Worktree of its own, with its own path and its own branch. Each Worktree uses the one clone. To merge the branches, cut a Worktree for the merge target, and run git merge in a command there. No fetch is necessary, because each branch is in the clone. Then push once.
Cuts of one clone wait for each other, so they do not collide.
Remove a Worktree
jr2 has no Effect that removes a Worktree. To remove one, run git worktree remove in a command:
// No `--force`: git refuses a Worktree with changes, and the output holds its exit code.
// The state below goes on with either result: a Worktree that stays does no harm here.
remove: command(["git", "worktree", "remove", arg("path")], { timeout: "1m" }),Invoke the command in a different Worktree. The clone is always there, so the example names it:
// The clone is not the Worktree that goes, so the command runs there.
removing: {
invoke: {
src: "remove",
input: ({ context }) => ({ path: reviewTree(context), worktree: cloneTree(context) }),
onDone: "publishing",
},
},- The branch stays. Only the folder goes.
- A Worktree with changes or with untracked files stays too, and git exits with a code that is not 0. Route on
exitedto see it, or add--forceto the argv to drop those changes. Ignored files do not stop the removal. - jr2 keeps its record of the cut. A cut of the same path and the same branch makes the folder again. Its
foundislocal. A detached cut makes the folder again too. - jr2 deletes each Worktree with the Sandbox. Thus a Machine needs this recipe only to free the disk during a run.
Rules
These settle as refused, and nothing changes. Route them to your last arm:
- a path that is not a Worktree path:
"<path>" is not a Worktree path: /work/<slot>/<name>, with one segment in <name> - the path of the clone:
"<path>" is the clone: it stays as the attach left it; cut a sibling - a name that starts with
.or-:"<path>": a Worktree's name starts with neither . nor - - a slot that the Workspace does not have:
"<path>" names Repo Slot "<slot>", which its Workspace does not carry (<slots>) - no branch and no commit, or both:
a cut names a branch, a commit in `detach`, or a `handoff` fromon a detached cut:a detached cut takes no `from`expect: "new"on a branch that exists:<branch> exists, and this cut makes only a new branchexpect: "existing"on a branch that does not exist:<branch> does not exist, and this cut makes nothing- a re-cut that does not agree with the first cut:
<path> was cut for <branch>, not <other>,<path> was cut detached, not for <branch>, or<path> was cut from <from>, not <other> - a folder that no cut made:
<path> is a folder and no Worktree: a cut removes nothing it did not make - a detached cut of a Worktree that no cut made:
<path> is a Worktree no cut made, and a detached cut forces only its own - a commit that the clone does not hold, also after a fetch:
no commit "<sha>" in this clone - a branch that
default/or a different Worktree holds:<path> holds <branch>: read it there, or cut another branch - a name that the clone does not hold, after a fetch that failed:
<branch> is not in this clone, and the remote did not answer, so it may exist there: <warning> - a
fromon a branch that exists:<branch> exists, and it is not at `from` "<from>": `from` starts a new branch and moves no branch
A name that git or the push refuses also settles refused. The reason says why, for example "<name>" is not a branch name.
A cut gets the Git LFS files of its commit before it changes git. When the Repo cache cannot get one, the cut settles refused, and nothing changes. <commit> is the commit of the cut, and <files> is the large file or <n> large files: the node cache cannot get <files> of <commit>: <list>. <list> names at most five files, as <path> (<oid>): <why>, with ; between them. <oid> is the first 12 hex digits of the oid. When more files are missing, <list> ends ; and <n> more. The ask for the files gets what is left of the timeout of the Effect, less one minute. A file that does not come in that time also makes the cut refused, with this text.
The cut also settles refused, and nothing changes, for each of these:
- no time is left for the ask, so no ask goes.
<list>names the files as<path> (<oid>):the Effect's timeout left no time to ask the node cache for <files> of <commit>: <list> - jr2 cannot ask for the files:
cannot ask for the large files of <commit>: <why> - jr2 cannot read the result of the ask:
jr2-lfs printed no result for the large files of <commit>: <output>
A cut checks out no submodule. The folder of a submodule stays empty. To work in the code of a submodule, bind its Repo as a Repo Slot of its own (Workspaces).
These are not refused, because no word of a run can cause them:
createMachinerefuses an Effect'sonDonewith a guard on its last arm:machine "<id>": state "<state>" (Effect "<slot>") has an onDone with no unguarded last arm — … (ADR-0075)jr2 uprefuses aworktree()in a Workspace with no Repo Slot:workflow "<workflow>": worktree "<slot>" runs in Workspace of workflow "<workflow>", which has no Repo Slot: a cut makes a Worktree of a Repo Slot, and there is none — declare one: repos: { app: "<url>" } (ADR-0075)- when a
worktree()starts, it refuses the same Workspace:worktree "<slot>" runs under a Workspace with no Repo Slot: a cut makes a Worktree of a Repo Slot, and there is none — declare one: repos: { app: "<url>" } (ADR-0075) - a Repo Slot name that starts with
., because/work/.jr2/is reserved for jr2. See Bind a shipped Machine's Open parts.
Read next
- Workspaces: the clone, the folders, and what names a Worktree.
- Effects: where a cut runs, and what a restart does to it.
- Push and sign a branch: the
pushEffect. - Set an Agent's access and Dials: a reviewer in a detached Worktree.
- Let an Agent write a Chart: a cut that you lend to a Chart.
- Review in a nested Workspace: a cut at a Handoff.
- Reference:
worktree,WorktreeOptions,WorktreeInput,WorktreeOutputandbranchName. - ADR-0075: a Machine cuts a Worktree, and the Workspace only clones.