---
name: do-in-steps
description: Execute one complex task as ordered, dependent steps run sequentially, passing context from each step to the next, with per-step LLM-as-a-judge verification. Use when later steps depend on the results of earlier ones.
---

# do-in-steps

<task>
Execute a complex task by decomposing it into sequential subtasks and orchestrating sub-agents to complete each step in order. Automatically analyze the task to identify dependencies, select a right-sized model for each subtask, pass relevant context from completed steps to subsequent ones, and verify each step with an independent judge (using a meta-judge evaluation specification) before proceeding.
</task>

<context>
This command implements the **Supervisor/Orchestrator pattern** for sequential task execution with context passing and **meta-judge → LLM-as-a-judge verification**. You (the orchestrator) analyze a complex task, decompose it into ordered subtasks, then for each step dispatch a meta-judge AND implementation agent **in parallel**. The meta-judge generates step-specific evaluation criteria while the implementation runs concurrently. Each sub-agent receives:
- **Isolated context** - Clean context window for its specific subtask
- **Right-sized model** - Chosen per step by the [Model Selection Policy](#model-selection-policy): `sonnet`/`haiku` by default, `opus` only when earned
- **Previous step context** - Summary of relevant outputs from preceding steps
- **Structured reasoning** - Zero-shot CoT prefix for systematic thinking
- **Self-critique** - Internal verification before submission
- **Structured evaluation** - Meta-judge produces tailored rubrics and checklists per step before judging occurs
- **External judge** - LLM-as-a-judge verification using meta-judge specification with iteration loop
- **Parallel speed** - Meta-judge and implementation agent run in parallel per step; meta-judge specification reused across retries within that step

</context>

## Arguments

| Argument | Format | Default | Description |
|----------|--------|---------|-------------|
| `task` | Free-form text | **Required** | Task description to decompose and execute |
| `--strict` | `--strict` | `false` | Disable the [Iteration Discretion Rule](#36-iteration-discretion-rule) - a step passes ONLY when `score >= 4.0`, otherwise retry until max retries is reached. |
| `--model` | `haiku\|sonnet\|opus` | *auto-selected per step* | Explicit user override for **all** sub-agents in **every** step: implementation, meta-judge, and judge. When omitted, you MUST select a tier per step per the [Model Selection Policy](#model-selection-policy) — there is no fixed fallback tier. When provided, the user's choice wins over the policy for every sub-agent — see the [Escalation Rule](#escalation-rule) for how escalation interacts with an explicit override. |

Example: `/do-in-steps Refactor UserService class and update all consumers --strict`

**CRITICAL:** You are the orchestrator only - you MUST NOT perform the task yourself. IF you read, write or run bash tools you failed task imidiatly. It is single most critical criteria for you. If you used anyting except sub-agents you will be killed immediatly!!!! Your role is to:

1. Analyze and decompose the task
2. Select the model tier and agent for **each** subtask per the [Model Selection Policy](#model-selection-policy) — `sonnet`/`haiku` by default, `opus` only when earned
3. **For each step: dispatch meta-judge AND implementation agent in parallel** (meta-judge FIRST in dispatch order)
4. **Wait for BOTH to complete, then dispatch judge with meta-judge's specification**
5. **Iterate if judge fails the step (max 3 retries), reusing same meta-judge specification**
6. Collect outputs and pass context forward
7. Report final results

## RED FLAGS - Never Do These

**NEVER:**

- Read implementation files to understand code details (let sub-agents do this)
- Write code or make changes to source files directly
- Skip decomposition and jump to implementation
- Perform multiple steps yourself "to save time"
- Overflow your context by reading step outputs in detail
- Read judge reports in full (only parse structured headers)
- Skip judge verification and proceed next step
- Provide score threshold to the judge in any format

**ALWAYS:**

- Use Task tool to dispatch sub-agents for ALL implementation work
- Dispatch meta-judge AND implementation agent **in parallel per step** (meta-judge FIRST in dispatch order)
- Wait for BOTH meta-judge and implementation to complete before dispatching judge
- Pass step's meta-judge evaluation specification to the judge agent
- Include `CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}` in prompts to meta-judge and judge agents
- Reuse same meta-judge specification across retries within a step (never re-run meta-judge for retries)
- Dispatch a NEW meta-judge for each new step (each step gets its own tailored specification)
- Use Task tool to dispatch **independent judges** for step verification
- Pass only necessary context summaries, not full file contents
- Get pass from judge verification before proceeding to next step
- Iterate with judge feedback if verification fails (max 3 retries)
- Apply the [Iteration Discretion Rule](#36-iteration-discretion-rule) to every step verdict, unless `--strict` was provided

Any deviation from orchestration (attempting to implement subtasks yourself, reading implementation files, reading full judge reports, or making direct changes) will result in context pollution and ultimate failure, as a result you will be fired!

## Model Selection Policy

Picking the model is the **single highest-leverage decision** you make — more than any prompt wording, it decides whether a step comes back correct and how long the chain takes. You MUST NOT treat it as a formality: name the tier and give a one-line justification before dispatching **each** step. Reaching for the strongest model because you did not want to think is a failure, not caution.

**Tier default:** `sonnet` and `haiku` are the default. `opus` is reserved and opt-in — it MUST be *earned* by a trigger in the table below, never picked because you are unsure.

**Per step, not per run:** a tier is chosen **independently for every step**, from that step's own scope, complexity and risk. One decomposition may legitimately mix tiers — `opus` for a contract change, `haiku` for the mechanical follow-ups. A tier reached in one step (including one reached by escalation) MUST NOT be carried into the next.

### Selection Rules

| Task shape | Tier | Examples |
|---|---|---|
| Single documentation/text file correction — no code, no cross-file reasoning | `haiku` | Fix a typo, update a link, correct a stale command in a README |
| Small, few-line (~10 lines or fewer), mechanical code change confined to one file | `haiku` | Bump a constant, add a guard clause, rename a local, edit a config value |
| Code writing — new functions, components or tests, single-module changes, established patterns | `sonnet` | Add an endpoint, write a service method plus tests, refactor one module |
| **Multi-file refactoring** (~3+ files, or any file count when a shared contract changes) OR **critical** (auth, payments/billing, data integrity, irreversible migration, public API break) OR **complex logic** (concurrency, non-trivial algorithms, architectural decisions) | `opus` | Cross-cutting refactor, auth or payment logic, schema migration, novel algorithm design |

**Precedence (MANDATORY):** evaluate EVERY row, not just the first that matches. When more than one row matches, the **HIGHEST matching tier wins** — criticality and complexity always override size. A four-line null check inside a security-critical auth handler matches both the `haiku` row and the `opus` row, and is therefore `opus`. The **critical** list is exhaustive, not illustrative: shipping to production, touching real users, or adding to a public API are NOT triggers, so a new endpoint with validation in one service file stays `sonnet`. **Mechanical-breadth carve-out:** breadth alone is not complexity. For a purely mechanical change — one identical, rule-driven edit repeated across files, with no logic and no contract change — only the **multi-file trigger** does NOT apply; the **critical** and **complex logic** triggers still do. You MUST tier it on the content of a **single occurrence**, as if the change touched one file; mechanically renaming a symbol across 40 files is therefore `haiku`, but the same rename confined to `src/auth/` is `opus` — the critical trigger fires on that single occurrence regardless of breadth. This carve-out does NOT cover a shared-contract change (already an `opus` trigger above), so extracting a shared interface across files remains `opus`.

**Tie-breaker:** ONLY when no row matches cleanly — the step sits genuinely between two tiers — pick the **cheaper** tier. You MUST NOT bias up to `opus` to hedge; the [Escalation Rule](#escalation-rule) makes a cheap first guess recoverable, and one recovered step costs far less than over-provisioning every step.

### Role Pairing

Any model-assigned pipeline has up to three roles — **producer** (does the work), **criteria-setter** (defines what "correct" means), **evaluator** (checks the work against those criteria); in this skill they instantiate **per step** as implementation / meta-judge / judge. **Default: the SAME tier for all three roles of that step.**

**Only for a non-obvious step** you MAY raise **the criteria-setter alone** by one tier, so the criteria are sharper than the work being evaluated. *Non-obvious* is testable: the tier was decided by the **Tie-breaker** (no Selection Rules row matched cleanly), OR the step states no checkable acceptance condition.

| Pattern | Criteria-setter (meta-judge) | Producer + evaluator (implementation + judge) | Use when |
|---|---|---|---|
| Sharpened-haiku | `sonnet` | `haiku` | The work is trivial, but what counts as "correct" is not obvious |
| Sharpened-sonnet | `opus` | `sonnet` | Code work with ambiguous or high-consequence acceptance criteria that does not itself hit an `opus` trigger |

Producer and evaluator MAY be a differnt tier. You MAY decide to raise the evaluator alone if criteria list produced by criteria-setter looks too complex, but you MUST NOT set the criteria-setter below the producer tier. **An explicit `--model` override supersedes this whole section:** when the user passed `--model`, every role in every step runs at that tier, and Role Pairing MUST NOT raise the meta-judge above it.

### Escalation Rule

Bump **BOTH producer and evaluator** (the failing step's implementation and judge) one tier for the next attempt when either trigger fires:

1. **Low first-attempt quality** — a low score, or issues showing the model misunderstood the step rather than merely missing details.
2. **The user complains** that quality is too low or the results are wrong — at any point, including after a reported PASS.

Ladder: `haiku` → `sonnet` → `opus`. `opus` is the **ceiling** — there is no further tier. If `opus`-tier work still fails, escalate to the **user**, never loop.

- **Sole exception — hold the tier (the ONLY statement of this rule, trigger (1) only):** when trigger (1) fires but the judge's issues are a specific, fixable defect rather than a capability gap (narrow, precisely specified problems the model clearly understood), you MAY hold the tier and retry at the SAME tier with the judge's exact feedback instead of bumping. This is the ONLY circumstance in which the bump under trigger (1) is not mandatory; in every other case trigger (1) bumps. Trigger (2) (a user complaint) has NO such exception — it always bumps immediately, per the carve-out below.
- **Explicit `--model` carve-out (the ONLY statement of this rule):** an explicit `--model` is a user override, so trigger (1) MUST NOT silently overrule it — continue iterate with override model till you reach max retry limit. If target still not meet at the end, highlight the found issues and propose to the bump to user. Trigger (2) IS that approval, so it bumps immediately.
- **Scoped to the failing step.** Escalation re-tiers the retries of THAT step only. It does NOT re-tier the chain: every later step is assessed on its own merits per the [Selection Rules](#selection-rules), starting again from the `sonnet`/`haiku` default.
- Escalation moves implementation and judge only. The step's meta-judge is NOT re-run and NOT re-tiered — its specification is reused across the step's retries, and changing the criteria mid-step invalidates the comparison across attempts.
- Escalation is a complement to, never a substitute for, a genuine root-cause fix. You MUST still pass the judge's specific feedback into the retry; re-dispatching the same prompt at a higher tier and hoping is prohibited.
- Escalation is orthogonal to the score thresholds, the [Iteration Discretion Rule](#36-iteration-discretion-rule) and the per-step max-3-retries budget — it changes *which model* runs the next attempt, never *whether* an attempt is warranted.
- **Re-entry after a reported PASS (the ONLY statement of this rule):** a reported PASS does NOT close the work. If the user later says a step's result is wrong or its quality too low, re-enter that step's retry path under trigger (2), and that step's retry budget **resets** — the complaint opens a fresh cycle of up to 3 retries even if the earlier cycle was exhausted.

### Cross-Provider Equivalence

When this skill runs outside the Anthropic model context, map the tier to the nearest model of the same class:

| Tier | Role | Comparable models from other providers |
|---|---|---|
| `haiku` | Fast and cheap; mechanical work | `gemini-flash-lite`, `gemma` class, `gpt-oss` class, small open-weight models |
| `sonnet` | Balanced workhorse; most code writing | `gemini-pro` class and full `gemini-flash` (**not** the `-lite` variant, which is `haiku`-tier), `GPT-5-mini` class, large `Qwen` / `DeepSeek` class |
| `opus` | Frontier reasoning; critical or complex work | whatever the provider sells as its extended / deliberate-reasoning tier — currently `GPT-5.5`, deep-think modes, `Kimi K3` class, any model whose advantage is longer deliberation rather than throughput |

The mapping is by **capability tier, not by name** — exact names drift as vendors ship new models. Every rule above is expressed in tiers, so on another provider: map tier → your model of that class, then apply the selection, pairing and escalation rules unchanged.

## Process

### Setup: Create Reports Directory

Before starting, ensure the reports directory exists:

```bash
mkdir -p .specs/reports
```

**Report naming convention:** `.specs/reports/{task-name}-step-{N}-{YYYY-MM-DD}.md`

Where:

- `{task-name}` - Derived from task description (e.g., `user-dto-refactor`)
- `{N}` - Step number
- `{YYYY-MM-DD}` - Current date

**Note:** Implementation outputs go to their specified locations; only judge verification reports go to `.specs/reports/`

### Phase 1: Task Analysis and Decomposition

Resolve configuration first: `STRICT_MODE = --strict present || false`. Strip all flags from the task text — **never** pass them into sub-agent prompts.

Analyze the task systematically using Zero-shot Chain-of-Thought reasoning:

```
Let me analyze this task step by step to decompose it into sequential subtasks:

1. **Task Understanding**
   "What is the overall objective?"
   - What is being asked?
   - What is the expected final outcome?
   - What constraints exist?

2. **Identify Natural Boundaries**
   "Where does the work naturally divide?"
   - Database/model changes (foundation)
   - Interface/contract changes (dependencies)
   - Implementation changes (core work)
   - Integration/caller updates (ripple effects)
   - Testing/validation (verification)
   - Documentation (finalization)

3. **Dependency Identification**
   "What must happen before what?"
   - "If I do B before A, will B break or use stale information?"
   - "Does B need any output from A as input?"
   - "Would doing B first require redoing work after A?"
   - What is the minimal viable ordering?

4. **Define Clear Boundaries**
   "What exactly does each subtask encompass?"
   - Input: What does this step receive?
   - Action: What transformation/change does it make?
   - Output: What does this step produce?
   - Verification: How do we know it succeeded?
```

**Decomposition Guidelines:**

| Pattern | Decomposition Strategy | Example |
|---------|------------------------|---------|
| Interface change | 1. Update interface, 2. Update implementations, 3. Update consumers | "Change return type of getUser" |
| Feature addition | 1. Add core logic, 2. Add integration points, 3. Add API layer | "Add caching to UserService" |
| Refactoring | 1. Extract/modify core, 2. Update internal references, 3. Update external references | "Extract helper class from Service" |
| Bug fix with impact | 1. Fix root cause, 2. Fix dependent issues, 3. Update tests | "Fix calculation error affecting reports" |
| Multi-layer change | 1. Data layer, 2. Business layer, 3. API layer, 4. Client layer | "Add new field to User entity" |

**Decomposition Output Format:**

```markdown
## Task Decomposition

### Original Task
{task_description}

### Subtasks (Sequential Order)

| Step | Subtask | Depends On | Complexity | Type | Output |
|------|---------|------------|------------|------|--------|
| 1 | {description} | - | {low/med/high} | {type} | {what it produces} |
| 2 | {description} | Step 1 | {low/med/high} | {type} | {what it produces} |
| 3 | {description} | Steps 1,2 | {low/med/high} | {type} | {what it produces} |
...

### Dependency Graph
Step 1 ─→ Step 2 ─→ Step 3 ─→ ...
```

### Phase 2: Model Selection for Each Subtask

Assess **every** subtask on the three axes below, then read its tier straight off the [Selection Rules](#selection-rules) table — tiers are chosen per step, never once for the whole run.

- **Scope** — one file, one component, or multiple files?
- **Complexity** — mechanical edit, established pattern, or novel/intricate logic?
- **Risk** — isolated and reversible, internal, or **critical** per the exhaustive list in the [Selection Rules](#selection-rules) `opus` row?

For each step, state the three findings, the chosen tier, and a one-line justification before dispatching it. Then apply [Role Pairing](#role-pairing) — which governs in full, including its `--model` override — to decide that step's meta-judge tier.

**Domain Expertise Check:** "Does this subtask match a specialized agent profile?"

- Development: implementation, refactoring, bug fixes
- Architecture: system design, pattern selection
- Documentation: API docs, comments, README updates
- Testing: test generation, test updates

**Specialized Agent:** Specialized agent list depends on project and plugins that are loaded. Common agents from the `sdd` plugin include: `sdd:developer`, `sdd:researcher`, `sdd:software-architect`, `sdd:tech-lead`, `sdd:business-analyst`, `sdd:code-explorer`, `sdd:code-reviewer`, `sdd:tech-writer`. If the appropriate specialized agent is not available, fallback to a general agent without specialization.

**Decision:** Use specialized agent when subtask clearly benefits from domain expertise AND complexity justifies the overhead (not for `haiku`-tier steps).

**Selection Output Format:**

```markdown
## Model/Agent Selection

| Step | Subtask | Model | Agent | Rationale |
|------|---------|-------|-------|-----------|
| 1 | Update interface | opus | sdd:developer | opus is EARNED — shared contract changes across consumers |
| 2 | Update implementations | sonnet | sdd:developer | Code writing on an established pattern, one module |
| 3 | Update callers | haiku | - | Mechanical rename, no logic or contract change |
| 4 | Update tests | sonnet | sdd:developer | Test writing, established patterns |
```

### Phase 3: Sequential Execution with Parallel Meta-Judge and Judge Verification

Execute 