delegation
Original:🇺🇸 English
Translated
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.
9installs
Sourcelvlup-sw/exarchos
Added on
NPX Install
npx skill4agent add lvlup-sw/exarchos delegationTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →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 command
/delegate - 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 , do not call this skill — see for the lightweight path.
workflowType === "oneshot"@skills/oneshot-workflow/SKILL.mdCore 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 . Parallel agents in the same worktree will corrupt branch state.
git worktree
Rationalization patterns that violate this principle are catalogued in .
references/rationalization-refutation.mdDelegation Modes
The default mode dispatches each task using the runtime's spawn primitive: .
subagenttaskUse the from task classifications when available. If no classification exists (e.g., fixer dispatch), omit to inherit the session default.
recommendedModelprepare_delegationmodelPre-Dispatch Schema Discovery
Before dispatching, query decision runbooks to classify the work and select the right strategy:
- Task complexity: to get the cognitive complexity classification tree. Low-complexity tasks can use the scaffolder agent spec for faster execution.
exarchos_orchestrate({ action: "runbook", id: "task-classification" }) - Dispatch strategy: for dispatch strategy (parallel vs sequential, team sizing, isolation mode).
exarchos_orchestrate({ action: "runbook", id: "dispatch-decision" })
Step 1: Prepare
Use the composite action to validate readiness in a single call. This replaces manual script invocations and individual checks.
prepare_delegationAuthoritative spec: the canonical list of preconditions, blockers, and arguments forlives in the runtime — query it withprepare_delegationif anything in this skill drifts from observed behavior. Treat the runtimeexarchos_orchestrate({ action: "describe", actions: ["prepare_delegation"] })output as the source of truth.describe
Step 0 — Pre-emit (required before prepare_delegation
)
prepare_delegationBefore calling , the workflow stream must contain a event for each task. The readiness view counts these events to populate ; without them, returns .
prepare_delegationtask.assignedtaskCountprepare_delegation{ 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>",
tasks: [{ id: "task-001", title: "...", modules: [...] }, ...]
})The composite action performs:
- Worktree creation — creates with
.worktrees/task-<id>, runsgit worktree addnpm install - State validation — verifies workflow state is in phase, plan exists, plan approved
delegate - Quality signal assembly — queries view; if
code_quality, returns quality hints to embed in prompts. EmitsgatePassRate < 0.80on success (no pre-query needed)gate.executed('plan-coverage') - Benchmark detection — sets if any task has benchmark criteria
verification.hasBenchmarks - Readiness verdict — returns or
{ ready: true, worktrees: [...], qualityHints: [...] }{ ready: false, reason: "..." }
If with : the response includes a field (e.g. "checkout the feature/phase branch before dispatching delegation"). Apply the hint, then re-call.
blocked: truereason: "current-branch-protected"hintIf : Stop. Report the reason to the user. Do not proceed.
ready: falseIf : Extract the paths and for prompt construction.
ready: trueworktreesqualityHintsTask Extraction
From the implementation plan, extract for each task:
- Full task description (paste inline; never reference external files)
- Files to create/modify with absolute worktree paths
- Test file paths 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.mdStep 2: Dispatch
Build subagent prompts using as the template. Each prompt MUST include the full task context — this is the fresh-context principle in action.
references/implementer-prompt.mdPrompt 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:
- Full task description (requirements, acceptance criteria)
- Working directory (worktree path from Step 1)
- File paths to create/modify and test file paths
- Quality hints (if any)
- PBT flag when
propertyTests: true
Full prompt template (default):
For each task:
- Fill the implementer prompt template with task-specific details
- Set the to the worktree path from Step 1
Working Directory - Include quality hints (if any) in the Quality Signals section
- Include PBT section from when
references/pbt-patterns.mdpropertyTests: true - Include testing patterns from
references/testing-patterns.md
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 fromin 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.references/implementer-prompt.md
For parallel grouping strategy and model selection, see .
references/parallel-strategy.mdStep 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:Execute the returned steps in order. Stop on gate failure. If the runbook action is unavailable, useexarchos_orchestrate({ action: "runbook", id: "task-completion" })to retrieve gate schemas and run manually:describeexarchos_orchestrate({ action: "describe", actions: ["check_tdd_compliance", "check_static_analysis", "task_complete"] })
-
Extract provenance from subagent report — parse the subagent's completion output and extract structured provenance fields (,
implements,tests). These fields are reported by the subagent following the Provenance Reporting section of the implementer prompt.files -
Verify worktree state — confirm each worktree has cleanand passing tests
git status -
Run blocking gates — therunbook (referenced above) defines the exact gate sequence (TDD compliance, static analysis, then task_complete). On any gate failure, keep the task in-progress and report findings. All gate handlers auto-emit
task-completionevents, so manualgate.executedcalls are not needed.exarchos_event -
Pass provenance in task completion — when marking a task complete, pass the extracted provenance fields in theparameter so they flow into the
resultevent:task.completed
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"]
}
})- Update workflow state — set each passing to
tasks[].statusvia"complete"exarchos_workflow set - 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.
- Schema sync — if any task modified API files (,
*Endpoints.cs), runModels/*.csnpm run sync:schemas
Failure Recovery
When a task fails:
- Read the failure output from the runtime's result-collection primitive ()
inline reply from task --agent (no separate collection API) - Diagnose root cause — do NOT trust the implementer's self-assessment (see R3 adversarial posture)
- Fix the task using the fixer flow below
- Run the runbook gate chain after the fix completes
task-fix
For the full recovery flow with a concrete example, see .
references/worked-example.mdFix 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 runbook gate chain:
If runbook unavailable, use to retrieve gate schemas:
task-fixexarchos_orchestrate({ action: "runbook", id: "task-fix" })describeexarchos_orchestrate({ action: "describe", actions: ["check_tdd_compliance", "check_static_analysis", "task_complete"] })Fix Mode (--fixes)
Handles review failures instead of initial implementation. Uses template with adversarial verification posture, dispatches fix tasks per issue, then re-invokes review to re-integrate fixes.
references/fixer-prompt.mdArguments: — state JSON containing review results in or .
--fixes <state-file-path>.reviews.<taskId>.specReview.reviews.<taskId>.qualityReviewFor detailed fix-mode process, see .
references/fix-mode.mdDeprecated:has been superseded by--pr-fixes. Use the shepherd skill for PR feedback workflows./exarchos:shepherd
Context Compaction Recovery
If context compaction occurs during delegation:
- Query workflow state: with
exarchos_workflow getfields: ["tasks"] - Check active worktrees: and verify branch state
ls .worktrees/ - Reconcile: replays the event stream and patches stale task state (CAS-protected)
exarchos_workflow reconcile - Do NOT re-create branches or re-dispatch agents until confirmed lost
Worktree State Schema
Worktree entries are stored as in workflow state. Each entry requires:
worktrees["<wt-id>"]| Field | Type | Required | Notes |
|---|---|---|---|
| string | Yes | Git branch name |
| string | Conditional | Single task ID (use for 1-task worktrees) |
| string[] | Conditional | Multiple task IDs (use for multi-task worktrees) |
| | Yes | Worktree lifecycle status |
Either or (non-empty array) is required — at least one must be present.
taskIdtasksSingle-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/workflow-state/references/phase-transitions.mdQuick reference: The → transition requires guard — all must be in workflow state.
delegatereviewall-tasks-completetasks[].status"complete"Before transitioning to review: You MUST first update all task statuses tovia"complete"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.exarchos_workflow set
Worktree-Bearing Tasks: Auto-Detour to merge-pending
merge-pendingWhen a event carries a worktree association ( or ), the HSM auto-transitions through before reaching . The projection surfaces a verb (idempotency-keyed by ) so a runtime that consumes will dispatch the merge automatically.
task.completeddata.worktreedata.worktreePathfeature/merge-pendingreviewnext_actionsmerge_orchestrate${streamId}:merge_orchestrate:${taskId}next_actionsThe merge lands the subagent's branch on the integration branch via a local with a recorded rollback SHA — see . The HSM exits back to once the merge terminates ( / / ), at which point either re-enters for the next worktree-bearing task or transitions on to when all delegation is complete.
git merge@skills/merge-orchestrator/SKILL.mdmerge-pendingdelegatecompletedrolled-backaborteddelegatemerge-pendingreviewThis detour is invisible to the delegation skill itself — the all-tasks-complete guard still gates the transition. The merge-pending substate just sits between task completion and the next dispatch decision.
delegate → reviewTask Status Values
| Status | When to use |
|---|---|
| Task not yet started |
| Task actively being worked on |
| Task finished successfully |
| Task encountered an error (requires fix cycle) |
Schema Discovery
Use for
parameter schemas and
for phase transitions, guards, and playbook guidance. Use
for orchestrate action schemas.
exarchos_workflow({ action: "describe", actions: ["set", "init"] })exarchos_workflow({ action: "describe", playbook: "feature" })exarchos_orchestrate({ action: "describe", actions: ["check_tdd_compliance", "task_complete"] })When integration advances mid-wave
Runbook for recovering when a subagent worktree's branch has diverged from the
integration branch. Triggered by ancestry preflight: the
failure message links here verbatim and includes the manual
command. Auto-rebase is not wired today (tracked in #1119) — operators
must drive recovery by hand.
merge_orchestrategit rebaseSymptom
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: skills-src/delegation/SKILL.md#when-integration-advances-mid-waveThis 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
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 is clean.
git status-
Capture the rollback SHA before doing anything destructive:bash
git rev-parse <feature-branch> > /tmp/rollback.shaKeep this until the merge has been verified. If anything goes wrong,on the feature branch restores the pre-rebase state. The filename is intentionally branch-name-free so slash-delimited branches likegit reset --hard "$(cat /tmp/rollback.sha)"don't break the path with embeddedfeature/dr-6characters./ -
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 passblindly; that drops the subagent's work.--strategy-option=theirs -
Re-run ancestry preflight from the main worktree:typescript
exarchos_orchestrate({ action: "merge_orchestrate", featureId: "<featureId>", taskId: "<taskId>", })The preflight should now pass. Proceed with the orchestrator's normal merge flow.
Rollback procedure
If the rebase produces conflicts you cannot resolve safely, or the merge
still fails after rebase:
-
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)" -
Mark the taskin 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.
failed -
Record the incident by emitting aevent with
merge.abortedand the failing branch's pre-rebase SHA so the convergence view captures the rollback.reason: "ancestry-rebase-conflict"
Why no auto-rebase yet
Auto-rebase is deferred to issue #1119. 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):
- Verify all in workflow state
tasks[].status === "complete" - Update state: with
exarchos_workflow setphase: "review" - Invoke:
[Invoke the exarchos:review skill with args: <plan-path>]
This is NOT a human checkpoint — the workflow continues autonomously.
References
| Document | Purpose |
|---|---|
| Full prompt template for implementation tasks |
| Fix agent prompt with adversarial verification posture |
| Complete delegation trace with recovery path (R1) |
| Common rationalizations and counter-arguments (R2) |
| Parallel grouping and model selection |
| Arrange/Act/Assert, naming, mocking conventions |
| Property-based testing patterns |
| Detailed fix-mode process |
| State patterns and benchmark labeling |
| Common failure modes and resolutions |
| Adaptive team composition |
| Cross-platform step-by-step delegation reference |
| Worktree isolation rules |