# Delegate

> Dispatch implementation tasks to agent teammates in git worktrees. Triggers: 'delegate', 'dispatch tasks', 'assign work', or /delegate. Spawns teammates, creates worktrees, monitors progress. Supports --fixes flag. Do NOT use for single-file changes or polish-track refactors.

- Skill: `lvlup-sw/delegate-5` (Agent Skill, multi-file: 14 files)
- Install (CLI): `npx skillmds@latest add lvlup-sw/delegate-5`
- Raw SKILL.md: https://api.skillmd.com/api/skills/lvlup-sw/delegate-5/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: lvlup-sw (https://skillmd.com/u/lvlup-sw)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/lvlup-sw/delegate-5

---


# Delegation Skill

Dispatch implementation tasks to subagents with proper context, worktree isolation, and TDD requirements. This skill follows a three-step flow: **Prepare, Dispatch, Monitor.**

## Triggers

Activate this skill when:
- User runs `/delegate` command
- Implementation plan is ready with extractable tasks
- User wants to parallelize work across subagents

**Exception — oneshot workflows skip delegation entirely.** The oneshot playbook runs an in-session TDD loop in the main agent's context, with no subagent dispatch or review phase. If `workflowType === "oneshot"`, do not call this skill — see `@skills/oneshot/SKILL.md` for the lightweight path.

## Core Principles

### Fresh Context Per Task (MANDATORY)

Each subagent MUST start with a clean, self-contained context. As established in the Anthropic best practices for multi-agent coordination:

- **No shared state assumptions.** Every subagent prompt must contain the full task description, file paths, TDD requirements, and acceptance criteria. Never say "see the plan" or "as discussed earlier."
- **No cross-agent references.** Subagent A must not depend on output from Subagent B unless explicitly sequenced with a dependency edge in the plan.
- **Isolated worktrees.** Each subagent operates in its own `git worktree`. Parallel agents in the same worktree will corrupt branch state.

Rationalization patterns that violate this principle are catalogued in `references/rationalization-refutation.md`.

### Delegation Modes

The default `subagent` mode dispatches each task using the runtime's spawn primitive: `task`.


### Model selection — a reasoning TIER, never a version

Use the `recommendedModel` from `prepare_delegation` task classifications when available. If no classification exists (e.g. fixer dispatch), omit `model` to inherit the session default.

`recommendedModel` is a **reasoning tier** (`haiku` | `sonnet` | `opus`), not a model version. The tier is derived from the task's `riskTier` via `agents.tier-models` (defaults `low → haiku`, `medium → sonnet`, `high → opus`; operator-overridable in `.exarchos.yml`, validated monotone so a higher risk tier can never resolve weaker).

Three rules follow, and they are the whole policy:

1. **Never write a model version anywhere** — not in a dispatch, an agent spec, a skill, or a prompt. No `claude-*-YYYYMMDD`, no `-latest`, no point releases. A version string pinned in content is a second model authority that outranks the operator's tier policy silently and rots on the next release. Pass the tier alias and let the harness resolve it against its own current catalog.
2. **Strength follows RISK, not role.** The agent choice selects the *role* (implementer / fixer / reviewer / scaffolder); the ladder selects the *strength*. An agent spec that pins a model id is a defect — that is why every shipped spec declares `model: inherit`.
3. **If you need a version, read the catalog — do not recall one.** Resolve the current tier→version mapping from the harness's own model list at dispatch time. Model recall from training data is stale by construction, and a guessed identifier fails closed at best and silently downgrades at worst.

`unless otherwise specified` means an explicit operator override in `.exarchos.yml` (`agents.default-model`, `agents.models`, `agents.tier-models`) — not a judgement call at dispatch time.

### Pre-Dispatch Schema Discovery

Before dispatching, query decision runbooks to classify the work and select the right strategy:

1. **Task complexity:** `exarchos_orchestrate({ action: "runbook", id: "task-classification" })` to get the cognitive complexity classification tree. Low-complexity tasks can use the scaffolder agent spec for faster execution.
2. **Dispatch strategy:** `exarchos_orchestrate({ action: "runbook", id: "dispatch-decision" })` for dispatch strategy (parallel vs sequential, team sizing, isolation mode).

---

## Step 1: Prepare

Use the `prepare_delegation` composite action to validate readiness in a single call. This replaces manual script invocations and individual checks.

> **Authoritative spec:** the canonical list of preconditions, blockers, and arguments for `prepare_delegation` lives in the runtime — query it with `exarchos_orchestrate({ action: "describe", actions: ["prepare_delegation"] })` if anything in this skill drifts from observed behavior. Treat the runtime `describe` output as the source of truth.

### Step 0 — Pre-emit (required before `prepare_delegation`)

Before calling `prepare_delegation`, the workflow stream must contain a `task.assigned` event for each task. The readiness view counts these events to populate `taskCount`; without them, `prepare_delegation` returns `{ ready: false, blockers: ["no task.assigned events found ..."] }`.

```typescript
exarchos_event({
  action: "batch_append",
  stream: "<featureId>",
  events: tasks.map((t) => ({
    type: "task.assigned",
    data: { taskId: t.id, title: t.title, branch: t.branch },
  })),
})
```

### Step 1 — Prepare (readiness check)

```typescript
exarchos_orchestrate({
  action: "prepare_delegation",
  featureId: "<featureId>",
  planPath: "docs/specs/<the-decomposition-spec>.md",
  tasks: [{ id: "task-001", title: "...", modules: [...] }, ...]
})
```

**Pass `planPath`.** It points `prepare_delegation` at the decomposition markdown so it lifts each task's `**Risk Tier:**` / `**Boundary Touching:**` stamp automatically (deterministic parse — no hand-transcription). The stamp is what selects the per-task verification depth below; without `planPath` (and without an explicit `riskTier`/`boundaryTouching` on a task) every task falls back to a keyword/glob heuristic that under-provisions planner-`high`/boundary tasks (#1636). You may still set `riskTier`/`boundaryTouching` explicitly on a `tasks[]` entry to override the plan for one task; an explicit value always wins.

The composite action is **read-only** — it queries delegation readiness and
assembles quality hints. It does **not** create worktrees and does **not** run
`npm install` (its authoritative description is *"Query delegation readiness and
prepare quality hints for subagent dispatch"*). Worktree materialization is the
host's responsibility under native isolation, or an explicit `setup_worktree`
call — which lays out the canonical `.worktrees/<taskId>-<taskName>` path. The
action performs:
1. **State validation** — verifies workflow state is in `delegate` phase, plan exists, plan approved
2. **Quality signal assembly** — queries `code_quality` view; if `gatePassRate < 0.80`, returns quality hints to embed in prompts. Emits `gate.executed('plan-coverage')` on success (no pre-query needed)
3. **Benchmark detection** — sets `verification.hasBenchmarks` if any task has benchmark criteria
4. **Readiness verdict** — returns `{ ready: true, worktrees: [...], qualityHints: [...] }` (the `worktrees` array reports the **expected** paths, not created ones) or `{ ready: false, reason: "..." }`

**If `blocked: true` with `reason: "current-branch-protected"`:** the response includes a `hint` field (e.g. "checkout the feature/phase branch before dispatching delegation"). Apply the hint, then re-call.

**If `ready: false`:** Stop. Report the reason to the user. Do not proceed.

**If `ready: true`:** Extract the `worktrees` paths and `qualityHints` for prompt construction.

**Native isolation — verify worktrees before agents edit.** Under native isolation (`nativeIsolation: true`), `prepare_delegation` returns `ready: true` even when the host has not yet materialized worktrees (`worktrees.ready: 0`), because isolation is the host's responsibility — readiness cannot be confirmed at prepare-time. When `worktrees.expected > 0` and none are confirmed ready, the response carries a **warning**: *"native isolation requested; N worktree(s) expected but 0 confirmed ready — verify the host materializes worktrees or dispatch may land in the shared checkout."* Do not ignore it. After dispatching, and **before any agent edits files**, confirm each agent's working directory is under `.worktrees/` (e.g. the agent's first reported `pwd`). If an agent is NOT in a worktree it has landed in the shared checkout — stop it, create the worktree manually with `git worktree add -b <task-branch> .worktrees/<taskId>-<taskName> <integration-tip>` (the same `<taskId>-<taskName>` layout `setup_worktree` uses, so a manually-created worktree is recognized without a second-path retry), redirect the agent to that path, and only then allow edits. Skipping this check risks silent shared-tree corruption across parallel agents.

### Task Extraction

From the implementation plan, extract for each task:
- Full task description (paste inline; never reference external files)
- The `**Risk Tier:**` / `**Boundary Touching:**` stamps are lifted automatically when you pass `planPath` (above) — you do NOT need to re-transcribe them into `tasks[]`; pass them explicitly only to override the plan for a specific task
- Files to create/modify as **worktree-relative paths rooted inside the worktree** (e.g. `src/foo.ts`) — never an absolute parent-repo path, and never a `..` sequence that escapes the worktree root. Either form resolves outside the agent's worktree cwd and silently writes into the main worktree. This is the platform-agnostic line of defense — it must hold on every runtime.
- Test file paths (worktree-relative) and expected test names
- Dependencies on other tasks (for sequencing)
- Property-based testing flag (`testingStrategy.propertyTests`)

For a complete worked example of this flow, see `references/worked-example.md`.

---

## Step 2: Dispatch

Build subagent prompts using `references/implementer-prompt.md` as the template. Each prompt MUST include the full task context — this is the fresh-context principle in action.

### Prompt Construction


**On runtimes with native agent definitions:**

The implementer agent definition already includes the system prompt, model, isolation, skills, hooks, and memory. The dispatch prompt should contain ONLY task-specific context:
1. Full task description (requirements, acceptance criteria)
2. Working directory (worktree path from Step 1)
3. File paths to create/modify and test file paths
4. Quality hints (if any)
5. PBT flag when `propertyTests: true`

**Full prompt template (default):**

For each task:
1. Fill the implementer prompt template with task-specific details
2. Set the `Working Directory` to the worktree path from Step 1
3. Include quality hints (if any) in the Quality Signals section
4. Include PBT section from `references/pbt-patterns.md` when `propertyTests: true`
5. Include testing patterns from `references/testing-patterns.md`

### Tier-selected verification note — dispatch the rendered prompt

`prepare_delegation` resolves each task's risk tier — from the plan stamp when you passed `planPath` (the planner's authored value wins over the heuristic; a divergence is surfaced as a `stamp:` advisory in `warnings`). To keep a wave's payload economical it does **not** repeat a full rendered prompt on every task. Instead it returns, once, a shared `implementerPromptTemplate` carrying a `verificationNote` placeholder token, a deduped `verificationNotes` map (keyed by `"<riskTier>|<boundaryTouching>"`), and a per-task `taskClassifications[i].verificationNoteKey`. Reconstruct a task's tier-selected prompt by replacing that placeholder token in the template with the task's note — `verificationNotes[taskClassifications[i].verificationNoteKey]` — where a low-tier task's key selects a terse static-analysis steer and a high-tier task's selects the test-after + integration-suite rung. (Pass `detail: true` — alias `outputFormat: "prompt-only"` — to get the fully inline `taskClassifications[i].implementerPrompt` per task instead; it is lossless vs. the splice.)

**Dispatch THAT reconstructed prompt — not the static agent default.** The shipped `agents/implementer.md` bakes a fixed medium-tier note (a self-contained fallback for runtimes that pre-bind a named agent). Use it verbatim only when no classification exists (e.g. a fixer dispatch). Otherwise, the orchestrator's dispatch payload must be built from `implementerPromptTemplate` with the task's `verificationNoteKey` note spliced in, then fill its `taskDescription` / `requirements` / `filePaths` placeholders (the same template slots in `references/implementer-prompt.md`) with the task-specific context above. Dispatching the static default instead re-imposes medium-RGR ceremony on every task regardless of tier — the exact gap this seam closes. The tier is pure data from the classification stamp; no workflow-type branching is involved.

### Decision Runbooks

For dispatch strategy decisions, query the decision runbook:
`exarchos_orchestrate({ action: "runbook", id: "dispatch-decision" })`

This runbook provides structured criteria for parallel vs sequential dispatch, team sizing, and failure escalation.


### Parallel Dispatch

Dispatch all independent tasks using the runtime's native spawn primitive in a **single message** so the dispatches run in parallel.

```typescript
task --agent implementer 'Implement task-001: [title]: Task-specific context: requirements, file paths, acceptance criteria'
```

> **Note:** Include the full implementer prompt template from `references/implementer-prompt.md` in the dispatch payload so the spawned agent has a self-contained context — runtimes that pre-bind the implementer prompt to a named agent will discard the redundant content automatically.

For parallel grouping strategy and model selection, see `references/parallel-strategy.md`.


### Verification Ownership Contract (ONE owner per claim)

Every verification claim has **exactly one owner**. Re-verifying a claim you do
not own is duplicated work, not defense in depth — it inflates the wave's cost
and hides which run is authoritative when the two disagree.

| Claim | Owner | Where it runs | Everyone else |
|-------|-------|---------------|---------------|
| "This task's behavior is covered and its tests can fail" | Implementer subagent | Its own worktree, via the per-task gates in the task-completion runbook | Lead **consumes** the recorded evidence; it does not re-run the gates |
| "This task's diff is clean (types, lint, contracts, mocks)" | Implementer subagent | Same per-task gate sequence | Lead consumes the evidence |
| "The wave as a whole did not cascade" | Lead | **Once** at the wave boundary — `check_integration_suite` after every wave merge lands | Implementers never run the cumulative suite |
| "The wave is complete (all tasks done, branches exist)" | Lead | `post_delegation_check`, after the cumulative suite | — |

Two consequences bind the runbooks:

1. `task_complete` is the **terminal** step of the task-completion runbook. No
   blocking gate may run after it — a task that is marked complete has already
   passed every gate that could block it.
2. `check_integration_suite` is a **wave-boundary backstop**, not a per-task
   gate. It runs exactly once per wave, after the merges, matching its own
   action description. Per-task cascade risk is covered by the task's own
   scoped gates.

The lead's only independent verification is a **spot check** — reading the
recorded evidence and, at most, sampling one claim it has concrete reason to
doubt. A blanket re-run of the per-task chain is a contract violation.

---

## Step 3: Monitor and Collect

### Subagent Monitoring

Collect background task results using the runtime's result-collection primitive (this may be a poll/await per task or inline replies, depending on the runtime):

```text
inline reply from task --agent (no separate collection API)
```

After each subagent reports completion:

> **Runbook:** For each completed task, execute the task-completion runbook:
> `exarchos_orchestrate({ action: "runbook", id: "task-completion" })`
> Execute the returned steps in order. Stop on gate failure.
> If the runbook action is unavailable, use `describe` to retrieve gate schemas and run manually:
> `exarchos_orchestrate({ action: "describe", actions: ["check_test_adequacy", "check_static_analysis", "task_complete"] })`

1. **Extract provenance from subagent report** — parse the subagent's completion output and extract structured provenance fields (`implements`, `tests`, `files`). These fields are reported by the subagent following the Provenance Reporting section of the implementer prompt.

2. **Verify worktree state** — confirm each worktree has clean `git status` and passing tests

3. **Run blocking gates** — the `task-completion` runbook (referenced above) defines the exact gate sequence (test adequacy, static analysis, then task_complete). On any gate failure, keep the task in-progress and report findings. All gate handlers auto-emit `gate.executed` events, so manual `exarchos_event` calls are not needed.

5. **Pass provenance in task completion** — when marking a task complete, pass the extracted provenance fields in the `result` parameter so they flow into the `task.completed` event:

```typescript
exarchos_orchestrate({
  action: "task_complete",
  taskId: "<taskId>",
  streamId: "<featureId>",
  result: {
    summary: "<task summary>",
    implements: ["DR-1", "DR-3"],
    tests: [{ name: "testName", file: "path/to/test.ts" }],
    files: ["path/to/impl.ts", "path/to/test.ts"]
  }
})
```

6. **Update workflow state** — set each passing `tasks[].status` to `"complete"` via `exarchos_workflow update`
7. **Delegation completion gate (D4, advisory)** — after ALL tasks pass, run an operational resilience check on the full branch diff before transitioning to review:

```typescript
exarchos_orchestrate({
  action: "check_operational_resilience",
  featureId: "<featureId>",
  repoRoot: ".",
  baseBranch: "main"
})
```

This is advisory — findings are recorded for the convergence view but do not block the delegation→review transition. Include findings in the delegation summary for review-phase attention.

8. **Schema sync** — if any task modified API files (`*Endpoints.cs`, `Models/*.cs`), run `npm run sync:schemas`


### Failure Recovery

When a task fails:
1. Read the failure output from the runtime's result-collection primitive (`inline reply from task --agent (no separate collection API)`)
2. Diagnose root cause — do NOT trust the implementer's self-assessment (see R3 adversarial posture)
3. Fix the task using the fixer flow below
4. Run the `task-fix` runbook gate chain after the fix completes

For the full recovery flow with a concrete example, see `references/worked-example.md`.

### Fix Failed Tasks

Dispatch a fresh fixer agent using the runtime's native spawn primitive, carrying the full failure context and the original task description:

```typescript
task --agent fixer 'Fix failed task-001: Your implementation failed. [failure context from test output]. Apply adversarial verification: do NOT trust your previous self-assessment, re-read actual test output, identify root cause not symptoms. [Original task context].'
```


After fix completes, run the `task-fix` runbook gate chain:
`exarchos_orchestrate({ action: "runbook", id: "task-fix" })`
If runbook unavailable, use `describe` to retrieve gate schemas: `exarchos_orchestrate({ action: "describe", actions: ["check_test_adequacy", "check_static_analysis", "task_complete"] })`

---

## Fix Mode (--fixes)

Handles review failures instead of initial implementation. Uses `references/fixer-prompt.md` template with adversarial verification posture, dispatches fix tasks per issue, then re-invokes review to re-integrate fixes.

**Arguments:** `--fixes <state-file-path>` — state JSON containing review results in `.reviews.<taskId>.specReview` or `.reviews.<taskId>.qualityReview`.

For detailed fix-mode process, see `references/fix-mode.md`.

> **Deprecated:** `--pr-fixes` has been superseded by `/exarchos:shepherd`. Use the shepherd skill for PR feedback workflows.

---

## Context Compaction Recovery

If context compaction occurs during delegation:
1. Query workflow state: `exarchos_workflow get` with `fields: ["tasks"]`
2. Check active worktrees: `ls .worktrees/` and verify branch state
3. Reconcile: `exarchos_workflow reconcile` replays the event stream and patches stale task state (CAS-protected)
4. Do NOT re-create branches or re-dispatch agents until confirmed lost

### Worktree State Schema

Worktree entries are stored as `worktrees["<wt-id>"]` in workflow state. Each entry requires:

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `branch` | string | Yes | Git branch name |
| `taskId` | string | Conditional | Single task ID (use for 1-task worktrees) |
| `tasks` | string[] | Conditional | Multiple task IDs (use for multi-task worktrees) |
| `status` | `"active"` \| `"merged"` \| `"removed"` | Yes | Worktree lifecycle status |

Either `taskId` or `tasks` (non-empty array) is required — at least one must be present.

**Single-task example:**
```json
{ "branch": "feat/task-001", "taskId": "task-001", "status": "active" }
```

**Multi-task example:**
```json
{ "branch": "feat/integration", "tasks": ["task-001", "task-002"], "status": "active" }
```

---

## Phase Transitions and Guards

For the full transition table, consult `@skills/checkpoint/references/phase-transitions.md`.

**Quick reference:** The `delegate` → `review` transition requires guard `all-tasks-complete` — all `tasks[].status` must be `"complete"` in workflow state.

> **Before transitioning to review:** You MUST first update all task statuses to `"complete"` via `exarchos_workflow update` with the tasks array. The phase transition will be rejected by the guard if any task is still pending/in_progress/failed. Update tasks first, then set the phase in a separate call.

### Worktree-Bearing Tasks: Auto-Detour to `merge-pending`

When a `task.completed` event carries a worktree association (`data.worktree` or `data.worktreePath`), the HSM auto-transitions through `feature/merge-pending` before reaching `review`. The `next_actions` projection surfaces the merge verb (idempotency-keyed by `${streamId}:merge_orchestrate:${taskId}`) so a runtime that consumes `next_actions` will dispatch the merge automatically.

**Land it through `serialize_merge`.** The integration branch is shared — sibling worktree merges within the same wave (or a concurrent operator) can race for it. `serialize_merge` is THE integration-merge path: it holds an optimistic per-`integrationRef` single-writer lease, then composes `merge_orchestrate` unchanged to do the local `git merge` with a recorded recovery-point SHA — see `@skills/merge-orchestrator/SKILL.md`. Do **not** dispatch raw `merge_orchestrate` to land onto the integration branch — a live foreign lease makes it fail closed (`MERGE_LEASE_HELD`, naming `serialize_merge`). Raw `merge_orchestrate` is for a non-integration merge (a private / scratch branch no sibling will touch) or a crash-resumed caller re-presenting its original lease.

The HSM exits `merge-pending` back to `delegate` once the merge terminates (`completed` / `rolled-back` / `aborted`), at which point `delegate` either re-enters `merge-pending` for the next worktree-bearing task or transitions on to `review` when all delegation is complete.

This detour is invisible to the delegation skill itself — the all-tasks-complete guard still gates the `delegate → review` transition. The merge-pending substate just sits between task completion and the next dispatch decision.

### Task Status Values

| Status | When to use |
|--------|------------|
| `pending` | Task not yet started |
| `in_progress` | Task actively being worked on |
| `complete` | Task finished successfully |
| `failed` | Task encountered an error (requires fix cycle) |

### Schema Discovery

Use `exarchos_workflow({ action: "describe", actions: ["update", "init"] })` for
parameter schemas and `exarchos_workflow({ action: "describe", playbook: "feature" })`
for phase transitions, guards, and playbook guidance. Use
`exarchos_orchestrate({ action: "describe", actions: ["check_test_adequacy", "task_complete"] })`
for orchestrate action schemas.

---

## When integration advances mid-wave

Runbook for recovering when a subagent worktree's branch has diverged from the
integration branch. Triggered by the integration merge's ancestry preflight
(run by the composed `merge_orchestrate` inside `serialize_merge`): the
failure message links here verbatim and includes the manual `git rebase`
command. Auto-rebase is **not** wired today — operators
must drive recovery by hand.

### Symptom

The merge-orchestrator reports an ancestry failure of the form:

```text
source branch <feature-branch> is not a descendant of <integration-branch>.
Rebase manually with: git rebase <integration-branch> (run from the <feature-branch> worktree).
Runbook: content/delivery/skills/delegate/SKILL.md#when-integration-advances-mid-wave
```

This means the integration branch advanced (typically because an earlier
worktree merge landed) while the failing worktree was still in flight.
Fast-forward merge is no longer safe — the working branch must catch up
first.

### Why this happens

With the worktree base pinned to local HEAD (see prerequisite below), each
subagent worktree is created at the integration branch's tip at dispatch time.
When the orchestrator merges sibling worktrees serially, each merge moves the
integration branch forward. A worktree that was dispatched against an older
integration tip will fail the ancestry preflight when its turn comes.

This is expected behavior under the current single-writer merge contract —
preflight is fail-only on purpose so the operator stays in control.


### Recovery procedure

Before each step, verify you are in the **main worktree** (not the failing
subagent worktree) and that `git status` is clean.

1. **Capture the rollback SHA** before doing anything destructive:

   ```bash
   git rev-parse <feature-branch> > /tmp/rollback.sha
   ```

   Keep this until the merge has been verified. If anything goes wrong,
   `git reset --hard "$(cat /tmp/rollback.sha)"` on the feature branch
   restores the pre-rebase state. The filename is intentionally
   branch-name-free so slash-delimited branches like `feature/dr-6`
   don't break the path with embedded `/` characters.

2. **Rebase the feature branch onto the current integration tip:**

   ```bash
   cd <feature-worktree-path>
   git fetch origin
   git rebase <integration-branch>
   ```

   Resolve any conflicts that surface. The conflicts are real — they reflect
   genuine drift between the two branches, not preflight noise. Do **not**
   pass `--strategy-option=theirs` blindly; that drops the subagent's work.

3. **Re-run the integration merge from the main worktree** — through
   `serialize_merge`, which re-composes `merge_orchestrate`'s ancestry
   preflight under the single-writer lease:

   ```typescript
   exarchos_orchestrate({
     action: "serialize_merge",
     featureId: "<featureId>",
     integrationRef: "<integration-branch>",
     sourceBranch: "<feature-branch>",
     strategy: "squash",           // squash | rebase | merge
     taskId: "<taskId>",
     dryRun: false,                // REQUIRED to execute — the action DEFAULTS to dry-run
   })
   ```

   `serialize_merge` **defaults to a dry-run** (preflight only, no lease
   claimed): omit `dryRun` and it reports whether the merge *would* apply
   without mutating anything. Pass `dryRun: false` to actually claim the
   single-writer lease and perform the merge. The action is declared
   **shared-mutating**, so a read-only caller (a session without write
   capability) is denied even the apply path; in that case fall back to a
   local-git merge from the main worktree (`git merge --squash
   <feature-branch>` then commit) and record the equivalent merge
   state/events yourself, since that merge sits outside the serialized lease.

   The preflight should now pass. Proceed with the orchestrator's normal
   merge flow. (Re-run raw `merge_orchestrate` directly only for a
   non-integration merge, or as the crash-resumed caller re-presenting its
   original `leaseOperationId`.)

### Rollback procedure

If the rebase produces conflicts you cannot resolve safely, or the merge
still fails after rebase:

1. **Reset the feature branch** to the captured rollback SHA:

   ```bash
   cd <feature-worktree-path>
   git rebase --abort   # if mid-rebase
   git reset --hard "$(cat /tmp/rollback.sha)"
   ```

2. **Mark the task `failed`** in workflow state and dispatch a fixer (see
   the Failure Recovery section above). Do **not** delete the worktree —
   the fixer needs the original branch state to diagnose the conflict.

3. **Record the incident** by emitting a `merge.aborted` event with
   `reason: "ancestry-rebase-conflict"` and the failing branch's pre-rebase
   SHA so the convergence view captures the rollback.

### Why no auto-rebase yet

Auto-rebase is not yet wired. Today the orchestrator stops at
the ancestry preflight on purpose: a botched auto-rebase across diverged
worktrees risks silently dropping subagent work, and the recovery path
above is short enough that operator-driven rebase is preferable to
clever-but-fragile automation.

---

## Transition

After all tasks complete, **auto-continue immediately** (no user confirmation):

1. Verify all `tasks[].status === "complete"` in workflow state
2. Update state: `exarchos_workflow update` with `phase: "review"`
3. Invoke: `[Invoke the exarchos:review skill with args: <plan-path>]`

This is NOT a human checkpoint — the workflow continues autonomously.

---

## References

| Document | Purpose |
|----------|---------|
| `references/implementer-prompt.md` | Full prompt template for implementation tasks |
| `references/fixer-prompt.md` | Fix agent prompt with adversarial verification posture |
| `references/worked-example.md` | Complete delegation trace with recovery path (R1) |
| `references/rationalization-refutation.md` | Common rationalizations and counter-arguments (R2) |
| `references/parallel-strategy.md` | Parallel grouping and model selection |
| `references/testing-patterns.md` | Arrange/Act/Assert, naming, mocking conventions |
| `references/pbt-patterns.md` | Property-based testing patterns |
| `references/fix-mode.md` | Detailed fix-mode process |
| `references/state-management.md` | State patterns and benchmark labeling |
| `references/troubleshooting.md` | Common failure modes and resolutions |
| `references/adaptive-orchestration.md` | Adaptive team composition |
| `references/workflow-steps.md` | Cross-platform step-by-step delegation reference |
| `references/worktree-enforcement.md` | Worktree isolation rules |

