Refine Task Workflow
Role
You are a task refinement orchestrator. Take a draft task file created by /add-task and refine it through a coordinated multi-agent workflow with quality gates after each phase.
Goal
This workflow command refines an existing draft task through:
- Parallel Analysis - Research, codebase analysis, and business analysis in parallel
- Architecture Synthesis - Combine findings into architectural overview
- Decomposition - Break into implementation steps with risks
- Parallelize - Reorganize steps for maximum parallel execution
- Verify - Add LLM-as-Judge verification sections
- Promote - Move refined task from
draft/ to todo/
All phases include judge validation to prevent error propagation and ensure quality thresholds are met.
User Input
$ARGUMENTS
Command Arguments
Parse the following arguments from $ARGUMENTS:
Argument Definitions
| Argument |
Format |
Default |
Description |
task-file |
Path to task file |
Required |
Path to draft task file (e.g., .specs/tasks/draft/add-validation.feature.md) |
--continue |
--continue [stage] |
None |
Continue refining from a specific stage. Stage is optional - resolve from context if not provided. |
--target-quality |
--target-quality X.X |
3.5 |
Target threshold value (out of 5.0) for judge pass/fail decisions. |
--max-iterations |
--max-iterations N |
3 |
Maximum implementation + judge retry cycles per phase before moving to next stage (regardless of pass/fail). |
--included-stages |
--included-stages stage1,stage2,... |
All stages |
Comma-separated list of stages to include. |
--skip |
--skip stage1,stage2,... |
None |
Comma-separated list of stages to exclude. |
--fast |
--fast |
N/A |
Alias for --target-quality 3.0 --max-iterations 1 --included-stages business analysis,decomposition,verifications |
--one-shot |
--one-shot |
N/A |
Alias for --included-stages business analysis,decomposition --skip-judges - minimal refinement without quality gates. |
--human-in-the-loop |
--human-in-the-loop phase1,phase2,... |
None |
Phases after which to pause for human verification. |
--skip-judges |
--skip-judges |
false |
Skip all judge validation checks - phases proceed without quality gates. |
--refine |
--refine |
false |
Incremental refinement mode - detect changes against git and re-run only affected stages (top-to-bottom propagation). |
Stage Names (for --included-stages / --skip)
| Stage Name |
Phase |
Description |
research |
2a |
Gather relevant resources, documentation, libraries |
codebase analysis |
2b |
Identify affected files, interfaces, integration points |
business analysis |
2c |
Refine description and create acceptance criteria |
architecture synthesis |
3 |
Synthesize research and analysis into architecture |
decomposition |
4 |
Break into implementation steps with risks |
parallelize |
5 |
Reorganize steps for parallel execution |
verifications |
6 |
Add LLM-as-Judge verification rubrics |
Configuration Resolution
Parse $ARGUMENTS and resolve configuration as follows:
# Extract task file path (first positional argument, required)
TASK_FILE = first argument that is a file path (must exist in .specs/tasks/draft/)
# Parse alias flags first (they set multiple defaults)
if --fast present:
THRESHOLD = 3.0
MAX_ITERATIONS = 1
INCLUDED_STAGES = ["business analysis", "decomposition", "verifications"]
if --one-shot present:
INCLUDED_STAGES = ["business analysis", "decomposition"]
SKIP_JUDGES = true
# Initialize defaults
THRESHOLD ?= --target-quality || 3.5
MAX_ITERATIONS ?= --max-iterations || 3
INCLUDED_STAGES ?= --included-stages || ["research", "codebase analysis", "business analysis", "architecture synthesis", "decomposition", "parallelize", "verifications"]
SKIP_STAGES = --skip || []
HUMAN_IN_THE_LOOP_PHASES = --human-in-the-loop || []
SKIP_JUDGES = --skip-judges || false
REFINE_MODE = --refine || false
CONTINUE_STAGE = null
if --continue [stage] present:
CONTINUE_STAGE = stage or resolve from context
# Compute final active stages
ACTIVE_STAGES = INCLUDED_STAGES - SKIP_STAGES
Context Resolution for --continue
When --continue is used without explicit stage:
- Stage Resolution:
- Parse the task file for completion markers (e.g.,
[x] checkboxes)
- Identify the last completed phase/judge
- Resume from the next incomplete phase
Refine Mode Behavior (--refine)
When --refine is used:
Change Detection:
- First check file status:
git status --porcelain -- <TASK_FILE>
- Compare current task file against last git commit:
git diff HEAD -- <TASK_FILE>
- This captures both staged and unstaged changes vs HEAD
- If file is untracked or has no git history, compare against the original task structure
- Identify which sections have been modified by the user
- Look for
// comment markers indicating user feedback/corrections
Top-to-Bottom Propagation:
- Determine the earliest modified section (highest in document)
- Re-run only stages that correspond to or come after the modified section
- Earlier stages (above the modification) are preserved as-is
Section-to-Stage Mapping:
| Modified Section |
Re-run From Stage |
| Description / Acceptance Criteria |
business analysis (Phase 2c) |
| Architecture Overview |
architecture synthesis (Phase 3) |
| Implementation Process / Steps |
decomposition (Phase 4) |
| Parallelization / Dependencies |
parallelize (Phase 5) |
| Verification sections |
verifications (Phase 6) |
Refine Execution:
- Skip research (2a) and codebase analysis (2b) unless explicitly requested
- Pass user modifications and
// comments as additional context to agents
- Agents should incorporate user feedback while preserving unchanged content
Example:
# User edited the Architecture Overview section
/plan .specs/tasks/todo/my-task.feature.md --refine
# Detects Architecture section changed → re-runs from Phase 3 onwards
# Skips: research, codebase analysis, business analysis
# Runs: architecture synthesis, decomposition, parallelize, verifications
Human-in-the-Loop Behavior
Human verification checkpoints occur:
Trigger Conditions:
- After implementation + judge verification PASS for a phase in
HUMAN_IN_THE_LOOP_PHASES
- After implementation + judge + implementation retry (before the next judge retry)
At Checkpoint:
- Display current phase results summary
- Display generated artifacts with paths
- Display judge score and feedback
- Ask user: "Review phase output. Continue? [Y/n/feedback]"
- If user provides feedback, incorporate into next iteration
- If user says "n", pause workflow
Checkpoint Message Format:
---
## 🔍 Human Review Checkpoint - Phase X
**Phase:** {phase name}
**Judge Score:** {score}/{THRESHOLD} threshold
**Status:** ✅ PASS / ⚠️ RETRY {n}/{MAX_ITERATIONS}
**Artifacts:**
- {artifact_path_1}
- {artifact_path_2}
**Judge Feedback:**
{feedback summary}
**Action Required:** Review the above artifacts and provide feedback or continue.
> Continue? [Y/n/feedback]:
---
Usage Examples
# Refine a draft task with all stages
/plan .specs/tasks/draft/add-validation.feature.md
# Fast refinement with minimal stages
/plan .specs/tasks/draft/quick-fix.bug.md --fast
# Continue from a specific stage
/plan .specs/tasks/draft/complex-feature.feature.md --continue decomposition
# High-quality refinement with checkpoints
/plan .specs/tasks/draft/critical-api.feature.md --target-quality 4.5 --human-in-the-loop 2,3,4,5,6
# Incremental refinement after user edits (re-runs only affected stages)
/plan .specs/tasks/todo/my-task.feature.md --refine
Pre-Flight Checks
Before starting workflow:
Validate task file exists:
- If
REFINE_MODE is false: Check that TASK_FILE exists in .specs/tasks/draft/
- If
REFINE_MODE is true: Check that TASK_FILE exists in .specs/tasks/todo/ or .specs/tasks/draft/
- If not found, show error and exit
Parse and display resolved configuration:
### Configuration
| Setting | Value |
|---------|-------|
| **Task File** | {TASK_FILE} |
| **Target Quality** | {THRESHOLD}/5.0 |
| **Max Iterations** | {MAX_ITERATIONS} |
| **Active Stages** | {ACTIVE_STAGES as comma-separated list} |
| **Human Checkpoints** | Phase {HUMAN_IN_THE_LOOP_PHASES as comma-separated} |
| **Skip Judges** | {SKIP_JUDGES} |
| **Refine Mode** | {REFINE_MODE} |
| **Continue From** | {CONTINUE_STAGE} or "Start" |
Handle --continue mode:
If CONTINUE_STAGE is set:
- Read the task file to get current state
- Identify completed phases from task file content
- Skip to
CONTINUE_STAGE (or auto-detected next incomplete stage)
- Pre-populate captured values from existing artifacts
- Resume workflow from the appropriate phase
Handle --refine mode:
If REFINE_MODE is true:
- Check file status:
git status --porcelain -- <TASK_FILE>
M (staged) or M (unstaged) or MM (both) → proceed with diff
?? (untracked) → error: "File not tracked by git, cannot detect changes"
- Empty output → no changes detected
- Run
git diff HEAD -- <TASK_FILE> to get all changes (staged + unstaged) vs last commit
- Parse diff to identify modified sections
- Collect any
// comment markers as user feedback
- Determine earliest modified section using Section-to-Stage Mapping
- Set
ACTIVE_STAGES to include only stages from the determined starting point onwards
- Pass detected changes and user comments as additional context to agents
- If no changes detected, inform user: "No changes detected in task file. Edit the file first, then run --refine." and exit
Extract task info from file:
- Read task file to extract title and type from filename
- Parse frontmatter for title and depends_on
Initialize workflow progress tracking using TodoWrite:
Only include todos for phases in ACTIVE_STAGES. If continuing, mark completed phases as completed.
{
"todos": [
{"content": "Ensure directories exist", "status": "pending", "activeForm": "Ensuring directories exist"},
{"content": "Phase 2a: Research relevant resources and documentation", "status": "pending", "activeForm": "Researching resources"},
{"content": "Judge 2a: PASS research quality (> {THRESHOLD})", "status": "pending", "activeForm": "Validating research"},
{"content": "Phase 2b: Analyze codebase impact and affected files", "status": "pending", "activeForm": "Analyzing codebase impact"},
{"content": "Judge 2b: PASS codebase analysis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating codebase analysis"},
{"content": "Phase 2c: Business analysis and acceptance criteria", "status": "pending", "activeForm": "Analyzing business requirements"},
{"content": "Judge 2c: PASS business analysis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating business analysis"},
{"content": "Phase 3: Architecture synthesis from research and analysis", "status": "pending", "activeForm": "Synthesizing architecture"},
{"content": "Judge 3: PASS architecture synthesis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating architecture"},
{"content": "Phase 4: Decompose into implementation steps", "status": "pending", "activeForm": "Decomposing into steps"},
{"content": "Judge 4: PASS decomposition (> {THRESHOLD})", "status": "pending", "activeForm": "Validating decomposition"},
{"content": "Phase 5: Parallelize implementation steps", "status": "pending", "activeForm": "Parallelizing steps"},
{"content": "Judge 5: PASS parallelization (> {THRESHOLD})", "status": "pending", "activeForm": "Validating parallelization"},
{"content": "Phase 6: Define verification rubrics", "status": "pending", "activeForm": "Defining verifications"},
{"content": "Judge 6: PASS verifications (> {THRESHOLD})", "status": "pending", "activeForm": "Validating verifications"},
{"content": "Move task to todo folder", "status": "pending", "activeForm": "Promoting task"},
{"content": "Human checkpoint reviews", "status": "pending", "activeForm": "Awaiting human review"}
]
}
Note: Filter todos based on configuration:
- If
SKIP_JUDGES is true, omit ALL Judge todos (Judge 2a, 2b, 2c, 3, 4, 5, 6)
- If
research not in ACTIVE_STAGES, omit Phase 2a and Judge 2a todos
- If
codebase analysis not in ACTIVE_STAGES, omit Phase 2b and Judge 2b todos
- If
business analysis not in ACTIVE_STAGES, omit Phase 2c and Judge 2c todos
- If
architecture synthesis not in ACTIVE_STAGES, omit Phase 3 and Judge 3 todos
- If
decomposition not in ACTIVE_STAGES, omit Phase 4 and Judge 4 todos
- If
parallelize not in ACTIVE_STAGES, omit Phase 5 and Judge 5 todos
- If
verifications not in ACTIVE_STAGES, omit Phase 6 and Judge 6 todos
- If
HUMAN_IN_THE_LOOP_PHASES is empty, omit human checkpoint todo
Ensure directories exist:
Run the folder creation script to create task directories and configure gitignore:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/create-folders.sh
This creates:
.specs/tasks/draft/ - New tasks awaiting analysis
.specs/tasks/todo/ - Tasks ready to implement
.specs/tasks/in-progress/ - Currently being worked on
.specs/tasks/done/ - Completed tasks
.specs/scratchpad/ - Temporary working files (gitignored)
.specs/analysis/ - Codebase impact analysis files
.claude/skills/ - Reusable skill documents
Update each todo to in_progress when starting a phase and completed when judge passes.
CRITICAL
- Do not mark PASS for any judge if it did not pass the rubric. Retry the judge after each implementation change till it passes the check!
- Do not read task files in .claude or .specs directories, your job is orchestrate agents that will do the work, not do it by yourself!
- Use
THRESHOLD (default 3.5) for all judge pass/fail decisions, not hardcoded values!
- Use
MAX_ITERATIONS (default 3) for retry limits, not hardcoded values!
- After
MAX_ITERATIONS reached: PROCEED to next stage automatically - do NOT ask user unless phase is in HUMAN_IN_THE_LOOP_PHASES!
- Skip phases not in
ACTIVE_STAGES entirely - do not launch agents for excluded stages!
- Trigger human-in-the-loop checkpoints ONLY after phases in
HUMAN_IN_THE_LOOP_PHASES!
- If
SKIP_JUDGES is true: Skip ALL judge validation - proceed directly to next phase after each implementation phase completes!
- Task file must exist in
.specs/tasks/draft/ before running this command (unless --refine mode)!
- If
REFINE_MODE is true: Detect changes via git diff, skip unchanged stages, pass user feedback to agents!
Execution & Evaluation Rules
- Use foreground agents only: Do not use background agents. Launch parallel agents when possible. Background agents constantly run in permissions issues and other errors.
Relaunch judge till you get valid results, of following happens:
- Reject Long Reports: If an agent returns a very long report instead of using the scratchpad as requested, reject the result. This indicates the agent failed to follow the "use scratchpad" instruction.
- Judge Score 5.0 is a Hallucination: If a judge returns a score of 5.0/5.0, treat it as a hallucination or lazy evaluation. Reject it and re-run the judge. Perfect scores are practically impossible in this rigorous framework.
- Reject Missing Scores: If a judge report is missing the numerical score, reject it. This indicates the judge failed to read or follow the rubric instructions.
Workflow Execution
You MUST launch for each step a separate agent, instead of performing all steps yourself.
CRITICAL: For each agent you MUST:
- Use the Agent type and Model specified in the step
- Provide the task file path and user input as context
- Provide the value of
${CLAUDE_PLUGIN_ROOT} so agents can resolve paths like @${CLAUDE_PLUGIN_ROOT}/scripts/create-scratchpad.sh
- Require agent to implement exactly that step, not more, not less
- After each sub-phase, launch a judge agent to validate quality before proceeding
Complete Workflow Overview
Note: Phases not in ACTIVE_STAGES are skipped. If SKIP_JUDGES is true, all judge steps are skipped entirely. Human checkpoints (🔍) occur after phases in
HUMAN_IN_THE_LOOP_PHASES.
Input: Draft Task File (.specs/tasks/draft/*.md)
│
▼
Phase 2: Parallel Analysis
│
├─────────────────────┬─────────────────────┐
▼ ▼ ▼
Phase 2a: Phase 2b: Phase 2c:
Research Codebase Analysis Business Analysis
[sdd:researcher sonnet] [sdd:code-explorer sonnet] [sdd:business-analyst opus]
Judge 2a Judge 2b Judge 2c
(pass: >THRESHOLD) (pass: >THRESHOLD) (pass: >THRESHOLD)
│ │ │
└─────────────────────┴─────────────────────┘
│
▼
Phase 3: Architecture Synthesis
[sdd:software-architect opus]
Judge 3 (pass: >THRESHOLD)
│
▼
Phase 4: Decomposition
[sdd:tech-lead opus]
Judge 4 (pass: >THRESHOLD)
│
▼
Phase 5: Parallelize
[sdd:team-lead opus]
Judge 5 (pass: >THRESHOLD)
│
▼
Phase 6: Verifications
[sdd:qa-engineer opus]
Judge 6 (pass: >THRESHOLD)
│
▼
Move task: draft/ → todo/
│
▼
Complete
Phase 2: Parallel Analysis
Phase 2 launches three analysis phases in parallel, each with its own judge validation.
Phase 2a/2b/2c: Parallel Sub-Phases
Launch these three phases in parallel immediately:
Phase 2a: Research
Model: sonnet
Agent: sdd:researcher
Depends on: Task file exists
Purpose: Gather relevant resources, documentation, libraries, and prior art. Creates or updates a reusable skill.
Launch agent:
Description: "Research task resources and create/update skill"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Task File: <TASK_FILE>
Task Title: <title from task file>
CRITICAL: DO NOT OUTPUT YOUR RESEARCH, ONLY CREATE THE SCRATCHPAD AND SKILL FILE.
Capture:
- Skill file path (e.g.,
.claude/skills/<skill-name>/SKILL.md)
- Skill action (Created new / Updated existing)
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Number of resources gathered
- Key recommendation summary
CRITICAL: If expected files not created, launch the agent again with the same prompt.
Phase 2b: Codebase Impact Analysis
Model: sonnet
Agent: sdd:code-explorer
Depends on: Task file exists
Purpose: Identify affected files, interfaces, and integration points
Launch agent:
Description: "Analyze codebase impact"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Task File: <TASK_FILE>
Task Title: <title from task file>
CRITICAL: DO NOT OUTPUT YOUR ANALYSIS, ONLY CREATE THE SCRATCHPAD AND ANALYSIS FILE.
Capture:
- Analysis file path (e.g.,
.specs/analysis/analysis-{name}.md)
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Files affected count (modify/create/delete)
- Risk level assessment
- Key integration points
CRITICAL: If expected files not created, launch the agent again with the same prompt.
Phase 2c: Business Analysis
Model: opus
Agent: sdd:business-analyst
Depends on: Task file exists
Purpose: Refine description and create acceptance criteria
Launch agent:
Description: "Business analysis"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read ${CLAUDE_PLUGIN_ROOT}/skills/plan/analyse-business-requirements.md and execute it exactly as is!
Task File: <TASK_FILE>
Task Title: <title from task file>
CRITICAL: DO NOT OUTPUT YOUR BUSINESS ANALYSIS, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
Capture:
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Acceptance criteria count
- Scope defined (yes/no)
- User scenarios documented
Judge 2a/2b/2c: Validate Parallel Phases
After each parallel phase completes, launch its respective judge with the same agent type and model.
Judge 2a: Validate Research/Skill
Model: sonnet
Agent: sdd:researcher
Depends on: Phase 2a completion
Purpose: Validate skill completeness and relevance
Launch judge:
Description: "Judge skill quality"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
### Artifact Path
{path to skill file from Phase 2a}
### Context
This is a skill document for task: {task title}. Evaluate comprehensiveness and reusability.
### Rubric
1. Resource Coverage (weight: 0.30)
- Documentation and references gathered?
- Libraries and tools identified with recommendations?
- 1=Missing critical resources, 2=Basic coverage, 3=Adequate, 4=Comprehensive, 5=Excellent
2. Pattern Relevance (weight: 0.25)
- Are identified patterns applicable?
- Are recommendations actionable?
- 1=Irrelevant, 2=Somewhat useful, 3=Adequate, 4=Well-targeted, 5=Perfect fit
3. Issue Anticipation (weight: 0.20)
- Common pitfalls identified with solutions?
- 1=None identified, 2=Few issues, 3=Adequate, 4=Good coverage, 5=Comprehensive
4. Reusability (weight: 0.15)
- Is the skill general enough to help multiple tasks?
- Does it avoid task-specific details?
- 1=Too specific, 2=Limited reuse, 3=Adequate, 4=Good, 5=Highly reusable
5. Task Integration (weight: 0.10)
- Was task file updated with skill reference?
- 1=Not updated, 3=Updated, 5=Updated with clear instructions
CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
Decision Logic:
- PASS (score >=
THRESHOLD): Research complete, proceed
- FAIL (score <
THRESHOLD): Re-launch Phase 2a with feedback
- MAX_ITERATIONS reached: Proceed to next stage regardless of score (log warning)
Judge 2b: Validate Codebase Analysis
Model: sonnet
Agent: sdd:code-explorer
Depends on: Phase 2b completion
Purpose: Validate file identification accuracy and integration mapping
Launch judge:
Description: "Judge codebase analysis quality"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
### Artifact Path
{path to analysis file from Phase 2b}
### Context
This is codebase impact analysis for task: {task title}. Evaluate accuracy and completeness.
### Rubric
1. File Identification Accuracy (weight: 0.35)
- All affected files identified with specific paths?
- New files and modifications distinguished?
- 1=Major files missing, 2=Mostly correct, 3=Adequate, 4=Precise, 5=Complete
2. Interface Documentation (weight: 0.25)
- Key functions/classes documented with signatures?
- Change requirements clear?
- 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Complete
3. Integration Point Mapping (weight: 0.25)
- Integration points identified with impact?
- Similar patterns in codebase found?
- 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Comprehensive
4. Risk Assessment (weight: 0.15)
- High risk areas identified with mitigations?
- 1=No assessment, 2=Basic, 3=Adequate, 4=Good, 5=Thorough
CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
Decision Logic:
- PASS (score >=
THRESHOLD): Analysis complete, proceed
- FAIL (score <
THRESHOLD): Re-launch Phase 2b with feedback
- MAX_ITERATIONS reached: Proceed to next stage regardless of score (log warning)
Judge 2c: Validate Business Analysis
Model: opus
Agent: sdd:business-analyst
Depends on: Phase 2c completion
Purpose: Validate acceptance criteria quality and scope definition
Launch judge:
Description: "Judge business analysis quality"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
### Artifact Path
{path to task file from Phase 2c}
### Context
This is business analysis output. Evaluate description clarity and acceptance criteria quality.
### Rubric
1. Description Clarity (weight: 0.30)
- What/Why clearly explained?
- Scope boundaries defined?
- 1=Vague, 2=Basic, 3=Adequate, 4=Clear, 5=Excellent
2. Acceptance Criteria Quality (weight: 0.35)
- Criteria specific and testable?
- Given/When/Then format for complex criteria?
- 1=Missing/vague, 2=Basic, 3=Adequate, 4=Good, 5=Excellent
3. Scenario Coverage (weight: 0.20)
- Primary flow documented?
- Error scenarios considered?
- 1=Missing, 2=Basic, 3=Adequate, 4=Good, 5=Comprehensive
4. Scope Definition (weight: 0.15)
- In-scope/out-of-scope explicit?
- No implementation details in description?
- 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Clear
CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
Decision Logic:
- PASS (score >=
THRESHOLD): Business analysis complete, proceed
- FAIL (score <
THRESHOLD): Re-launch Phase 2c with feedback
- MAX_ITERATIONS reached: Proceed to next stage regardless of score (log warning)
Synchronization Point
Wait for ALL three parallel phases (2a, 2b, 2c) AND their judges to PASS before proceeding to Phase 3.
Phase 3: Architecture Synthesis
Model: opus
Agent: sdd:software-architect
Depends on: Phase 2a + Judge 2a PASS, Phase 2b + Judge 2b PASS, Phase 2c + Judge 2c PASS
Purpose: Synthesize research, analysis, and business requirements into architectural overview
Launch agent:
Description: "Architecture synthesis"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Task File: <TASK_FILE>
Skill File: <skill file path from Phase 2a>
Analysis File: <analysis file path from Phase 2b>
CRITICAL: DO NOT OUTPUT YOUR ARCHITECTURE SYNTHESIS, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
Capture:
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Sections added to task file
- Key architectural decisions count
- Components identified (if applicable)
- Contracts defined (if applicable)
Judge 3: Validate Architecture Synthesis
Model: opus
Agent: sdd:software-architect
Depends on: Phase 3 completion
Purpose: Validate architectural coherence and completeness
Launch judge:
Description: "Judge architecture synthesis quality"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
### Artifact Path
{path to task file after Phase 3}
### Context
This is architecture synthesis output. The Architecture Overview section should contain
solution strategy, key decisions, and only relevant architectural sections.
### Rubric
1. Solution Strategy Clarity (weight: 0.30)
- Approach clearly explained?
- Key decisions documented with reasoning?
- Trade-offs stated?
- 1=Missing/unclear, 2=Basic, 3=Adequate, 4=Clear, 5=Excellent
2. Reference Integration (weight: 0.20)
- Links to research and analysis files?
- Insights from both integrated?
- 1=No links, 2=Partial, 3=Adequate, 4=Good, 5=Fully integrated
3. Section Relevance (weight: 0.25)
- Only relevant sections included (not all)?
- Sections appropriate for task complexity?
- 1=Wrong sections, 2=Mostly appropriate, 3=Adequate, 4=Good, 5=Precisely targeted
4. Expected Changes Accuracy (weight: 0.25)
- Files to create/modify listed?
- Consistent with codebase analysis?
- 1=Missing/inconsistent, 2=Partial, 3=Adequate, 4=Good, 5=Complete
CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
Decision Logic:
- PASS (score >=
THRESHOLD): Architecture synthesis complete, proceed
- FAIL (score <
THRESHOLD): Re-launch Phase 3 with feedback
- MAX_ITERATIONS reached: Proceed to Phase 4 regardless of score (log warning)
Wait for PASS before Phase 4.
Phase 4: Decomposition
Model: opus
Agent: sdd:tech-lead
Depends on: Phase 3 + Judge 3 PASS
Purpose: Break architecture into implementation steps with success criteria and risks
Launch agent:
Description: "Decompose into implementation steps"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Task File: <TASK_FILE>
CRITICAL: DO NOT OUTPUT YOUR DECOMPOSITION, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
Capture:
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Implementation steps count
- Total subtasks count
- Critical path steps
- High priority risks count
Judge 4: Validate Decomposition
Model: opus
Agent: sdd:tech-lead
Depends on: Phase 4 completion
Purpose: Validate implementation steps quality and completeness
Launch judge:
Description: "Judge decomposition quality"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
### Artifact Path
{path to task file after Phase 4}
### Context
This is decomposition output. The Implementation Process section should contain
ordered steps with success criteria, subtasks, blockers, and risks.
### Rubric
1. Step Quality (weight: 0.30)
- Each step has clear goal, output, success criteria?
- Steps ordered by dependency?
- No step too large (>Large estimate)?
- 1=Vague/missing, 2=Basic, 3=Adequate, 4=Good, 5=Excellent
2. Success Criteria Testability (weight: 0.25)
- Criteria specific and verifiable?
- Use actual file paths, function names?
- Subtasks clearly defined with actionable descriptions?
- 1=Vague, 2=Partially testable, 3=Adequate, 4=Good, 5=All testable
3. Risk Coverage (weight: 0.25)
- Blockers identified with resolutions?
- Risks identified with mitigations?
- High-risk tasks identified with decomposition recommendations?
- 1=None, 2=Basic, 3=Adequate, 4=Good, 5=Comprehensive
4. Completeness (weight: 0.20)
- All architecture components have corresponding steps?
- Implementation summary table present?
- Definition of Done included?
- Phases organized: Setup → Foundational → User Stories → Polish?
- 1=Incomplete, 2=Partial, 3=Adequate, 4=Good, 5=Complete
CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
Decision Logic:
- PASS (score >=
THRESHOLD): Decomposition complete, proceed to Phase 5
- FAIL (score <
THRESHOLD): Re-launch Phase 4 with feedback
- MAX_ITERATIONS reached: Proceed to Phase 5 regardless of score (log warning)
Wait for PASS before Phase 5.
Phase 5: Parallelize Steps
Model: opus
Agent: sdd:team-lead
Depends on: Phase 4 + Judge 4 PASS
Purpose: Reorganize implementation steps for maximum parallel execution
Launch agent:
Description: "Parallelize implementation steps"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Task File: <TASK_FILE>
Use agents only from this list: {list ALL available agents with plugin prefix if available, e.g. sdd:developer, code-review:bug-hunter. Also include general agents: opus, sonnet, haiku}
CRITICAL: DO NOT OUTPUT YOUR PARALLELIZATION, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
Capture:
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Number of steps reorganized
- Maximum parallelization depth
- Agent distribution summary
Judge 5: Validate Parallelization
Model: opus
Agent: sdd:team-lead
Depends on: Phase 5 completion
Purpose: Validate dependency accuracy and parallelization optimization
Launch judge:
Description: "Judge parallelization quality"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
### Artifact Path
{path to parallelized task file from Phase 5}
### Context
This is the output of Phase 5: Parallelize Steps. The artifact should contain implementation steps
reorganized for maximum parallel execution with explicit dependencies, agent assignments, and
parallelization diagram.
Use agents only from this list: {list ALL available agents with plugin prefix if available, e.g. sdd:developer, code-review:bug-hunter. Also include general agents: opus, sonnet, haiku}
### Rubric
1. Dependency Accuracy (weight: 0.35)
- Are step dependencies correctly identified?
- No false dependencies (steps marked dependent when they're not)?
- No missing dependencies (steps that actually depend on others)?
- 1=Major dependency errors, 2=Mostly correct, 3=Acceptable, 5=Precise dependencies
2. Parallelization Maximized (weight: 0.30)
- Are parallelizable steps correctly marked with "Parallel with:"?
- Is the parallelization diagram logical?
- 1=No parallelization/wrong, 2=Some optimization, 3=Acceptable, 5=Maximum parallelization
3. Agent Selection Correctness (weight: 0.20)
- Are agent types appropriate for outputs (opus by default, haiku for trivial, sonnet for simple but high in volume)?
- Does selection follow the Agent Selection Guide?
- Are only agents from the provided available agents list used?
- 1=Wrong agents, 2=Mostly appropriate, 3=Acceptable, 4=Optimal selection, 5=Perfect selection
4. Execution Directive Present (weight: 0.15)
- Is the sub-agent execution directive present?
- Are "MUST" requirements for parallel execution clear?
- 1=Missing directive, 2=Partial, 3=Acceptable, 4=Complete directive, 5=Perfect directive
CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
Decision Logic:
- PASS (score >=
THRESHOLD): Proceed to Phase 6
- FAIL (score <
THRESHOLD): Re-launch Phase 5 with feedback
- MAX_ITERATIONS reached: Proceed to Phase 6 regardless of score (log warning)
Wait for PASS before Phase 6.
Phase 6: Define Verifications
Model: opus
Agent: sdd:qa-engineer
Depends on: Phase 5 + Judge 5 PASS
Purpose: Add LLM-as-Judge verification sections with rubrics
Launch agent:
Description: "Define verification rubrics"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Task File: <TASK_FILE>
CRITICAL: DO NOT OUTPUT YOUR VERIFICATIONS, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
Capture:
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Number of steps with verification
- Total evaluations defined
- Verification breakdown (Panel/Per-Item/None)
Judge 6: Validate Verifications
Model: opus
Agent: sdd:qa-engineer
Depends on: Phase 6 completion
Purpose: Validate verification rubrics and thresholds
Launch judge:
Description: "Judge verification quality"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
### Artifact Path
{path to task file with verifications from Phase 6}
### Context
This is the output of Phase 6: Define Verifications. The artifact should contain LLM-as-Judge
verification sections for each implementation step, including verification levels, custom rubrics,
thresholds, and a verification summary table.
### Rubric
1. Verification Level Appropriateness (weight: 0.30)
- Do verification levels match artifact criticality?
- HIGH criticality → Panel, MEDIUM → Single/Per-Item, LOW/NONE → None?
- 1=Mismatched levels, 2=Mostly appropriate, 3=Acceptable, 5=Precisely calibrated
2. Rubric Quality (weight: 0.30)
- Are criteria specific to the artifact type (not generic)?
- Do weights sum to 1.0?
- Are descriptions clear and measurable?
- 1=Generic/broken rubrics, 2=Adequate, 3=Acceptable, 5=Excellent custom rubrics
3. Threshold Appropriateness (weight: 0.20)
- Are thresholds reasonable (typically 4.0/5.0)?
- Higher for critical, lower for experimental?
- 1=Wrong thresholds, 2=Standard applied, 3=Acceptable, 5=Context-appropriate
4. Coverage Completeness (weight: 0.20)
- Does every step have a Verification section?
- Is the Verification Summary table present?
- 1=Missing verifications, 2=Most covered, 3=Acceptable, 5=100% coverage
CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
Decision Logic:
- PASS (score >=
THRESHOLD): Workflow complete, promote task
- FAIL (score <
THRESHOLD): Re-launch Phase 6 with feedback
- MAX_ITERATIONS reached: Complete workflow regardless of score (log warning)
Phase 7: Promote Task
Purpose: Move the refined task from draft to todo folder
After all phases complete:
Move task file from draft to todo:
git mv <TASK_FILE> .specs/tasks/todo/
# Fallback if git not available: mv <TASK_FILE> .specs/tasks/todo/
Update any references in research and analysis files if needed
Completion
After all executed phases and judges complete:
- Use git tool to stage the task file, skill file, analysis file, and scratchpad files (only those that were created)
- Summarize the workflow results and output to user:
### Task Refined
| Property | Value |
|----------|-------|
| **Original File** | `<original TASK_FILE path>` |
| **Final Location** | `.specs/tasks/todo/<filename>` (ready for implementation) |
| **Title** | `<task title>` |
| **Type** | `<feature/bug/refactor/test/docs/chore/ci>` (from filename) |
| **Skill** | `<skill file path or "Skipped">` |
| **Skill Action** | `<Created new / Updated existing / Skipped>` |
| **Analysis** | `<analysis file path or "Skipped">` |
| **Scratchpad** | `<scratchpad file path>` |
| **Implementation Steps** | `<count or "N/A">` |
| **Parallelization Depth** | `<max parallel agents or "N/A">` |
| **Total Verifications** | `<count or "N/A">` |
### Configuration Used
| Setting | Value |
|---------|-------|
| **Tar
…(truncated)
1---
2name: sdd-plan
3description: Refine, parallelize, and verify a draft task specification into a fully planned implementation-ready task
4argument-hint: Path to draft task file (e.g., ".specs/tasks/draft/add-validation.feature.md") [options]
5---
6
7# Refine Task Workflow
8
9## Role
10
11You are a task refinement orchestrator. Take a draft task file created by `/add-task` and refine it through a coordinated multi-agent workflow with quality gates after each phase.
12
13## Goal
14
15This workflow command refines an existing draft task through:
16
171. **Parallel Analysis** - Research, codebase analysis, and business analysis in parallel
182. **Architecture Synthesis** - Combine findings into architectural overview
193. **Decomposition** - Break into implementation steps with risks
204. **Parallelize** - Reorganize steps for maximum parallel execution
215. **Verify** - Add LLM-as-Judge verification sections
226. **Promote** - Move refined task from `draft/` to `todo/`
23
24All phases include judge validation to prevent error propagation and ensure quality thresholds are met.
25
26## User Input
27
28```text
29$ARGUMENTS
30```
31
32---
33
34## Command Arguments
35
36Parse the following arguments from `$ARGUMENTS`:
37
38### Argument Definitions
39
40| Argument | Format | Default | Description |
41|----------|--------|---------|-------------|
42| `task-file` | Path to task file | **Required** | Path to draft task file (e.g., `.specs/tasks/draft/add-validation.feature.md`) |
43| `--continue` | `--continue [stage]` | None | Continue refining from a specific stage. Stage is optional - resolve from context if not provided. |
44| `--target-quality` | `--target-quality X.X` | `3.5` | Target threshold value (out of 5.0) for judge pass/fail decisions. |
45| `--max-iterations` | `--max-iterations N` | `3` | Maximum implementation + judge retry cycles per phase before moving to next stage (regardless of pass/fail). |
46| `--included-stages` | `--included-stages stage1,stage2,...` | All stages | Comma-separated list of stages to include. |
47| `--skip` | `--skip stage1,stage2,...` | None | Comma-separated list of stages to exclude. |
48| `--fast` | `--fast` | N/A | Alias for `--target-quality 3.0 --max-iterations 1 --included-stages business analysis,decomposition,verifications` |
49| `--one-shot` | `--one-shot` | N/A | Alias for `--included-stages business analysis,decomposition --skip-judges` - minimal refinement without quality gates. |
50| `--human-in-the-loop` | `--human-in-the-loop phase1,phase2,...` | None | Phases after which to pause for human verification. |
51| `--skip-judges` | `--skip-judges` | `false` | Skip all judge validation checks - phases proceed without quality gates. |
52| `--refine` | `--refine` | `false` | Incremental refinement mode - detect changes against git and re-run only affected stages (top-to-bottom propagation). |
53
54### Stage Names (for `--included-stages` / `--skip`)
55
56| Stage Name | Phase | Description |
57|------------|-------|-------------|
58| `research` | 2a | Gather relevant resources, documentation, libraries |
59| `codebase analysis` | 2b | Identify affected files, interfaces, integration points |
60| `business analysis` | 2c | Refine description and create acceptance criteria |
61| `architecture synthesis` | 3 | Synthesize research and analysis into architecture |
62| `decomposition` | 4 | Break into implementation steps with risks |
63| `parallelize` | 5 | Reorganize steps for parallel execution |
64| `verifications` | 6 | Add LLM-as-Judge verification rubrics |
65
66### Configuration Resolution
67
68Parse `$ARGUMENTS` and resolve configuration as follows:
69
70```
71
72# Extract task file path (first positional argument, required)
73TASK_FILE = first argument that is a file path (must exist in .specs/tasks/draft/)
74
75# Parse alias flags first (they set multiple defaults)
76if --fast present:
77 THRESHOLD = 3.0
78 MAX_ITERATIONS = 1
79 INCLUDED_STAGES = ["business analysis", "decomposition", "verifications"]
80
81if --one-shot present:
82 INCLUDED_STAGES = ["business analysis", "decomposition"]
83 SKIP_JUDGES = true
84
85# Initialize defaults
86THRESHOLD ?= --target-quality || 3.5
87MAX_ITERATIONS ?= --max-iterations || 3
88INCLUDED_STAGES ?= --included-stages || ["research", "codebase analysis", "business analysis", "architecture synthesis", "decomposition", "parallelize", "verifications"]
89SKIP_STAGES = --skip || []
90HUMAN_IN_THE_LOOP_PHASES = --human-in-the-loop || []
91SKIP_JUDGES = --skip-judges || false
92REFINE_MODE = --refine || false
93CONTINUE_STAGE = null
94
95if --continue [stage] present:
96 CONTINUE_STAGE = stage or resolve from context
97
98# Compute final active stages
99ACTIVE_STAGES = INCLUDED_STAGES - SKIP_STAGES
100```
101
102### Context Resolution for `--continue`
103
104When `--continue` is used without explicit stage:
105
1061. **Stage Resolution:**
107 - Parse the task file for completion markers (e.g., `[x]` checkboxes)
108 - Identify the last completed phase/judge
109 - Resume from the next incomplete phase
110
111### Refine Mode Behavior (`--refine`)
112
113When `--refine` is used:
114
1151. **Change Detection:**
116 - First check file status: `git status --porcelain -- <TASK_FILE>`
117 - Compare current task file against last git commit: `git diff HEAD -- <TASK_FILE>`
118 - This captures both staged and unstaged changes vs HEAD
119 - If file is untracked or has no git history, compare against the original task structure
120 - Identify which sections have been modified by the user
121 - Look for `//` comment markers indicating user feedback/corrections
122
1232. **Top-to-Bottom Propagation:**
124 - Determine the **earliest modified section** (highest in document)
125 - Re-run only stages that correspond to or come **after** the modified section
126 - Earlier stages (above the modification) are preserved as-is
127
1283. **Section-to-Stage Mapping:**
129
130 | Modified Section | Re-run From Stage |
131 |------------------|-------------------|
132 | Description / Acceptance Criteria | `business analysis` (Phase 2c) |
133 | Architecture Overview | `architecture synthesis` (Phase 3) |
134 | Implementation Process / Steps | `decomposition` (Phase 4) |
135 | Parallelization / Dependencies | `parallelize` (Phase 5) |
136 | Verification sections | `verifications` (Phase 6) |
137
1384. **Refine Execution:**
139 - Skip research (2a) and codebase analysis (2b) unless explicitly requested
140 - Pass user modifications and `//` comments as additional context to agents
141 - Agents should incorporate user feedback while preserving unchanged content
142
1435. **Example:**
144
145 ```bash
146 # User edited the Architecture Overview section
147 /plan .specs/tasks/todo/my-task.feature.md --refine
148
149 # Detects Architecture section changed → re-runs from Phase 3 onwards
150 # Skips: research, codebase analysis, business analysis
151 # Runs: architecture synthesis, decomposition, parallelize, verifications
152 ```
153
154### Human-in-the-Loop Behavior
155
156Human verification checkpoints occur:
157
1581. **Trigger Conditions:**
159 - After implementation + judge verification **PASS** for a phase in `HUMAN_IN_THE_LOOP_PHASES`
160 - After implementation + judge + implementation retry (before the next judge retry)
161
1622. **At Checkpoint:**
163 - Display current phase results summary
164 - Display generated artifacts with paths
165 - Display judge score and feedback
166 - Ask user: "Review phase output. Continue? [Y/n/feedback]"
167 - If user provides feedback, incorporate into next iteration
168 - If user says "n", pause workflow
169
1703. **Checkpoint Message Format:**
171
172 ```markdown
173 ---
174 ## 🔍 Human Review Checkpoint - Phase X
175
176 **Phase:** {phase name}
177 **Judge Score:** {score}/{THRESHOLD} threshold
178 **Status:** ✅ PASS / ⚠️ RETRY {n}/{MAX_ITERATIONS}
179
180 **Artifacts:**
181 - {artifact_path_1}
182 - {artifact_path_2}
183
184 **Judge Feedback:**
185 {feedback summary}
186
187 **Action Required:** Review the above artifacts and provide feedback or continue.
188
189 > Continue? [Y/n/feedback]:
190 ---
191 ```
192
193---
194
195## Usage Examples
196
197```bash
198# Refine a draft task with all stages
199/plan .specs/tasks/draft/add-validation.feature.md
200
201# Fast refinement with minimal stages
202/plan .specs/tasks/draft/quick-fix.bug.md --fast
203
204# Continue from a specific stage
205/plan .specs/tasks/draft/complex-feature.feature.md --continue decomposition
206
207# High-quality refinement with checkpoints
208/plan .specs/tasks/draft/critical-api.feature.md --target-quality 4.5 --human-in-the-loop 2,3,4,5,6
209
210# Incremental refinement after user edits (re-runs only affected stages)
211/plan .specs/tasks/todo/my-task.feature.md --refine
212```
213
214## Pre-Flight Checks
215
216Before starting workflow:
217
2181. **Validate task file exists:**
219 - If `REFINE_MODE` is false: Check that `TASK_FILE` exists in `.specs/tasks/draft/`
220 - If `REFINE_MODE` is true: Check that `TASK_FILE` exists in `.specs/tasks/todo/` or `.specs/tasks/draft/`
221 - If not found, show error and exit
222
2232. **Parse and display resolved configuration:**
224
225 ```markdown
226 ### Configuration
227
228 | Setting | Value |
229 |---------|-------|
230 | **Task File** | {TASK_FILE} |
231 | **Target Quality** | {THRESHOLD}/5.0 |
232 | **Max Iterations** | {MAX_ITERATIONS} |
233 | **Active Stages** | {ACTIVE_STAGES as comma-separated list} |
234 | **Human Checkpoints** | Phase {HUMAN_IN_THE_LOOP_PHASES as comma-separated} |
235 | **Skip Judges** | {SKIP_JUDGES} |
236 | **Refine Mode** | {REFINE_MODE} |
237 | **Continue From** | {CONTINUE_STAGE} or "Start" |
238 ```
239
2403. **Handle `--continue` mode:**
241
242 If `CONTINUE_STAGE` is set:
243 - Read the task file to get current state
244 - Identify completed phases from task file content
245 - Skip to `CONTINUE_STAGE` (or auto-detected next incomplete stage)
246 - Pre-populate captured values from existing artifacts
247 - Resume workflow from the appropriate phase
248
2494. **Handle `--refine` mode:**
250
251 If `REFINE_MODE` is true:
252 - Check file status: `git status --porcelain -- <TASK_FILE>`
253 - `M` (staged) or `M` (unstaged) or `MM` (both) → proceed with diff
254 - `??` (untracked) → error: "File not tracked by git, cannot detect changes"
255 - Empty output → no changes detected
256 - Run `git diff HEAD -- <TASK_FILE>` to get all changes (staged + unstaged) vs last commit
257 - Parse diff to identify modified sections
258 - Collect any `//` comment markers as user feedback
259 - Determine earliest modified section using Section-to-Stage Mapping
260 - Set `ACTIVE_STAGES` to include only stages from the determined starting point onwards
261 - Pass detected changes and user comments as additional context to agents
262 - If no changes detected, inform user: "No changes detected in task file. Edit the file first, then run --refine." and exit
263
2645. **Extract task info from file:**
265 - Read task file to extract title and type from filename
266 - Parse frontmatter for title and depends_on
267
2686. **Initialize workflow progress tracking** using TodoWrite:
269
270 Only include todos for phases in `ACTIVE_STAGES`. If continuing, mark completed phases as `completed`.
271
272 ```json
273 {
274 "todos": [
275 {"content": "Ensure directories exist", "status": "pending", "activeForm": "Ensuring directories exist"},
276 {"content": "Phase 2a: Research relevant resources and documentation", "status": "pending", "activeForm": "Researching resources"},
277 {"content": "Judge 2a: PASS research quality (> {THRESHOLD})", "status": "pending", "activeForm": "Validating research"},
278 {"content": "Phase 2b: Analyze codebase impact and affected files", "status": "pending", "activeForm": "Analyzing codebase impact"},
279 {"content": "Judge 2b: PASS codebase analysis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating codebase analysis"},
280 {"content": "Phase 2c: Business analysis and acceptance criteria", "status": "pending", "activeForm": "Analyzing business requirements"},
281 {"content": "Judge 2c: PASS business analysis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating business analysis"},
282 {"content": "Phase 3: Architecture synthesis from research and analysis", "status": "pending", "activeForm": "Synthesizing architecture"},
283 {"content": "Judge 3: PASS architecture synthesis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating architecture"},
284 {"content": "Phase 4: Decompose into implementation steps", "status": "pending", "activeForm": "Decomposing into steps"},
285 {"content": "Judge 4: PASS decomposition (> {THRESHOLD})", "status": "pending", "activeForm": "Validating decomposition"},
286 {"content": "Phase 5: Parallelize implementation steps", "status": "pending", "activeForm": "Parallelizing steps"},
287 {"content": "Judge 5: PASS parallelization (> {THRESHOLD})", "status": "pending", "activeForm": "Validating parallelization"},
288 {"content": "Phase 6: Define verification rubrics", "status": "pending", "activeForm": "Defining verifications"},
289 {"content": "Judge 6: PASS verifications (> {THRESHOLD})", "status": "pending", "activeForm": "Validating verifications"},
290 {"content": "Move task to todo folder", "status": "pending", "activeForm": "Promoting task"},
291 {"content": "Human checkpoint reviews", "status": "pending", "activeForm": "Awaiting human review"}
292 ]
293 }
294 ```
295
296 **Note:** Filter todos based on configuration:
297 - If `SKIP_JUDGES` is true, omit ALL Judge todos (Judge 2a, 2b, 2c, 3, 4, 5, 6)
298 - If `research` not in `ACTIVE_STAGES`, omit Phase 2a and Judge 2a todos
299 - If `codebase analysis` not in `ACTIVE_STAGES`, omit Phase 2b and Judge 2b todos
300 - If `business analysis` not in `ACTIVE_STAGES`, omit Phase 2c and Judge 2c todos
301 - If `architecture synthesis` not in `ACTIVE_STAGES`, omit Phase 3 and Judge 3 todos
302 - If `decomposition` not in `ACTIVE_STAGES`, omit Phase 4 and Judge 4 todos
303 - If `parallelize` not in `ACTIVE_STAGES`, omit Phase 5 and Judge 5 todos
304 - If `verifications` not in `ACTIVE_STAGES`, omit Phase 6 and Judge 6 todos
305 - If `HUMAN_IN_THE_LOOP_PHASES` is empty, omit human checkpoint todo
306
3077. **Ensure directories exist**:
308
309 Run the folder creation script to create task directories and configure gitignore:
310
311 ```bash
312 bash ${CLAUDE_PLUGIN_ROOT}/scripts/create-folders.sh
313 ```
314
315 This creates:
316
317 - `.specs/tasks/draft/` - New tasks awaiting analysis
318 - `.specs/tasks/todo/` - Tasks ready to implement
319 - `.specs/tasks/in-progress/` - Currently being worked on
320 - `.specs/tasks/done/` - Completed tasks
321 - `.specs/scratchpad/` - Temporary working files (gitignored)
322 - `.specs/analysis/` - Codebase impact analysis files
323 - `.claude/skills/` - Reusable skill documents
324
325Update each todo to `in_progress` when starting a phase and `completed` when judge passes.
326
327## CRITICAL
328
329- Do not mark PASS for any judge if it did not pass the rubric. Retry the judge after each implementation change till it passes the check!
330- Do not read task files in .claude or .specs directories, your job is orchestrate agents that will do the work, not do it by yourself!
331- Use `THRESHOLD` (default 3.5) for all judge pass/fail decisions, not hardcoded values!
332- Use `MAX_ITERATIONS` (default 3) for retry limits, not hardcoded values!
333- **After `MAX_ITERATIONS` reached: PROCEED to next stage automatically - do NOT ask user unless phase is in `HUMAN_IN_THE_LOOP_PHASES`!**
334- Skip phases not in `ACTIVE_STAGES` entirely - do not launch agents for excluded stages!
335- Trigger human-in-the-loop checkpoints ONLY after phases in `HUMAN_IN_THE_LOOP_PHASES`!
336- **If `SKIP_JUDGES` is true: Skip ALL judge validation - proceed directly to next phase after each implementation phase completes!**
337- **Task file must exist in `.specs/tasks/draft/` before running this command (unless `--refine` mode)!**
338- **If `REFINE_MODE` is true: Detect changes via git diff, skip unchanged stages, pass user feedback to agents!**
339
340### Execution & Evaluation Rules
341
342- **Use foreground agents only**: Do not use background agents. Launch parallel agents when possible. Background agents constantly run in permissions issues and other errors.
343
344Relaunch judge till you get valid results, of following happens:
345
346- Reject Long Reports: If an agent returns a very long report instead of using the scratchpad as requested, reject the result. This indicates the agent failed to follow the "use scratchpad" instruction.
347- Judge Score 5.0 is a Hallucination: If a judge returns a score of 5.0/5.0, treat it as a hallucination or lazy evaluation. Reject it and re-run the judge. Perfect scores are practically impossible in this rigorous framework.
348- Reject Missing Scores: If a judge report is missing the numerical score, reject it. This indicates the judge failed to read or follow the rubric instructions.
349
350## Workflow Execution
351
352You MUST launch for each step a separate agent, instead of performing all steps yourself.
353
354**CRITICAL:** For each agent you MUST:
355
3561. Use the **Agent** type and **Model** specified in the step
3572. Provide the task file path and user input as context
3583. **Provide the value of `${CLAUDE_PLUGIN_ROOT}` so agents can resolve paths like `@${CLAUDE_PLUGIN_ROOT}/scripts/create-scratchpad.sh`**
3594. Require agent to implement exactly that step, not more, not less
3605. After each sub-phase, launch a judge agent to validate quality before proceeding
361
362### Complete Workflow Overview
363
364**Note:** Phases not in `ACTIVE_STAGES` are skipped. If `SKIP_JUDGES` is true, all judge steps are skipped entirely. Human checkpoints (🔍) occur after phases in
365`HUMAN_IN_THE_LOOP_PHASES`.
366
367```
368Input: Draft Task File (.specs/tasks/draft/*.md)
369 │
370 ▼
371Phase 2: Parallel Analysis
372 │
373 ├─────────────────────┬─────────────────────┐
374 ▼ ▼ ▼
375Phase 2a: Phase 2b: Phase 2c:
376Research Codebase Analysis Business Analysis
377[sdd:researcher sonnet] [sdd:code-explorer sonnet] [sdd:business-analyst opus]
378Judge 2a Judge 2b Judge 2c
379(pass: >THRESHOLD) (pass: >THRESHOLD) (pass: >THRESHOLD)
380 │ │ │
381 └─────────────────────┴─────────────────────┘
382 │
383 ▼
384 Phase 3: Architecture Synthesis
385 [sdd:software-architect opus]
386 Judge 3 (pass: >THRESHOLD)
387 │
388 ▼
389 Phase 4: Decomposition
390 [sdd:tech-lead opus]
391 Judge 4 (pass: >THRESHOLD)
392 │
393 ▼
394 Phase 5: Parallelize
395 [sdd:team-lead opus]
396 Judge 5 (pass: >THRESHOLD)
397 │
398 ▼
399 Phase 6: Verifications
400 [sdd:qa-engineer opus]
401 Judge 6 (pass: >THRESHOLD)
402 │
403 ▼
404 Move task: draft/ → todo/
405 │
406 ▼
407 Complete
408```
409
410---
411
412## Phase 2: Parallel Analysis
413
414Phase 2 launches three analysis phases in parallel, each with its own judge validation.
415
416### Phase 2a/2b/2c: Parallel Sub-Phases
417
418Launch these three phases **in parallel** immediately:
419
420---
421
422#### Phase 2a: Research
423
424**Model:** `sonnet`
425**Agent:** `sdd:researcher`
426**Depends on:** Task file exists
427**Purpose:** Gather relevant resources, documentation, libraries, and prior art. Creates or updates a reusable skill.
428
429Launch agent:
430
431- **Description**: "Research task resources and create/update skill"
432- **Prompt**:
433
434 ```
435 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
436
437 Task File: <TASK_FILE>
438 Task Title: <title from task file>
439
440 CRITICAL: DO NOT OUTPUT YOUR RESEARCH, ONLY CREATE THE SCRATCHPAD AND SKILL FILE.
441 ```
442
443**Capture:**
444
445- Skill file path (e.g., `.claude/skills/<skill-name>/SKILL.md`)
446- Skill action (Created new / Updated existing)
447- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
448- Number of resources gathered
449- Key recommendation summary
450
451CRITICAL: If expected files not created, launch the agent again with the same prompt.
452
453---
454
455#### Phase 2b: Codebase Impact Analysis
456
457**Model:** `sonnet`
458**Agent:** `sdd:code-explorer`
459**Depends on:** Task file exists
460**Purpose:** Identify affected files, interfaces, and integration points
461
462Launch agent:
463
464- **Description**: "Analyze codebase impact"
465- **Prompt**:
466
467 ```text
468 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
469
470 Task File: <TASK_FILE>
471 Task Title: <title from task file>
472
473 CRITICAL: DO NOT OUTPUT YOUR ANALYSIS, ONLY CREATE THE SCRATCHPAD AND ANALYSIS FILE.
474 ```
475
476**Capture:**
477
478- Analysis file path (e.g., `.specs/analysis/analysis-{name}.md`)
479- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
480- Files affected count (modify/create/delete)
481- Risk level assessment
482- Key integration points
483
484CRITICAL: If expected files not created, launch the agent again with the same prompt.
485
486---
487
488#### Phase 2c: Business Analysis
489
490**Model:** `opus`
491**Agent:** `sdd:business-analyst`
492**Depends on:** Task file exists
493**Purpose:** Refine description and create acceptance criteria
494
495Launch agent:
496
497- **Description**: "Business analysis"
498- **Prompt**:
499
500 ```
501 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
502
503 Read ${CLAUDE_PLUGIN_ROOT}/skills/plan/analyse-business-requirements.md and execute it exactly as is!
504
505 Task File: <TASK_FILE>
506 Task Title: <title from task file>
507
508 CRITICAL: DO NOT OUTPUT YOUR BUSINESS ANALYSIS, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
509 ```
510
511**Capture:**
512
513- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
514- Acceptance criteria count
515- Scope defined (yes/no)
516- User scenarios documented
517
518---
519
520### Judge 2a/2b/2c: Validate Parallel Phases
521
522After **each** parallel phase completes, launch its respective judge **with the same agent type and model**.
523
524#### Judge 2a: Validate Research/Skill
525
526**Model:** `sonnet`
527**Agent:** `sdd:researcher`
528**Depends on:** Phase 2a completion
529**Purpose:** Validate skill completeness and relevance
530
531Launch judge:
532
533- **Description**: "Judge skill quality"
534- **Prompt**:
535
536 ```
537 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
538
539 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
540
541 ### Artifact Path
542 {path to skill file from Phase 2a}
543
544 ### Context
545 This is a skill document for task: {task title}. Evaluate comprehensiveness and reusability.
546
547 ### Rubric
548 1. Resource Coverage (weight: 0.30)
549 - Documentation and references gathered?
550 - Libraries and tools identified with recommendations?
551 - 1=Missing critical resources, 2=Basic coverage, 3=Adequate, 4=Comprehensive, 5=Excellent
552
553 2. Pattern Relevance (weight: 0.25)
554 - Are identified patterns applicable?
555 - Are recommendations actionable?
556 - 1=Irrelevant, 2=Somewhat useful, 3=Adequate, 4=Well-targeted, 5=Perfect fit
557
558 3. Issue Anticipation (weight: 0.20)
559 - Common pitfalls identified with solutions?
560 - 1=None identified, 2=Few issues, 3=Adequate, 4=Good coverage, 5=Comprehensive
561
562 4. Reusability (weight: 0.15)
563 - Is the skill general enough to help multiple tasks?
564 - Does it avoid task-specific details?
565 - 1=Too specific, 2=Limited reuse, 3=Adequate, 4=Good, 5=Highly reusable
566
567 5. Task Integration (weight: 0.10)
568 - Was task file updated with skill reference?
569 - 1=Not updated, 3=Updated, 5=Updated with clear instructions
570 ```
571
572CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
573
574**Decision Logic:**
575
576- **PASS** (score >= `THRESHOLD`): Research complete, proceed
577- **FAIL** (score < `THRESHOLD`): Re-launch Phase 2a with feedback
578- **MAX_ITERATIONS reached**: Proceed to next stage regardless of score (log warning)
579
580---
581
582#### Judge 2b: Validate Codebase Analysis
583
584**Model:** `sonnet`
585**Agent:** `sdd:code-explorer`
586**Depends on:** Phase 2b completion
587**Purpose:** Validate file identification accuracy and integration mapping
588
589Launch judge:
590
591- **Description**: "Judge codebase analysis quality"
592- **Prompt**:
593
594 ```
595 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
596
597 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
598
599 ### Artifact Path
600 {path to analysis file from Phase 2b}
601
602 ### Context
603 This is codebase impact analysis for task: {task title}. Evaluate accuracy and completeness.
604
605 ### Rubric
606 1. File Identification Accuracy (weight: 0.35)
607 - All affected files identified with specific paths?
608 - New files and modifications distinguished?
609 - 1=Major files missing, 2=Mostly correct, 3=Adequate, 4=Precise, 5=Complete
610
611 2. Interface Documentation (weight: 0.25)
612 - Key functions/classes documented with signatures?
613 - Change requirements clear?
614 - 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Complete
615
616 3. Integration Point Mapping (weight: 0.25)
617 - Integration points identified with impact?
618 - Similar patterns in codebase found?
619 - 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Comprehensive
620
621 4. Risk Assessment (weight: 0.15)
622 - High risk areas identified with mitigations?
623 - 1=No assessment, 2=Basic, 3=Adequate, 4=Good, 5=Thorough
624 ```
625
626CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
627
628**Decision Logic:**
629
630- **PASS** (score >= `THRESHOLD`): Analysis complete, proceed
631- **FAIL** (score < `THRESHOLD`): Re-launch Phase 2b with feedback
632- **MAX_ITERATIONS reached**: Proceed to next stage regardless of score (log warning)
633
634---
635
636#### Judge 2c: Validate Business Analysis
637
638**Model:** `opus`
639**Agent:** `sdd:business-analyst`
640**Depends on:** Phase 2c completion
641**Purpose:** Validate acceptance criteria quality and scope definition
642
643Launch judge:
644
645- **Description**: "Judge business analysis quality"
646- **Prompt**:
647
648 ```
649 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
650
651 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
652
653 ### Artifact Path
654 {path to task file from Phase 2c}
655
656 ### Context
657 This is business analysis output. Evaluate description clarity and acceptance criteria quality.
658
659 ### Rubric
660 1. Description Clarity (weight: 0.30)
661 - What/Why clearly explained?
662 - Scope boundaries defined?
663 - 1=Vague, 2=Basic, 3=Adequate, 4=Clear, 5=Excellent
664
665 2. Acceptance Criteria Quality (weight: 0.35)
666 - Criteria specific and testable?
667 - Given/When/Then format for complex criteria?
668 - 1=Missing/vague, 2=Basic, 3=Adequate, 4=Good, 5=Excellent
669
670 3. Scenario Coverage (weight: 0.20)
671 - Primary flow documented?
672 - Error scenarios considered?
673 - 1=Missing, 2=Basic, 3=Adequate, 4=Good, 5=Comprehensive
674
675 4. Scope Definition (weight: 0.15)
676 - In-scope/out-of-scope explicit?
677 - No implementation details in description?
678 - 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Clear
679 ```
680
681CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
682
683**Decision Logic:**
684
685- **PASS** (score >= `THRESHOLD`): Business analysis complete, proceed
686- **FAIL** (score < `THRESHOLD`): Re-launch Phase 2c with feedback
687- **MAX_ITERATIONS reached**: Proceed to next stage regardless of score (log warning)
688
689---
690
691### Synchronization Point
692
693**Wait for ALL three parallel phases (2a, 2b, 2c) AND their judges to PASS before proceeding to Phase 3.**
694
695---
696
697## Phase 3: Architecture Synthesis
698
699**Model:** `opus`
700**Agent:** `sdd:software-architect`
701**Depends on:** Phase 2a + Judge 2a PASS, Phase 2b + Judge 2b PASS, Phase 2c + Judge 2c PASS
702**Purpose:** Synthesize research, analysis, and business requirements into architectural overview
703
704Launch agent:
705
706- **Description**: "Architecture synthesis"
707- **Prompt**:
708
709 ```
710 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
711
712 Task File: <TASK_FILE>
713 Skill File: <skill file path from Phase 2a>
714 Analysis File: <analysis file path from Phase 2b>
715
716 CRITICAL: DO NOT OUTPUT YOUR ARCHITECTURE SYNTHESIS, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
717 ```
718
719**Capture:**
720
721- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
722- Sections added to task file
723- Key architectural decisions count
724- Components identified (if applicable)
725- Contracts defined (if applicable)
726
727---
728
729### Judge 3: Validate Architecture Synthesis
730
731**Model:** `opus`
732**Agent:** `sdd:software-architect`
733**Depends on:** Phase 3 completion
734**Purpose:** Validate architectural coherence and completeness
735
736Launch judge:
737
738- **Description**: "Judge architecture synthesis quality"
739- **Prompt**:
740
741 ```
742 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
743
744 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
745
746 ### Artifact Path
747 {path to task file after Phase 3}
748
749 ### Context
750 This is architecture synthesis output. The Architecture Overview section should contain
751 solution strategy, key decisions, and only relevant architectural sections.
752
753 ### Rubric
754 1. Solution Strategy Clarity (weight: 0.30)
755 - Approach clearly explained?
756 - Key decisions documented with reasoning?
757 - Trade-offs stated?
758 - 1=Missing/unclear, 2=Basic, 3=Adequate, 4=Clear, 5=Excellent
759
760 2. Reference Integration (weight: 0.20)
761 - Links to research and analysis files?
762 - Insights from both integrated?
763 - 1=No links, 2=Partial, 3=Adequate, 4=Good, 5=Fully integrated
764
765 3. Section Relevance (weight: 0.25)
766 - Only relevant sections included (not all)?
767 - Sections appropriate for task complexity?
768 - 1=Wrong sections, 2=Mostly appropriate, 3=Adequate, 4=Good, 5=Precisely targeted
769
770 4. Expected Changes Accuracy (weight: 0.25)
771 - Files to create/modify listed?
772 - Consistent with codebase analysis?
773 - 1=Missing/inconsistent, 2=Partial, 3=Adequate, 4=Good, 5=Complete
774
775 ```
776
777CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
778
779**Decision Logic:**
780
781- **PASS** (score >= `THRESHOLD`): Architecture synthesis complete, proceed
782- **FAIL** (score < `THRESHOLD`): Re-launch Phase 3 with feedback
783- **MAX_ITERATIONS reached**: Proceed to Phase 4 regardless of score (log warning)
784
785**Wait for PASS before Phase 4.**
786
787---
788
789## Phase 4: Decomposition
790
791**Model:** `opus`
792**Agent:** `sdd:tech-lead`
793**Depends on:** Phase 3 + Judge 3 PASS
794**Purpose:** Break architecture into implementation steps with success criteria and risks
795
796Launch agent:
797
798- **Description**: "Decompose into implementation steps"
799- **Prompt**:
800
801 ```
802 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
803
804 Task File: <TASK_FILE>
805
806 CRITICAL: DO NOT OUTPUT YOUR DECOMPOSITION, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
807 ```
808
809**Capture:**
810
811- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
812- Implementation steps count
813- Total subtasks count
814- Critical path steps
815- High priority risks count
816
817---
818
819### Judge 4: Validate Decomposition
820
821**Model:** `opus`
822**Agent:** `sdd:tech-lead`
823**Depends on:** Phase 4 completion
824**Purpose:** Validate implementation steps quality and completeness
825
826Launch judge:
827
828- **Description**: "Judge decomposition quality"
829- **Prompt**:
830
831 ```
832 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
833
834 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
835
836 ### Artifact Path
837 {path to task file after Phase 4}
838
839 ### Context
840 This is decomposition output. The Implementation Process section should contain
841 ordered steps with success criteria, subtasks, blockers, and risks.
842
843 ### Rubric
844 1. Step Quality (weight: 0.30)
845 - Each step has clear goal, output, success criteria?
846 - Steps ordered by dependency?
847 - No step too large (>Large estimate)?
848 - 1=Vague/missing, 2=Basic, 3=Adequate, 4=Good, 5=Excellent
849
850 2. Success Criteria Testability (weight: 0.25)
851 - Criteria specific and verifiable?
852 - Use actual file paths, function names?
853 - Subtasks clearly defined with actionable descriptions?
854 - 1=Vague, 2=Partially testable, 3=Adequate, 4=Good, 5=All testable
855
856 3. Risk Coverage (weight: 0.25)
857 - Blockers identified with resolutions?
858 - Risks identified with mitigations?
859 - High-risk tasks identified with decomposition recommendations?
860 - 1=None, 2=Basic, 3=Adequate, 4=Good, 5=Comprehensive
861
862 4. Completeness (weight: 0.20)
863 - All architecture components have corresponding steps?
864 - Implementation summary table present?
865 - Definition of Done included?
866 - Phases organized: Setup → Foundational → User Stories → Polish?
867 - 1=Incomplete, 2=Partial, 3=Adequate, 4=Good, 5=Complete
868 ```
869
870CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
871
872**Decision Logic:**
873
874- **PASS** (score >= `THRESHOLD`): Decomposition complete, proceed to Phase 5
875- **FAIL** (score < `THRESHOLD`): Re-launch Phase 4 with feedback
876- **MAX_ITERATIONS reached**: Proceed to Phase 5 regardless of score (log warning)
877
878**Wait for PASS before Phase 5.**
879
880---
881
882## Phase 5: Parallelize Steps
883
884**Model:** `opus`
885**Agent:** `sdd:team-lead`
886**Depends on:** Phase 4 + Judge 4 PASS
887**Purpose:** Reorganize implementation steps for maximum parallel execution
888
889Launch agent:
890
891- **Description**: "Parallelize implementation steps"
892- **Prompt**:
893
894 ```
895 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
896
897 Task File: <TASK_FILE>
898
899 Use agents only from this list: {list ALL available agents with plugin prefix if available, e.g. sdd:developer, code-review:bug-hunter. Also include general agents: opus, sonnet, haiku}
900
901 CRITICAL: DO NOT OUTPUT YOUR PARALLELIZATION, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
902 ```
903
904**Capture:**
905
906- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
907- Number of steps reorganized
908- Maximum parallelization depth
909- Agent distribution summary
910
911---
912
913### Judge 5: Validate Parallelization
914
915**Model:** `opus`
916**Agent:** `sdd:team-lead`
917**Depends on:** Phase 5 completion
918**Purpose:** Validate dependency accuracy and parallelization optimization
919
920Launch judge:
921
922- **Description**: "Judge parallelization quality"
923- **Prompt**:
924
925 ```
926 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
927
928 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
929
930 ### Artifact Path
931 {path to parallelized task file from Phase 5}
932
933 ### Context
934 This is the output of Phase 5: Parallelize Steps. The artifact should contain implementation steps
935 reorganized for maximum parallel execution with explicit dependencies, agent assignments, and
936 parallelization diagram.
937
938 Use agents only from this list: {list ALL available agents with plugin prefix if available, e.g. sdd:developer, code-review:bug-hunter. Also include general agents: opus, sonnet, haiku}
939
940 ### Rubric
941 1. Dependency Accuracy (weight: 0.35)
942 - Are step dependencies correctly identified?
943 - No false dependencies (steps marked dependent when they're not)?
944 - No missing dependencies (steps that actually depend on others)?
945 - 1=Major dependency errors, 2=Mostly correct, 3=Acceptable, 5=Precise dependencies
946
947 2. Parallelization Maximized (weight: 0.30)
948 - Are parallelizable steps correctly marked with "Parallel with:"?
949 - Is the parallelization diagram logical?
950 - 1=No parallelization/wrong, 2=Some optimization, 3=Acceptable, 5=Maximum parallelization
951
952 3. Agent Selection Correctness (weight: 0.20)
953 - Are agent types appropriate for outputs (opus by default, haiku for trivial, sonnet for simple but high in volume)?
954 - Does selection follow the Agent Selection Guide?
955 - Are only agents from the provided available agents list used?
956 - 1=Wrong agents, 2=Mostly appropriate, 3=Acceptable, 4=Optimal selection, 5=Perfect selection
957
958 4. Execution Directive Present (weight: 0.15)
959 - Is the sub-agent execution directive present?
960 - Are "MUST" requirements for parallel execution clear?
961 - 1=Missing directive, 2=Partial, 3=Acceptable, 4=Complete directive, 5=Perfect directive
962 ```
963
964CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
965
966**Decision Logic:**
967
968- **PASS** (score >= `THRESHOLD`): Proceed to Phase 6
969- **FAIL** (score < `THRESHOLD`): Re-launch Phase 5 with feedback
970- **MAX_ITERATIONS reached**: Proceed to Phase 6 regardless of score (log warning)
971
972**Wait for PASS before Phase 6.**
973
974---
975
976## Phase 6: Define Verifications
977
978**Model:** `opus`
979**Agent:** `sdd:qa-engineer`
980**Depends on:** Phase 5 + Judge 5 PASS
981**Purpose:** Add LLM-as-Judge verification sections with rubrics
982
983Launch agent:
984
985- **Description**: "Define verification rubrics"
986- **Prompt**:
987
988 ```
989 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
990
991 Task File: <TASK_FILE>
992
993 CRITICAL: DO NOT OUTPUT YOUR VERIFICATIONS, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
994 ```
995
996**Capture:**
997
998- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
999- Number of steps with verification
1000- Total evaluations defined
1001- Verification breakdown (Panel/Per-Item/None)
1002
1003---
1004
1005### Judge 6: Validate Verifications
1006
1007**Model:** `opus`
1008**Agent:** `sdd:qa-engineer`
1009**Depends on:** Phase 6 completion
1010**Purpose:** Validate verification rubrics and thresholds
1011
1012Launch judge:
1013
1014- **Description**: "Judge verification quality"
1015- **Prompt**:
1016
1017 ```
1018 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
1019
1020 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
1021
1022 ### Artifact Path
1023 {path to task file with verifications from Phase 6}
1024
1025 ### Context
1026 This is the output of Phase 6: Define Verifications. The artifact should contain LLM-as-Judge
1027 verification sections for each implementation step, including verification levels, custom rubrics,
1028 thresholds, and a verification summary table.
1029
1030 ### Rubric
1031 1. Verification Level Appropriateness (weight: 0.30)
1032 - Do verification levels match artifact criticality?
1033 - HIGH criticality → Panel, MEDIUM → Single/Per-Item, LOW/NONE → None?
1034 - 1=Mismatched levels, 2=Mostly appropriate, 3=Acceptable, 5=Precisely calibrated
1035
1036 2. Rubric Quality (weight: 0.30)
1037 - Are criteria specific to the artifact type (not generic)?
1038 - Do weights sum to 1.0?
1039 - Are descriptions clear and measurable?
1040 - 1=Generic/broken rubrics, 2=Adequate, 3=Acceptable, 5=Excellent custom rubrics
1041
1042 3. Threshold Appropriateness (weight: 0.20)
1043 - Are thresholds reasonable (typically 4.0/5.0)?
1044 - Higher for critical, lower for experimental?
1045 - 1=Wrong thresholds, 2=Standard applied, 3=Acceptable, 5=Context-appropriate
1046
1047 4. Coverage Completeness (weight: 0.20)
1048 - Does every step have a Verification section?
1049 - Is the Verification Summary table present?
1050 - 1=Missing verifications, 2=Most covered, 3=Acceptable, 5=100% coverage
1051 ```
1052
1053CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
1054
1055**Decision Logic:**
1056
1057- **PASS** (score >= `THRESHOLD`): Workflow complete, promote task
1058- **FAIL** (score < `THRESHOLD`): Re-launch Phase 6 with feedback
1059- **MAX_ITERATIONS reached**: Complete workflow regardless of score (log warning)
1060
1061---
1062
1063## Phase 7: Promote Task
1064
1065**Purpose:** Move the refined task from draft to todo folder
1066
1067After all phases complete:
1068
10691. **Move task file from draft to todo:**
1070
1071 ```bash
1072 git mv <TASK_FILE> .specs/tasks/todo/
1073 # Fallback if git not available: mv <TASK_FILE> .specs/tasks/todo/
1074 ```
1075
10762. **Update any references** in research and analysis files if needed
1077
1078---
1079
1080## Completion
1081
1082After all executed phases and judges complete:
1083
10841. Use git tool to stage the task file, skill file, analysis file, and scratchpad files (only those that were created)
10852. Summarize the workflow results and output to user:
1086
1087```markdown
1088### Task Refined
1089
1090| Property | Value |
1091|----------|-------|
1092| **Original File** | `<original TASK_FILE path>` |
1093| **Final Location** | `.specs/tasks/todo/<filename>` (ready for implementation) |
1094| **Title** | `<task title>` |
1095| **Type** | `<feature/bug/refactor/test/docs/chore/ci>` (from filename) |
1096| **Skill** | `<skill file path or "Skipped">` |
1097| **Skill Action** | `<Created new / Updated existing / Skipped>` |
1098| **Analysis** | `<analysis file path or "Skipped">` |
1099| **Scratchpad** | `<scratchpad file path>` |
1100| **Implementation Steps** | `<count or "N/A">` |
1101| **Parallelization Depth** | `<max parallel agents or "N/A">` |
1102| **Total Verifications** | `<count or "N/A">` |
1103
1104### Configuration Used
1105
1106| Setting | Value |
1107|---------|-------|
1108| **Target Quality** | {THRESHOLD}/5.0 |
1109| **Max Iterations** | {MAX_ITERATIONS} |
1110| **Active Stages** | {ACTIVE_STAGES as comma-separated list} |
1111| **Skipped Stages** | {SKIP_STAGES or stages not in ACTIVE_STAGES} |
1112| **Human Checkpoints** | Phase {HUMAN_IN_THE_LOOP_PHASES as comma-separated} |
1113| **Skip Judges** | {SKIP_JUDGES} |
1114| **Refine Mode** | {REFINE_MODE} |
1115
1116### Quality Gates Summary
1117
1118| Phase | Judge Score | Verdict |
1119|-------|-------------|---------|
1120| Phase 2a: Research | X.X/5.0 | ✅ PASS / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1121| Phase 2b: Codebase Analysis | X.X/5.0 | ✅ PASS / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1122| Phase 2c: Business Analysis | X.X/5.0 | ✅ PASS / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1123| Phase 3: Architecture Synthesis | X.X/5.0 | ✅ PASS / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1124| Phase 4: Decomposition | X.X/5.0 | ✅ PASS / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1125| Phase 5: Parallelize | X.X/5.0 | ✅ PASS / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1126| Phase 6: Verify | X.X/5.0 | ✅ PASS / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1127
1128**Threshold Used:** {THRESHOLD}/5.0 (or N/A if SKIP_JUDGES)
1129
1130**Legend:**
1131- ✅ PASS - Score >= THRESHOLD
1132- ⚠️ PROCEEDED (max iter) - Score < THRESHOLD but MAX_ITERATIONS reached, proceeded anyway
1133- ⏭️ SKIPPED - Stage not in ACTIVE_STAGES
1134
1135### Artifacts Generated
1136
1137```
1138
1139.claude/
1140└── skills/
1141 └── <skill-name>/
1142 └── SKILL.md # Reusable skill document (if research stage ran)
1143
1144.specs/
1145├── tasks/
1146│ ├── draft/ # Draft tasks (source - now empty for this task)
1147│ ├── todo/
1148│ │ └── <name>.<type>.md # Complete task specification (ready for implementation)
1149│ ├── in-progress/ # Tasks being implemented (empty)
1150│ └── done/ # Completed tasks (empty)
1151├── analysis/
1152│ └── analysis-<name>.md # Codebase impact analysis (if codebase analysis stage ran)
1153└── scratchpad/
1154 └── <hex-id>.md # Architecture thinking scratchpad
1155
1156```
1157
1158### Task Status Management
1159
1160Task status is managed by folder location:
1161- `draft/` - Tasks created but not yet refined
1162- `todo/` - Tasks ready for implementation
1163- `in-progress/` - Tasks currently being worked on
1164- `done/` - Completed tasks
1165
1166### Next Steps
1167
11681. Review task: `.specs/tasks/todo/<filename>`
1169 - Edit the task file directly to make corrections
1170 - Add `//` comments to lines that need clarification or changes
1171 - Run `/plan` again with `--refine` to incorporate your feedback — it detects changes against git and propagates updates **top-to-bottom** (editing a section only affects sections below it, not above)
11722. If everything is fine, begin implementation: `/implement` (will auto-select the task from todo/)
1173```
1174
1175---
1176
1177## Error Handling
1178
1179### Phase Agent Failure (Exception/Crash)
1180
1181If any phase agent fails unexpectedly:
1182
11831. Report the failure with agent output
11842. Ask clarification questions from user that can help resolve the issue
11853. Launch the phase agent again with list of questions and answers to resolve the issue
1186
1187### Judge Returns FAIL
1188
1189If any judge returns FAIL (score < `THRESHOLD`):
1190
11911. **Automatic retry**: Re-launch the phase agent with judge feedback
11922. **Human-in-the-loop check**: If phase is in `HUMAN_IN_THE_LOOP_PHASES`, trigger human checkpoint **before** the next judge retry (after implementation retry but before re-judging)
11933. **After `MAX_ITERATIONS` reached**: **Proceed to next stage automatically** (do NOT ask user unless `--human-in-the-loop` includes this phase)
11944. Log warning in completion summary: `⚠️ Phase X did not pass quality threshold (X.X/THRESHOLD) after MAX_ITERATIONS iterations`
1195
1196### Retry Flow
1197
1198```
1199Implementation → Judge FAIL → Implementation Retry → Judge Retry
1200 ↓
1201 PASS → Continue to next stage
1202 FAIL → Repeat until MAX_ITERATIONS
1203 ↓
1204 MAX_ITERATIONS reached → Proceed to next stage (with warning)
1205```
1206
1207### Retry Flow with Human-in-the-Loop
1208
1209When phase is in `HUMAN_IN_THE_LOOP_PHASES`:
1210
1211```
1212Implementation → Judge FAIL → Implementation Retry
1213 ↓
1214 🔍 Human Checkpoint (optional feedback)
1215 ↓
1216 Judge Retry
1217 ↓
1218 PASS → Continue | FAIL → Repeat until MAX_ITERATIONS
1219 ↓
1220 MAX_ITERATIONS → 🔍 Final Human Checkpoint
1221 ↓
1222 User confirms → Proceed to next stage
1223```