do-in-steps
Arguments
| Argument |
Format |
Default |
Description |
task |
Free-form text |
Required |
Task description to decompose and execute |
--strict |
--strict |
false |
Disable the 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 — there is no fixed fallback tier. When provided, the user's choice wins over the policy for every sub-agent — see the 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:
- Analyze and decompose the task
- Select the model tier and agent for each subtask per the Model Selection Policy —
sonnet/haiku by default, opus only when earned
- For each step: dispatch meta-judge AND implementation agent in parallel (meta-judge FIRST in dispatch order)
- Wait for BOTH to complete, then dispatch judge with meta-judge's specification
- Iterate if judge fails the step (max 3 retries), reusing same meta-judge specification
- Collect outputs and pass context forward
- 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 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 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:
- Low first-attempt quality — a low score, or issues showing the model misunderstood the step rather than merely missing details.
- 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, 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 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:
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:
## 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 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
opus row?
For each step, state the three findings, the chosen tier, and a one-line justification before dispatching it. Then apply 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:
## 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 subtasks one by one. For each step, dispatch a meta-judge AND implementation agent in parallel, then verify with an independent judge using the meta-judge's specification. Iterate if needed, then pass context forward.
Execution Flow per Step:
┌──────────────────────────────────────────────────────────────────────────────┐
│ Step N │
│ │
│ ┌──────────────┐ │
│ │ Meta-Judge │──┐ (parallel) │
│ │ (Sub-agent) │ │ │
│ └──────────────┘ │ ┌──────────────┐ ┌──────────────────────┐ │
│ ├──▶│ Judge │────▶│ Parse Verdict │ │
│ ┌──────────────┐ │ │ (Sub-agent) │ │ (Orchestrator) │ │
│ │ Implementer │──┘ └──────────────┘ └──────────────────────┘ │
│ │ (Sub-agent) │ │ │
│ └──────────────┘ ▼ │
│ ▲ ┌──────────────────────────────┐ │
│ │ │ PASS (≥4.0)? │ │
│ │ │ ├─ YES → Next Step │ │
│ │ │ ├─ ≥3.0 → Rule 3.6 │ │
│ │ │ └─ NO → Retry? │ │
│ │ │ ├─ <3 retries → Retry │ │
│ │ │ └─ ≥3 retries → Escalate │ │
│ │ └──────────────────────────────┘ │
│ │ │ │
│ └────────────── feedback ────────────────────┘ │
│ (retries reuse same meta-judge spec, no new meta-judge) │
└──────────────────────────────────────────────────────────────────────────────┘
3.1 Context Passing Protocol
After each subtask completes, extract relevant context for subsequent steps:
Context to pass forward:
- Files modified (paths only, not contents)
- Key changes made (summary)
- New interfaces/APIs introduced
- Decisions made that affect later steps
- Warnings or considerations for subsequent steps
Context filtering:
- Pass ONLY information relevant to remaining subtasks
- Do NOT pass implementation details that don't affect later steps
- Keep context summaries concise (max 200 words per step)
Context Size Guideline: If cumulative context exceeds ~500 words, summarize older steps more aggressively. Sub-agents can read files directly if they need details.
Example of Context Accumulation (Concrete):
## Completed Steps Summary
### Step 1: Define UserRepository Interface
- **What was done:** Created `src/repositories/UserRepository.ts` with interface definition
- **Key outputs:**
- Interface: `IUserRepository` with methods: `findById`, `findByEmail`, `create`, `update`, `delete`
- Types: `UserCreateInput`, `UserUpdateInput` in `src/types/user.ts`
- **Relevant for next steps:**
- Implementation must fulfill `IUserRepository` interface
- Use the defined input types for method signatures
### Step 2: Implement UserRepository
- **What was done:** Created `src/repositories/UserRepositoryImpl.ts` implementing `IUserRepository`
- **Key outputs:**
- Class: `UserRepositoryImpl` with all interface methods implemented
- Uses existing database connection from `src/db/connection.ts`
- **Relevant for next steps:**
- Import repository from `src/repositories/UserRepositoryImpl`
- Constructor requires `DatabaseConnection` injection
3.2 Sub-Agent Prompt Construction
For each subtask, construct the prompt with these mandatory components:
3.2.1 Zero-shot Chain-of-Thought Prefix (REQUIRED - MUST BE FIRST)
## Reasoning Approach
Before taking any action, think through this subtask systematically.
Let's approach this step by step:
1. "Let me understand what was done in previous steps..."
- What context am I building on?
- What interfaces/patterns were established?
- What constraints did previous steps introduce?
2. "Let me understand what this step requires..."
- What is the specific objective?
- What are the boundaries of this step?
- What must I NOT change (preserve from previous steps)?
3. "Let me plan my approach..."
- What specific modifications are needed?
- What order should I make them?
- What could go wrong?
4. "Let me verify my approach before implementing..."
- Does my plan achieve the objective?
- Am I consistent with previous steps' changes?
- Is there a simpler way?
Work through each step explicitly before implementing.
3.2.2 Task Body
<task>
{Subtask description}
</task>
<subtask_context>
Step {N} of {total_steps}: {subtask_name}
</subtask_context>
<previous_steps_context>
{Summary of relevant outputs from previous steps - ONLY if this is not the first step}
- Step 1: {what was done, key files modified, relevant decisions}
- Step 2: {what was done, key files modified, relevant decisions}
...
</previous_steps_context>
<constraints>
- Focus ONLY on this specific subtask
- Build upon (do not undo) changes from previous steps
- Follow existing code patterns and conventions
- Produce output that subsequent steps can build upon
- Critical: you not allowed to use any mutation git commands, including, but not limited: commit, stash, push, checkout, reset, revert, etc. Except cases when task EXPLICITLY allows or requires it. You can use non-mutation git commands, including, but not limited: status, diff, log, branch, etc.
</constraints>
<input>
{What this subtask receives - files, context, dependencies}
</input>
<output>
{Expected deliverable - modified files, new files, summary of changes}
CRITICAL: At the end of your work, provide a "Context for Next Steps" section with:
- Files modified (full paths)
- Key changes summary (3-5 bullet points)
- Any decisions that affect later steps
- Warnings or considerations for subsequent steps
</output>
3.2.3 Self-Critique Suffix (REQUIRED - MUST BE LAST)
## Self-Critique Verification (MANDATORY)
Before completing, verify your work integrates properly with previous steps. Do not submit unverified changes.
### Verification Questions
Generate verification questions based on the subtask description and the previous steps context. Examples:
| # | Question | Evidence Required |
|---|----------|-------------------|
| 1 | Does my work build correctly on previous step outputs? | [Specific evidence] |
| 2 | Did I maintain consistency with established patterns/interfaces? | [Specific evidence] |
| 3 | Does my solution address ALL requirements for this step? | [Specific evidence] |
| 4 | Did I stay within my scope (not modifying unrelated code)? | [List any out-of-scope changes] |
| 5 | Is my output ready for the next step to build upon? | [Check against dependency graph] |
### Answer Each Question with Evidence
Examine your solution and provide specific evidence for each question:
[Q1] Previous Step Integration:
- Previous step output: [relevant context received]
- How I built upon it: [specific integration]
- Any conflicts: [resolved or flagged]
[Q2] Pattern Consistency:
- Patterns established: [list]
- How I followed them: [evidence]
- Any deviations: [justified or fixed]
[Q3] Requirement Completeness:
- Required: [what was asked]
- Delivered: [what you did]
- Gap analysis: [any gaps]
[Q4] Scope Adherence:
- In-scope changes: [list]
- Out-of-scope changes: [none, or justified]
[Q5] Output Readiness:
- What later steps need: [based on decomposition]
- What I provided: [specific outputs]
- Completeness: [HIGH/MEDIUM/LOW]
### Revise If Needed
If ANY verification question reveals a gap:
1. **FIX** - Address the specific gap identified
2. **RE-VERIFY** - Confirm the fix resolves the issue
3. **UPDATE** - Update the "Context for Next Steps" section
CRITICAL: Do not submit until ALL verification questions have satisfactory answers.
3.3 Parallel Meta-Judge Dispatch
CRITICAL: For each step, dispatch the meta-judge AND implementation agent in parallel in a single message with two Task tool calls. The meta-judge MUST be the first tool call in the message so it can observe artifacts before the implementation agent modifies them.
Both agents run as foreground agents. Wait for BOTH to complete before proceeding to judge dispatch.
Meta-Judge Prompt (per step):
## Task
Generate an evaluation specification yaml for the following step. You will produce rubrics, checklists, and scoring criteria that a judge agent will use to evaluate the implementation artifact.
CLAUDE_PLUGIN_ROOT=`${CLAUDE_PLUGIN_ROOT}`
## User Prompt
{Original task description from user}
## Step Being Evaluated
Step {N}/{total}: {subtask_name}
{subtask_description}
- Input: {what this step receives}
- Expected output: {what this step should produce}
## Previous Steps Context
{Summary of what previous steps accomplished}
## Artifact Type
{code | documentation | configuration | etc.}
## Instructions
Return only the final evaluation specification YAML in your response.
Dispatch Example
Send BOTH Task tool calls in a single message. Meta-judge first, implementation second:
Message with 2 tool calls:
Tool call 1 (meta-judge):
- description: "Meta-judge Step {N}/{total}: {subtask_name}"
- model: {meta-judge model — the user's `--model` if one was passed; otherwise the same tier as this step's implementation, or one tier up per Role Pairing}
- subagent_type: "sadd:meta-judge"
Tool call 2 (implementation):
- description: "Step {N}/{total}: {subtask_name}"
- model: {implementation model — the user's `--model` if one was passed; otherwise the model selected for this step}
- subagent_type: "{selected agent type}"
Wait for BOTH to return before proceeding to judge dispatch.
3.4 Judge Verification Protocol
After BOTH meta-judge and implementation agent complete, dispatch an independent judge to verify the step using the meta-judge evaluation specification.
CRITICAL: Provide to the judge EXACT meta-judge's evaluation specification YAML, do not skip or add anything, do not modify it in any way, do not shorten or summarize any text in it!
3.4.1 Analyze the Pre-existing Changes Section
Before dispatching the judge for each step, assess whether there are pre-existing changes in the codebase that the judge needs to be aware of. The "Pre-existing Changes" section prevents the judge from confusing prior modifications with the current step's implementation agent's work.
When to include:
- Previous steps' changes from the SAME do-in-steps run (steps 1..N-1 when judging step N) — this is the most common case in sequential execution. When running step N, the judge MUST know about changes from steps 1..N-1 as pre-existing. Each completed step's output (files created/modified, key changes) becomes pre-existing context for subsequent step judges.
- Previous do-in-steps or do-and-judge task runs completed earlier in the same session
- User's manual modifications made before invoking the skill (visible from conversation context or in git)
- Changes from other tools or agents that ran before this task
When to omit:
- This is step 1 with no known prior changes (no earlier session tasks, no user modifications) — omit the section entirely
- On retries within the SAME step, do NOT include the implementation agent's own previous attempt as "pre-existing changes" — those are part of the current step's iteration cycle
Content guidelines:
- Use a high-level summary: task description, list of affected files/modules, general nature of changes (created, modified, deleted)
- Do NOT include code blocks, diffs, or line-level details — keep it concise
- Label each source clearly: "Step 1: {description}", "Step 2: {description}", "User modifications (before current task)", etc.
- If multiple sources of pre-existing changes exist, use separate subsections for each (one per completed step, plus any external sources)
- Leverage the Context Passing Protocol output (section 3.1) — the "Completed Steps Summary" already tracks what each step produced
CRITICAL: avoid reading full codebase or git history, just use high-level git diff/status to determine which files were changed, or use conversation context and completed step summaries to determine pre-existing changes.
Prompt template for step judge:
You are evaluating Step {N}/{total}: {subtask_name} against an evaluation specification produced by the meta judge.
CLAUDE_PLUGIN_ROOT=`${CLAUDE_PLUGIN_ROOT}`
## Original Task
{overall_task_description}
## Step Requirements
{subtask_description}
- Input: {what this step receives}
- Expected output: {what this step should produce}
## Previous Steps Context
{Summary of what previous steps accomplished}
{IF pre-existing changes are known (previous steps, prior tasks, or user modifications), include the following section — otherwise omit entirely}
## Pre-existing Changes (Context Only)
The following changes were made BEFORE the current step's implementation agent started working. They are NOT part of the current step's output. Focus your evaluation on the current step's changes. Only verify pre-existing changed files/logic if they directly relate to the current step's requirements.
### {Source of changes: e.g., "Step 1: {step description}" or "Previous Task: {task description}" or "User modifications (before current task)"}
{High-level summary: what was done, which files/modules were created or modified}
### {Additional source if applicable}
{High-level summary}
{END conditional section}
## Evaluation Specification
```yaml
{meta-judge's evaluation specification YAML}
Implementation Output
{Path to files modified by implementation agent}
{Context for Next Steps section from implementation agent}
Instructions
Follow your full judge process as defined in your agent instructions!
Output
CRITICAL: You must reply with this exact structured evaluation report format in YAML at the START of your response!
CRITICAL: NEVER provide score threshold, in any format, including `threshold_pass` or anything different. Judge MUST not know what threshold for score is, in order to not be biased!!!
**Dispatch:**
Use Task tool:
- description: "Judge Step {N}/{total}: {subtask_name}"
- prompt: {judge verification prompt with exact meta-judge specification YAML, and Pre-existing Changes section if applicable}
- model: {judge model — the user's
--model if one was passed; otherwise MUST equal this step's current implementation model, including after escalation}
- subagent_type: "sadd:judge"
#### 3.5 Dispatch, Verify, and Iterate
For each subtask in sequence:
Dispatch meta-judge AND implementation agent IN PARALLEL (single message, 2 tool calls):
Tool call 1 (meta-judge — MUST be first):
Use Task tool:
- description: "Meta-judge Step {N}/{total}: {subtask_name}"
- prompt: {meta-judge prompt with step requirements and context}
- model: {meta-judge model — the user's --model if one was passed; otherwise the same tier as this step's implementation, or one tier up per Role Pairing}
- subagent_type: "sadd:meta-judge"
Tool call 2 (implementation):
Use Task tool:
- description: "Step {N}/{total}: {subtask_name}"
- prompt: {constructed prompt with CoT + task + previous context + self-critique}
- model: {implementation model — the user's --model if one was passed; otherwise the model selected for this step}
- subagent_type: "{selected agent type}"
Wait for BOTH to complete. Collect outputs:
- From meta-judge: Extract evaluation specification YAML
- From implementation: Parse "Context for Next Steps" section, note files modified
Dispatch judge sub-agent (with this step's meta-judge specification):
Use Task tool:
- description: "Judge Step {N}/{total}: {subtask_name}"
- prompt: {judge verification prompt with step requirements, implementation output, and meta-judge specification YAML}
- model: {judge model — the user's
--model if one was passed; otherwise MUST equal this step's current implementation model, including after escalation}
- subagent_type: "sadd:judge"
Parse judge verdict (DO NOT read full report):
Extract from judge reply:
- VERDICT: PASS or FAIL
- SCORE: X.X/5.0
- ISSUES: List of problems (if any)
- IMPROVEMENTS: List of suggestions (if any)
Decision based on verdict:
If score ≥4.0:
→ VERDICT: PASS
→ Proceed to next step with accumulated context
→ Include IMPROVEMENTS in context as optional enhancements
If 3.0 ≤ score <4.0 and NOT STRICT_MODE:
→ Apply the Iteration Discretion Rule (3.6)
→ accepted → VERDICT: PASS (report outstanding issues and proceed)
→ declined → VERDICT: FAIL → go to "Check retry count" below
Otherwise (score <3.0, or score <4.0 with STRICT_MODE):
→ VERDICT: FAIL
→ Check retry count for this step
If retries < 3:
→ Decide this step's retry tier per "3.5.1 Model Escalation on Retry" below
(per the Escalation Rule — bump BOTH, unless its sole hold exception applies)
→ Dispatch retry implementation agent at that tier with:
- Original step requirements
- Judge's ISSUES list as feedback
- Path to judge report for details
- Instruction to fix specific issues
→ Return to judge verification with SAME meta-judge specification from this step,
dispatching the judge at the retry tier (judge always matches implementation)
→ Do NOT re-run meta-judge for retries, and do NOT re-tier it
If retries ≥ 3:
→ Escalate to user (see Error Handling)
→ Do NOT proceed to next step
Proceed to next subtask with accumulated context
→ Next step gets a NEW meta-judge dispatched in parallel with its implementation agent
##### 3.5.1 Model Escalation on Retry
Before dispatching any retry you MUST decide this step's tier explicitly per the [Escalation Rule](#escalation-rule) — which governs in full, including its sole hold exception — and state the decision in your step report. Retry-specific anchors on top of it:
- **Trigger (1) is anchored at `score < 3.0`** here (or issues showing the model misunderstood the step rather than merely missing details).
- The retry's judge MUST be dispatched at the same tier as the retry implementation; the step's meta-judge is neither re-run nor re-tiered.
- The escalated tier applies to **this step's remaining attempts only** — the next step is re-assessed from scratch per [Phase 2](#phase-2-model-selection-for-each-subtask).
- If `opus` still fails, escalate to the user per [Error Handling](#if-step-fails-after-max-retries).
**Retry prompt template for implementation agent:**
```markdown
## Retry Required: Step {N}/{total}
Your previous implementation did not pass judge verification.
<original_requirements>
{subtask_description}
</original_requirements>
<judge_feedback>
VERDICT: FAIL
SCORE: {score}/5.0
ISSUES:
{list of issues from judge}
Full report available at: {path_to_judge_report}
</judge_feedback>
<your_previous_output>
{files modified in previous attempt}
</your_previous_output>
Instructions:
Let's fix the identified issues step by step.
1. First, review each issue the judge identified
2. For each issue, determine the root cause
3. Plan the fix for each issue
4. Implement ALL fixes
5. Verify your fixes address each issue
6. Provide updated "Context for Next Steps" section
CRITICAL: Focus on fixing the specific issues identified. Do not rewrite everything.
3.6 Iteration Discretion Rule
Your main task is to COMPLETE the task within targe
…(truncated)
1---
2name: do-in-steps
3description: 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.
4---
5
6# do-in-steps
7
8<task>
9Execute 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.
10</task>
11
12<context>
13This 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:
14- **Isolated context** - Clean context window for its specific subtask
15- **Right-sized model** - Chosen per step by the [Model Selection Policy](#model-selection-policy): `sonnet`/`haiku` by default, `opus` only when earned
16- **Previous step context** - Summary of relevant outputs from preceding steps
17- **Structured reasoning** - Zero-shot CoT prefix for systematic thinking
18- **Self-critique** - Internal verification before submission
19- **Structured evaluation** - Meta-judge produces tailored rubrics and checklists per step before judging occurs
20- **External judge** - LLM-as-a-judge verification using meta-judge specification with iteration loop
21- **Parallel speed** - Meta-judge and implementation agent run in parallel per step; meta-judge specification reused across retries within that step
22
23</context>
24
25## Arguments
26
27| Argument | Format | Default | Description |
28|----------|--------|---------|-------------|
29| `task` | Free-form text | **Required** | Task description to decompose and execute |
30| `--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. |
31| `--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. |
32
33Example: `/do-in-steps Refactor UserService class and update all consumers --strict`
34
35**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:
36
371. Analyze and decompose the task
382. 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
393. **For each step: dispatch meta-judge AND implementation agent in parallel** (meta-judge FIRST in dispatch order)
404. **Wait for BOTH to complete, then dispatch judge with meta-judge's specification**
415. **Iterate if judge fails the step (max 3 retries), reusing same meta-judge specification**
426. Collect outputs and pass context forward
437. Report final results
44
45## RED FLAGS - Never Do These
46
47**NEVER:**
48
49- Read implementation files to understand code details (let sub-agents do this)
50- Write code or make changes to source files directly
51- Skip decomposition and jump to implementation
52- Perform multiple steps yourself "to save time"
53- Overflow your context by reading step outputs in detail
54- Read judge reports in full (only parse structured headers)
55- Skip judge verification and proceed next step
56- Provide score threshold to the judge in any format
57
58**ALWAYS:**
59
60- Use Task tool to dispatch sub-agents for ALL implementation work
61- Dispatch meta-judge AND implementation agent **in parallel per step** (meta-judge FIRST in dispatch order)
62- Wait for BOTH meta-judge and implementation to complete before dispatching judge
63- Pass step's meta-judge evaluation specification to the judge agent
64- Include `CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}` in prompts to meta-judge and judge agents
65- Reuse same meta-judge specification across retries within a step (never re-run meta-judge for retries)
66- Dispatch a NEW meta-judge for each new step (each step gets its own tailored specification)
67- Use Task tool to dispatch **independent judges** for step verification
68- Pass only necessary context summaries, not full file contents
69- Get pass from judge verification before proceeding to next step
70- Iterate with judge feedback if verification fails (max 3 retries)
71- Apply the [Iteration Discretion Rule](#36-iteration-discretion-rule) to every step verdict, unless `--strict` was provided
72
73Any 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!
74
75## Model Selection Policy
76
77Picking 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.
78
79**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.
80
81**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.
82
83### Selection Rules
84
85| Task shape | Tier | Examples |
86|---|---|---|
87| 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 |
88| 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 |
89| 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 |
90| **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 |
91
92**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`.
93
94**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.
95
96### Role Pairing
97
98Any 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.**
99
100**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.
101
102| Pattern | Criteria-setter (meta-judge) | Producer + evaluator (implementation + judge) | Use when |
103|---|---|---|---|
104| Sharpened-haiku | `sonnet` | `haiku` | The work is trivial, but what counts as "correct" is not obvious |
105| Sharpened-sonnet | `opus` | `sonnet` | Code work with ambiguous or high-consequence acceptance criteria that does not itself hit an `opus` trigger |
106
107Producer 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.
108
109### Escalation Rule
110
111Bump **BOTH producer and evaluator** (the failing step's implementation and judge) one tier for the next attempt when either trigger fires:
112
1131. **Low first-attempt quality** — a low score, or issues showing the model misunderstood the step rather than merely missing details.
1142. **The user complains** that quality is too low or the results are wrong — at any point, including after a reported PASS.
115
116Ladder: `haiku` → `sonnet` → `opus`. `opus` is the **ceiling** — there is no further tier. If `opus`-tier work still fails, escalate to the **user**, never loop.
117
118- **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.
119- **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.
120- **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.
121- 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.
122- 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.
123- 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.
124- **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.
125
126### Cross-Provider Equivalence
127
128When this skill runs outside the Anthropic model context, map the tier to the nearest model of the same class:
129
130| Tier | Role | Comparable models from other providers |
131|---|---|---|
132| `haiku` | Fast and cheap; mechanical work | `gemini-flash-lite`, `gemma` class, `gpt-oss` class, small open-weight models |
133| `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 |
134| `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 |
135
136The 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.
137
138## Process
139
140### Setup: Create Reports Directory
141
142Before starting, ensure the reports directory exists:
143
144```bash
145mkdir -p .specs/reports
146```
147
148**Report naming convention:** `.specs/reports/{task-name}-step-{N}-{YYYY-MM-DD}.md`
149
150Where:
151
152- `{task-name}` - Derived from task description (e.g., `user-dto-refactor`)
153- `{N}` - Step number
154- `{YYYY-MM-DD}` - Current date
155
156**Note:** Implementation outputs go to their specified locations; only judge verification reports go to `.specs/reports/`
157
158### Phase 1: Task Analysis and Decomposition
159
160Resolve configuration first: `STRICT_MODE = --strict present || false`. Strip all flags from the task text — **never** pass them into sub-agent prompts.
161
162Analyze the task systematically using Zero-shot Chain-of-Thought reasoning:
163
164```
165Let me analyze this task step by step to decompose it into sequential subtasks:
166
1671. **Task Understanding**
168 "What is the overall objective?"
169 - What is being asked?
170 - What is the expected final outcome?
171 - What constraints exist?
172
1732. **Identify Natural Boundaries**
174 "Where does the work naturally divide?"
175 - Database/model changes (foundation)
176 - Interface/contract changes (dependencies)
177 - Implementation changes (core work)
178 - Integration/caller updates (ripple effects)
179 - Testing/validation (verification)
180 - Documentation (finalization)
181
1823. **Dependency Identification**
183 "What must happen before what?"
184 - "If I do B before A, will B break or use stale information?"
185 - "Does B need any output from A as input?"
186 - "Would doing B first require redoing work after A?"
187 - What is the minimal viable ordering?
188
1894. **Define Clear Boundaries**
190 "What exactly does each subtask encompass?"
191 - Input: What does this step receive?
192 - Action: What transformation/change does it make?
193 - Output: What does this step produce?
194 - Verification: How do we know it succeeded?
195```
196
197**Decomposition Guidelines:**
198
199| Pattern | Decomposition Strategy | Example |
200|---------|------------------------|---------|
201| Interface change | 1. Update interface, 2. Update implementations, 3. Update consumers | "Change return type of getUser" |
202| Feature addition | 1. Add core logic, 2. Add integration points, 3. Add API layer | "Add caching to UserService" |
203| Refactoring | 1. Extract/modify core, 2. Update internal references, 3. Update external references | "Extract helper class from Service" |
204| Bug fix with impact | 1. Fix root cause, 2. Fix dependent issues, 3. Update tests | "Fix calculation error affecting reports" |
205| Multi-layer change | 1. Data layer, 2. Business layer, 3. API layer, 4. Client layer | "Add new field to User entity" |
206
207**Decomposition Output Format:**
208
209```markdown
210## Task Decomposition
211
212### Original Task
213{task_description}
214
215### Subtasks (Sequential Order)
216
217| Step | Subtask | Depends On | Complexity | Type | Output |
218|------|---------|------------|------------|------|--------|
219| 1 | {description} | - | {low/med/high} | {type} | {what it produces} |
220| 2 | {description} | Step 1 | {low/med/high} | {type} | {what it produces} |
221| 3 | {description} | Steps 1,2 | {low/med/high} | {type} | {what it produces} |
222...
223
224### Dependency Graph
225Step 1 ─→ Step 2 ─→ Step 3 ─→ ...
226```
227
228### Phase 2: Model Selection for Each Subtask
229
230Assess **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.
231
232- **Scope** — one file, one component, or multiple files?
233- **Complexity** — mechanical edit, established pattern, or novel/intricate logic?
234- **Risk** — isolated and reversible, internal, or **critical** per the exhaustive list in the [Selection Rules](#selection-rules) `opus` row?
235
236For 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.
237
238**Domain Expertise Check:** "Does this subtask match a specialized agent profile?"
239
240- Development: implementation, refactoring, bug fixes
241- Architecture: system design, pattern selection
242- Documentation: API docs, comments, README updates
243- Testing: test generation, test updates
244
245**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.
246
247**Decision:** Use specialized agent when subtask clearly benefits from domain expertise AND complexity justifies the overhead (not for `haiku`-tier steps).
248
249**Selection Output Format:**
250
251```markdown
252## Model/Agent Selection
253
254| Step | Subtask | Model | Agent | Rationale |
255|------|---------|-------|-------|-----------|
256| 1 | Update interface | opus | sdd:developer | opus is EARNED — shared contract changes across consumers |
257| 2 | Update implementations | sonnet | sdd:developer | Code writing on an established pattern, one module |
258| 3 | Update callers | haiku | - | Mechanical rename, no logic or contract change |
259| 4 | Update tests | sonnet | sdd:developer | Test writing, established patterns |
260```
261
262### Phase 3: Sequential Execution with Parallel Meta-Judge and Judge Verification
263
264Execute subtasks one by one. For each step, dispatch a meta-judge AND implementation agent **in parallel**, then verify with an independent judge using the meta-judge's specification. Iterate if needed, then pass context forward.
265
266**Execution Flow per Step:**
267
268```
269┌──────────────────────────────────────────────────────────────────────────────┐
270│ Step N │
271│ │
272│ ┌──────────────┐ │
273│ │ Meta-Judge │──┐ (parallel) │
274│ │ (Sub-agent) │ │ │
275│ └──────────────┘ │ ┌──────────────┐ ┌──────────────────────┐ │
276│ ├──▶│ Judge │────▶│ Parse Verdict │ │
277│ ┌──────────────┐ │ │ (Sub-agent) │ │ (Orchestrator) │ │
278│ │ Implementer │──┘ └──────────────┘ └──────────────────────┘ │
279│ │ (Sub-agent) │ │ │
280│ └──────────────┘ ▼ │
281│ ▲ ┌──────────────────────────────┐ │
282│ │ │ PASS (≥4.0)? │ │
283│ │ │ ├─ YES → Next Step │ │
284│ │ │ ├─ ≥3.0 → Rule 3.6 │ │
285│ │ │ └─ NO → Retry? │ │
286│ │ │ ├─ <3 retries → Retry │ │
287│ │ │ └─ ≥3 retries → Escalate │ │
288│ │ └──────────────────────────────┘ │
289│ │ │ │
290│ └────────────── feedback ────────────────────┘ │
291│ (retries reuse same meta-judge spec, no new meta-judge) │
292└──────────────────────────────────────────────────────────────────────────────┘
293```
294
295#### 3.1 Context Passing Protocol
296
297After each subtask completes, extract relevant context for subsequent steps:
298
299**Context to pass forward:**
300
301- Files modified (paths only, not contents)
302- Key changes made (summary)
303- New interfaces/APIs introduced
304- Decisions made that affect later steps
305- Warnings or considerations for subsequent steps
306
307**Context filtering:**
308
309- Pass ONLY information relevant to remaining subtasks
310- Do NOT pass implementation details that don't affect later steps
311- Keep context summaries concise (max 200 words per step)
312
313**Context Size Guideline:** If cumulative context exceeds ~500 words, summarize older steps more aggressively. Sub-agents can read files directly if they need details.
314
315**Example of Context Accumulation (Concrete):**
316
317```markdown
318## Completed Steps Summary
319
320### Step 1: Define UserRepository Interface
321- **What was done:** Created `src/repositories/UserRepository.ts` with interface definition
322- **Key outputs:**
323 - Interface: `IUserRepository` with methods: `findById`, `findByEmail`, `create`, `update`, `delete`
324 - Types: `UserCreateInput`, `UserUpdateInput` in `src/types/user.ts`
325- **Relevant for next steps:**
326 - Implementation must fulfill `IUserRepository` interface
327 - Use the defined input types for method signatures
328
329### Step 2: Implement UserRepository
330- **What was done:** Created `src/repositories/UserRepositoryImpl.ts` implementing `IUserRepository`
331- **Key outputs:**
332 - Class: `UserRepositoryImpl` with all interface methods implemented
333 - Uses existing database connection from `src/db/connection.ts`
334- **Relevant for next steps:**
335 - Import repository from `src/repositories/UserRepositoryImpl`
336 - Constructor requires `DatabaseConnection` injection
337```
338
339#### 3.2 Sub-Agent Prompt Construction
340
341For each subtask, construct the prompt with these mandatory components:
342
343##### 3.2.1 Zero-shot Chain-of-Thought Prefix (REQUIRED - MUST BE FIRST)
344
345```markdown
346## Reasoning Approach
347
348Before taking any action, think through this subtask systematically.
349
350Let's approach this step by step:
351
3521. "Let me understand what was done in previous steps..."
353 - What context am I building on?
354 - What interfaces/patterns were established?
355 - What constraints did previous steps introduce?
356
3572. "Let me understand what this step requires..."
358 - What is the specific objective?
359 - What are the boundaries of this step?
360 - What must I NOT change (preserve from previous steps)?
361
3623. "Let me plan my approach..."
363 - What specific modifications are needed?
364 - What order should I make them?
365 - What could go wrong?
366
3674. "Let me verify my approach before implementing..."
368 - Does my plan achieve the objective?
369 - Am I consistent with previous steps' changes?
370 - Is there a simpler way?
371
372Work through each step explicitly before implementing.
373```
374
375##### 3.2.2 Task Body
376
377```markdown
378<task>
379{Subtask description}
380</task>
381
382<subtask_context>
383Step {N} of {total_steps}: {subtask_name}
384</subtask_context>
385
386<previous_steps_context>
387{Summary of relevant outputs from previous steps - ONLY if this is not the first step}
388- Step 1: {what was done, key files modified, relevant decisions}
389- Step 2: {what was done, key files modified, relevant decisions}
390...
391</previous_steps_context>
392
393<constraints>
394- Focus ONLY on this specific subtask
395- Build upon (do not undo) changes from previous steps
396- Follow existing code patterns and conventions
397- Produce output that subsequent steps can build upon
398- Critical: you not allowed to use any mutation git commands, including, but not limited: commit, stash, push, checkout, reset, revert, etc. Except cases when task EXPLICITLY allows or requires it. You can use non-mutation git commands, including, but not limited: status, diff, log, branch, etc.
399
400</constraints>
401
402<input>
403{What this subtask receives - files, context, dependencies}
404</input>
405
406<output>
407{Expected deliverable - modified files, new files, summary of changes}
408
409CRITICAL: At the end of your work, provide a "Context for Next Steps" section with:
410- Files modified (full paths)
411- Key changes summary (3-5 bullet points)
412- Any decisions that affect later steps
413- Warnings or considerations for subsequent steps
414</output>
415```
416
417##### 3.2.3 Self-Critique Suffix (REQUIRED - MUST BE LAST)
418
419```markdown
420## Self-Critique Verification (MANDATORY)
421
422Before completing, verify your work integrates properly with previous steps. Do not submit unverified changes.
423
424### Verification Questions
425
426Generate verification questions based on the subtask description and the previous steps context. Examples:
427
428| # | Question | Evidence Required |
429|---|----------|-------------------|
430| 1 | Does my work build correctly on previous step outputs? | [Specific evidence] |
431| 2 | Did I maintain consistency with established patterns/interfaces? | [Specific evidence] |
432| 3 | Does my solution address ALL requirements for this step? | [Specific evidence] |
433| 4 | Did I stay within my scope (not modifying unrelated code)? | [List any out-of-scope changes] |
434| 5 | Is my output ready for the next step to build upon? | [Check against dependency graph] |
435
436### Answer Each Question with Evidence
437
438Examine your solution and provide specific evidence for each question:
439
440[Q1] Previous Step Integration:
441- Previous step output: [relevant context received]
442- How I built upon it: [specific integration]
443- Any conflicts: [resolved or flagged]
444
445[Q2] Pattern Consistency:
446- Patterns established: [list]
447- How I followed them: [evidence]
448- Any deviations: [justified or fixed]
449
450[Q3] Requirement Completeness:
451- Required: [what was asked]
452- Delivered: [what you did]
453- Gap analysis: [any gaps]
454
455[Q4] Scope Adherence:
456- In-scope changes: [list]
457- Out-of-scope changes: [none, or justified]
458
459[Q5] Output Readiness:
460- What later steps need: [based on decomposition]
461- What I provided: [specific outputs]
462- Completeness: [HIGH/MEDIUM/LOW]
463
464### Revise If Needed
465
466If ANY verification question reveals a gap:
4671. **FIX** - Address the specific gap identified
4682. **RE-VERIFY** - Confirm the fix resolves the issue
4693. **UPDATE** - Update the "Context for Next Steps" section
470
471CRITICAL: Do not submit until ALL verification questions have satisfactory answers.
472```
473
474#### 3.3 Parallel Meta-Judge Dispatch
475
476**CRITICAL**: For each step, dispatch the meta-judge AND implementation agent **in parallel in a single message** with two Task tool calls. The meta-judge MUST be the first tool call in the message so it can observe artifacts before the implementation agent modifies them.
477
478Both agents run as **foreground** agents. Wait for BOTH to complete before proceeding to judge dispatch.
479
480**Meta-Judge Prompt (per step):**
481
482```markdown
483## Task
484
485Generate an evaluation specification yaml for the following step. You will produce rubrics, checklists, and scoring criteria that a judge agent will use to evaluate the implementation artifact.
486
487CLAUDE_PLUGIN_ROOT=`${CLAUDE_PLUGIN_ROOT}`
488
489## User Prompt
490{Original task description from user}
491
492## Step Being Evaluated
493Step {N}/{total}: {subtask_name}
494{subtask_description}
495- Input: {what this step receives}
496- Expected output: {what this step should produce}
497
498## Previous Steps Context
499{Summary of what previous steps accomplished}
500
501## Artifact Type
502{code | documentation | configuration | etc.}
503
504## Instructions
505Return only the final evaluation specification YAML in your response.
506```
507
508**Dispatch Example**
509
510Send BOTH Task tool calls in a single message. Meta-judge first, implementation second:
511
512```
513Message with 2 tool calls:
514 Tool call 1 (meta-judge):
515 - description: "Meta-judge Step {N}/{total}: {subtask_name}"
516 - model: {meta-judge model — the user's `--model` if one was passed; otherwise the same tier as this step's implementation, or one tier up per Role Pairing}
517 - subagent_type: "sadd:meta-judge"
518
519 Tool call 2 (implementation):
520 - description: "Step {N}/{total}: {subtask_name}"
521 - model: {implementation model — the user's `--model` if one was passed; otherwise the model selected for this step}
522 - subagent_type: "{selected agent type}"
523```
524
525Wait for BOTH to return before proceeding to judge dispatch.
526
527#### 3.4 Judge Verification Protocol
528
529After BOTH meta-judge and implementation agent complete, dispatch an **independent judge** to verify the step using the meta-judge evaluation specification.
530
531CRITICAL: Provide to the judge EXACT meta-judge's evaluation specification YAML, do not skip or add anything, do not modify it in any way, do not shorten or summarize any text in it!
532
533##### 3.4.1 Analyze the Pre-existing Changes Section
534
535Before dispatching the judge for each step, assess whether there are pre-existing changes in the codebase that the judge needs to be aware of. The "Pre-existing Changes" section prevents the judge from confusing prior modifications with the current step's implementation agent's work.
536
537**When to include:**
538
539- Previous steps' changes from the SAME do-in-steps run (steps 1..N-1 when judging step N) — this is the most common case in sequential execution. When running step N, the judge MUST know about changes from steps 1..N-1 as pre-existing. Each completed step's output (files created/modified, key changes) becomes pre-existing context for subsequent step judges.
540- Previous do-in-steps or do-and-judge task runs completed earlier in the same session
541- User's manual modifications made before invoking the skill (visible from conversation context or in git)
542- Changes from other tools or agents that ran before this task
543
544**When to omit:**
545
546- This is step 1 with no known prior changes (no earlier session tasks, no user modifications) — omit the section entirely
547- On retries within the SAME step, do NOT include the implementation agent's own previous attempt as "pre-existing changes" — those are part of the current step's iteration cycle
548
549**Content guidelines:**
550
551- Use a high-level summary: task description, list of affected files/modules, general nature of changes (created, modified, deleted)
552- Do NOT include code blocks, diffs, or line-level details — keep it concise
553- Label each source clearly: "Step 1: {description}", "Step 2: {description}", "User modifications (before current task)", etc.
554- If multiple sources of pre-existing changes exist, use separate subsections for each (one per completed step, plus any external sources)
555- Leverage the Context Passing Protocol output (section 3.1) — the "Completed Steps Summary" already tracks what each step produced
556
557CRITICAL: avoid reading full codebase or git history, just use high-level git diff/status to determine which files were changed, or use conversation context and completed step summaries to determine pre-existing changes.
558
559**Prompt template for step judge:**
560
561```markdown
562You are evaluating Step {N}/{total}: {subtask_name} against an evaluation specification produced by the meta judge.
563
564CLAUDE_PLUGIN_ROOT=`${CLAUDE_PLUGIN_ROOT}`
565
566## Original Task
567{overall_task_description}
568
569## Step Requirements
570{subtask_description}
571- Input: {what this step receives}
572- Expected output: {what this step should produce}
573
574## Previous Steps Context
575{Summary of what previous steps accomplished}
576
577{IF pre-existing changes are known (previous steps, prior tasks, or user modifications), include the following section — otherwise omit entirely}
578
579## Pre-existing Changes (Context Only)
580
581The following changes were made BEFORE the current step's implementation agent started working. They are NOT part of the current step's output. Focus your evaluation on the current step's changes. Only verify pre-existing changed files/logic if they directly relate to the current step's requirements.
582
583### {Source of changes: e.g., "Step 1: {step description}" or "Previous Task: {task description}" or "User modifications (before current task)"}
584{High-level summary: what was done, which files/modules were created or modified}
585
586### {Additional source if applicable}
587{High-level summary}
588
589{END conditional section}
590
591## Evaluation Specification
592
593```yaml
594{meta-judge's evaluation specification YAML}
595```
596
597## Implementation Output
598{Path to files modified by implementation agent}
599{Context for Next Steps section from implementation agent}
600
601## Instructions
602
603Follow your full judge process as defined in your agent instructions!
604
605## Output
606
607CRITICAL: You must reply with this exact structured evaluation report format in YAML at the START of your response!
608```
609
610CRITICAL: NEVER provide score threshold, in any format, including `threshold_pass` or anything different. Judge MUST not know what threshold for score is, in order to not be biased!!!
611
612**Dispatch:**
613
614```
615Use Task tool:
616 - description: "Judge Step {N}/{total}: {subtask_name}"
617 - prompt: {judge verification prompt with exact meta-judge specification YAML, and Pre-existing Changes section if applicable}
618 - model: {judge model — the user's `--model` if one was passed; otherwise MUST equal this step's current implementation model, including after escalation}
619 - subagent_type: "sadd:judge"
620```
621
622#### 3.5 Dispatch, Verify, and Iterate
623
624For each subtask in sequence:
625
626```
6271. Dispatch meta-judge AND implementation agent IN PARALLEL (single message, 2 tool calls):
628 Tool call 1 (meta-judge — MUST be first):
629 Use Task tool:
630 - description: "Meta-judge Step {N}/{total}: {subtask_name}"
631 - prompt: {meta-judge prompt with step requirements and context}
632 - model: {meta-judge model — the user's `--model` if one was passed; otherwise the same tier as this step's implementation, or one tier up per Role Pairing}
633 - subagent_type: "sadd:meta-judge"
634
635 Tool call 2 (implementation):
636 Use Task tool:
637 - description: "Step {N}/{total}: {subtask_name}"
638 - prompt: {constructed prompt with CoT + task + previous context + self-critique}
639 - model: {implementation model — the user's `--model` if one was passed; otherwise the model selected for this step}
640 - subagent_type: "{selected agent type}"
641
6422. Wait for BOTH to complete. Collect outputs:
643 - From meta-judge: Extract evaluation specification YAML
644 - From implementation: Parse "Context for Next Steps" section, note files modified
645
6463. Dispatch judge sub-agent (with this step's meta-judge specification):
647 Use Task tool:
648 - description: "Judge Step {N}/{total}: {subtask_name}"
649 - prompt: {judge verification prompt with step requirements, implementation output, and meta-judge specification YAML}
650 - model: {judge model — the user's `--model` if one was passed; otherwise MUST equal this step's current implementation model, including after escalation}
651 - subagent_type: "sadd:judge"
652
6534. Parse judge verdict (DO NOT read full report):
654 Extract from judge reply:
655 - VERDICT: PASS or FAIL
656 - SCORE: X.X/5.0
657 - ISSUES: List of problems (if any)
658 - IMPROVEMENTS: List of suggestions (if any)
659
6605. Decision based on verdict:
661
662 If score ≥4.0:
663 → VERDICT: PASS
664 → Proceed to next step with accumulated context
665 → Include IMPROVEMENTS in context as optional enhancements
666
667 If 3.0 ≤ score <4.0 and NOT STRICT_MODE:
668 → Apply the Iteration Discretion Rule (3.6)
669 → accepted → VERDICT: PASS (report outstanding issues and proceed)
670 → declined → VERDICT: FAIL → go to "Check retry count" below
671
672 Otherwise (score <3.0, or score <4.0 with STRICT_MODE):
673 → VERDICT: FAIL
674 → Check retry count for this step
675
676 If retries < 3:
677 → Decide this step's retry tier per "3.5.1 Model Escalation on Retry" below
678 (per the Escalation Rule — bump BOTH, unless its sole hold exception applies)
679 → Dispatch retry implementation agent at that tier with:
680 - Original step requirements
681 - Judge's ISSUES list as feedback
682 - Path to judge report for details
683 - Instruction to fix specific issues
684 → Return to judge verification with SAME meta-judge specification from this step,
685 dispatching the judge at the retry tier (judge always matches implementation)
686 → Do NOT re-run meta-judge for retries, and do NOT re-tier it
687
688 If retries ≥ 3:
689 → Escalate to user (see Error Handling)
690 → Do NOT proceed to next step
691
6926. Proceed to next subtask with accumulated context
693 → Next step gets a NEW meta-judge dispatched in parallel with its implementation agent
694```
695
696##### 3.5.1 Model Escalation on Retry
697
698Before dispatching any retry you MUST decide this step's tier explicitly per the [Escalation Rule](#escalation-rule) — which governs in full, including its sole hold exception — and state the decision in your step report. Retry-specific anchors on top of it:
699
700- **Trigger (1) is anchored at `score < 3.0`** here (or issues showing the model misunderstood the step rather than merely missing details).
701- The retry's judge MUST be dispatched at the same tier as the retry implementation; the step's meta-judge is neither re-run nor re-tiered.
702- The escalated tier applies to **this step's remaining attempts only** — the next step is re-assessed from scratch per [Phase 2](#phase-2-model-selection-for-each-subtask).
703- If `opus` still fails, escalate to the user per [Error Handling](#if-step-fails-after-max-retries).
704
705**Retry prompt template for implementation agent:**
706
707```markdown
708## Retry Required: Step {N}/{total}
709
710Your previous implementation did not pass judge verification.
711
712<original_requirements>
713{subtask_description}
714</original_requirements>
715
716<judge_feedback>
717VERDICT: FAIL
718SCORE: {score}/5.0
719ISSUES:
720{list of issues from judge}
721
722Full report available at: {path_to_judge_report}
723</judge_feedback>
724
725<your_previous_output>
726{files modified in previous attempt}
727</your_previous_output>
728
729Instructions:
730Let's fix the identified issues step by step.
731
7321. First, review each issue the judge identified
7332. For each issue, determine the root cause
7343. Plan the fix for each issue
7354. Implement ALL fixes
7365. Verify your fixes address each issue
7376. Provide updated "Context for Next Steps" section
738
739CRITICAL: Focus on fixing the specific issues identified. Do not rewrite everything.
740```
741
742#### 3.6 Iteration Discretion Rule
743
744Your main task is to COMPLETE the task within target quality, and iteration effort MUST stay proportionate to each step's size. Two failure modes are equally real:
745
746- Burning retries and context on nitpicks so the overall task never completes → **the task is failed**.
747- Accepting a step whose quality is genuinely too poor to be considered complete → **an even worse failure**.
748
749Apply to every judge score:
750
751- **`score < 3.0` → FAIL, unconditionally. No discretion.** Retry with judge feedback until the step passes or max retries is reached.
752- **`3.0 <= score < 4.0` → discretion band.** ONLY inside this band MAY you decide that a step below the `4.0` target is acceptable. The fixed `4.0` target puts the effective floor at `3.0`, so no separate bounded-drop guard is needed.
753- Inside the band, when the outstanding issues are ONLY low/medium priority (any High or Critical finding removes discretion entirely) AND none of them breaks a target requirement of the step or causes a meaningful defect (i.e. they are nitpicks), you MUST reason FIRST — before dispatching a retry — about whether another attempt is worth the time and context cost.
754- **At most ONE nitpick-driven retry**, and it counts against the retry budget. If it again surfaces only nitpicks, you MUST mark the step PASS (`ACCEPTED`), carry the outstanding issues forward in the accumulated context, report them in the final summary, and continue with the next step. If it returns a score below `3.0`, the unconditional-FAIL rule applies instead.
755- You MUST be critical, NOT lenient. Stopping short of target MUST be an intentional decision grounded in the absence of real, requirement-breaking issues — later steps build on this one. A genuine blocking issue that prevents completing the step within max retries MUST be escalated as a failure, never papered over.
756- **If `STRICT_MODE` is true, this whole rule is DISABLED**: stop only when `score >= 4.0` or max retries is reached. `--strict` changes nothing else — the `4.0` target, the max-retry limit, the `< 3.0` unconditional FAIL and meta-judge/judge dispatch are unaffected.
757
758### Phase 4: Final Summary and Report
759
760After all subtasks complete and pass verification, reply with a comprehensive report:
761
762```markdown
763## Sequential Execution Summary
764
765**Overall Task:** {original task description}
766**Total Steps:** {count}
767**Total Agents:** {meta_judges(one per step) + implementation_agents + judge_agents + retry_agents}
768**Strict Mode:** {STRICT_MODE}
769
770### Step-by-Step Results
771
772| Step | Subtask | Model | Judge Score | Retries | Status |
773|------|---------|-------|-------------|---------|--------|
774| 1 | {name} | {model} | {X.X}/5.0 | {0-3} | PASS |
775| 2 | {name} | {model} | {X.X}/5.0 | {0-3} | PASS |
776| ... | ... | ... | ... | ... | ... |
777
778Status is `PASS` (score >= 4.0), `ACCEPTED` (below target per the [Iteration Discretion Rule](#36-iteration-discretion-rule) — list the outstanding nitpicks under Follow-up Recommendations), or `FAILED`.
779
780**Model** is the tier the step finished at; when [escalation](#351-model-escalation-on-retry) fired, record it as `{starting tier} → {final tier}`.
781
782### Files Modified (All Steps)
783- {file1}: {what changed, which step}
784- {file2}: {what changed, which step}
785...
786
787### Key Decisions Made
788- Step 1: {decision and rationale}
789- Step 2: {decision and rationale}
790...
791
792### Integration Points
793{How the steps connected and built upon each other}
794
795### Judge Verification Summary
796| Step | Initial Score | Final Score | Issues Fixed |
797|------|---------------|-------------|--------------|
798| 1 | {X.X} | {X.X} | {count or "None"} |
799| 2 | {X.X} | {X.X} | {count or "None"} |
800
801### Meta-Judge Specifications
802One evaluation specification generated per step (in parallel with implementation), reused across retries within each step.
803
804
805### Follow-up Recommendations
806{Any improvements suggested by judges, tests to run, or manual verification needed}
807```
808
809## Error Handling
810
811### If Judge Verification Fails (Score <4.0)
812
813The judge-verified iteration loop handles most failures automatically (a score in `3.0..4.0` is FAIL only after the [Iteration Discretion Rule](#36-iteration-discretion-rule) declines to accept it):
814
815```
816Judge FAIL (Retry Available):
817 1. Parse ISSUES from judge verdict
818 2. Dispatch retry implementation agent with feedback
819 3. Re-verify with judge (using same step's meta-judge specification — do NOT re-run meta-judge)
820 4. Repeat until PASS or max retries (3)
821```
822
823### If Step Fails After Max Retries
824
825When a step fails judge verification three times:
826
8271. **STOP** - Do not proceed with broken foundation
8282. **Report** - Provide failure analysis:
829 - Original step requirements
830 - All judge verdicts and scores
831 - Persistent issues across retries
8323. **Escalate** - Present options to user:
833 - Provide additional context/guidance for retry
834 - Re-run this step at the next model tier up (omit this option if the step already reached `opus`)
835 - Modify step requirements
836 - Skip step (if optional)
837 - Abort and report partial progress
8384. **Wait** - Do NOT proceed without user decision
839
840**Escalation Report Format:**
841
842```markdown
843## Step {N} Failed Verification (Max Retries Exceeded)
844
845### Step Requirements
846{subtask_description}
847
848### Verification History
849| Attempt | Score | Key Issues |
850|---------|-------|------------|
851| 1 | {X.X}/5.0 | {issues} |
852| 2 | {X.X}/5.0 | {issues} |
853| 3 | {X.X}/5.0 | {issues} |
854| 4 | {X.X}/5.0 | {issues} |
855
856### Persistent Issues
857{Issues that appeared in multiple attempts}
858
859### Judge Reports
860- .specs/reports/{task-name}-step-{N}-attempt-1.md
861- .specs/reports/{task-name}-step-{N}-attempt-2.md
862- .specs/reports/{task-name}-step-{N}-attempt-3.md
863- .specs/reports/{task-name}-step-{N}-attempt-4.md
864
865### Options
8661. **Provide guidance** - Give additional context for another retry
8672. **Escalate the tier** - Re-run this step's implementation and judge one tier up (omit this option if the step already reached `opus`)
8683. **Modify requirements** - Simplify or clarify step requirements
8694. **Skip step** - Mark as skipped and continue (if non-critical)
8705. **Abort** - Stop execution and preserve partial progress
871
872Awaiting your decision...
873```
874
875**Never:**
876
877- Continue past a failed step after max retries
878- Skip judge verification to "save time"
879- Ignore persistent issues across retries
880- Make assumptions about what might have worked
881
882### If Context is Missing
883
8841. **Do NOT guess** what previous steps produced
8852. **Re-examine** previous step output for missing information
8863. **Check judge reports** - they may have noted missing elements
8874. **Dispatch clarification sub-agent** if needed to extract missing context
8885. **Update context passing** for future similar tasks
889
890### If Steps Conflict
891
8921. **Stop execution** at conflict point
8932. **Analyze:** Was decomposition incorrect? Are steps actually dependent?
8943. **Check judge feedback** - judges may have flagged integration issues
8954. **Options:**
896 - Re-order steps if dependency was missed
897 - Combine conflicting steps into one
898 - Add reconciliation step between conflicting steps
899
900## Examples
901
902### Example 1: Sequential Steps Building on Each Other (Pre-existing Changes from Previous Steps)
903
904**Input:**
905
906```
907/do-in-steps implement user management feature
908```
909
910**Phase 1 - Decomposition:**
911
912| Step | Subtask | Depends On | Complexity | Type | Output |
913|------|---------|------------|------------|------|--------|
914| 1 | Create User model and database schema | - | Medium | Implementation | User model, migration files |
915| 2 | Add CRUD endpoints for users | Step 1 | Medium | Implementation | REST API routes, controller |
916| 3 | Add authentication integration | Steps 1,2 | High | Implementation | Auth middleware, JWT handling |
917
918**Phase 2 - Model Selection:**
919
920| Step | Subtask | Model | Rationale |
921|------|---------|-------|-----------|
922| 1 | Create User model and schema | sonnet | Code writing on an established pattern; the greenfield `users` table is reversible, so the irreversible-migration trigger does not fire |
923| 2 | Add CRUD endpoints | sonnet | Code writing in one module; "adding to a public API" is NOT on the exhaustive critical list |
924| 3 | Add authentication integration | opus | opus is EARNED — the critical trigger fires on auth (JWT issuance and route protection) |
925
926**Phase 3 - Execution with Pre-existing Changes Accumulation:**
927
928```
929Step 1: Create User model and database schema
930 Parallel dispatch: Meta-judge + Implementation
931 Judge Verification (with step 1 meta-judge spec):
932 NOTE: No pre-existing changes — this is step 1 with no prior session tasks.
933 The "Pre-existing Changes" section is OMITTED from the judge prompt.
934
935 Judge prompt sent:
936 ┌─────────────────────────────────────────────────────────
937 │ You are evaluating Step 1/3: Create User model and
938 │ database schema against an evaluation specification
939 │ produced by the meta judge.
940 │
941 │ CLAUDE_PLUGIN_ROOT=...
942 │
943 │ ## Original Task
944 │ Implement user management feature
945 │
946 │ ## Step Requirements
947 │ Create User model and database schema with proper
948 │ fields and relationships.
949 │
950 │ ## Previous Steps Context
951 │ None (first step)
952 │
953 │ ## Evaluation Specification
954 │ ```yaml
955 │ {meta-judge's evaluation specification YAML}
956 │ ```
957 │
958 │ ## Implementation Output
959 │ Files: src/models/User.ts (new), migrations/001_create_users.ts (new)
960 │ Key changes: Created User model with id, email, name, passwordHash...
961 │
962 │ ## Instructions
963 │ Follow your full judge process...
964 └─────────────────────────────────────────────────────────
965
966 → Judge (Sonnet — same tier as implementation): PASS, SCORE: 4.2/5.0
967 → Context passed forward: User model fields, migration file paths
968
969Step 2: Add CRUD endpoints for users
970 Parallel dispatch: Meta-judge + Implementation (both Sonnet)
971 Judge Verification (with step 2 meta-judge spec):
972 NOTE: Pre-existing changes detected — Step 1 created the User model.
973 Include "Pre-existing Changes" section so the judge does not confuse
974 Step 1's files with Step 2's implementation work.
975
976 Judge prompt sent:
977 ┌─────────────────────────────────────────────────────────
978 │ You are evaluating Step 2/3: Add CRUD endpoints for
979 │ users against an evaluation specification produced by
980 │ the meta judge.
981 │
982 │ CLAUDE_PLUGIN_ROOT=...
983 │
984 │ ## Original Task
985 │ Implement user management feature
986 │
987 │ ## Step Requirements
988 │ Add CRUD endpoints (create, read, update, delete) for
989 │ user management with proper validation and error handling.
990 │
991 │ ## Previous Steps Context
992 │ Step 1 created User model with fields: id, email, name,
993 │ passwordHash, createdAt, updatedAt.
994 │
995 │ ## Pre-existing Changes (Context Only)
996 │
997 │ The following changes were made BEFORE the current
998 │ step's implementation agent started working. They are
999 │ NOT part of the current step's output. Focus your
1000 │ evaluation on the current step's changes. Only verify
1001 │ pre-existing changed files/logic if they directly
1002 │ relate to the current step's requirements.
1003 │
1004 │ ### Step 1: "Create User model and database schema"
1005 │ The following files were created as part of Step 1:
1006 │ - src/models/User.ts (new) - User model with fields:
1007 │ id, email, name, passwordHash, createdAt, updatedAt
1008 │ - migrations/001_create_users.ts (new) - Database
1009 │ migration for users table
1010 │
1011 │ These files exist in the codebase and may be referenced
1012 │ by the current step, but evaluate only the changes made
1013 │ by Step 2's implementation agent.
1014 │
1015 │ ## Evaluation Specification
1016 │ ```yaml
1017 │ {meta-judge's evaluation specification YAML}
1018 │ ```
1019 │
1020 │ ## Implementation Output
1021 │ Files: src/controllers/UserController.ts (new),
1022 │ src/routes/users.ts (new), src/app.ts (modified)
1023 │ Key changes: Added REST endpoints for user CRUD...
1024 │
1025 │ ## Instructions
1026 │ Follow your full judge process...
1027 └─────────────────────────────────────────────────────────
1028
1029 → Judge (Sonnet — same tier as implementation): PASS, SCORE: 4.4/5.0
1030 → Context passed forward: API routes, controller patterns
1031
1032Step 3: Add authentication integration
1033 Parallel dispatch: Meta-judge + Implementation (both Opus — critical trigger)
1034 Judge Verification (with step 3 meta-judge spec):
1035 NOTE: Pre-existing changes include BOTH Step 1 AND Step 2.
1036 The judge needs to know about all prior steps' output.
1037
1038 Judge prompt sent:
1039 ┌─────────────────────────────────────────────────────────
1040 │ You are evaluating Step 3/3: Add authentication
1041 │ integration against an evaluation specification
1042 │ produced by the meta judge.
1043 │
1044 │ CLAUDE_PLUGIN_ROOT=...
1045 │
1046 │ ## Original Task
1047 │ Implement user management feature
1048 │
1049 │ ## Step Requirements
1050 │ Add JWT-based authentication with login/register
1051 │ endpoints and middleware for protecting user routes.
1052 │
1053 │ ## Previous Steps Context
1054 │ Step 1 created User model. Step 2 added CRUD endpoints
1055 │ at /api/users with UserController.
1056 │
1057 │ ## Pre-existing Changes (Context Only)
1058 │
1059 │ The following changes were made BEFORE the current
1060 │ step's implementation agent started working. They are
1061 │ NOT part of the current step's output. Focus your
1062 │ evaluation on the current step's changes. Only verify
1063 │ pre-existing changed files/logic if they directly
1064 │ relate to the current step's requirements.
1065 │
1066 │ ### Step 1: "Create User model and database schema"
1067 │ - src/models/User.ts (new) - User model with fields:
1068 │ id, email, name, passwordHash, createdAt, updatedAt
1069 │ - migrations/001_create_users.ts (new) - Database
1070 │ migration for users table
1071 │
1072 │ ### Step 2: "Add CRUD endpoints for users"
1073 │ - src/controllers/UserController.ts (new) - REST
1074 │ controller with create, read, update, delete handlers
1075 │ - src/routes/users.ts (new) - Express router for
1076 │ /api/users endpoints
1077 │ - src/app.ts (modified) - Registered user routes
1078 │
1079 │ These files exist in the codebase and may be modified
1080 │ by the current step, but evaluate only the changes made
1081 │ by Step 3's implementation agent.
1082 │
1083 │ ## Evaluation Specification
1084 │ ```yaml
1085 │ {meta-judge's evaluation specification YAML}
1086 │ ```
1087 │
1088 │ ## Implementation Output
1089 │ Files: src/auth/AuthMiddleware.ts (new),
1090 │ src/routes/auth.ts (new), src/app.ts (modified),
1091 │ src/routes/users.ts (modified)
1092 │ Key changes: Added JWT auth with login/register...
1093 │
1094 │ ## Instructions
1095 │ Follow your full judge process...
1096 └─────────────────────────────────────────────────────────
1097
1098 → Judge (Opus — same tier as implementation): PASS, SCORE: 4.1/5.0
1099```
1100
1101**Final Summary:**
1102
1103- Total Agents: 10 (3 meta-judges + 3 implementations + 0 retries + 3 judges)
1104- Pre-existing Changes Progression:
1105 - Step 1 judge: None
1106 - Step 2 judge: Step 1 output (2 files)
1107 - Step 3 judge: Steps 1+2 output (5 files)
1108- All Judge Scores: 4.2, 4.4, 4.1
1109
1110---
1111
1112### Example 2: User-Modified Codebase + Sequential Steps (Mixed Pre-existing Changes Sources)
1113
1114**Scenario:**
1115
1116The user has been working on a payment processing module during the conversation. They modified several files (added a new PaymentGateway interface, updated configuration) before invoking do-in-steps.
1117
1118**Input:**
1119
1120```
1121/do-in-steps fix and improve payment processing
1122```
1123
1124**Phase 1 - Decomposition:**
1125
1126| Step | Subtask | Depends On | Complexity | Type | Output |
1127|------|---------|------------|------------|------|--------|
1128| 1 | Fix payment validation bugs | - | Medium | Bug fix | Corrected validation logic |
1129| 2 | Add retry logic for failed payments | Step 1 | High | Implementation | Retry mechanism with backoff |
1130
1131**Phase 2 - Model Selection:**
1132
1133| Step | Subtask | Model | Rationale |
1134|------|---------|-------|-----------|
1135| 1 | Fix payment validation bugs | opus | opus is EARNED — small in scope, but precedence makes criticality override size: payments are on the critical list |
1136| 2 | Add retry logic for failed payments | opus | opus is EARNED — payments (critical) plus retry/backoff sequencing around money movement (complex logic) |
1137
1138Both steps land on `opus` because the *domain* earns it, not because the run does — see Example 3 for a chain that mixes tiers.
1139
1140**Phase 3 - Execution with Mixed Pre-existing Changes:**
1141
1142```
1143Step 1: Fix payment validation bugs
1144 Parallel dispatch: Meta-judge + Implementation (both Opus — critical trigger)
1145 Judge Verification (Opus, with step 1 meta-judge spec):
1146 NOTE: Pre-existing changes detected from USER modifications.
1147 The user modified payment files before this task — include those
1148 so the judge focuses only on the bug fix, not the user's prior work.
1149
1150 Judge prompt sent:
1151 ┌─────────────────────────────────────────────────────────
1152 │ You are evaluating Step 1/2: Fix payment validation
1153 │ bugs against an evaluation specification produced by
1154 │ the meta judge.
1155 │
1156 │ CLAUDE_PLUGIN_ROOT=...
1157 │
1158 │ ## Original Task
1159 │ Fix and improve payment processing
1160 │
1161 │ ## Step Requirements
1162 │ Fix validation bugs in payment amount and currency
1163 │ checks that allow invalid transactions to proceed.
1164 │
1165 │ ## Previous Steps Context
1166 │ None (first step)
1167 │
1168 │ ## Pre-existing Changes (Context Only)
1169 │
1170 │ The following changes were made BEFORE the current
1171 │ step's implementation agent started working. They are
1172 │ NOT part of the current step's output. Focus your
1173 │ evaluation on the current step's changes. Only verify
1174 │ pre-existing changed files/logic if they directly
1175 │ relate to the current step's requirements.
1176 │
1177 │ ### User modifications (before current task)
1178 │ The user made changes to the following files/modules
1179 │ before this task was started:
1180 │ - src/payments/PaymentGateway.ts (new) - Payment
1181 │ gateway interface definition
1182 │ - src/payments/StripeAdapter.ts (modified) - Updated
1183 │ to implement new PaymentGateway interface
1184 │ - src/config/payment.config.ts (modified) - Added
1185 │ gateway configuration settings
1186 │
1187 │ The current task focuses on fixing validation bugs.
1188 │ Pre-existing changes to payment files may overlap with
1189 │ the current step's scope — evaluate whether the
1190 │ implementation agent's changes correctly fix the bugs
1191 │ without breaking the pre-existing modifications.
1192 │
1193 │ ## Evaluation Specification
1194 │ ```yaml
1195 │ {meta-judge's evaluation specification YAML}
1196 │ ```
1197 │
1198 │ ## Implementation Output
1199 │ Files: src/payments/PaymentValidator.ts (modified),
1200 │ tests/payments/PaymentValidator.test.ts (modified)
1201 │ Key changes: Fixed amount validation to reject negative
1202 │ values, added currency code format check...
1203 │
1204 │ ## Instructions
1205 │ Follow your full judge process...
1206 └─────────────────────────────────────────────────────────
1207
1208 → VERDICT: PASS, SCORE: 4.3/5.0
1209 → Context passed forward: Validation fixes, affected files
1210
1211Step 2: Add retry logic for failed payments
1212 Parallel dispatch: Meta-judge + Implementation (both Opus — critical trigger)
1213 Judge Verification (Opus, with step 2 meta-judge spec):
1214 NOTE: Pre-existing changes now include BOTH the user's modifications
1215 AND Step 1's output. The judge needs both sources to correctly
1216 attribute changes.
1217
1218 Judge prompt sent:
1219 ┌─────────────────────────────────────────────────────────
1220 │ You are evaluating Step 2/2: Add retry logic for failed
1221 │ payments against an evaluation specification produced by
1222 │ the meta judge.
1223 │
1224 │ CLAUDE_PLUGIN_ROOT=...
1225 │
1226 │ ## Original Task
1227 │ Fix and improve payment processing
1228 │
1229 │ ## Step Requirements
1230 │ Add retry mechanism with exponential backoff for failed
1231 │ payment transactions, with configurable max retries.
1232 │
1233 │ ## Previous Steps Context
1234 │ Step 1 fixed payment validation bugs in
1235 │ PaymentValidator.ts (amount and currency checks).
1236 │
1237 │ ## Pre-existing Changes (Context Only)
1238 │
1239 │ The following changes were made BEFORE the current
1240 │ step's implementation agent started working. They are
1241 │ NOT part of the current step's output. Focus your
1242 │ evaluation on the current step's changes. Only verify
1243 │ pre-existing changed files/logic if they directly
1244 │ relate to the current step's requirements.
1245 │
1246 │ ### User modifications (before current task)
1247 │ - src/payments/PaymentGateway.ts (new) - Payment
1248 │ gateway interface definition
1249 │ - src/payments/StripeAdapter.ts (modified) - Updated
1250 │ to implement new PaymentGateway interface
1251 │ - src/config/payment.config.ts (modified) - Added
1252 │ gateway configuration settings
1253 │
1254 │ ### Step 1: "Fix payment validation bugs"
1255 │ - src/payments/PaymentValidator.ts (modified) - Fixed
1256 │ amount validation and currency code format checks
1257 │ - tests/payments/PaymentValidator.test.ts (modified) -
1258 │ Added regression tests for validation fixes
1259 │
1260 │ These files exist in the codebase and may be modified
1261 │ by the current step, but evaluate only the changes made
1262 │ by Step 2's implementation agent.
1263 │
1264 │ ## Evaluation Specification
1265 │ ```yaml
1266 │ {meta-judge's evaluation specification YAML}
1267 │ ```
1268 │
1269 │ ## Implementation Output
1270 │ Files: src/payments/PaymentRetryService.ts (new),
1271 │ src/payments/StripeAdapter.ts (modified),
1272 │ src/config/payment.config.ts (modified),
1273 │ tests/payments/PaymentRetryService.test.ts (new)
1274 │ Key changes: Added PaymentRetryService with exponential
1275 │ backoff, integrated into StripeAdapter...
1276 │
1277 │ ## Instructions
1278 │ Follow your full judge process...
1279 └─────────────────────────────────────────────────────────
1280
1281 → VERDICT: PASS, SCORE: 4.5/5.0
1282```
1283
1284**Final Summary:**
1285
1286- Total Agents: 7 (2 meta-judges + 2 implementations + 0 retries + 2 judges)
1287- Pre-existing Changes Progression:
1288 - Step 1 judge: User modifications (3 files)
1289 - Step 2 judge: User modifications (3 files) + Step 1 output (2 files)
1290- All Judge Scores: 4.3, 4.5
1291
1292---
1293
1294### Example 3: Multi-file Refactoring with Escalation
1295
1296**Input:**
1297
1298```
1299/do-in-steps Rename 'userId' to 'accountId' across the codebase - this affects interfaces, implementations, and callers
1300```
1301
1302**Phase 1 - Decomposition:**
1303
1304| Step | Subtask | Depends On | Complexity | Type | Output |
1305|------|---------|------------|------------|------|--------|
1306| 1 | Update interface definitions | - | High | Refactoring | Updated interfaces |
1307| 2 | Update implementations of those interfaces | Step 1 | Low | Refactoring | Updated implementations |
1308| 3 | Update callers and consumers | Step 2 | Low | Refactoring | Updated caller files |
1309| 4 | Update tests | Step 3 | Low | Testing | Updated test files |
1310| 5 | Update documentation | Step 4 | Low | Documentation | Updated docs |
1311
1312**Phase 2 - Model Selection:**
1313
1314| Step | Subtask | Model | Rationale |
1315|------|---------|-------|-----------|
1316| 1 | Update interfaces | opus | opus is EARNED — a shared contract changes, which is an `opus` trigger at any file count |
1317| 2 | Update implementations | haiku | Mechanical-breadth carve-out: one rule-driven rename repeated per file, tiered on a single occurrence |
1318| 3 | Update callers | haiku | Same carve-out — mechanical rename, no logic or contract change |
1319| 4 | Update tests | haiku | Mechanical test fixes mirroring the rename |
1320| 5 | Update documentation | haiku | Single-purpose text correction, no code |
1321
1322**Phase 3 - Execution with Escalation (each step has parallel meta-judge + implementation):**
1323
1324```
1325Step 1: Update interfaces
1326 Parallel dispatch: Meta-judge + Implementation (both Opus — shared contract change)
1327 → Judge (Opus, sadd:judge, with step 1 meta-judge spec): PASS, 4.3/5.0
1328
1329Step 2: Update implementations
1330 Parallel dispatch: Meta-judge + Implementation (both Haiku)
1331 NOTE: Step 1's opus tier does NOT carry forward — Step 2 is tiered on
1332 its own merits (mechanical rename).
1333 → Judge (Haiku, sadd:judge, with step 2 meta-judge spec): PASS, 4.0/5.0
1334
1335Step 3: Update callers (Problem Detected — model escalation within the step)
1336 Parallel dispatch: Meta-judge (Haiku) + Implementation (Haiku)
1337 Attempt 1 (Haiku impl + Haiku judge): Judge FAIL, 2.5/5.0
1338 → ISSUES: Missed 12 occurrences in legacy module
1339 → score < 3.0 → trigger (1) fires. Missed occurrences read as a capability
1340 gap, not a narrow fixable defect, so the sole hold exception does not
1341 apply → mandatory bump: haiku → sonnet.
1342 Meta-judge NOT re-run, NOT re-tiered — same spec reused.
1343 Attempt 2 (Sonnet impl + Sonnet judge, same step 3 meta-judge spec): FAIL, 2.8/5.0
1344 → ISSUES: Still missing 4 occurrences, found new deprecated API usage
1345 → still < 3.0 → still a capability gap, not a narrow fixable defect →
1346 mandatory bump again: sonnet → opus
1347 Attempt 3 (Opus impl + Opus judge, same spec): FAIL, 3.2/5.0
1348 → ISSUES: 2 occurrences in dynamically generated code
1349 → at the `opus` ceiling — no bump available regardless of the hold
1350 exception; retry at `opus` with exact feedback.
1351 Attempt 4 (Opus impl + Opus judge, same spec): FAIL, 3.3/5.0
1352 → ISSUES: Dynamic code generation still not fully addressed
1353
1354 ESCALATION TO USER:
1355 "Step 3 failed after 4 attempts (haiku → sonnet → opus). Persistent issue:
1356 Dynamic code generation in LegacyAdapter.ts generates 'userId' at runtime.
1357 Options: 1) Provide guidance, 2) Modify requirements, 3) Skip, 4) Abort"
1358 (Tier escalation is NOT offered as an option — already at the opus ceiling.)
1359
1360 User response: "Update LegacyAdapter to use string template with accountId"
1361
1362 Attempt 5 (with user guidance, Opus, same step 3 meta-judge spec): Judge PASS, 4.1/5.0
1363
1364Step 4-5: Each with parallel meta-judge + implementation, complete without issues
1365 NOTE: Step 3's escalation to opus is scoped to Step 3. Steps 4 and 5 are
1366 re-assessed from scratch and both run at Haiku.
1367```
1368
1369Total Agents: 20 (5 meta-judges + 5 implementations + 5 retries + 5 judges)
1370
1371---
1372
1373## Best Practices
1374
1375### Task Decomposition
1376
1377- **Be explicit:** Each subtask should have a clear, verifiable outcome
1378- **Define verification points:** What should the judge check for each step?
1379- **Minimize steps:** Combine related work; don't over-decompose
1380- **Validate dependencies:** Ensure each step has what it needs from previous steps
1381- **Plan context:** Identify what context needs to pass between steps
1382
1383### Model Selection
1384
1385The rules govern in the [Model Selection Policy](#model-selection-policy); these are the habits that make them stick:
1386
1387- **Justify out loud, per step** - state scope, complexity and risk plus the resulting tier before dispatching each step; this is the highest-leverage decision in the run
1388- **`opus` is earned, never a hedge** - resolve every overlap and tie by the [Selection Rules](#selection-rules) precedence and tie-breaker, never by instinct
1389- **Tier each step on its own merits** - a chain mixes tiers; a neighbouring step's tier (or an escalated one) is not evidence about this step
1390- **One tier across roles** - raise only the criteria-setter (meta-judge), and only for a non-obvious step ([Role Pairing](#role-pairing))
1391- **Escalate on evidence** - a clearly-too-low attempt or a user quality complaint ([Escalation Rule](#escalation-rule)), scoped to the failing step
1392
1393### Context Passing Guidelines
1394
1395| Scenario | What to Pass | What to Omit |
1396|----------|--------------|--------------|
1397| Interface defined in step 1 | Full interface definition | Implementation details |
1398| Implementation in step 2 | Key patterns, file locations | Internal logic |
1399| Integration in step 3 | Usage patterns, entry points | Step 2 internal details |
1400| Judge feedback for retry | ISSUES list, report path | Full report contents |
1401
1402**Keep context focused:**
1403
1404- Pass what the next step NEEDS to build on
1405- Omit internal details that don't affect subsequent steps
1406- Highlight patterns/conventions to maintain consistency
1407- Include judge IMPROVEMENTS as optional enhancements
1408- **Track pre-existing changes** - Pass context about prior modifications (including previous steps) to the judge to prevent attribution confusion
1409
1410### Meta-Judge + Judge Verification
1411
1412- **Never skip meta-judge** - Tailored evaluation criteria produce better judgments than generic ones
1413- **One meta-judge per step** - Each step gets its own meta-judge dispatched in parallel with implementation
1414- **Reuse meta-judge spec across retries within a step** - On retry, reuse the same step's meta-judge specification; do NOT re-run meta-judge
1415- **New meta-judge for each new step** - Different steps have different requirements, so each gets a fresh meta-judge
1416- **Meta-judge FIRST in parallel dispatch** - Always the first tool call in the message
1417- **Parse only headers from judge** - Don't read full reports to avoid context pollution
1418- **Include CLAUDE_PLUGIN_ROOT** - Both meta-judge and judge need the resolved plugin root path
1419- **Meta-judge YAML** - Pass only the meta-judge YAML to the judge, do not add any additional text or comments to it!
1420- **After self-critique:** Judge reviews work that already passed internal verification
1421- **Independent verification:** Judge is different agent than implementer
1422- **Structured output:** Always parse VERDICT/SCORE from reply, not full report
1423- **Max retries:** 3 attempts before escalating to user
1424- **Feedback loop:** Pass judge ISSUES to retry implementation agent
1425- **Return to judge verification with same step's meta-judge specification** on retry
1426
1427### Quality Assurance
1428
1429- **Two-layer verification:** Self-critique (internal) + Judge (external)
1430- **Self-critique first:** Implementation agents verify own work before submission
1431- **External judge second:** Independent judge catches blind spots self-critique misses
1432- **Iteration loop:** Retry with feedback until passing or max retries
1433- **Proportionate iteration:** Apply the [Iteration Discretion Rule](#36-iteration-discretion-rule) — at most ONE nitpick-driven retry, never below `3.0`, disabled by `--strict`
1434- **Chain validation:** Judges check integration with previous steps
1435- **Escalation:** Don't proceed past failed steps - get user input
1436- **Final integration test:** After all steps, verify the complete change works together
1437
1438## Context Format Reference
1439
1440### Implementation Agent Output Format
1441
1442```markdown
1443## Context for Next Steps
1444
1445### Files Modified
1446- `src/dto/UserDTO.ts` (new file)
1447- `src/services/UserService.ts` (modified)
1448
1449### Key Changes Summary
1450- Created UserDTO with fields: id (string), name (string), email (string), createdAt (Date)
1451- UserDTO includes static `fromUser(user: User): UserDTO` factory method
1452- Added `toDTO()` method to User class for convenience
1453
1454### Decisions That Affect Later Steps
1455- Used class-based DTO (not interface) to enable transformation methods
1456- Opted for explicit mapping over automatic serialization for better control
1457
1458### Warnings for Subsequent Steps
1459- UserDTO does NOT include password field - ensure no downstream code expects it
1460- The `createdAt` field is formatted as ISO string in JSON serialization
1461
1462### Verification Points
1463- TypeScript compiles without errors
1464- UserDTO.fromUser() correctly maps all User properties
1465- Existing service tests still pass
1466```
1467
1468### Judge Verdict Format (Structured Header)
1469
1470```markdown
1471---
1472VERDICT: PASS
1473SCORE: 4.2/5.0
1474ISSUES:
1475 - None
1476IMPROVEMENTS:
1477 - Consider adding input validation to fromUser() method
1478 - Add JSDoc comments for better IDE support
1479---
1480
1481## Detailed Evaluation
1482[Evidence and analysis following meta-judge specification rubrics...]
1483```
1484
1485### Judge Verdict Format (FAIL Example)
1486
1487```markdown
1488---
1489VERDICT: FAIL
1490SCORE: 2.8/5.0
1491ISSUES:
1492 - Missing User->UserDTO mapping logic in getUser() method
1493 - Return type annotation changed but actual return value still returns User object
1494 - No null handling for optional User fields
1495IMPROVEMENTS:
1496 - Add static fromUser() factory method to UserDTO
1497 - Implement toDTO() as instance method on User class
1498---
1499```
1500
1501**Key Insight:** Complex tasks with dependencies benefit from sequential execution where each step operates in a fresh context while receiving only the relevant outputs from previous steps. **Per-step meta-judge evaluation specifications** ensure tailored evaluation criteria specific to each step's requirements, while running in parallel with implementation for speed. **External judge verification** catches blind spots that self-critique misses, while the **iteration loop** (reusing the same step's meta-judge spec) ensures quality before proceeding. This prevents both context pollution and error propagation.