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 (description, acceptance criteria, test strategy) in parallel
- Architecture Synthesis - Combine findings into architectural overview
- Decomposition - Break into per-step sub-task files, grouped into independently verifiable phases with dependencies, parallel groups, agent/model assignments and a reviewer model per phase
- Promote - Move refined task from
draft/ to todo/
All model-assigned 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 - same stages as --one-shot, but judges still run, at a lowered threshold with a single retry. |
--one-shot |
--one-shot |
N/A |
Alias for --included-stages business analysis,decomposition --skip-judges - same stages as --fast, but no judge runs at all and no quality gate is applied. |
--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). |
--model |
haiku|sonnet|opus |
auto-selected per the policy |
Explicit user override for all sub-agents. When omitted, resolve each phase's tier per the Model Selection Policy. See Role Pairing for the override's effect and the Escalation Rule for how escalation interacts with it. |
--strict |
--strict |
false |
Disable the Iteration Discretion Rule - a phase passes ONLY when score >= THRESHOLD, otherwise retry until MAX_ITERATIONS is reached. |
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 (checklist, regular checks, rubric, test strategy, definition of done) |
architecture synthesis |
3 |
Synthesize research and analysis into architecture |
decomposition |
4 |
Break into per-step sub-task files grouped into verifiable phases, with dependencies, parallel groups and agent/model assignments |
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"]
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"]
SKIP_STAGES = --skip || []
HUMAN_IN_THE_LOOP_PHASES = --human-in-the-loop || []
SKIP_JUDGES = --skip-judges || false
REFINE_MODE = --refine || false
STRICT_MODE = --strict || false
CONTINUE_STAGE = null
# Model tiers - governed in full by the Model Selection Policy
MODEL_OVERRIDE = --model || null
BASELINE_TIER = MODEL_OVERRIDE || tier of the overall task per the Selection Rules
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 (checklist, regular checks, rubric, test strategy, definition of done) |
business analysis (Phase 2c) |
| Architecture Overview |
architecture synthesis (Phase 3) |
Implementation Process (Parallelization Overview / Phase Overview), or any sub-task file under .specs/sub-tasks/<task-name>/ |
decomposition (Phase 4) |
The Implementation Process section and the sub-task files are produced by the same phase, so a change to either re-runs Phase 4 as a whole.
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
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 / ☑️ ACCEPTED / ⚠️ 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
# Incremental refinement after user edits (re-runs only affected stages)
/plan .specs/tasks/todo/my-task.feature.md --refine
# Strict mode: never accept a phase below target - retry until THRESHOLD or MAX_ITERATIONS
/plan .specs/tasks/draft/critical-api.feature.md --strict
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} |
| **Strict Mode** | {STRICT_MODE} |
| **Continue From** | {CONTINUE_STAGE} or "Start" |
| **Model** | `{MODEL_OVERRIDE}` (user override) or "auto — baseline `{BASELINE_TIER}`: {one-line justification}" |
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 sub-task files and verifiable phases", "status": "pending", "activeForm": "Decomposing into steps and phases"},
{"content": "Judge 4: PASS decomposition (> {THRESHOLD})", "status": "pending", "activeForm": "Validating decomposition"},
{"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)
- 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
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/sub-tasks/ - Per-step sub-task files written by Phase 4 (tracked in git)
.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
- Never record a verdict the judge report does not support: no PASS without a passing rubric result, and no ☑️ ACCEPTED without the Iteration Discretion Rule actually permitting it. Otherwise 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!
- If
STRICT_MODE is true: The Iteration Discretion Rule is DISABLED - a phase passes ONLY on score >= THRESHOLD, otherwise retry until MAX_ITERATIONS!
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.
Iteration Discretion Rule
Your main task is to COMPLETE the planning within target quality. Two failure modes are equally real:
- Burning iterations and context on nitpicks so the overall task never completes → the task is failed.
- Promoting a plan whose quality is genuinely too poor to be considered complete → an even worse failure.
This rule governs the **Decision Logic:** block of every phase:
score < 3.0 → FAIL, unconditionally. No discretion. Re-launch the phase with judge feedback until it passes or MAX_ITERATIONS is reached.
3.0 <= score < 5.0 → discretion band. ONLY inside this band MAY you decide that a phase below THRESHOLD (default 3.5) is acceptable.
- Bounded drop: NEVER accept a score more than
1.0 below THRESHOLD — the effective floor is max(3.0, THRESHOLD - 1.0), i.e. 3.0 at the default THRESHOLD 3.5 and 3.5 at --target-quality 4.5. With THRESHOLD <= 3.0 (e.g. --fast) there is no discretion band at all.
- 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 phase or causes a meaningful defect (i.e. they are nitpicks), you MUST reason FIRST — before re-launching the phase — about whether iterating (or marking the phase failed) is worth the time and context cost.
- At most ONE nitpick-driven iteration, and it counts against
MAX_ITERATIONS. If it again surfaces only nitpicks, you MUST mark the phase PASS (☑️ ACCEPTED in the summary table), report the outstanding issues in the completion summary, and continue with the next phase. If it returns a score below the floor max(3.0, THRESHOLD - 1.0), the FAIL path applies instead.
- You MUST be critical, NOT lenient. Stopping short of target MUST be an intentional decision grounded in the absence of real, requirement-breaking issues. A genuine blocking issue that prevents completing the phase within
MAX_ITERATIONS MUST be reported as a failure, never papered over.
- If
STRICT_MODE is true, this whole rule is DISABLED: stop only when score >= THRESHOLD or MAX_ITERATIONS is reached. --strict changes nothing else — THRESHOLD, MAX_ITERATIONS, the < 3.0 unconditional FAIL, human-in-the-loop checkpoints, judge dispatch and --skip-judges are unaffected. With --skip-judges (or --one-shot) no score is produced at all, so both this rule and --strict are inert.
Model Selection Policy
Picking the model is the single highest-leverage decision you make — more than any prompt wording, it decides whether the plan comes back correct and how long the run takes. You MUST NOT treat it as a formality: name the tier and give a one-line justification before dispatching each phase agent. Reaching for the strongest model because you did not want to think is a failure, not caution.
Tier default: sonnet is the working default, and sonnet/haiku cover the majority of runs. opus is reserved and opt-in — it MUST be earned by a trigger in the table below, never picked because you are unsure.
Selection Rules
Assess the overall task being planned — the draft task file's title and type plus the user's input — against this table. The matching row is the run's BASELINE_TIER. (The same table also tiers a single unit of work, which is why Phase 4 receives it verbatim to assign a model per implementation step, and how Judge 4 grades those assignments.)
| Task shape |
Tier |
Examples |
| Straightforward — one already-understood change with an obvious shape: a single file, and an established pattern, no new dependency, no open design question, and "done" is already evident from the draft |
haiku |
Fix a typo in one README, add a config flag, bump a dependency version, correct a log message |
| Typical — ordinary feature, fix or refactor work: a handful of files inside one module or service, established patterns, local design choices only |
sonnet |
Add a REST endpoint to an existing service, add form validation, extract a helper and its tests |
| Complex — breadth (~3+ modules/services, or any breadth when a shared contract changes) OR critical domain (auth, payments/billing, data integrity, irreversible migration, public API break) OR open design (concurrency, non-trivial algorithms, a new subsystem, architecture not yet decided) |
opus |
Re-architect the payments subsystem across 12 modules, design a new event pipeline, plan a schema migration |
Precedence (MANDATORY): evaluate EVERY row, not just the first that matches. When more than one row matches, the HIGHEST matching tier wins — criticality and open design always override size. The critical domain list is exhaustive, not illustrative: shipping to production, touching real users, or adding to an existing public API are NOT triggers, so a new endpoint with validation in one service stays sonnet. Mechanical-breadth carve-out: breadth alone is not complexity — for one identical, rule-driven edit repeated across many files with no logic and no contract change, only the breadth trigger does not apply (critical domain and open design still do); tier it on a single occurrence, so a mechanical rename across 40 files is haiku, while the same rename confined to src/auth/ is opus.
Tie-breaker: ONLY when no row matches cleanly — the task sits genuinely between two tiers — pick sonnet, the working default. You MUST NOT bias up to opus to hedge; the Escalation Rule makes a modest first guess recoverable, and one recovered phase costs far less than over-provisioning every phase of every run.
Phase Weighting
BASELINE_TIER is the tier of every model-assigned phase, with exactly one stated deviation:
| Phase |
Weight |
Tier |
| Phase 3: Architecture Synthesis |
Heavy — the only phase that makes open design decisions rather than applying settled ones; three inputs are synthesized here and every later phase, plus the implementation itself, inherits the result |
one tier above BASELINE_TIER, capped at opus |
| Phases 2a, 2b, 2c, 4 |
Standard |
BASELINE_TIER |
Every model-assigned phase appears in exactly ONE row, so each resolves to exactly ONE tier. The cap means an opus baseline leaves all phases at opus. Promotion is a file move you perform yourself — no sub-agent, no tier. See Role Pairing for the --model override.
Not to be confused with the per-step tiers inside the plan. The tiers above govern the planning agents you launch. The Model: recorded in each sub-task file and the Reviewer model: recorded for each phase are decided by Phase 4 for the implementation run, from the per-step policy Phase 4's launch prompt carries — they are independent of BASELINE_TIER.
Role Pairing
This pipeline has two model-assigned roles per phase: the producer (the phase agent) and the evaluator (its judge). A judge ALWAYS runs at the tier of the phase it validates, including after escalation. You MUST NOT tier a judge independently of its phase.
An explicit --model supersedes this entire policy (the ONLY statement of this rule): every phase agent and every judge runs at the user's tier, the BASELINE_TIER assessment does NOT run, and Phase Weighting never deviates from it.
Escalation Rule
Bump BOTH the phase agent and its judge one tier for the next iteration of that phase when either trigger fires:
- Low first-iteration quality — a low score, or judge issues showing the model misunderstood the phase 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 or a finished run.
Ladder: haiku → sonnet → opus. opus is the ceiling — there is no further tier. If opus-tier work still fails, report it and 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 re-launch the phase 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) 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 — report the low-quality evidence, propose the bump, and re-launch at the user's tier unless they approve. Trigger (2) IS that approval, so it bumps immediately.
--skip-judges carve-out (the ONLY statement of this rule): with no judge running, there is no score or judge issue for trigger (1) to read, so trigger (1) cannot fire. Trigger (2) is user-initiated, not judge-derived, so it is unaffected — a user complaint under --skip-judges (or --one-shot) still bumps the tier for that phase's re-launch.
- Scoped to the failing phase. An escalated tier applies to that phase's remaining iterations only; every later phase resumes from its own Phase Weighting tier.
- 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 re-launch; re-launching the same prompt at a higher tier and hoping is prohibited.
- Escalation is orthogonal to
THRESHOLD, MAX_ITERATIONS, STRICT_MODE and the Iteration Discretion Rule — it changes which model runs the next iteration, never whether one is warranted. When the Iteration Discretion Rule accepts a phase, no iteration happens, so nothing escalates.
- Re-entry after a finished phase (the ONLY statement of this rule): a ✅ PASS or ☑️ ACCEPTED does NOT close the work. A later user quality complaint re-enters that phase under trigger (2) — through
--continue or --refine — and MAX_ITERATIONS resets for it, with the phase and its judge running at the bumped tier.
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 planning phases |
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, weighting, pairing and escalation rules unchanged.
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 specified in the phase, and the Model tier resolved per the Model Selection Policy
- 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] [sdd:code-explorer] [sdd:business-analyst]
all three at baseline tier
Judge 2a Judge 2b Judge 2c
(pass: >THRESHOLD) (pass: >THRESHOLD) (pass: >THRESHOLD)
│ │ │
└─────────────────────┴─────────────────────┘
│
▼
Phase 3: Architecture Synthesis
[sdd:software-architect] baseline+1 (cap opus)
Judge 3 (pass: >THRESHOLD)
│
▼
Phase 4: Decomposition
[sdd:tech-lead] baseline
→ task file: ## Implementation Process
→ .specs/sub-tasks/<task-name>/NN-<step-slug>.md
Judge 4 (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: BASELINE_TIER per Phase Weighting — standard weight: gathering and summarizing resources for an already-scoped task, no design decisions.
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: BASELINE_TIER per Phase Weighting — standard weight: reading the codebase to locate files and integration points scales with the task's own breadth, which the baseline already reflects.
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: BASELINE_TIER per Phase Weighting — standard weight: structured elicitation and checklist/rubric/test-strategy derivation driven end-to-end by the agent's own STAGES 1-10, not open-ended synthesis — the procedure, not the model, carries the rigour here.
Agent: sdd:business-analyst
Depends on: Task file exists
Purpose: Refine the description and produce the single ## Acceptance Criteria section — checklist, regular checks, rubric, rubric score definitions, test strategy and definition of done, mixing business and technical criteria
Launch agent:
Description: "Business analysis"
Prompt:
CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
Task File: <TASK_FILE>
Task Title: <title from task file>
Execute your own Core Process (STAGES 1-10) in full.
CRITICAL: DO NOT OUTPUT YOUR BUSINESS ANALYSIS. Create the scratchpad, then write the task file's `# Description` and the single `## Acceptance Criteria` section at your STAGE 10.
Capture:
- Scratchpad file path (e.g.,
.specs/scratchpad/<hex-id>.md)
- Scope defined (yes/no)
- User scenarios documented
- Checklist items count (essential / important / optional / pitfall)
- Regular checks count
- Rubric dimensions count (weights sum: 1.0)
- Test strategy applies (true/false) and test types selected
- Quality gates and project guidelines discovered
CRITICAL: If the task file's # Description or ## Acceptance Criteria section was not written, launch the agent again with the same prompt.
Judge 2a/2b/2c: Validate Parallel Phases
After each parallel phase completes, launch its respective judge with the same agent type as that phase, at the tier Role Pairing gives it.
Judge 2a: Validate Research/Skill
Model: Phase 2a's tier — see Role Pairing
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, at the tier per the Escalation Rule (unless accepted per the Iteration Discretion Rule)
- MAX_ITERATIONS reached: Proceed to next stage regardless of score (log warning)
Judge 2b: Validate Codebase Analysis
Model: Phase 2b's tier — see Role Pairing
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, at the tier per the Escalation Rule (unless accepted per the Iteration Discretion Rule)
- MAX_ITERATIONS reached: Proceed to next stage regardless of score (log warning)
Judge 2c: Validate Business Analysis
Model: Phase 2c's tier — see Role Pairing
Agent: sdd:business-analyst
Depends on: Phase 2c completion
Purpose: Validate the refined description and the whole ## Acceptance Criteria section — checklist, regular checks, rubric, score definitions, test strategy and definition of done
Weight derivation: criteria 1-4 are the original business-analysis criteria at their former proportions (0.30/0.35/0.20/0.15) scaled by 0.60, with the 0.01 rounding remainder given to the highest-weighted of them, totalling 0.61; criteria 5-7 — imported when rubric and test-strategy review folded into this judge — spl
…(truncated)
1---
2name: plan-task
3description: Refine a draft task specification into a fully planned, implementation-ready task with acceptance criteria, architecture, per-step sub-task files and verifiable phases
4---
5
6# Refine Task Workflow
7
8## Role
9
10You 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.
11
12## Goal
13
14This workflow command refines an existing draft task through:
15
161. **Parallel Analysis** - Research, codebase analysis, and business analysis (description, acceptance criteria, test strategy) in parallel
172. **Architecture Synthesis** - Combine findings into architectural overview
183. **Decomposition** - Break into per-step sub-task files, grouped into independently verifiable phases with dependencies, parallel groups, agent/model assignments and a reviewer model per phase
194. **Promote** - Move refined task from `draft/` to `todo/`
20
21All model-assigned phases include judge validation to prevent error propagation and ensure quality thresholds are met.
22
23## User Input
24
25```text
26$ARGUMENTS
27```
28
29---
30
31## Command Arguments
32
33Parse the following arguments from `$ARGUMENTS`:
34
35### Argument Definitions
36
37| Argument | Format | Default | Description |
38|----------|--------|---------|-------------|
39| `task-file` | Path to task file | **Required** | Path to draft task file (e.g., `.specs/tasks/draft/add-validation.feature.md`) |
40| `--continue` | `--continue [stage]` | None | Continue refining from a specific stage. Stage is optional - resolve from context if not provided. |
41| `--target-quality` | `--target-quality X.X` | `3.5` | Target threshold value (out of 5.0) for judge pass/fail decisions. |
42| `--max-iterations` | `--max-iterations N` | `3` | Maximum implementation + judge retry cycles per phase before moving to next stage (regardless of pass/fail). |
43| `--included-stages` | `--included-stages stage1,stage2,...` | All stages | Comma-separated list of stages to include. |
44| `--skip` | `--skip stage1,stage2,...` | None | Comma-separated list of stages to exclude. |
45| `--fast` | `--fast` | N/A | Alias for `--target-quality 3.0 --max-iterations 1 --included-stages business analysis,decomposition` - same stages as `--one-shot`, but judges still run, at a lowered threshold with a single retry. |
46| `--one-shot` | `--one-shot` | N/A | Alias for `--included-stages business analysis,decomposition --skip-judges` - same stages as `--fast`, but no judge runs at all and no quality gate is applied. |
47| `--human-in-the-loop` | `--human-in-the-loop phase1,phase2,...` | None | Phases after which to pause for human verification. |
48| `--skip-judges` | `--skip-judges` | `false` | Skip all judge validation checks - phases proceed without quality gates. |
49| `--refine` | `--refine` | `false` | Incremental refinement mode - detect changes against git and re-run only affected stages (top-to-bottom propagation). |
50| `--model` | `haiku\|sonnet\|opus` | *auto-selected per the policy* | Explicit user override for all sub-agents. When omitted, resolve each phase's tier per the [Model Selection Policy](#model-selection-policy). See [Role Pairing](#role-pairing) for the override's effect and the [Escalation Rule](#escalation-rule) for how escalation interacts with it. |
51| `--strict` | `--strict` | `false` | Disable the [Iteration Discretion Rule](#iteration-discretion-rule) - a phase passes ONLY when `score >= THRESHOLD`, otherwise retry until `MAX_ITERATIONS` is reached. |
52
53### Stage Names (for `--included-stages` / `--skip`)
54
55| Stage Name | Phase | Description |
56|------------|-------|-------------|
57| `research` | 2a | Gather relevant resources, documentation, libraries |
58| `codebase analysis` | 2b | Identify affected files, interfaces, integration points |
59| `business analysis` | 2c | Refine description and create acceptance criteria (checklist, regular checks, rubric, test strategy, definition of done) |
60| `architecture synthesis` | 3 | Synthesize research and analysis into architecture |
61| `decomposition` | 4 | Break into per-step sub-task files grouped into verifiable phases, with dependencies, parallel groups and agent/model assignments |
62
63### Configuration Resolution
64
65Parse `$ARGUMENTS` and resolve configuration as follows:
66
67```
68
69# Extract task file path (first positional argument, required)
70TASK_FILE = first argument that is a file path (must exist in .specs/tasks/draft/)
71
72# Parse alias flags first (they set multiple defaults)
73if --fast present:
74 THRESHOLD = 3.0
75 MAX_ITERATIONS = 1
76 INCLUDED_STAGES = ["business analysis", "decomposition"]
77
78if --one-shot present:
79 INCLUDED_STAGES = ["business analysis", "decomposition"]
80 SKIP_JUDGES = true
81
82# Initialize defaults
83THRESHOLD ?= --target-quality || 3.5
84MAX_ITERATIONS ?= --max-iterations || 3
85INCLUDED_STAGES ?= --included-stages || ["research", "codebase analysis", "business analysis", "architecture synthesis", "decomposition"]
86SKIP_STAGES = --skip || []
87HUMAN_IN_THE_LOOP_PHASES = --human-in-the-loop || []
88SKIP_JUDGES = --skip-judges || false
89REFINE_MODE = --refine || false
90STRICT_MODE = --strict || false
91CONTINUE_STAGE = null
92
93# Model tiers - governed in full by the Model Selection Policy
94MODEL_OVERRIDE = --model || null
95BASELINE_TIER = MODEL_OVERRIDE || tier of the overall task per the Selection Rules
96
97
98if --continue [stage] present:
99 CONTINUE_STAGE = stage or resolve from context
100
101# Compute final active stages
102ACTIVE_STAGES = INCLUDED_STAGES - SKIP_STAGES
103```
104
105### Context Resolution for `--continue`
106
107When `--continue` is used without explicit stage:
108
1091. **Stage Resolution:**
110 - Parse the task file for completion markers (e.g., `[x]` checkboxes)
111 - Identify the last completed phase/judge
112 - Resume from the next incomplete phase
113
114### Refine Mode Behavior (`--refine`)
115
116When `--refine` is used:
117
1181. **Change Detection:**
119 - First check file status: `git status --porcelain -- <TASK_FILE>`
120 - Compare current task file against last git commit: `git diff HEAD -- <TASK_FILE>`
121 - This captures both staged and unstaged changes vs HEAD
122 - If file is untracked or has no git history, compare against the original task structure
123 - Identify which sections have been modified by the user
124 - Look for `//` comment markers indicating user feedback/corrections
125
1262. **Top-to-Bottom Propagation:**
127 - Determine the **earliest modified section** (highest in document)
128 - Re-run only stages that correspond to or come **after** the modified section
129 - Earlier stages (above the modification) are preserved as-is
130
1313. **Section-to-Stage Mapping:**
132
133 | Modified Section | Re-run From Stage |
134 |------------------|-------------------|
135 | Description / Acceptance Criteria (checklist, regular checks, rubric, test strategy, definition of done) | `business analysis` (Phase 2c) |
136 | Architecture Overview | `architecture synthesis` (Phase 3) |
137 | Implementation Process (Parallelization Overview / Phase Overview), or any sub-task file under `.specs/sub-tasks/<task-name>/` | `decomposition` (Phase 4) |
138
139 The Implementation Process section and the sub-task files are produced by the same phase, so a change to either re-runs Phase 4 as a whole.
140
1414. **Refine Execution:**
142 - Skip research (2a) and codebase analysis (2b) unless explicitly requested
143 - Pass user modifications and `//` comments as additional context to agents
144 - Agents should incorporate user feedback while preserving unchanged content
145
1465. **Example:**
147
148 ```bash
149 # User edited the Architecture Overview section
150 /plan .specs/tasks/todo/my-task.feature.md --refine
151
152 # Detects Architecture section changed → re-runs from Phase 3 onwards
153 # Skips: research, codebase analysis, business analysis
154 # Runs: architecture synthesis, decomposition
155 ```
156
157### Human-in-the-Loop Behavior
158
159Human verification checkpoints occur:
160
1611. **Trigger Conditions:**
162 - After implementation + judge verification **PASS** for a phase in `HUMAN_IN_THE_LOOP_PHASES`
163 - After implementation + judge + implementation retry (before the next judge retry)
164
1652. **At Checkpoint:**
166 - Display current phase results summary
167 - Display generated artifacts with paths
168 - Display judge score and feedback
169 - Ask user: "Review phase output. Continue? [Y/n/feedback]"
170 - If user provides feedback, incorporate into next iteration
171 - If user says "n", pause workflow
172
1733. **Checkpoint Message Format:**
174
175 ```markdown
176 ---
177 ## 🔍 Human Review Checkpoint - Phase X
178
179 **Phase:** {phase name}
180 **Judge Score:** {score}/{THRESHOLD} threshold
181 **Status:** ✅ PASS / ☑️ ACCEPTED / ⚠️ RETRY {n}/{MAX_ITERATIONS}
182
183 **Artifacts:**
184 - {artifact_path_1}
185 - {artifact_path_2}
186
187 **Judge Feedback:**
188 {feedback summary}
189
190 **Action Required:** Review the above artifacts and provide feedback or continue.
191
192 > Continue? [Y/n/feedback]:
193 ---
194 ```
195
196---
197
198## Usage Examples
199
200```bash
201# Refine a draft task with all stages
202/plan .specs/tasks/draft/add-validation.feature.md
203
204# Fast refinement with minimal stages
205/plan .specs/tasks/draft/quick-fix.bug.md --fast
206
207# Continue from a specific stage
208/plan .specs/tasks/draft/complex-feature.feature.md --continue decomposition
209
210# High-quality refinement with checkpoints
211/plan .specs/tasks/draft/critical-api.feature.md --target-quality 4.5 --human-in-the-loop 2,3,4
212
213# Incremental refinement after user edits (re-runs only affected stages)
214/plan .specs/tasks/todo/my-task.feature.md --refine
215
216# Strict mode: never accept a phase below target - retry until THRESHOLD or MAX_ITERATIONS
217/plan .specs/tasks/draft/critical-api.feature.md --strict
218```
219
220## Pre-Flight Checks
221
222Before starting workflow:
223
2241. **Validate task file exists:**
225 - If `REFINE_MODE` is false: Check that `TASK_FILE` exists in `.specs/tasks/draft/`
226 - If `REFINE_MODE` is true: Check that `TASK_FILE` exists in `.specs/tasks/todo/` or `.specs/tasks/draft/`
227 - If not found, show error and exit
228
2292. **Parse and display resolved configuration:**
230
231 ```markdown
232 ### Configuration
233
234 | Setting | Value |
235 |---------|-------|
236 | **Task File** | {TASK_FILE} |
237 | **Target Quality** | {THRESHOLD}/5.0 |
238 | **Max Iterations** | {MAX_ITERATIONS} |
239 | **Active Stages** | {ACTIVE_STAGES as comma-separated list} |
240 | **Human Checkpoints** | Phase {HUMAN_IN_THE_LOOP_PHASES as comma-separated} |
241 | **Skip Judges** | {SKIP_JUDGES} |
242 | **Refine Mode** | {REFINE_MODE} |
243 | **Strict Mode** | {STRICT_MODE} |
244 | **Continue From** | {CONTINUE_STAGE} or "Start" |
245 | **Model** | `{MODEL_OVERRIDE}` (user override) or "auto — baseline `{BASELINE_TIER}`: {one-line justification}" |
246 ```
247
2483. **Handle `--continue` mode:**
249
250 If `CONTINUE_STAGE` is set:
251 - Read the task file to get current state
252 - Identify completed phases from task file content
253 - Skip to `CONTINUE_STAGE` (or auto-detected next incomplete stage)
254 - Pre-populate captured values from existing artifacts
255 - Resume workflow from the appropriate phase
256
2574. **Handle `--refine` mode:**
258
259 If `REFINE_MODE` is true:
260 - Check file status: `git status --porcelain -- <TASK_FILE>`
261 - `M` (staged) or `M` (unstaged) or `MM` (both) → proceed with diff
262 - `??` (untracked) → error: "File not tracked by git, cannot detect changes"
263 - Empty output → no changes detected
264 - Run `git diff HEAD -- <TASK_FILE>` to get all changes (staged + unstaged) vs last commit
265 - Parse diff to identify modified sections
266 - Collect any `//` comment markers as user feedback
267 - Determine earliest modified section using Section-to-Stage Mapping
268 - Set `ACTIVE_STAGES` to include only stages from the determined starting point onwards
269 - Pass detected changes and user comments as additional context to agents
270 - If no changes detected, inform user: "No changes detected in task file. Edit the file first, then run --refine." and exit
271
2725. **Extract task info from file:**
273 - Read task file to extract title and type from filename
274 - Parse frontmatter for title and depends_on
275
2766. **Initialize workflow progress tracking** using TodoWrite:
277
278 Only include todos for phases in `ACTIVE_STAGES`. If continuing, mark completed phases as `completed`.
279
280 ```json
281 {
282 "todos": [
283 {"content": "Ensure directories exist", "status": "pending", "activeForm": "Ensuring directories exist"},
284 {"content": "Phase 2a: Research relevant resources and documentation", "status": "pending", "activeForm": "Researching resources"},
285 {"content": "Judge 2a: PASS research quality (> {THRESHOLD})", "status": "pending", "activeForm": "Validating research"},
286 {"content": "Phase 2b: Analyze codebase impact and affected files", "status": "pending", "activeForm": "Analyzing codebase impact"},
287 {"content": "Judge 2b: PASS codebase analysis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating codebase analysis"},
288 {"content": "Phase 2c: Business analysis and acceptance criteria", "status": "pending", "activeForm": "Analyzing business requirements"},
289 {"content": "Judge 2c: PASS business analysis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating business analysis"},
290 {"content": "Phase 3: Architecture synthesis from research and analysis", "status": "pending", "activeForm": "Synthesizing architecture"},
291 {"content": "Judge 3: PASS architecture synthesis (> {THRESHOLD})", "status": "pending", "activeForm": "Validating architecture"},
292 {"content": "Phase 4: Decompose into sub-task files and verifiable phases", "status": "pending", "activeForm": "Decomposing into steps and phases"},
293 {"content": "Judge 4: PASS decomposition (> {THRESHOLD})", "status": "pending", "activeForm": "Validating decomposition"},
294 {"content": "Move task to todo folder", "status": "pending", "activeForm": "Promoting task"},
295 {"content": "Human checkpoint reviews", "status": "pending", "activeForm": "Awaiting human review"}
296 ]
297 }
298 ```
299
300 **Note:** Filter todos based on configuration:
301 - If `SKIP_JUDGES` is true, omit ALL Judge todos (Judge 2a, 2b, 2c, 3, 4)
302 - If `research` not in `ACTIVE_STAGES`, omit Phase 2a and Judge 2a todos
303 - If `codebase analysis` not in `ACTIVE_STAGES`, omit Phase 2b and Judge 2b todos
304 - If `business analysis` not in `ACTIVE_STAGES`, omit Phase 2c and Judge 2c todos
305 - If `architecture synthesis` not in `ACTIVE_STAGES`, omit Phase 3 and Judge 3 todos
306 - If `decomposition` not in `ACTIVE_STAGES`, omit Phase 4 and Judge 4 todos
307 - If `HUMAN_IN_THE_LOOP_PHASES` is empty, omit human checkpoint todo
308
3097. **Ensure directories exist**:
310
311 Run the folder creation script to create task directories and configure gitignore:
312
313 ```bash
314 bash ${CLAUDE_PLUGIN_ROOT}/scripts/create-folders.sh
315 ```
316
317 This creates:
318
319 - `.specs/tasks/draft/` - New tasks awaiting analysis
320 - `.specs/tasks/todo/` - Tasks ready to implement
321 - `.specs/tasks/in-progress/` - Currently being worked on
322 - `.specs/tasks/done/` - Completed tasks
323 - `.specs/sub-tasks/` - Per-step sub-task files written by Phase 4 (tracked in git)
324 - `.specs/scratchpad/` - Temporary working files (gitignored)
325 - `.specs/analysis/` - Codebase impact analysis files
326 - `.claude/skills/` - Reusable skill documents
327
328Update each todo to `in_progress` when starting a phase and `completed` when judge passes.
329
330## CRITICAL
331
332- Never record a verdict the judge report does not support: no PASS without a passing rubric result, and no ☑️ ACCEPTED without the [Iteration Discretion Rule](#iteration-discretion-rule) actually permitting it. Otherwise retry the judge after each implementation change till it passes the check!
333- 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!
334- Use `THRESHOLD` (default 3.5) for all judge pass/fail decisions, not hardcoded values!
335- Use `MAX_ITERATIONS` (default 3) for retry limits, not hardcoded values!
336- **After `MAX_ITERATIONS` reached: PROCEED to next stage automatically - do NOT ask user unless phase is in `HUMAN_IN_THE_LOOP_PHASES`!**
337- Skip phases not in `ACTIVE_STAGES` entirely - do not launch agents for excluded stages!
338- Trigger human-in-the-loop checkpoints ONLY after phases in `HUMAN_IN_THE_LOOP_PHASES`!
339- **If `SKIP_JUDGES` is true: Skip ALL judge validation - proceed directly to next phase after each implementation phase completes!**
340- **Task file must exist in `.specs/tasks/draft/` before running this command (unless `--refine` mode)!**
341- **If `REFINE_MODE` is true: Detect changes via git diff, skip unchanged stages, pass user feedback to agents!**
342- **If `STRICT_MODE` is true: The [Iteration Discretion Rule](#iteration-discretion-rule) is DISABLED - a phase passes ONLY on `score >= THRESHOLD`, otherwise retry until `MAX_ITERATIONS`!**
343
344### Execution & Evaluation Rules
345
346- **Use foreground agents only**: Do not use background agents. Launch parallel agents when possible. Background agents constantly run in permissions issues and other errors.
347
348Relaunch judge till you get valid results, of following happens:
349
350- 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.
351- 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.
352- 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.
353
354#### Iteration Discretion Rule
355
356Your main task is to COMPLETE the planning within target quality. Two failure modes are equally real:
357
358- Burning iterations and context on nitpicks so the overall task never completes → **the task is failed**.
359- Promoting a plan whose quality is genuinely too poor to be considered complete → **an even worse failure**.
360
361This rule governs the `**Decision Logic:**` block of every phase:
362
363- **`score < 3.0` → FAIL, unconditionally. No discretion.** Re-launch the phase with judge feedback until it passes or `MAX_ITERATIONS` is reached.
364- **`3.0 <= score < 5.0` → discretion band.** ONLY inside this band MAY you decide that a phase below `THRESHOLD` (default 3.5) is acceptable.
365- **Bounded drop:** NEVER accept a score more than `1.0` below `THRESHOLD` — the effective floor is `max(3.0, THRESHOLD - 1.0)`, i.e. `3.0` at the default `THRESHOLD` 3.5 and `3.5` at `--target-quality 4.5`. With `THRESHOLD <= 3.0` (e.g. `--fast`) there is no discretion band at all.
366- 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 phase or causes a meaningful defect (i.e. they are nitpicks), you MUST reason FIRST — before re-launching the phase — about whether iterating (or marking the phase failed) is worth the time and context cost.
367- **At most ONE nitpick-driven iteration**, and it counts against `MAX_ITERATIONS`. If it again surfaces only nitpicks, you MUST mark the phase PASS (☑️ ACCEPTED in the summary table), report the outstanding issues in the completion summary, and continue with the next phase. If it returns a score below the floor `max(3.0, THRESHOLD - 1.0)`, the FAIL path applies instead.
368- You MUST be critical, NOT lenient. Stopping short of target MUST be an intentional decision grounded in the absence of real, requirement-breaking issues. A genuine blocking issue that prevents completing the phase within `MAX_ITERATIONS` MUST be reported as a failure, never papered over.
369- **If `STRICT_MODE` is true, this whole rule is DISABLED**: stop only when `score >= THRESHOLD` or `MAX_ITERATIONS` is reached. `--strict` changes nothing else — `THRESHOLD`, `MAX_ITERATIONS`, the `< 3.0` unconditional FAIL, human-in-the-loop checkpoints, judge dispatch and `--skip-judges` are unaffected. With `--skip-judges` (or `--one-shot`) no score is produced at all, so both this rule and `--strict` are inert.
370
371## Model Selection Policy
372
373Picking the model is the **single highest-leverage decision** you make — more than any prompt wording, it decides whether the plan comes back correct and how long the run takes. You MUST NOT treat it as a formality: name the tier and give a one-line justification before dispatching **each** phase agent. Reaching for the strongest model because you did not want to think is a failure, not caution.
374
375**Tier default:** `sonnet` is the working default, and `sonnet`/`haiku` cover the majority of runs. `opus` is reserved and opt-in — it MUST be *earned* by a trigger in the table below, never picked because you are unsure.
376
377### Selection Rules
378
379Assess the **overall task being planned** — the draft task file's title and type plus the user's input — against this table. The matching row is the run's `BASELINE_TIER`. (The same table also tiers a *single unit of work*, which is why Phase 4 receives it verbatim to assign a model per implementation step, and how Judge 4 grades those assignments.)
380
381| Task shape | Tier | Examples |
382|---|---|---|
383| **Straightforward** — one already-understood change with an obvious shape: a single file, and an established pattern, no new dependency, no open design question, and "done" is already evident from the draft | `haiku` | Fix a typo in one README, add a config flag, bump a dependency version, correct a log message |
384| **Typical** — ordinary feature, fix or refactor work: a handful of files inside one module or service, established patterns, local design choices only | `sonnet` | Add a REST endpoint to an existing service, add form validation, extract a helper and its tests |
385| **Complex** — **breadth** (~3+ modules/services, or any breadth when a shared contract changes) OR **critical domain** (auth, payments/billing, data integrity, irreversible migration, public API break) OR **open design** (concurrency, non-trivial algorithms, a new subsystem, architecture not yet decided) | `opus` | Re-architect the payments subsystem across 12 modules, design a new event pipeline, plan a schema migration |
386
387**Precedence (MANDATORY):** evaluate EVERY row, not just the first that matches. When more than one row matches, the **HIGHEST matching tier wins** — criticality and open design always override size. The **critical domain** list is exhaustive, not illustrative: shipping to production, touching real users, or *adding* to an existing public API are NOT triggers, so a new endpoint with validation in one service stays `sonnet`. **Mechanical-breadth carve-out:** breadth alone is not complexity — for one identical, rule-driven edit repeated across many files with no logic and no contract change, only the **breadth** trigger does not apply (critical domain and open design still do); tier it on a **single occurrence**, so a mechanical rename across 40 files is `haiku`, while the same rename confined to `src/auth/` is `opus`.
388
389**Tie-breaker:** ONLY when no row matches cleanly — the task sits genuinely between two tiers — pick `sonnet`, the working default. You MUST NOT bias up to `opus` to hedge; the [Escalation Rule](#escalation-rule) makes a modest first guess recoverable, and one recovered phase costs far less than over-provisioning every phase of every run.
390
391### Phase Weighting
392
393`BASELINE_TIER` is the tier of **every** model-assigned phase, with exactly one stated deviation:
394
395| Phase | Weight | Tier |
396|---|---|---|
397| Phase 3: Architecture Synthesis | **Heavy** — the only phase that makes open design decisions rather than applying settled ones; three inputs are synthesized here and every later phase, plus the implementation itself, inherits the result | **one tier above `BASELINE_TIER`**, capped at `opus` |
398| Phases 2a, 2b, 2c, 4 | Standard | `BASELINE_TIER` |
399
400Every model-assigned phase appears in exactly ONE row, so each resolves to exactly ONE tier. The cap means an `opus` baseline leaves all phases at `opus`. [Promotion](#promote-task) is a file move you perform yourself — no sub-agent, no tier. See [Role Pairing](#role-pairing) for the `--model` override.
401
402**Not to be confused with the per-step tiers inside the plan.** The tiers above govern the *planning* agents you launch. The `Model:` recorded in each sub-task file and the `Reviewer model:` recorded for each phase are decided by Phase 4 for the *implementation* run, from the per-step policy Phase 4's launch prompt carries — they are independent of `BASELINE_TIER`.
403
404### Role Pairing
405
406This pipeline has two model-assigned roles per phase: the **producer** (the phase agent) and the **evaluator** (its judge). **A judge ALWAYS runs at the tier of the phase it validates**, including after escalation. You MUST NOT tier a judge independently of its phase.
407
408**An explicit `--model` supersedes this entire policy (the ONLY statement of this rule):** every phase agent and every judge runs at the user's tier, the `BASELINE_TIER` assessment does NOT run, and [Phase Weighting](#phase-weighting) never deviates from it.
409
410### Escalation Rule
411
412Bump **BOTH the phase agent and its judge** one tier for the next iteration of that phase when either trigger fires:
413
4141. **Low first-iteration quality** — a low score, or judge issues showing the model misunderstood the phase rather than merely missing details.
4152. **The user complains** that quality is too low or the results are wrong — at any point, including after a reported PASS or a finished run.
416
417Ladder: `haiku` → `sonnet` → `opus`. `opus` is the **ceiling** — there is no further tier. If `opus`-tier work still fails, report it and escalate to the **user**; never loop.
418
419- **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 re-launch the phase 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) has NO such exception — it always bumps immediately, per the carve-out below.
420- **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 — report the low-quality evidence, *propose* the bump, and re-launch at the user's tier unless they approve. Trigger (2) IS that approval, so it bumps immediately.
421- **`--skip-judges` carve-out (the ONLY statement of this rule):** with no judge running, there is no score or judge issue for trigger (1) to read, so trigger (1) cannot fire. Trigger (2) is user-initiated, not judge-derived, so it is unaffected — a user complaint under `--skip-judges` (or `--one-shot`) still bumps the tier for that phase's re-launch.
422- **Scoped to the failing phase.** An escalated tier applies to that phase's remaining iterations only; every later phase resumes from its own [Phase Weighting](#phase-weighting) tier.
423- 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 re-launch; re-launching the same prompt at a higher tier and hoping is prohibited.
424- Escalation is orthogonal to `THRESHOLD`, `MAX_ITERATIONS`, `STRICT_MODE` and the [Iteration Discretion Rule](#iteration-discretion-rule) — it changes *which model* runs the next iteration, never *whether* one is warranted. When the Iteration Discretion Rule accepts a phase, no iteration happens, so nothing escalates.
425- **Re-entry after a finished phase (the ONLY statement of this rule):** a ✅ PASS or ☑️ ACCEPTED does NOT close the work. A later user quality complaint re-enters that phase under trigger (2) — through `--continue` or `--refine` — and `MAX_ITERATIONS` **resets** for it, with the phase and its judge running at the bumped tier.
426
427### Cross-Provider Equivalence
428
429When this skill runs outside the Anthropic model context, map the tier to the nearest model of the same class:
430
431| Tier | Role | Comparable models from other providers |
432|---|---|---|
433| `haiku` | Fast and cheap; mechanical work | `gemini-flash-lite`, `gemma` class, `gpt-oss` class, small open-weight models |
434| `sonnet` | Balanced workhorse; most planning phases | `gemini-pro` class and full `gemini-flash` (**not** the `-lite` variant, which is `haiku`-tier), `GPT-5-mini` class, large `Qwen` / `DeepSeek` class |
435| `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 |
436
437The 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, weighting, pairing and escalation rules unchanged.
438
439## Workflow Execution
440
441You MUST launch for each step a separate agent, instead of performing all steps yourself.
442
443**CRITICAL:** For each agent you MUST:
444
4451. Use the **Agent** type specified in the phase, and the **Model** tier resolved per the [Model Selection Policy](#model-selection-policy)
4462. Provide the task file path and user input as context
4473. **Provide the value of `${CLAUDE_PLUGIN_ROOT}` so agents can resolve paths like `@${CLAUDE_PLUGIN_ROOT}/scripts/create-scratchpad.sh`**
4484. Require agent to implement exactly that step, not more, not less
4495. After each sub-phase, launch a judge agent to validate quality before proceeding
450
451### Complete Workflow Overview
452
453**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
454`HUMAN_IN_THE_LOOP_PHASES`.
455
456```
457Input: Draft Task File (.specs/tasks/draft/*.md)
458 │
459 ▼
460Phase 2: Parallel Analysis
461 │
462 ├─────────────────────┬─────────────────────┐
463 ▼ ▼ ▼
464Phase 2a: Phase 2b: Phase 2c:
465Research Codebase Analysis Business Analysis
466[sdd:researcher] [sdd:code-explorer] [sdd:business-analyst]
467all three at baseline tier
468Judge 2a Judge 2b Judge 2c
469(pass: >THRESHOLD) (pass: >THRESHOLD) (pass: >THRESHOLD)
470 │ │ │
471 └─────────────────────┴─────────────────────┘
472 │
473 ▼
474 Phase 3: Architecture Synthesis
475 [sdd:software-architect] baseline+1 (cap opus)
476 Judge 3 (pass: >THRESHOLD)
477 │
478 ▼
479 Phase 4: Decomposition
480 [sdd:tech-lead] baseline
481 → task file: ## Implementation Process
482 → .specs/sub-tasks/<task-name>/NN-<step-slug>.md
483 Judge 4 (pass: >THRESHOLD)
484 │
485 ▼
486 Move task: draft/ → todo/
487 │
488 ▼
489 Complete
490```
491
492---
493
494## Phase 2: Parallel Analysis
495
496Phase 2 launches three analysis phases in parallel, each with its own judge validation.
497
498### Phase 2a/2b/2c: Parallel Sub-Phases
499
500Launch these three phases **in parallel** immediately:
501
502---
503
504#### Phase 2a: Research
505
506**Model:** `BASELINE_TIER` per [Phase Weighting](#phase-weighting) — standard weight: gathering and summarizing resources for an already-scoped task, no design decisions.
507**Agent:** `sdd:researcher`
508**Depends on:** Task file exists
509**Purpose:** Gather relevant resources, documentation, libraries, and prior art. Creates or updates a reusable skill.
510
511Launch agent:
512
513- **Description**: "Research task resources and create/update skill"
514- **Prompt**:
515
516 ```
517 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
518
519 Task File: <TASK_FILE>
520 Task Title: <title from task file>
521
522 CRITICAL: DO NOT OUTPUT YOUR RESEARCH, ONLY CREATE THE SCRATCHPAD AND SKILL FILE.
523 ```
524
525**Capture:**
526
527- Skill file path (e.g., `.claude/skills/<skill-name>/SKILL.md`)
528- Skill action (Created new / Updated existing)
529- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
530- Number of resources gathered
531- Key recommendation summary
532
533CRITICAL: If expected files not created, launch the agent again with the same prompt.
534
535---
536
537#### Phase 2b: Codebase Impact Analysis
538
539**Model:** `BASELINE_TIER` per [Phase Weighting](#phase-weighting) — standard weight: reading the codebase to locate files and integration points scales with the task's own breadth, which the baseline already reflects.
540**Agent:** `sdd:code-explorer`
541**Depends on:** Task file exists
542**Purpose:** Identify affected files, interfaces, and integration points
543
544Launch agent:
545
546- **Description**: "Analyze codebase impact"
547- **Prompt**:
548
549 ```text
550 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
551
552 Task File: <TASK_FILE>
553 Task Title: <title from task file>
554
555 CRITICAL: DO NOT OUTPUT YOUR ANALYSIS, ONLY CREATE THE SCRATCHPAD AND ANALYSIS FILE.
556 ```
557
558**Capture:**
559
560- Analysis file path (e.g., `.specs/analysis/analysis-{name}.md`)
561- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
562- Files affected count (modify/create/delete)
563- Risk level assessment
564- Key integration points
565
566CRITICAL: If expected files not created, launch the agent again with the same prompt.
567
568---
569
570#### Phase 2c: Business Analysis
571
572**Model:** `BASELINE_TIER` per [Phase Weighting](#phase-weighting) — standard weight: structured elicitation and checklist/rubric/test-strategy derivation driven end-to-end by the agent's own STAGES 1-10, not open-ended synthesis — the procedure, not the model, carries the rigour here.
573**Agent:** `sdd:business-analyst`
574**Depends on:** Task file exists
575**Purpose:** Refine the description and produce the single `## Acceptance Criteria` section — checklist, regular checks, rubric, rubric score definitions, test strategy and definition of done, mixing business and technical criteria
576
577Launch agent:
578
579- **Description**: "Business analysis"
580- **Prompt**:
581
582 ```
583 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
584
585 Task File: <TASK_FILE>
586 Task Title: <title from task file>
587
588 Execute your own Core Process (STAGES 1-10) in full.
589
590 CRITICAL: DO NOT OUTPUT YOUR BUSINESS ANALYSIS. Create the scratchpad, then write the task file's `# Description` and the single `## Acceptance Criteria` section at your STAGE 10.
591 ```
592
593**Capture:**
594
595- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
596- Scope defined (yes/no)
597- User scenarios documented
598- Checklist items count (essential / important / optional / pitfall)
599- Regular checks count
600- Rubric dimensions count (weights sum: 1.0)
601- Test strategy applies (true/false) and test types selected
602- Quality gates and project guidelines discovered
603
604CRITICAL: If the task file's `# Description` or `## Acceptance Criteria` section was not written, launch the agent again with the same prompt.
605
606---
607
608### Judge 2a/2b/2c: Validate Parallel Phases
609
610After **each** parallel phase completes, launch its respective judge **with the same agent type** as that phase, at the tier [Role Pairing](#role-pairing) gives it.
611
612#### Judge 2a: Validate Research/Skill
613
614**Model:** Phase 2a's tier — see [Role Pairing](#role-pairing)
615**Agent:** `sdd:researcher`
616**Depends on:** Phase 2a completion
617**Purpose:** Validate skill completeness and relevance
618
619Launch judge:
620
621- **Description**: "Judge skill quality"
622- **Prompt**:
623
624 ```
625 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
626
627 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
628
629 ### Artifact Path
630 {path to skill file from Phase 2a}
631
632 ### Context
633 This is a skill document for task: {task title}. Evaluate comprehensiveness and reusability.
634
635 ### Rubric
636 1. Resource Coverage (weight: 0.30)
637 - Documentation and references gathered?
638 - Libraries and tools identified with recommendations?
639 - 1=Missing critical resources, 2=Basic coverage, 3=Adequate, 4=Comprehensive, 5=Excellent
640
641 2. Pattern Relevance (weight: 0.25)
642 - Are identified patterns applicable?
643 - Are recommendations actionable?
644 - 1=Irrelevant, 2=Somewhat useful, 3=Adequate, 4=Well-targeted, 5=Perfect fit
645
646 3. Issue Anticipation (weight: 0.20)
647 - Common pitfalls identified with solutions?
648 - 1=None identified, 2=Few issues, 3=Adequate, 4=Good coverage, 5=Comprehensive
649
650 4. Reusability (weight: 0.15)
651 - Is the skill general enough to help multiple tasks?
652 - Does it avoid task-specific details?
653 - 1=Too specific, 2=Limited reuse, 3=Adequate, 4=Good, 5=Highly reusable
654
655 5. Task Integration (weight: 0.10)
656 - Was task file updated with skill reference?
657 - 1=Not updated, 3=Updated, 5=Updated with clear instructions
658 ```
659
660CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
661
662**Decision Logic:**
663
664- **PASS** (score >= `THRESHOLD`): Research complete, proceed
665- **FAIL** (score < `THRESHOLD`): Re-launch Phase 2a with feedback, at the tier per the [Escalation Rule](#escalation-rule) (unless accepted per the [Iteration Discretion Rule](#iteration-discretion-rule))
666- **MAX_ITERATIONS reached**: Proceed to next stage regardless of score (log warning)
667
668---
669
670#### Judge 2b: Validate Codebase Analysis
671
672**Model:** Phase 2b's tier — see [Role Pairing](#role-pairing)
673**Agent:** `sdd:code-explorer`
674**Depends on:** Phase 2b completion
675**Purpose:** Validate file identification accuracy and integration mapping
676
677Launch judge:
678
679- **Description**: "Judge codebase analysis quality"
680- **Prompt**:
681
682 ```
683 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
684
685 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
686
687 ### Artifact Path
688 {path to analysis file from Phase 2b}
689
690 ### Context
691 This is codebase impact analysis for task: {task title}. Evaluate accuracy and completeness.
692
693 ### Rubric
694 1. File Identification Accuracy (weight: 0.35)
695 - All affected files identified with specific paths?
696 - New files and modifications distinguished?
697 - 1=Major files missing, 2=Mostly correct, 3=Adequate, 4=Precise, 5=Complete
698
699 2. Interface Documentation (weight: 0.25)
700 - Key functions/classes documented with signatures?
701 - Change requirements clear?
702 - 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Complete
703
704 3. Integration Point Mapping (weight: 0.25)
705 - Integration points identified with impact?
706 - Similar patterns in codebase found?
707 - 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Comprehensive
708
709 4. Risk Assessment (weight: 0.15)
710 - High risk areas identified with mitigations?
711 - 1=No assessment, 2=Basic, 3=Adequate, 4=Good, 5=Thorough
712 ```
713
714CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
715
716**Decision Logic:**
717
718- **PASS** (score >= `THRESHOLD`): Analysis complete, proceed
719- **FAIL** (score < `THRESHOLD`): Re-launch Phase 2b with feedback, at the tier per the [Escalation Rule](#escalation-rule) (unless accepted per the [Iteration Discretion Rule](#iteration-discretion-rule))
720- **MAX_ITERATIONS reached**: Proceed to next stage regardless of score (log warning)
721
722---
723
724#### Judge 2c: Validate Business Analysis
725
726**Model:** Phase 2c's tier — see [Role Pairing](#role-pairing)
727**Agent:** `sdd:business-analyst`
728**Depends on:** Phase 2c completion
729**Purpose:** Validate the refined description and the whole `## Acceptance Criteria` section — checklist, regular checks, rubric, score definitions, test strategy and definition of done
730**Weight derivation:** criteria 1-4 are the original business-analysis criteria at their former proportions (0.30/0.35/0.20/0.15) scaled by 0.60, with the 0.01 rounding remainder given to the highest-weighted of them, totalling 0.61; criteria 5-7 — imported when rubric and test-strategy review folded into this judge — split the remaining 0.39 evenly at 0.13 each. Preserve that 0.61/0.39 split when adding or dropping a criterion, so the weights still sum to 1.00.
731
732Launch judge:
733
734- **Description**: "Judge business analysis quality"
735- **Prompt**:
736
737 ```
738 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
739
740 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
741
742 ### Artifact Path
743 {path to task file from Phase 2c}
744
745 ### Context
746 This is business analysis output. The task file should contain a refined `# Description`
747 (with Scope Included/Excluded and User Scenarios) and exactly one `## Acceptance Criteria`
748 section holding six sub-blocks in this order: `**Checklist:**` (table
749 `| ID | Question | Category | Importance |`, IDs `CK-n`/`HR-n`), `**Regular Checks:**`
750 (checkbox list), `**Rubric:**` (table `| Criterion | Weight |`), `**Rubric Score Definitions:**`
751 (one `###` section per criterion, each ending in an `Anchors` list carrying `score_2`, `score_4`
752 and `contrast` — excerpt anchors that pin 2 and 4, NOT 1-5 bins), `**Test Strategy:**` (Criticality + Test Matrix
753 table + `Test Cases to Cover` grouped under `#### CK-N:` headings) and `**Definition of Done:**`.
754 Business and technical criteria are mixed inside each sub-block — there is no separate business
755 criteria list, and no section other than `## Acceptance Criteria` may carry evaluation content.
756
757 ### Rubric
758 1. Description Clarity (weight: 0.18)
759 - What/Why/Who clearly explained?
760 - Business value stated, constraints named?
761 - 1=Vague, 2=Basic, 3=Adequate, 4=Clear, 5=Excellent
762
763 2. Criteria Quality (weight: 0.22)
764 - Is every `**Checklist:**` row a boolean YES/NO question that is specific and testable?
765 - Are Category (`hard_rule`/`principle`) and Importance filled for every row, with stable `CK-n`/`HR-n` IDs?
766 - Do business and technical criteria appear mixed, rather than as a separate business list?
767 - Is `**Definition of Done:**` present and derived from those criteria?
768 - 1=Missing/vague, 2=Basic, 3=Adequate, 4=Good, 5=Excellent
769
770 3. Scenario Coverage (weight: 0.12)
771 - Primary, alternative and error flows documented under **User Scenarios**?
772 - Are the error and edge scenarios actually represented by checklist items or test cases?
773 - 1=Missing, 2=Basic, 3=Adequate, 4=Good, 5=Comprehensive
774
775 4. Scope Definition (weight: 0.09)
776 - In-scope/out-of-scope explicit?
777 - No implementation details in the description?
778 - No invented file paths — artifacts cited only where the user prompt named them?
779 - 1=Missing, 2=Partial, 3=Adequate, 4=Good, 5=Clear
780
781 5. Rubric Quality (weight: 0.13)
782 - Are `**Rubric:**` criteria specific to this task (not generic)?
783 - Do the weights sum to 1.0?
784 - Does EVERY criterion in `**Rubric Score Definitions:**` carry an `Anchors` list naming all three of `score_2`, `score_4` and `contrast`, with no 1-5 bins, ratios, percentages or quality bands in its description or classification/instruction paragraph? (A `score_2`/`score_4` anchor excerpt may legitimately quote a figure — this restriction does not reach the anchors themselves.)
785 - Is each `score_2` / `score_4` a concrete excerpt of the deliverable a reader could point at (fenced text), NEVER a description of quality — `score_2` obviously FAILING that dimension and `score_4` obviously SATISFYING it?
786 - Do a criterion's two anchors differ on EXACTLY ONE observable thing, with its one-line `contrast` naming that single difference, so a judge can place an artifact between or past them on that axis alone?
787 - Is `Project Guidelines Alignment` present when project guideline files exist?
788 - 1=Generic/broken rubrics, 2=Adequate, 3=Acceptable, 4=Good custom rubrics, 5=Excellent custom rubrics
789
790 6. Coverage Completeness (weight: 0.13)
791 - Are all six sub-blocks present, in order, under a single `## Acceptance Criteria`?
792 - Does `**Regular Checks:**` use the project's actual discovered build/lint/test commands rather than placeholders?
793 - Is every checklist item carried by at least one rubric criterion, regular check or test case — no orphans?
794 - Is the task file free of scoring configuration (threshold values, judge counts, evaluation modes) and of any evaluation section other than `## Acceptance Criteria`?
795 - 1=Missing sub-blocks or orphans, 2=Most covered, 3=Acceptable, 4=Good, 5=100% coverage
796
797 7. Test Strategy Coverage (weight: 0.13)
798 - When the task carries testable behaviour, is `**Test Strategy:**` present with Criticality, a Test Matrix table (`| Type | Size | Framework | Dependencies | Gate |`) and a `Test Cases to Cover` list?
799 - Is every group headed `#### CK-N:` naming a checklist item that exists, with cases in `- [type] description` form?
800 - Does every testable checklist item have at least one test case (no orphans), and every Test Matrix row a corresponding case?
801 - If the strategy does not apply, is that stated with a reason rather than silently omitted?
802 - 1=Missing/empty Test Strategy, 2=Present but orphaned or unheaded groups, 3=All blocks present, 4=Full coverage of testable items, 5=Ideal coverage with boundary cases enumerated
803 ```
804
805CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
806
807**Decision Logic:**
808
809- **PASS** (score >= `THRESHOLD`): Business analysis complete, proceed
810- **FAIL** (score < `THRESHOLD`): Re-launch Phase 2c with feedback, at the tier per the [Escalation Rule](#escalation-rule) (unless accepted per the [Iteration Discretion Rule](#iteration-discretion-rule))
811- **MAX_ITERATIONS reached**: Proceed to next stage regardless of score (log warning)
812
813---
814
815### Synchronization Point
816
817**Wait for ALL three parallel phases (2a, 2b, 2c) AND their judges to PASS before proceeding to Phase 3.**
818
819---
820
821## Phase 3: Architecture Synthesis
822
823**Model:** One tier above `BASELINE_TIER`, capped at `opus`, per [Phase Weighting](#phase-weighting) — the sole **heavy** phase: it decides the solution strategy and trade-offs that every later phase and the implementation inherit.
824**Agent:** `sdd:software-architect`
825**Depends on:** Phase 2a + Judge 2a PASS, Phase 2b + Judge 2b PASS, Phase 2c + Judge 2c PASS
826**Purpose:** Synthesize research, analysis, and business requirements into architectural overview
827
828Launch agent:
829
830- **Description**: "Architecture synthesis"
831- **Prompt**:
832
833 ```
834 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
835
836 Task File: <TASK_FILE>
837 Skill File: <skill file path from Phase 2a>
838 Analysis File: <analysis file path from Phase 2b>
839
840 CRITICAL: DO NOT OUTPUT YOUR ARCHITECTURE SYNTHESIS, ONLY CREATE THE SCRATCHPAD AND UPDATE THE TASK FILE.
841 ```
842
843**Capture:**
844
845- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
846- Sections added to task file
847- Key architectural decisions count
848- Components identified (if applicable)
849- Contracts defined (if applicable)
850
851---
852
853### Judge 3: Validate Architecture Synthesis
854
855**Model:** Phase 3's tier — see [Role Pairing](#role-pairing)
856**Agent:** `sdd:software-architect`
857**Depends on:** Phase 3 completion
858**Purpose:** Validate architectural coherence and completeness
859
860Launch judge:
861
862- **Description**: "Judge architecture synthesis quality"
863- **Prompt**:
864
865 ```
866 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
867
868 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
869
870 ### Artifact Path
871 {path to task file after Phase 3}
872
873 ### Context
874 This is architecture synthesis output. The Architecture Overview section should contain
875 solution strategy, key decisions, and only relevant architectural sections.
876
877 ### Rubric
878 1. Solution Strategy Clarity (weight: 0.30)
879 - Approach clearly explained?
880 - Key decisions documented with reasoning?
881 - Trade-offs stated?
882 - 1=Missing/unclear, 2=Basic, 3=Adequate, 4=Clear, 5=Excellent
883
884 2. Reference Integration (weight: 0.20)
885 - Links to research and analysis files?
886 - Insights from both integrated?
887 - 1=No links, 2=Partial, 3=Adequate, 4=Good, 5=Fully integrated
888
889 3. Section Relevance (weight: 0.25)
890 - Only relevant sections included (not all)?
891 - Sections appropriate for task complexity?
892 - 1=Wrong sections, 2=Mostly appropriate, 3=Adequate, 4=Good, 5=Precisely targeted
893
894 4. Expected Changes Accuracy (weight: 0.25)
895 - Files to create/modify listed?
896 - Consistent with codebase analysis?
897 - 1=Missing/inconsistent, 2=Partial, 3=Adequate, 4=Good, 5=Complete
898
899 ```
900
901CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
902
903**Decision Logic:**
904
905- **PASS** (score >= `THRESHOLD`): Architecture synthesis complete, proceed
906- **FAIL** (score < `THRESHOLD`): Re-launch Phase 3 with feedback, at the tier per the [Escalation Rule](#escalation-rule) (unless accepted per the [Iteration Discretion Rule](#iteration-discretion-rule))
907- **MAX_ITERATIONS reached**: Proceed to Phase 4 regardless of score (log warning)
908
909**Wait for PASS before Phase 4.**
910
911---
912
913## Phase 4: Decomposition
914
915**Model:** `BASELINE_TIER` per [Phase Weighting](#phase-weighting) — standard weight: it applies an architecture Phase 3 already settled rather than making open design decisions, but still demands genuine per-step judgment — risks and mitigations specific to this task's own steps, a dependency graph that is neither over- nor under-constrained, and phase boundaries that each land on a working, verifiable milestone (see Judge 4's Risk Coverage, Dependency Accuracy and Phase Design criteria).
916**Agent:** `sdd:tech-lead`
917**Depends on:** Phase 3 + Judge 3 PASS
918**Purpose:** Break the architecture into implementation steps, write each step as its own sub-task file, and group them into independently verifiable phases with dependencies, parallel groups, per-step agent/model assignments and a reviewer model per phase
919
920Launch agent:
921
922- **Description**: "Decompose into sub-task files and phases"
923- **Prompt**:
924
925 ```
926 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
927
928 Task File: <TASK_FILE>
929
930 Use agents only from this list: {list ALL available agents with plugin prefix if available, e.g. sdd:developer, review:bug-hunter. Also include general agents: opus, sonnet, haiku}
931
932 Assign each step's model tier per this policy:
933 {paste the Selection Rules table plus its Precedence and Tie-breaker paragraphs from the orchestrator's Model Selection Policy verbatim, applied per implementation step; drop the cross-reference links, which do not resolve outside that file}
934
935 CRITICAL: DO NOT OUTPUT YOUR DECOMPOSITION. Create the scratchpad, write ONLY the `## Implementation Process` section (Parallelization Overview + Phase Overview) into the task file, and write every step as its own file under `.specs/sub-tasks/<task-name>/`.
936 ```
937
938**Capture:**
939
940- Scratchpad file path (e.g., `.specs/scratchpad/<hex-id>.md`)
941- Sub-task directory (`.specs/sub-tasks/<task-name>/`) and the sub-task files written
942- Implementation steps count (and how many were merged)
943- Total subtasks count
944- Phases count, with each phase's steps and reviewer model
945- Critical path steps
946- Max parallel width (peak concurrent steps — MUST be 1–5)
947- Agent/model distribution
948- High priority risks count
949
950CRITICAL: If the `## Implementation Process` section or any sub-task file listed in the Parallelization Overview is missing, launch the agent again with the same prompt.
951
952---
953
954### Judge 4: Validate Decomposition
955
956**Model:** Phase 4's tier — see [Role Pairing](#role-pairing)
957**Agent:** `sdd:tech-lead`
958**Depends on:** Phase 4 completion
959**Purpose:** Validate step quality, sub-task file completeness, dependency and parallelization accuracy, agent/model assignment and phase design
960
961Launch judge:
962
963- **Description**: "Judge decomposition quality"
964- **Prompt**:
965
966 ```
967 CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT}
968
969 Read @${CLAUDE_PLUGIN_ROOT}/prompts/judge.md for evaluation methodology and execute.
970
971 ### Artifact Path
972 {path to task file after Phase 4}
973 {path to the sub-task directory from Phase 4, e.g. .specs/sub-tasks/<task-name>/} — evaluate EVERY file in it
974
975 ### Context
976 This is decomposition output, written across two places. The task file carries ONLY the
977 `## Implementation Process` section: the sub-agent execution directive that governs how each step
978 is launched and how each phase is reviewed (its required content is spelled out under Completeness
979 below), a `### Parallelization Overview` (ASCII diagram with phase boundaries plus a step table
980 with columns `Step | Phase | Model | Agent | Depends on | Parallel with | Sub-Task File`) and a
981 `### Phase Overview` (per phase: `#### Phase N`, `Steps:`, `Reviewer model:`,
982 `Acceptance Criteria that should be fulfiled:`, a `Checklist items:` list citing `CK-n`/`HR-n` IDs from
983 the task file's `**Checklist:**` table, and a `Rubrics:` list citing criterion names from its
984 `**Rubric:**` table). Every step body lives in its own sub-task file at
985 `.specs/sub-tasks/<task-name>/<NN>-<step-slug>.md` with the fields `**Task File:**`, `**Phase:**`,
986 `**Model:**`, `**Agent:**`, `**Depends on:**`, `**Parallel with:**`, `**Note:**`, `**Goal:**`, a step
987 description, `#### Expected Output`, `#### Success Criteria`, `#### Subtasks` and `#### Blockers & Risks`.
988
989 By design these do NOT belong in the task file and MUST NOT be scored as missing: `### Implementation
990 Strategy`, a least-to-most decomposition chain, `### Step N:` bodies, `## Implementation Summary`,
991 `## Risks & Blockers Summary`, and a task-level Definition of Done (the Definition of Done lives in
992 `## Acceptance Criteria`, written by an earlier phase). Verification is PHASE-level: each phase names
993 one reviewer model; there are no per-step verification sections.
994
995 Use agents only from this list: {list ALL available agents with plugin prefix if available, e.g. sdd:developer, review:bug-hunter. Also include general agents: opus, sonnet, haiku}
996
997 ### Rubric
998 1. Step Quality (weight: 0.15)
999 - Does every sub-task file carry ALL required fields, with `None` written rather than a field omitted?
1000 - Does each have a clear `**Goal:**`, a real step description, and `#### Expected Output`?
1001 - Is each step meaningfully sized — neither so large it hides risk nor so small it wastes an agent run?
1002 - Is each sub-task file standalone-readable, naming every path, symbol and decision it builds on rather than relying on a neighbouring step?
1003 - 1=Vague/missing fields, 2=Basic, 3=Adequate, 4=Good, 5=Excellent
1004
1005 2. Success Criteria Testability (weight: 0.12)
1006 - Are `#### Success Criteria` specific and verifiable, using actual file paths and function names?
1007 - Are `#### Subtasks` actionable, each naming what it changes and where?
1008 - Does every step include writing its own tests as a subtask?
1009 - 1=Vague, 2=Partially testable, 3=Adequate, 4=Good, 5=All testable
1010
1011 3. Risk Coverage (weight: 0.10)
1012 - Does each sub-task file's `#### Blockers & Risks` table name blockers with resolutions and risks with mitigations, rated for Impact and Likelihood?
1013 - Are they specific to this step rather than a generic checklist restated per file?
1014 - 1=None, 2=Basic, 3=Adequate, 4=Good, 5=Comprehensive
1015
1016 4. Completeness (weight: 0.15)
1017 - Does every architecture component and expected change have a corresponding step?
1018 - Does every row of the Parallelization Overview table have a sub-task file at the recorded path, and every sub-task file a row — no orphans either way?
1019 - Is the sub-agent execution directive present in `## Implementation Process` — launch one agent per step, parallel steps in parallel, pass the task file path AND the step's sub-task file path, use the step's own Model and Agent, implement exactly that step, and run the code reviewer ONCE per phase at that phase's reviewer model?
1020 - Is the task file free of the sections listed as out of scope in the Context above?
1021 - 1=Incomplete, 2=Partial, 3=Adequate, 4=Good, 5=Complete
1022
1023 5. Dependency Accuracy (weight: 0.15)
1024 - Are `**Depends on:**` values correct — no false dependencies (steps sequenced that need not be), no missing ones (steps that truly need an earlier artifact)?
1025 - Do the sub-task files, the Parallelization Overview table and the diagram agree on every dependency?
1026 - Does each step's dependencies resolve to steps in the same or an earlier phase?
1027 - 1=Major dependency errors, 2=Mostly correct, 3=Acceptable, 4=Accurate, 5=Precise dependencies
1028
1029 6. Parallelization Maximized (weight: 0.10)
1030 - Are genuinely independent steps marked with `**Parallel with:**` rather than left sequential?
1031 - Is the ASCII diagram logical and does it show the phase boundaries?
1032 - Is peak concurrent width within 1–5 (target ~3) rather than unbounded?
1033 - 1=No parallelization/wrong, 2=Some optimization, 3=Acceptable, 4=Well optimized, 5=Maximum parallelization within the width bound
1034
1035 7. Agent/Model Selection Correctness (weight: 0.08)
1036 - Are agent types appropriate for what each step OUTPUTS, and drawn only from the provided available agents list?
1037 - Does each step's `**Model:**` follow the per-step model policy — `opus` earned by a breadth, critical-domain or open-design trigger rather than picked to be safe, `haiku` only for mechanical work?
1038 - 1=Wrong agents/tiers, 2=Mostly appropriate, 3=Acceptable, 4=Optimal selection, 5=Perfect selection
1039
1040 8. Phase Design (weight: 0.15)
1041 - Does EACH phase leave an independently verifiable milestone — a working application/service/solution that could be committed and run, PLUS the tests or other verification artifacts that let a reviewer judge it against the criteria listed for that phase?
1042 - Is EACH phase's `Reviewer model:` appropriate — never below the highest implementation tier used in that phase, and one tier above it unless the phase is small, uniform and mechanical?
1043 - Are phase sizes sensible — not one step per phase (review churn), not so many steps that a reviewer's findings force rewriting the whole phase? A single phase for the whole task is acceptable ONLY when no earlier point yields a working, verifiable state.
1044 - Does every checklist item and every rubric criterion in `## Acceptance Criteria` appear against at least one phase, and does each phase list only criteria genuinely due at that checkpoint rather than end-of-task criteria?
1045 - Is the task file free of threshold values, scores and judge configuration, which belong to the orchestrator?
1046 - 1=Phases are arbitrary cuts or leave a broken state, 2=Milestones partly hold or reviewer tiers are off, 3=Acceptable, 4=Well-designed milestones with justified reviewer tiers, 5=Every phase a clean, self-contained, correctly reviewed milestone
1047 ```
1048
1049CRITICAL: use prompt exactly as is, do not add anything else. Including output of implementation agent!!!
1050
1051**Decision Logic:**
1052
1053- **PASS** (score >= `THRESHOLD`): Decomposition complete, workflow done — promote the task
1054- **FAIL** (score < `THRESHOLD`): Re-launch Phase 4 with feedback, at the tier per the [Escalation Rule](#escalation-rule) (unless accepted per the [Iteration Discretion Rule](#iteration-discretion-rule))
1055- **MAX_ITERATIONS reached**: Promote the task regardless of score (log warning)
1056
1057**Wait for PASS before promoting the task.**
1058
1059---
1060
1061## Promote Task
1062
1063**Purpose:** Move the refined task from draft to todo folder. This is a file move you perform yourself — no sub-agent, no model tier, no judge.
1064
1065After all phases complete:
1066
10671. **Move task file from draft to todo:**
1068
1069 ```bash
1070 git mv <TASK_FILE> .specs/tasks/todo/
1071 # Fallback if git not available: mv <TASK_FILE> .specs/tasks/todo/
1072 ```
1073
10742. **Do NOT move `.specs/sub-tasks/<task-name>/`.** The sub-task folder is created at planning time and stays put while the task file travels `draft/` → `todo/` → `in-progress/` → `done/`, so the paths recorded in the Parallelization Overview never go stale.
1075
10763. **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, the sub-task files under `.specs/sub-tasks/<task-name>/`, 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| **Phases** | `<count, each with its reviewer model, or "N/A">` |
1102| **Max Parallel Width** | `<peak concurrent steps, 1–5, or "N/A">` |
1103| **Sub-Task Files** | `.specs/sub-tasks/<task-name>/ — <count> files` or `"N/A"` |
1104
1105### Configuration Used
1106
1107| Setting | Value |
1108|---------|-------|
1109| **Target Quality** | {THRESHOLD}/5.0 |
1110| **Max Iterations** | {MAX_ITERATIONS} |
1111| **Active Stages** | {ACTIVE_STAGES as comma-separated list} |
1112| **Skipped Stages** | {SKIP_STAGES or stages not in ACTIVE_STAGES} |
1113| **Human Checkpoints** | Phase {HUMAN_IN_THE_LOOP_PHASES as comma-separated} |
1114| **Skip Judges** | {SKIP_JUDGES} |
1115| **Refine Mode** | {REFINE_MODE} |
1116| **Strict Mode** | {STRICT_MODE} |
1117
1118### Quality Gates Summary
1119
1120| Phase | Judge Score | Verdict |
1121|-------|-------------|---------|
1122| Phase 2a: Research | X.X/5.0 | ✅ PASS / ☑️ ACCEPTED / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1123| Phase 2b: Codebase Analysis | X.X/5.0 | ✅ PASS / ☑️ ACCEPTED / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1124| Phase 2c: Business Analysis | X.X/5.0 | ✅ PASS / ☑️ ACCEPTED / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1125| Phase 3: Architecture Synthesis | X.X/5.0 | ✅ PASS / ☑️ ACCEPTED / ⚠️ PROCEEDED (max iter) / ⏭️ SKIPPED |
1126| Phase 4: Decomposition | X.X/5.0 | ✅ PASS / ☑️ ACCEPTED / ⚠️ 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- ☑️ ACCEPTED - Score in `max(3.0, THRESHOLD - 1.0)..THRESHOLD` accepted per the [Iteration Discretion Rule](#iteration-discretion-rule) (outstanding nitpicks listed below the table)
1133- ⚠️ PROCEEDED (max iter) - Score < THRESHOLD but MAX_ITERATIONS reached, proceeded anyway
1134- ⏭️ SKIPPED - Stage not in ACTIVE_STAGES
1135
1136**Outstanding Issues (accepted below THRESHOLD):**
1137
1138{For each ☑️ ACCEPTED phase: phase, remaining nitpicks with priority — omit this block when no phase was accepted}
1139
1140### Artifacts Generated
1141
1142```
1143
1144.claude/
1145└── skills/
1146 └── <skill-name>/
1147 └── SKILL.md # Reusable skill document (if research stage ran)
1148
1149.specs/
1150├── tasks/
1151│ ├── draft/ # Draft tasks (source - now empty for this task)
1152│ ├── todo/
1153│ │ └── <name>.<type>.md # Complete task specification (ready for implementation)
1154│ ├── in-progress/ # Tasks being implemented (empty)
1155│ └── done/ # Completed tasks (empty)
1156├── sub-tasks/
1157│ └── <task-name>/ # One folder per task — NEVER moves with the task file
1158│ ├── 01-<step-slug>.md # One sub-task file per implementation step
1159│ └── 02a-<step-slug>.md
1160├── analysis/
1161│ └── analysis-<name>.md # Codebase impact analysis (if codebase analysis stage ran)
1162└── scratchpad/
1163 └── <hex-id>.md # Architecture thinking scratchpad
1164
1165```
1166
1167### Task Status Management
1168
1169Task status is managed by folder location:
1170- `draft/` - Tasks created but not yet refined
1171- `todo/` - Tasks ready for implementation
1172- `in-progress/` - Tasks currently being worked on
1173- `done/` - Completed tasks
1174
1175### Next Steps
1176
11771. Review task: `.specs/tasks/todo/<filename>`
1178 - Edit the task file directly to make corrections
1179 - Add `//` comments to lines that need clarification or changes
1180 - 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)
11812. If everything is fine, begin implementation: `/implement` (will auto-select the task from todo/)
1182```
1183
1184---
1185
1186## Error Handling
1187
1188### Phase Agent Failure (Exception/Crash)
1189
1190If any phase agent fails unexpectedly:
1191
11921. Report the failure with agent output
11932. Ask clarification questions from user that can help resolve the issue
11943. Launch the phase agent again with list of questions and answers to resolve the issue
1195
1196### Judge Returns FAIL
1197
1198If any judge returns FAIL (score < `THRESHOLD`):
1199
12000. **Apply the [Iteration Discretion Rule](#iteration-discretion-rule) first**: if `score < 3.0` (or `STRICT_MODE` is true), always retry. If `max(3.0, THRESHOLD - 1.0) <= score < THRESHOLD` and only nitpicks remain, decide deliberately whether retrying is worth it — if you accept, mark the phase ☑️ ACCEPTED, list its outstanding nitpicks in the summary, and proceed to the next phase instead of steps 1-4; otherwise continue with step 1
12011. **Automatic retry**: Re-launch the phase agent with judge feedback, at the tier decided per the [Escalation Rule](#escalation-rule) — which governs in full, including its sole hold exception and its `--model` carve-out. Retry-specific anchors on top of it: trigger (1) is anchored at `score < 3.0` here (or judge issues showing the model misunderstood the phase); re-judge at the same tier as the re-launched phase; state the tier decision in the phase summary
12022. **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)
12033. **After `MAX_ITERATIONS` reached**: **Proceed to next stage automatically** (do NOT ask user unless `--human-in-the-loop` includes this phase)
12044. Log warning in completion summary: `⚠️ Phase X did not pass quality threshold (X.X/THRESHOLD) after MAX_ITERATIONS iterations`
1205
1206### Retry Flow
1207
1208```
1209Implementation → Judge FAIL → Implementation Retry → Judge Retry
1210 ↓
1211 PASS → Continue to next stage
1212 FAIL → Repeat until MAX_ITERATIONS
1213 ↓
1214 MAX_ITERATIONS reached → Proceed to next stage (with warning)
1215```
1216
1217### Retry Flow with Human-in-the-Loop
1218
1219When phase is in `HUMAN_IN_THE_LOOP_PHASES`:
1220
1221```
1222Implementation → Judge FAIL → Implementation Retry
1223 ↓
1224 🔍 Human Checkpoint (optional feedback)
1225 ↓
1226 Judge Retry
1227 ↓
1228 PASS → Continue | FAIL → Repeat until MAX_ITERATIONS
1229 ↓
1230 MAX_ITERATIONS → 🔍 Final Human Checkpoint
1231 ↓
1232 User confirms → Proceed to next stage
1233```