Subagents orchestration guide

From shinpr/claude-code-workflows · View interactive version

Subagents orchestration guide is an AI agent skill from the GitHub repository shinpr/claude-code-workflows. Guides subagent coordination through implementation workflows. Use when orchestrating multiple agents, managing workflow phases, or determining autonomous execution mode.

How to use this skill

Skill file

Subagents Orchestration Guide

Role: The Orchestrator

Explicit User Instruction: The user explicitly instructs and authorizes every subagent call named in the invoked recipe. Execute each applicable call when its prerequisites are met.

The orchestrator owns workflow decisions, routing, progress management, user interaction, the investigation and validation needed for those decisions, and explicitly assigned mechanical operations, using any available tool. Named specialists own explicitly assigned investigation and semantic deliverable creation or modification; invoke them before producing or changing code, tests, configuration, documents, task files, or other artifacts.

Workflow Subagent Context — Mandatory

This workflow's specialists are already self-contained through their agent definitions, loaded skills, and referenced artifacts. The smallest valid Agent prompt is the most reliable: the complete prompt is the exhaustive set of canonical field: value entries declared by the specialist's input contract. Preserve each value's meaning from its authoritative source and apply the canonical serialization declared for that field. This output discipline supersedes general-purpose prompt self-containment because added context competes with the specialist's loaded process and can prevent coherent completion.

This section governs the orchestrator's Agent prompt. Each specialist's agent definition owns its input acceptance and resolves its operational inputs. The orchestrator supplies the canonical contract entries unchanged.

First Action Rule

When receiving a new full-cycle task, retain the user's complete wording in the orchestrator and invoke requirement-analyzer with the Requirement Evidence Handoff below. Compare its scope evidence and cost evidence against that retained wording to judge requirement convergence and Structural Scale in the orchestrator. Dedicated design recipes use their own codebase-scoped bootstrap.

Requirement Evidence Handoff: pass requirements as the shortest verbatim user wording of the problem or desired user-visible or operational outcome, using an orchestrator working summary only when no such wording exists; pass context as the shortest user reason needed to interpret that outcome plus an environmental constraint only when it is essential. Keep the remaining requirement detail in the orchestrator for comparison after the result returns. The handoff supplies an evidence target; the retained wording supplies product requirements and exclusions. Classify evaluation requests, speculative ideas, and prescribed mechanisms from that retained wording rather than from the returned evidence, because a classification produced by an analyzer is inference presented in the same object as observation.

Build and judge the convergence record in the orchestrator with the requirement-convergence skill. Run its hearing protocol at the requirements stop point. Re-invoke requirement-analyzer only when an answer changes the repository analysis target or scope evidence; otherwise update the convergence and Structural Scale judgment directly.

Small Evidence Gate

Classify Small when scopeEvidence.executionRoute.status is evident, that route remains inside one responsibility, and every costEvidence.unknowns item is proven invariant to boundaries, persistence/shared contracts, and potentially durable choices. Positive route evidence identifies the supported route; an empty alternatives list supplies supporting context. When the requirements remain unresolved at this gate, invoke codebase-analyzer before assigning Structural Scale. Its result supports Small when analysisScope and currentPath establish one repository-supported route inside one responsibility and every candidateDecisionPoints, unknowns, and limitations item is proven classification-invariant. Other observed boundaries and outcomes route Medium or Large. Reuse that result as the Medium design analysis when the requirements remain unchanged. For Large, treat it as routing evidence, create and approve the PRD, then run the design analysis against the approved prd_path. ADR qualification occurs after codebase-analyzer returns credible technical options and the scope has passed the requirements stop.

Requirement Change Detection During Flow

After an analysis result returns, compare each user-facing or operational responsibility it exposes against the scope in the convergence record. When either leaving that responsibility as it is or changing it would alter the outcome or an exclusion, return it through the requirements gate before dependent design work; a technical choice about how to satisfy that scope continues through the design owners instead.

Treat a proposed change to the outcome, desired-future requirements, or non-goals as a requirement change. When evidence shows those value boundaries cannot all remain true, stop at the requirements gate and ask the user which boundary changes. A technical design or implementation correction that preserves them is not a requirement change, including removal of a technical choice that works but is no longer necessary; passage through an earlier phase does not establish that its means remain necessary. Update each affected technical artifact and resume from the earliest affected technical gate while preserving outputs that remain valid.

Requirement reopening after codebase analysis: When the first codebase-analyzer result after requirement confirmation shows existing behavior that serves a requirement's need and falls short only of extra behavior that requirement specifies, whichever field reports it, present it with its evidence and cost effect at one requirements stop before UI Spec, ADR, or Design Doc work, and let the user keep or change the requirement. The user selects requirements before any code is read, and every later phase builds and reviews against them without questioning them, so this is the one point where repository evidence can reduce them; judging such evidence as ruled out by the requirement removes the user's only chance to weigh it. Apply the answer through Handling Requirement Changes and continue; later analyses do not reopen requirements this way.

Orchestration Principles

Outcome Stewardship

The orchestrator steers the workflow toward the smallest sufficient set of deliverables and changes that achieves the outcome while satisfying binding constraints and required verification. Evaluate specialist proposals against that boundary before routing work.

Preserve specialist evidence ownership and approved artifacts as semantic sources so the workflow converges on the MVP; orchestrator-authored investigation targets, restatements, or follow-on instructions bias evidence and create unreviewed scope.

Delegation Boundary: What vs How

Pass the governing requirement source and the specialist's expected action. Investigation specialists discover affected paths and responsibility boundaries; artifact and execution specialists receive the paths or scope they must act on. Each specialist determines its execution method from repository evidence and applicable artifacts.

Decision precedence for routing:

  1. User instructions (explicit requests or constraints)
  2. Task files and design artifacts (Design Doc, PRD, work plan)
  3. Objective repo state (git status, file system, project configuration)
  4. Specialist judgment

Scope source classification:

Before routing specialist output, validate each claim that controls the next workflow decision against the highest applicable source above. Route according to that source; specialist judgment governs decisions left unresolved by items 1-3.

Specialist Result Acceptance

Each specialist's agent definition owns its canonical result shape. As receiver, the orchestrator chooses the next action from the result's semantic content, governing sources, produced artifacts, and repository state. Semantically equivalent labels, omitted optional fields, and absent transition labels remain acceptable when those sources support the next action. Resolve operational gaps through inspection or repository-local reversible judgment and continue unaffected work.

Continue incomplete implementation while repository evidence supplies an action that advances the outcome. When current authority and evidence cannot advance required implementation, finish with an incomplete report containing the remaining work and observed evidence. Treat a proof-only limitation differently: perform recovery available within the current authority and scope, run every available check, retain the complete limitation result, establish the recipe's normal reversible task boundary, and continue remaining tasks. Retry retained limitations before final verification and report only those that remain. Claim only the proof actually observed. User interaction is reserved for choosing a change to value boundaries or authorizing an irreversible external action.

Review Resolution

Apply references/review-resolution.md to actionable deliverable-review findings. The orchestrator decides dispositions, validates results, and routes work; the named specialist produces or changes deliverables.

Lite Mode

When the user requests Lite Mode (light mode), read references/lite-mode.md before the next workflow decision and apply it until the user withdraws the request.

Task Assignment with Responsibility Separation

| Specialist | Responsibility |

|---|---|

| task-executor | Implement scoped work and tests, and confirm added tests pass; leave whole-repository quality assurance to the quality-fixer. |

| quality-fixer | Run overall checks, fix quality failures, and return pass only after completing those fixes. |

For frontend work, substitute task-executor-frontend and quality-fixer-frontend; in fullstack work, select them by task layer.

Constraints Between Subagents

Workflow coordination is flat: the orchestrator issues every specialist call and receives every result. Specialist definitions keep Agent outside their tool sets.

Explicit Stop Points

Apply these approval stops when producing or materially revising an artifact in the current workflow. At each stop the user approves an action — completing the current phase, or authorizing implementation — rather than ratifying the artifact's technical content. Authority over required outcomes and explicit constraints comes from the user's own wording in the convergence record, not from passing a stop. A user instruction to proceed to a later phase accepts the preceding phases and authorizes entry into that phase; continue from that entry point rather than rechecking earlier review or approval records. In particular, a build instruction with an existing Work Plan grants batch approval for task materialization and implementation.

Before presenting an artifact at an approval stop, read its current version and base the presentation on that content. At the ADR batch and Design stops, state each quality level the artifacts selected where the requirements left it unset, so the user can raise one before dependent work. At the Design stop, also read the current PRD when present and state the user-visible outcome from it or the requirement context alongside major internal responsibility, contract, or refactoring changes, so the user can judge whether to proceed.

| Phase | Stop Point | User Action Required |

|-------|------------|---------------------|

| Requirements | After requirement-analyzer completes | Answer the requirement-convergence hearing, confirm the recorded requirements match their intent, then approve proceeding |

| PRD | After document-reviewer completes PRD review | Approve completing the PRD phase and proceeding |

| Requirement reopening | After the first codebase-analyzer result when it shows existing behavior that falls short of a requirement only by extra behavior that requirement specifies | Keep or change each affected requirement |

| UI Spec | After document-reviewer completes an applicable UI Spec review | Approve completing the UI Spec phase and proceeding |

| ADR batch | After document-reviewer reviews the complete qualifying batch | Approve completing the ADR batch phase and proceeding |

| Design | After design-sync completes consistency verification | Approve completing the design phase and proceeding |

| Work Plan | After work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) completes | Batch approval: authorize implementation within this outcome |

After applicable implementation authorization: User confirmation at the Requirements stop for Small, or Medium/Large batch approval, starts autonomous execution, which continues until completion or an escalation condition is reached.

Scale Determination and Document Requirements

| Scale | Structural condition | PRD | ADR batch | Design Doc | Work Plan |

|-------|----------------------|-----|-----------|------------|-----------|

| Small | One outcome has one evident repository-supported implementation inside one responsibility and no unresolved durable choice | Update when applicable | None | None | None |

| Medium | One outcome coordinates across a boundary or requires investigation of a potentially durable choice | Update when applicable | When one or more decision points pass both filters | Required | Required |

| Large | Independently valuable outcomes require separate design decisions | Required | When one or more decision points pass both filters | Required | Required |

File count supports the judgment but does not determine it. A qualifying durable decision sets the floor at Medium. Apply the Choice filter before the Durability filter after repository option evidence exists.

How to Call Subagents

Execution Method

Each subagent invocation is a fresh Agent tool call, isolating each phase's context; a SendMessage resume reuses the prior agent's context and breaks that isolation. Each call uses:

Orchestrator Execution Boundary

Tool choice does not define responsibility: the orchestrator may use any available tool for its owned work, while named specialists perform semantic deliverable creation or modification; the orchestrator writes only for mechanical operations explicitly assigned by the active workflow.

Prompt Construction Rule

The active workflow's input contract is already optimized to provide the specialist with the context for its owned result. The orchestrator preserves that optimization by passing its named fields in their declared forms; the prompt consists of those fields and values, while artifact paths and unchanged specialist outputs carry their own semantics.

Handling Requirement Changes

Use create mode for initial documents. For requirement-driven revisions, invoke the owning document specialist in update mode and add history:

Basic Flow: Planning and Implementation

Planning flow (per scale)

| Scale | Planning flow |

|-------|---------------|

| Large | requirement-analyzer → PRD → PRD review → codebase-analyzer → requirement reopening when applicable → conditional external/UI analysis and UI Spec → optional ADR batch/review/approval → Design Doc → code-verifier/Review Resolution → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review → task-decomposer |

| Medium | requirement-analyzer → codebase-analyzer → requirement reopening when applicable → conditional external/UI analysis and UI Spec → optional ADR batch/review/approval → Design Doc → code-verifier/Review Resolution → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review → task-decomposer |

| Small | requirement-analyzer → conditional codebase-analyzer when the Small evidence gate is unresolved → direct task execution (no Work Plan) |

The requirement-convergence and external-resource hearings run in the orchestrator. In an implementation workflow, confirmation at the Requirements stop authorizes the Small direct scope. Medium/Large implementation begins after Work Plan batch approval.

Rules:

Start the applicable Structural Scale flow at the user-requested phase. Before reporting completion, verify the artifacts and results required by every applicable phase from that entry point through completion, and complete any missing work within those phases. Return to an earlier phase when a material change invalidates its outcome, using Handling Requirement Changes.

Autonomous Execution Mode

Pre-Execution Gate

Verify commit capability before autonomous mode. Let task-executor and quality-fixer recover available test or quality tooling and retain an exact proof limitation for the remainder; escalate a known authority-bound prerequisite before entry.

User confirmation at the Requirements stop for Small, or Medium/Large batch approval, authorizes task-executor implementation and quality-fixer corrections until completion or escalation.

Autonomous Execution Summary

For Medium/Large, after batch approval, including an existing-plan build instruction, autonomously execute the following processes through completion or an escalation condition:

graph TD
    START[Batch approval] --> TD[task-decomposer]
    TD --> CYCLE[Per-task 4-step cycle, including commit]
    CYCLE -->|remaining tasks| CYCLE
    CYCLE -->|all tasks complete| REVIEW[Initial reviewer set or evidence-required reruns]
    CYCLE -->|recoverable or structurally incomplete result| CYCLE
    CYCLE -->|value-boundary choice or irreversible authorization| USER[Escalate or re-analyze]
    REVIEW -->|passed| REPORT[Completion report]
    REVIEW -->|actionable findings| RR[Review Resolution]
    RR -->|apply| FIX[owning author or executor + applicable verification]
    FIX --> REVIEW
    RR -->|all decline| REPORT

For Small, execute one direct-scope 4-step cycle. Complete after pass, or retry a retained verification_incomplete result once and complete with its exact repeated limitation. Small has no task decomposition, document-dependent post-implementation review, or task-file cleanup.

Post-Implementation Review Units (Medium/Large)

Review a Medium change with one code-reviewer. A Large change is more than one code-reviewer can read in full; partition it into units of Work Plan tasks. A unit holds a consuming task (one delivering a screen, route, command, or job) together with the tasks it depends on through Depends on, so a contract's producer, its consumer, and every test proving their behavior are reviewed together; tasks that several units depend on form one shared unit. Each completed task belongs to one unit, whose implementationFiles are the files changed by its tasks' commits. Run at most 3 reviewer calls concurrently. security-reviewer reviews the complete change once. The unit reviewer that reported a finding owns it under the fix-cycle and re-run rules.

Post-Implementation Review Status Routing (Medium/Large)

| Reviewer | Complete: empty finding set | Enter Review Resolution | Blocked |

|----------|---------------------------|-------------------------|---------|

| code-reviewer | verdict is pass | verdict is needs-improvement or needs-redesign | verdict is blocked → Apply Specialist Result Acceptance |

| security-reviewer | status is pass | status is needs_revision | status is blocked → Apply Specialist Result Acceptance |

Reviewer findings are candidates. Create correction work only from the Review Resolution apply set. A reviewer pass records phase passage: it grants no user-held execution authority and does not establish that the reviewed means remain necessary.

Fix-cycle handoff: Apply Review Resolution and invoke each correction owner it selects. For an author-owned technical-artifact correction, invoke the layer-appropriate technical designer in update mode, run the artifact's existing document-reviewer and applicable design-sync gates, then re-run the originating reviewer. For an executor-owned correction, invoke the layer-appropriate executor with its original task_file or direct-scope fields plus correction_findings as the complete apply finding objects verbatim with only their dispositions added, then branch on the executor result through the per-task cycle's step 2, including its conditional integration-test-reviewer path, and run the applicable quality gate. When both owners are required, Review Resolution's author-first re-evaluation controls the order. Carry prior_feedback only to a reviewer or verifier being rechecked. Post-implementation corrections stay uncommitted through this cycle: the reviewers read the current working tree, so run the applicable quality gate and re-run the originating reviewer on the uncommitted changes, and commit the applied corrections once through Commit Boundary Check after the complete review set reaches Review Resolution convergence.

Re-run rule: After an applied post-implementation correction, re-run only the reviewer that owns a corrected finding from its latest result. Retain every other passed reviewer result, including after another reviewer's correction, unless the check below finds that the correction invalidated the evidence that review relied on. Pass the previous complete result, dispositions, and correction diff or paths to the rerun. After Specialist Result Acceptance recovers a blocked review prerequisite, re-run that reviewer. Review Resolution convergence governs acceptance and preserves resolved declines.

After a correction or quality-fixer retry, compare its actual diff against the contracts, behavior, and verification evidence that the passed reviews relied on, whether or not the change stays inside the received findings: a shared contract corrected for one unit's finding can invalidate another unit's pass. Reconcile changes covered by an existing finding through its owner. For other changes that invalidate review evidence, invoke only the applicable code-reviewer or security-reviewer with the original governing documents and the affected implementationFiles, scoped to that diff and its directly affected boundary; omit prior_feedback because this is new changed code, not finding reconciliation. Apply Review Resolution to its findings. Retain unaffected passed results; unchanged output and behavior-neutral formatting require no review. This check does not reopen a passed reviewer merely because another reviewer’s correction touched the same file.

Conditions for Stopping Autonomous Execution

| Trigger | Action |

|---|---|

| Evidence shows the outcome, desired-future requirements, and non-goals cannot all remain true without a user choice | Apply Requirement Change Detection and ask which value boundary changes. |

| An irreversible external action requires authorization | Request authorization at the authority gate. |

| A subagent result uses a semantically equivalent label, omits a non-decision field, or leaves the next action implicit | Derive the next action from its semantic content, governing sources, produced artifacts, and repository state. |

| Required implementation remains incomplete | Continue while repository evidence supplies an advancing action; otherwise finish with an incomplete report and the observed evidence. |

| A subagent reports an environment or execution prerequisite | Recover it within current authority when practical, complete available checks, retain the proof limitation, and continue. Retry it before final verification and include it in the final report only if it remains. |

| A requirement changes | Apply Requirement Change Detection above. After task-decomposer starts, invalidate affected tasks; restart document design only when the requirement change invalidates an approved requirement, contract, data flow, verification strategy, or task boundary. |

| The user stops or interrupts | Stop autonomous execution. |

Task Execution Cycle

Commit Boundary Check

Immediately before a workflow commit:

  1. Use repository state at the commit boundary as the primary evidence and account for every actual change by mapping it to the outcome, a governing source, or a necessary dependency, test, generated artifact, or adjacent maintenance change.
  2. Every required change is ready for the task commit, accidental changes introduced during the task are removed, and existing worktree changes unrelated to the outcome remain intact.
  3. Commit the resulting change set. When repository evidence shows a change would alter the outcome, desired-future requirements, or non-goals, apply Requirement Change Detection before committing it.

For a verification_incomplete commit, append one trailer pair per retained limitation:

Verification-Limitation: <reason>
Verification-Affected: <affected check or command>

Derive the values from the quality-fixer result. Keep the complete result in orchestration state for the current run; the trailers preserve the minimum retry input after continuation.

Per-task cycle:

  1. Execute: record the current HEAD as diffBase, then invoke task-executor with task_file: [path] when one exists; for Small, invoke it with direct_scope as the convergence record's outcome and exclusions, governing_sources, and observable_verification
  2. Branch on executor result:
  1. Quality-fix: invoke quality-fixer with task_file when available; otherwise copy the executor's direct_scope, governing_sources, and observable_verification inputs unchanged, including correction_findings when supplied. Add upstream mutationEvidence and qualityCommand from the caller first or task otherwise
  1. Commit: apply Commit Boundary Check, then compose the message from changeSummary and execute git commit with Bash after pass or verification_incomplete; append the verification trailers for the latter

Before post-implementation verifiers, collect retained verification limitations from orchestration state and the verification trailers on task-boundary commits created by the workflow, then re-invoke the applicable quality-fixer once for each limitation using the same task inputs and its affected check or command. When the retry returns pass, remove that limitation from retained state. Route newly discovered incomplete implementation through the normal cycle, and retain a repeated verification_incomplete result for the final report. Commit any fixes produced by this retry through the same task cycle, then continue post-implementation verification.

Handoff Contracts

HC-01: requirement-analyzer → orchestrator and codebase-analyzer

HC-01b: convergence record → document owner

HC-02: codebase-analyzer → technical-designer

HC-03: technical-designer → code-verifier

HC-03b: applied design-evidence finding → technical-designer

HC-04: code-verifier + codebase-analyzer → document-reviewer

HC-05: code-verifier → next-layer technical-designer (fullstack only)

technical-designer → work-planner

Pass the Design Doc path. Work-planner maps governing sections and ACs to implementation tasks. The Work Plan does not turn missing coverage or missing design content into a user-confirmation item.

HC-06: acceptance-test-generator → work-planner

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.