---
name: orchestrate
description: Autonomously drive a goal to done — split it into tasks, delegate each to its own worktree agent (Herdr or Rex) that /ships it, steer them from here, merge the PRs that are safe, and clean up the worktrees
argument-hint: <goal>
---

The goal: $ARGUMENTS

You are the orchestrator. You plan, delegate, steer, verify, merge and clean up —
you don't write the code yourself. I will **never** go into the worktrees or talk
to the agents there: everything goes through you, and you keep going until the
goal is met.

Every multiplexer step goes through the helper that ships with `delegate`, so this
skill needs `delegate` installed next to it. Its path is relative to the base
directory this skill was loaded from: `<skill dir>/../delegate/scripts/multiplexer.sh`,
with `<skill dir>` replaced by the real absolute path. Source it at the start of each
Bash call (`. "<skill dir>/../delegate/scripts/multiplexer.sh"`) and check
`mux_backend` prints `herdr` or `rex` first. If the file is missing, say `delegate`
isn't installed in the same skills directory as this skill and stop; if
`mux_backend` prints anything else, say so and stop.

## 0. Ledger first — resume if it exists

All state lives in a ledger file, so you survive context compaction and `/loop`
re-runs. It goes inside the git dir, so it never gets committed:

```bash
LEDGER="$(git rev-parse --path-format=absolute --git-common-dir)/orchestrate/<goal-slug>.md"
```

If it already exists, **read it and resume** from where it says — don't re-plan
and don't re-delegate tasks that are already running. Otherwise create it with:
the goal, the definition of done, the base branch, the task list (id, title,
depends-on, status, agent name, handle, worktree path, branch, PR) and a
decision log. Update it after **every** state change, before doing anything else.

## 1. Pin down "done" — the only time you ask me

Scout the repo the way `delegate` does (read, write nothing). Then, in **one**
message, ask me only what genuinely forks the outcome and you can't settle from
the repo or a sensible default. Write the definition of done as a short checklist
of observable outcomes and show it to me with the plan.

After this, you're on your own. Default everything else and log the decision.

## 2. Plan the tasks

Split the goal into tasks that each make **one reviewable PR**:

- Small and independently mergeable. A task that would make a 1 500-line PR is
  two tasks.
- Explicit dependencies. A task that needs another one's code is **stacked** on
  it: it branches off the parent task's branch, and its PR targets that branch.
  Stack only real code dependencies; everything else goes straight on the base.
- Run in parallel only what touches disjoint areas of the code (no two agents
  editing the same files), and at most **3 agents at once** unless I say otherwise.

The base is the repo's default branch (`gh repo view --json defaultBranchRef`)
unless I named one.

## 3. Delegate each ready task

Use the **`delegate`** skill for each ready task (no dependencies, or its parent
reported `ready` or is merged), with
these overrides — you are the one the agent reports to, not me:

- **Skip delegate's "ask me" step**: you already settled the decisions in step 1.
  Pass them in the brief.
- **Base it on what it depends on**, after a fresh `git fetch origin`:
  `origin/<base>` for an independent task or one whose parent is merged,
  `origin/<parent branch>` for a stacked one. Record the parent in the ledger.
- **Stacked tasks** get in the brief: their base branch is `<parent branch>`, so
  `ship` diffs against it and the PR is opened with `--base <parent branch>`;
  never rebase onto `<base>` or retarget the PR on their own.
- **One group for the whole goal**: pass the same `<group>` to every task — a few
  plain words naming the goal (`dark mode`) — so all its agents sit as tabs in
  one place: a Herdr space named `<group>`, or the Rex session
  `<current session> / <group>` (shown with a branch icon). Each task's `<label>`
  names the task itself. Record the group in the ledger and reuse it on resume.
- **Agent names** `orc-<task-id>-<short>`, matching `[a-z][a-z0-9_-]{0,31}`.
- **Add to the brief, before `/ship`:**
  - Its place in the plan: the goal, what other tasks exist, what's already
    merged, what it must not touch because another agent owns it.
  - **Do not merge the PR and do not enable auto-merge.** The orchestrator merges.
  - **Run every browser headless** (QA included) unless the test genuinely
    can't — several agents run at once and nobody is watching their windows.
  - When blocked on a decision, don't guess on anything irreversible — stop and
    ask in your last message.
  - End **every** turn with exactly one status line:
    - `ORCHESTRATE: ready <pr-url>` — PR open, reviews and QA done, required CI green.
    - `ORCHESTRATE: question <the question>` — you need a decision to continue.
    - `ORCHESTRATE: failed <why>` — you can't finish this task.

Record the agent name, handle, worktree path and branch that `delegate` got back
in the ledger. Don't wait on one agent before delegating the next.

## 4. Steer — the loop

Repeat until the goal is done, one pass every 20 minutes (step 9):

0. **Clear out finished worktrees**: `mux_worktree_gc` drops every worktree whose
   PR is merged or closed, with its agents, space / session and local branch — yours
   and any earlier hand-off's. Update the ledger for the tasks it cleaned:
   `merged`, or `abandoned` if the PR was closed.
1. **Check on each running agent**: `mux_agent_status <name>`; when it's `idle`,
   `done` or `blocked`, read it with `mux_agent_read <name> 200` and find the last
   `ORCHESTRATE:` line. Don't block on `mux_agent_wait` between passes — the
   20-minute wake-up (step 9) is the wait. Under Rex the read only sees the agent's
   screen, not its scrollback, and under Herdr neither does a read while the agent
   is `working` or `blocked`: if the status line has scrolled off, ask the agent
   to repeat it rather than assuming there is none.
2. **Act on what it says**, always through `mux_agent_prompt <name> "..."`
   (for long prompts, `"$(cat <file>)"`):
   - `question` → answer it from the plan, the repo and the decisions you logged.
     Only bring it to me if it's one of the things in step 6.
   - `failed` → read why. Re-brief with what it was missing, or split / re-plan
     the task. A task that fails twice goes to me.
   - `blocked` (a permission or UI prompt) → inspect it, answer it.
   - Idle with no status line → ask it where it stands and to finish with the
     status line.
   - `ready` → step 5.
3. **Link stacks**: when a stacked task reports `ready`, link its PR on top of
   its parent's with `gh stack link <parent pr> <pr>` (or
   `gh stack link <stack number> <pr>` to grow an existing stack).
4. **Keep the others current**: after every merge, tell each agent with an open
   PR to rebase on its base — `origin/<base>`, or `origin/<parent branch>` when
   the parent pushed new commits — (if `gh pr view --json mergeStateStatus` says
   it's behind or conflicting) and confirm CI is still green. A rebase is the one
   case where pushing with `--force-with-lease` is fine.
5. **Delegate** tasks whose parent just reported `ready` or merged.
6. **Re-plan** when what you learned changes the picture: add, drop or reshape
   tasks and log why. The plan serves the goal, not the other way round.

Never edit files in a worktree yourself. You may read them to verify.

## 5. Review and merge

`ship` already ran two reviews, QA and CI. Before merging, check it yourself:

- **Scope**: `gh pr diff <n>` — every hunk belongs to this task, nothing from
  another task, no debug leftovers. It does what the task (and the goal) need.
- **Evidence**: the QA in the PR body actually exercised the change.
- **State**: `gh pr view <n> --json mergeable,mergeStateStatus,reviewDecision,statusCheckRollup`
  — mergeable, up to date with the base, every required check green, no
  unresolved review threads.

If something's off, send it back to the agent with what to fix and wait for a new
`ready`.

Then decide on **risk**. Merge it yourself when it's low risk: reversible with a
revert, covered by tests or QA, nothing in step 6. Use the merge method the repo
allows (`gh repo view --json squashMergeAllowed,mergeCommitAllowed,rebaseMergeAllowed`,
squash if allowed):

```bash
gh pr merge <n> --squash --delete-branch
```

A stacked PR merges through its stack, never on its own: `gh stack merge <n> --yes
--squash` merges every PR below it too, atomically, so check each of them as above
before you run it. Merge bottom-up as PRs become ready rather than waiting for the
whole stack.

Never `--admin`, never bypass branch protection. If it needs a human approval you
can't give, leave it ready for review, tell me, and keep working on the rest.

## 6. What you never do alone

Stop and ask me — but keep the other tasks moving meanwhile — before you merge
or decide anything that:

- Is a destructive or hard-to-revert migration, deletes data, or changes a public
  API / contract that others consume.
- Touches auth, permissions, payments, secrets, infra, deploy or CI configuration.
- Goes against what the goal or the definition of done said, or widens the scope.
- Needs a product call the repo can't answer.

If PushNotification is available, use it whenever you're waiting on me.

## 7. Clean up after every merge

As soon as a PR is merged (by you or anyone), its worktree is dead weight. The
`mux_worktree_gc` at the top of each pass catches it anyway; doing it right away
keeps the agent count honest:

1. Make sure the PR is really `MERGED` (`gh pr view <n> --json state`).
2. Stop the agent: `mux_agent_keys <name> ctrl+c ctrl+c`.
3. Remove the worktree, its agent and its tab: `mux_worktree_remove "<handle>" "<worktree path>"`.
   Only add `--force` if what's left is build output or QA artifacts — if there
   are uncommitted source changes, find out what they are first.
4. Delete the local branch if it's left (`git branch -D <branch>`) and
   `git fetch --prune`.
5. Mark the task `merged` in the ledger.

Do the same for a task you abandon: close its PR with a comment saying why, then
clean up. Only ever close spaces, sessions and worktrees **you created** — they're in
the ledger.

## 8. Finish

The goal is done when every item in the definition of done holds **on the base
branch after the merges** — check each one, don't infer it from the PRs. Then:

- **Tear everything down — nothing of yours may outlive the goal.** Go through
  every task in the ledger, whatever its status (merged, abandoned, failed,
  still waiting on me), and:
  1. Stop its agent if it's still alive: `mux_agent_keys <name> ctrl+c ctrl+c`.
  2. Remove its worktree, agent and tab: `mux_worktree_remove "<handle>" "<worktree path>"`
     (`--force` only for build output or QA artifacts, as in step 7).
  3. Delete its local branch if it's left (`git branch -D <branch>`).

  Then run `mux_worktree_gc` one last time and `git worktree prune && git fetch --prune`,
  and verify: no ledger worktree in `git worktree list`, `mux_agent_status` no
  longer finds any of the agents, and under Rex the group's session
  (`<current session> / <group>`) is gone — under Herdr, the `<group>` space is
  gone (`herdr-app ls`). If a session or space is still open with nothing of yours running in
  it, close it. A task still waiting on me keeps its open PR, but not its agent
  or worktree: say in the report that it can be picked up again with `delegate`.
- Stop the loop (step 9): no more wake-ups.
- Give me a short report: what got merged (PR links), anything left waiting on
  me, the decisions you defaulted, and follow-ups you noticed but kept out of scope.
- Mark the ledger `done`.

## 9. Run as a loop — check every 20 minutes, speak only on news

Once the tasks are delegated, don't sit blocking on one agent: run the steering
loop on a timer. Each wake-up is one pass of step 4 from the ledger, then you
schedule the next one **20 minutes** out (`ScheduleWakeup` with
`delaySeconds: 1200`, or `/loop 20m` if that's how you were started). Stop the
loop when the goal is done.

Each pass, compare what you see against the ledger and **only write to me when
something changed that I'd care about**: a PR merged or ready, an agent asking a
question you can't answer, a failure, a re-plan, something waiting on me, or the
goal done. Keep it to a few lines on what changed. If nothing changed — agents
still working, CI still running — say nothing: update the ledger's last-checked
time and schedule the next wake-up silently (mark it `noop`).
