Spec Workflow Orchestrator
Table of Contents
- Purpose
- When to Use
- Orchestration Workflow
- Agent Roles
- Quality Gates
- File Organization
- Best Practices
- Examples
Purpose
Transform ideas into development-ready specifications through:
- Comprehensive planning with requirement analysis and architecture design
- Quality-gated iterative refinement of specifications
- Complete handoff documentation for development teams
- Orchestration across planning phase with 4 specialized agents
When to Use
Auto-invoke when user requests:
- Planning: "Plan [application]", "Design [system]", "Spec out [feature]", "Create requirements for [service]"
- Architecture: "Architecture for [project]", "Technical design for [application]", "Design specifications"
- Requirements: "Requirements for [project]", "Analyze requirements", "User stories for [feature]"
- Pre-Development: "Ready for development", "Spec-based planning", "Development specifications"
Do NOT invoke for:
- Actual code implementation (this skill stops at planning)
- Quick prototypes or experiments
- Single-file scripts
- Tasks that need immediate coding
Orchestration Workflow
Planning Phase (spec-analyst → spec-architect → spec-planner)
Scope: Complete planning and analysis phase (ideation → development-ready specifications)
Key Activities (from battle-tested Phase 1):
- Requirements gathering and analysis
- System architecture design
- Task breakdown and estimation
- Risk assessment and mitigation planning
Quality Gates:
- Requirements completeness and clarity (>85%)
- Architecture feasibility validation
- Task breakdown granularity check
- Risk mitigation coverage
The orchestrator manages sequential execution of three specialized agents with quality gate validation.
Step 1: Query Analysis
Parse user's planning request and validate suitability:
- Identify project scope, constraints, and stakeholders
- Confirm request is suitable for planning workflow (not immediate coding)
- Determine if sufficient information provided (or elicit more details)
- Output: Planning scope definition ready for spec-analyst
Step 1.5: Project Naming & Existing Project Detection
Part A: Determine Project Slug
Determine project directory name for organizing deliverables:
- Derive project slug from user request (e.g., "Session Log Viewer" → "session-log-viewer")
- Or ask user: "What should we call this project? (for organizing planning files)"
Example Project Slugs:
- "Build a task manager" →
task-manager - "Session log viewer web app" →
session-log-viewer - "E-commerce product catalog" →
ecommerce-product-catalog
Part B: Check for Existing Project
Step B1: Check if project exists
Use Bash tool to check if project directory exists:
if [ -d "docs/projects/{project-slug}" ]; then
echo "existing"
else
echo "new"
fi
If NEW PROJECT (no directory exists):
# Create fresh directory structure
mkdir -p "docs/projects/{project-slug}/planning"
mkdir -p "docs/projects/{project-slug}/adrs"
echo "Fresh directories created"
Then use workflow_state.sh to save state:
.claude/utils/workflow_state.sh set "{project-slug}" "fresh" ""
Proceed to Step 2 with fresh planning mode.
If EXISTING PROJECT (directory exists):
Step B2: Ask user for choice
Use AskUserQuestion tool to ask:
{
"questions": [{
"question": "Project '{project-slug}' already has planning specifications. How would you like to proceed?",
"header": "Refine Specs",
"multiSelect": false,
"options": [
{
"label": "Refine existing specs",
"description": "Agents will read current files and improve them iteratively"
},
{
"label": "Archive + fresh start",
"description": "Move existing specs to .archive/{timestamp}/ and create new specs from scratch"
},
{
"label": "Create new version",
"description": "Create {project-slug}-v2/ directory for new planning iteration"
},
{
"label": "Cancel",
"description": "Stop the workflow without making changes"
}
]
}]
}
Step B3: Handle user choice
Store user's answer from AskUserQuestion response in variable USER_CHOICE.
If USER_CHOICE = "Refine existing specs":
- Save state as refinement mode:
# Capture user's additional requirements from conversation context
USER_INPUT="[Extract new requirements from user's latest messages]"
# Save to state file
.claude/utils/workflow_state.sh set "{project-slug}" "refinement" "$USER_INPUT"
- Set WORKFLOW_MODE = "refinement"
- Proceed to Step 2 with refinement mode prompts
If USER_CHOICE = "Archive + fresh start":
- Run archive utility:
# Archive existing specs with timestamp
.claude/utils/archive_project.sh "{project-slug}"
# This script:
# - Creates .archive/{timestamp}/ directory
# - Copies planning/ and adrs/ to archive
# - Verifies integrity
# - Deletes originals
# - Creates fresh planning/ and adrs/ directories
# - Returns exit code 0 on success, 1 on failure
- Check exit code and handle errors:
if [ $? -eq 0 ]; then
echo "Archive successful, proceeding with fresh planning"
else
echo "Archive failed, aborting workflow"
exit 1
fi
- Save state as fresh mode:
.claude/utils/workflow_state.sh set "{project-slug}" "fresh" ""
- Set WORKFLOW_MODE = "fresh"
- Proceed to Step 2 with fresh planning mode prompts
If USER_CHOICE = "Create new version":
- Detect next available version:
# Run version detection utility
NEW_SLUG=$(.claude/utils/detect_next_version.sh "{project-slug}")
# This returns: "{project-slug}-v2" or "{project-slug}-v3" etc.
# Exit code 0 on success, 1 if version limit reached (v99)
- Handle version detection result:
if [ $? -eq 0 ]; then
echo "Next version: $NEW_SLUG"
PROJECT_SLUG="$NEW_SLUG"
else
echo "ERROR: Version limit reached (v2-v99 all exist)"
echo "Consider using 'Archive + fresh start' instead"
exit 1
fi
- Create new versioned directory:
mkdir -p "docs/projects/$PROJECT_SLUG/planning"
mkdir -p "docs/projects/$PROJECT_SLUG/adrs"
- Save state with new slug:
.claude/utils/workflow_state.sh set "$PROJECT_SLUG" "fresh" ""
- Update PROJECT_SLUG variable to new version slug
- Set WORKFLOW_MODE = "fresh"
- Proceed to Step 2 with fresh planning mode prompts
If USER_CHOICE = "Cancel":
- Clear any partial state:
.claude/utils/workflow_state.sh clear
- Inform user:
Workflow cancelled. No changes made to existing project specs.
- Exit workflow gracefully (return to user)
Output:
PROJECT_SLUG(final slug, may be versioned)WORKFLOW_MODE("fresh" or "refinement")USER_INPUT(additional requirements if refinement mode, empty string otherwise)
Step 1.6: Placeholder Substitution
Before spawning agents, substitute placeholders in prompt templates with actual values:
Required Substitutions:
{project-slug}→ Actual project slug (e.g., "task-tracker-pwa" or "task-tracker-pwa-v2")[PROJECT_NAME]→ User-friendly project name extracted from original request (e.g., "Task Tracker PWA")[ADDITIONAL_REQUIREMENTS_FROM_USER]→ (Refinement mode only) User's new requirements from conversation[CHANGES_FROM_REQUIREMENTS]→ (Refinement mode only) Summary of requirement changes for architect
How to Extract Values:
PROJECT_NAME: Parse from original user request
- Example: "Build a task tracker PWA" → PROJECT_NAME = "Task Tracker PWA"
- Example: "Plan an e-commerce catalog" → PROJECT_NAME = "E-Commerce Catalog"
USER_INPUT for Refinement (saved in state file):
# Retrieve from state file
USER_INPUT=$(.claude/utils/workflow_state.sh get "user_input")
If empty (user just said "refine specs"), use generic guidance:
USER_INPUT="Review all sections for completeness, update metrics to be measurable, enhance clarity"
- Perform substitution before spawning each agent:
# Pseudocode for substitution
prompt_template = "Analyze requirements for [PROJECT_NAME]..."
actual_prompt = prompt_template
actual_prompt = actual_prompt.replace("{project-slug}", PROJECT_SLUG)
actual_prompt = actual_prompt.replace("[PROJECT_NAME]", PROJECT_NAME)
actual_prompt = actual_prompt.replace("[ADDITIONAL_REQUIREMENTS_FROM_USER]", USER_INPUT)
Example Substitution:
Before:
prompt: "Refine requirements for [PROJECT_NAME].
IMPORTANT: Read existing file at docs/projects/{project-slug}/planning/requirements.md first.
4. Enhance based on new user input: [ADDITIONAL_REQUIREMENTS_FROM_USER]"
After (for task-tracker-pwa, user wants "add offline support"):
prompt: "Refine requirements for Task Tracker PWA.
IMPORTANT: Read existing file at docs/projects/task-tracker-pwa/planning/requirements.md first.
4. Enhance based on new user input: Add offline support with service workers and local storage"
Step 2: Spawn spec-analyst Agent (Requirements Gathering and Analysis)
Use Task tool to spawn requirements analysis agent to perform Phase 1 Activity 1:
IMPORTANT: Apply placeholder substitution from Step 1.6 before spawning.
For Fresh Planning Mode:
subagent_type: "spec-analyst"
description: "Analyze requirements for {PROJECT_NAME}"
prompt: "Analyze requirements for {PROJECT_NAME}. Generate comprehensive requirements.md with:
- Executive Summary (project goals and scope)
- Functional Requirements (prioritized with IDs: FR1, FR2, etc.)
- Non-Functional Requirements (performance, security, scalability with metrics)
- User Stories with Acceptance Criteria (measurable criteria for each story)
- Stakeholder Analysis (identify all stakeholder groups and their needs)
- Assumptions and Constraints (technical, business, timeline)
- Success Metrics (how to measure project success)
Save to: docs/projects/{project-slug}/planning/requirements.md"
For Refinement Mode:
subagent_type: "spec-analyst"
description: "Refine requirements for {PROJECT_NAME}"
prompt: "Refine requirements for {PROJECT_NAME}.
IMPORTANT: Read existing file at docs/projects/{project-slug}/planning/requirements.md first.
Your task:
1. Analyze existing requirements document
2. Identify gaps, weak sections, or outdated content
3. Preserve well-written sections (don't rewrite what's already good)
4. Enhance based on new user input: {USER_INPUT}
5. Add missing sections or details
6. Update metrics to be more measurable
7. Ensure acceptance criteria are concrete and testable
Maintain document structure but improve quality and completeness.
Save updated version to: docs/projects/{project-slug}/planning/requirements.md"
Note: Replace {USER_INPUT} with actual value from state file or generic guidance.
Wait for completion → Read output: docs/projects/{project-slug}/planning/requirements.md
Expected Output: Comprehensive requirements document (typically 800-1,500 lines)
Step 3: Spawn spec-architect Agent (System Architecture Design)
Use Task tool to spawn architecture design agent to perform Phase 1 Activity 2:
For Fresh Planning Mode:
subagent_type: "spec-architect"
description: "Design system architecture for {PROJECT_NAME}"
prompt: "Design system architecture for {PROJECT_NAME} based on requirements at docs/projects/{project-slug}/planning/requirements.md.
Generate:
1. architecture.md with:
- Executive Summary
- Technology Stack (with justification for each choice)
- System Components (with interaction diagrams and relationships)
- Interface Specifications (APIs, CLIs, SDKs, data contracts as appropriate)
- Security Considerations (relevant security requirements and design patterns)
- Performance & Scalability (optimization strategies and scaling approach)
- Deployment Architecture (hosting, distribution, installation approach)
2. ADRs with Architecture Decision Records for key decisions:
- ADR format: Status, Context, Decision, Rationale, Consequences, Alternatives
- Create separate ADR for each major architectural decision
- Examples: technology choices, data storage strategy, communication patterns, security model
Save to: docs/projects/{project-slug}/planning/architecture.md, docs/projects/{project-slug}/adrs/*.md"
For Refinement Mode:
subagent_type: "spec-architect"
description: "Refine system architecture for {PROJECT_NAME}"
prompt: "Refine system architecture for {PROJECT_NAME}.
IMPORTANT: Read existing files first:
- docs/projects/{project-slug}/planning/architecture.md
- docs/projects/{project-slug}/adrs/*.md
- Updated requirements at docs/projects/{project-slug}/planning/requirements.md
Your task:
1. Review existing architecture and ADRs
2. Identify architectural gaps or areas needing improvement
3. Check if technology stack decisions still make sense
4. Enhance based on new/refined requirements: {USER_INPUT}
5. Add missing architectural components or considerations
6. Update existing ADRs if decisions have changed (mark old as 'Superseded', create new ADRs)
7. Preserve well-designed sections
Maintain consistency with existing ADRs but improve where needed.
Save to: docs/projects/{project-slug}/planning/architecture.md, docs/projects/{project-slug}/adrs/*.md"
Note: Use same {USER_INPUT} value from analyst step.
Wait for completion → Read outputs: docs/projects/{project-slug}/planning/architecture.md, docs/projects/{project-slug}/adrs/*.md
Expected Output: Architecture document (600-1,000 lines) + 3-5 ADRs (150-250 lines each)
Step 4: Spawn spec-planner Agent (Task Breakdown and Risk Assessment)
Use Task tool to spawn implementation planning agent to perform Phase 1 Activities 3 & 4:
For Fresh Planning Mode:
subagent_type: "spec-planner"
description: "Create implementation plan for {PROJECT_NAME}"
prompt: "Create implementation plan for {PROJECT_NAME} based on:
- Requirements: docs/projects/{project-slug}/planning/requirements.md
- Architecture: docs/projects/{project-slug}/planning/architecture.md
Generate tasks.md with:
1. Overview (total tasks, estimated effort, critical path, parallel streams)
2. Task Breakdown by Phase:
- Each task with: ID, complexity, effort estimate, dependencies, description
- Acceptance criteria for each task (concrete, measurable)
- Tasks should be atomic and implementable (1-8 hours each)
3. Risk Assessment:
- Technical risks with severity, probability, impact
- Mitigation strategies for each risk
4. Testing Strategy:
- Unit test coverage targets
- Integration test scenarios
- End-to-end test requirements
Save to: docs/projects/{project-slug}/planning/tasks.md"
For Refinement Mode:
subagent_type: "spec-planner"
description: "Refine implementation plan for {PROJECT_NAME}"
prompt: "Refine implementation plan for {PROJECT_NAME}.
IMPORTANT: Read existing files first:
- docs/projects/{project-slug}/planning/tasks.md
- Updated requirements at docs/projects/{project-slug}/planning/requirements.md
- Updated architecture at docs/projects/{project-slug}/planning/architecture.md
Your task:
1. Review existing task breakdown and risk assessment
2. Update tasks based on refined requirements/architecture changes
3. Add new tasks for new requirements
4. Remove or modify tasks that are no longer relevant
5. Re-assess effort estimates if architecture changed
6. Update risk assessment with any new technical risks
7. Preserve completed tasks or well-defined tasks
8. Ensure task dependencies are still accurate
Maintain task numbering continuity where possible.
Save to: docs/projects/{project-slug}/planning/tasks.md"
Wait for completion → Read output: docs/projects/{project-slug}/planning/tasks.md
Expected Output: Task breakdown document (500-800 lines with 15-30 tasks)
Step 5: Quality Gate Validation (Planning Phase Gate)
Orchestrator validates planning completeness using battle-tested Gate 1 criteria (see Quality Gates section):
Validation Process (from actual spec-orchestrator.md):
- Review all planning artifacts (requirements.md, architecture.md, tasks.md, adrs/*.md)
- Assess completeness against 4 core criteria checklist (100 points total):
- Requirements Completeness and Clarity (30 pts)
- Architecture Feasibility Assessment (30 pts)
- Task Breakdown Adequacy (25 pts)
- Risk Mitigation Coverage (15 pts)
- Validate technical feasibility (can this actually be built?)
- Calculate total score: Sum of all criteria points / 100
- Compare to threshold: ≥ 85% to pass (adapted from original 95%)
Decision:
- If score ≥ 85%: Proceed to Step 7 (Deliverable Handoff)
- If score < 85%: Proceed to Step 6 (Iteration Loop)
Step 6: Iteration Loop (Max 3 Iterations)
When quality gate fails, apply battle-tested feedback framework from actual spec-orchestrator.md:
1. Failure Analysis Process
- Identify Root Causes: Analyze why quality gate failed (which of the 4 criteria?)
- Impact Assessment: Determine scope of required corrections (1 agent or multiple?)
- Priority Classification: Categorize issues by severity (critical gaps vs. minor improvements)
- Resource Allocation: Decide which agent needs re-spawning (spec-analyst, spec-architect, or spec-planner)
2. Corrective Action Planning
- Create specific, actionable improvement tasks listing gaps
- Set realistic expectations (iteration should improve score +10-15%)
- Establish validation criteria (must address specific point deficiencies)
- Plan verification (re-run quality gate after re-spawning agent)
3. Communication Protocol
- Notify user of quality gate failure with specific score (e.g., "68/100, needs improvement")
- Provide clear explanation of corrective measures (which agent re-spawning, why)
- Update iteration count (attempt 1/3, 2/3, or 3/3)
- Set expectation: iterative refinement is normal, not a failure
4. Concrete Feedback Generation (Execution)
- Identify which checklist categories failed (< expected points)
- Determine root cause (requirements gap, architecture issue, tasks unclear)
- Generate specific, actionable feedback listing gaps with point values
- Re-spawn agent with previous output + feedback + gap list
Example Feedback for spec-analyst:
"Requirements analysis incomplete. Score: 68/100
Gaps identified:
- Non-functional requirements missing performance metrics (0/5 points)
→ Add specific metrics: API response time, throughput, concurrent users
- User stories lack measurable acceptance criteria (2/5 points)
→ Provide concrete, testable criteria for each story
- Stakeholder analysis incomplete (2/5 points)
→ Identify admin users, end users, external integrations
Please regenerate requirements.md addressing these specific gaps."
Re-spawn agent with feedback → Wait for revised output → Return to Step 5 (Quality Gate)
Iteration Limit Enforcement:
- Track iteration count per agent (max 3 total iterations)
- If iterations = 3 and score still < 85%: Escalate to user with current artifacts
- User decides: accept current quality OR provide manual guidance
Step 7: Deliverable Handoff
Generate planning summary and return artifacts to user:
Planning Summary Includes:
- Project scope and objectives (from requirements.md)
- Key architectural decisions (from ADRs)
- Implementation roadmap (from tasks.md with effort estimates)
- Technical risks and mitigation strategies (from tasks.md)
- Quality gate score (e.g., "92/100 - Planning phase complete")
- Next steps for development team
Deliverables Returned:
- 📄 docs/projects/{project-slug}/planning/requirements.md
- 📄 docs/projects/{project-slug}/planning/architecture.md
- 📄 docs/projects/{project-slug}/planning/tasks.md
- 📄 docs/projects/{project-slug}/adrs/*.md (3-5 Architecture Decision Records)
Status: "✅ Planning phase complete. Development-ready specifications available."
Handoff: Development team can begin implementation using planning artifacts as source of truth
Progress Tracking During Workflow
Use this battle-tested status report format (from actual spec-orchestrator.md) to track planning phase progress:
# Planning Workflow Status Report
**Project**: [Project Name]
**Started**: [Timestamp]
**Current Step**: [Agent in progress]
**Overall Progress**: [Percentage]
## Agent Execution Status
### ✅ spec-analyst (Complete)
- Requirements analysis completed
- Output: docs/projects/{project-slug}/planning/requirements.md (~1,200 lines)
- Duration: 45 minutes
- Status: ✅ COMPLETE
### 🔄 spec-architect (In Progress)
- Architecture design in progress
- Current task: Creating ADRs for technology stack decisions
- Output: docs/projects/{project-slug}/planning/architecture.md + docs/projects/{project-slug}/adrs/*.md
- Duration: 30 minutes elapsed
- Status: 🔄 IN PROGRESS
### ⏳ spec-planner (Pending)
- Waiting for architecture completion
- Will create: docs/projects/{project-slug}/planning/tasks.md
- Status: ⏳ PENDING
## Quality Gate Status
- Planning Gate: ⏳ Pending (waiting for all agents to complete)
- Threshold: ≥ 85%
- Iterations used: 0/3
## Artifacts Created
1. ✅ `docs/projects/{project-slug}/planning/requirements.md` - Complete requirements specification
2. 🔄 `docs/projects/{project-slug}/planning/architecture.md` - System architecture design (in progress)
3. 🔄 `docs/projects/{project-slug}/adrs/*.md` - Architecture Decision Records (2/5 complete)
4. ⏳ `docs/projects/{project-slug}/planning/tasks.md` - Task breakdown (pending)
## Next Steps
1. Complete spec-architect agent (architecture + remaining ADRs)
2. Spawn spec-planner agent for task breakdown
3. Execute quality gate validation
4. [If needed] Iterate based on feedback
## Risk Assessment
- ✅ All agents on track, no blocking issues identified
TodoWrite Integration: Use TodoWrite tool to maintain real-time task list tracking agent spawning and completion.
Agent Roles
Planning Phase (3 specialized agents):
The skill orchestrates these agents sequentially:
spec-analyst (Step 2): Requirements gathering and analysis
- Generates comprehensive requirements.md with functional/non-functional requirements
- Creates user stories with measurable acceptance criteria
- Documents stakeholder analysis and success metrics
- Output:
docs/projects/{project-slug}/planning/requirements.md(~800-1,500 lines)
spec-architect (Step 3): System architecture design and ADR creation
- Designs technology stack with justifications
- Defines system components, API specifications, security considerations
- Creates Architecture Decision Records for key choices
- Output:
docs/projects/{project-slug}/planning/architecture.md+docs/projects/{project-slug}/adrs/*.md(3-5 ADRs)
spec-planner (Step 4): Task breakdown, risk assessment, and testing strategy
- Breaks requirements and architecture into atomic implementation tasks (1-8 hours each)
- Identifies task dependencies and effort estimates
- Assesses technical risks with mitigation strategies
- Defines testing strategy (unit, integration, E2E)
- Output:
docs/projects/{project-slug}/planning/tasks.md(~500-800 lines with 15-30 tasks)
Note: The skill itself (this SKILL.md) acts as the orchestrator, managing sequential execution, quality gates (85% threshold), iteration loops with feedback, and deliverable handoff. There is no separate spec-orchestrator agent.
Quality Gates
Planning Gate (85% Threshold)
Purpose: Validate planning completeness before handoff to development team
Core Validation Criteria (from battle-tested Gate 1):
1. Requirements Completeness and Clarity
Weight: 30 points
Verify requirements artifacts are comprehensive and unambiguous:
- ✅ All functional requirements documented with clear IDs (FR1, FR2, etc.) - 10 pts
- ✅ Non-functional requirements specified with quantitative metrics - 8 pts
- ✅ User stories with measurable acceptance criteria - 7 pts
- ✅ Stakeholder needs identified and documented - 5 pts
Validation:
- Review requirements.md for completeness
- Check that all requirements are testable and unambiguous
- Confirm NFRs have specific metrics (e.g., "< 200ms" not "fast")
2. Architecture Feasibility Assessment
Weight: 30 points
Validate technical design is sound and implementable:
- ✅ System architecture addresses all functional requirements - 10 pts
- ✅ Technology stack justified with clear rationale (ADRs) - 8 pts
- ✅ Scalability and performance design documented - 7 pts
- ✅ Security and compliance considerations addressed - 5 pts
Validation:
- Review architecture.md and adrs/*.md
- Assess if architecture can realistically deliver requirements
- Verify technology choices align with team expertise and constraints
3. Task Breakdown Adequacy
Weight: 25 points
Ensure implementation plan is actionable and well-estimated:
- ✅ Tasks are atomic and implementable (1-8 hours each) - 12 pts
- ✅ Dependencies clearly identified with task IDs - 8 pts
- ✅ Effort estimates provided with complexity ratings - 5 pts
Validation:
- Review tasks.md for granularity (too large = hard to estimate)
- Check dependency graph has no cycles
- Verify estimates are realistic based on task complexity
4. Risk Mitigation Coverage
Weight: 15 points
Confirm technical risks are identified with mitigation strategies:
- ✅ Technical risks identified with severity and probability - 8 pts
- ✅ Mitigation strategies documented for each risk - 7 pts
Validation:
- Review risk assessment section in tasks.md
- Verify high-severity risks have concrete mitigation plans
- Check that risks are technical (not business/organizational)
Scoring Method:
- Score each criterion using point values above (total: 100 points)
- Calculate: Score = Sum of all points / 100
- Threshold: ≥ 85% to pass quality gate (adapted from original 95% for planning-only scope)
Validation Process (battle-tested 4-step method):
- Review all planning artifacts (requirements.md, architecture.md, tasks.md, adrs/*.md)
- Assess completeness against checklist above
- Validate technical feasibility (can this actually be built?)
- Confirm stakeholder alignment (does this meet the project goals?)
Maximum Iterations: 3 attempts per planning session
Feedback Loop Process
When Quality Gate Fails (Score < 85%):
Step 1: Failure Analysis
Categorize gaps by severity:
- Critical (0-50% score): Fundamental gaps requiring complete rework
- Major (51-74% score): Significant improvements needed
- Minor (75-84% score): Small refinements to reach threshold
Step 2: Root Cause Identification
Map failures to responsible agent:
- Requirements incomplete or unclear? → Re-spawn spec-analyst
- Architecture infeasible or under-specified? → Re-spawn spec-architect
- Tasks too vague or poorly estimated? → Re-spawn spec-planner
- Multiple issues? → Address in priority order (requirements first)
Step 3: Generate Specific Feedback
Create targeted feedback for agent re-spawning with:
- Current score and gap breakdown
- Specific items missing (reference checklist categories)
- Actionable improvements needed
- Concrete examples of what's expected
Example Feedback Templates:
For spec-analyst (Requirements Gap):
"Requirements analysis incomplete. Score: 68/100
Gaps identified:
- Non-functional requirements missing performance metrics (0/5 points)
→ Add specific metrics: API response time < 200ms p95, throughput > 1000 req/s,
concurrent users > 500
- User stories lack measurable acceptance criteria (2/5 points)
→ Provide concrete, testable criteria for each story
→ Example: 'AC1: User can create task within 2 seconds' (not 'AC1: Task creation works')
- Stakeholder analysis incomplete (2/5 points)
→ Identify: admin users, end users, API consumers, external integrations
→ Document needs and priorities for each stakeholder group
Please regenerate requirements.md addressing these specific gaps."
For spec-architect (Architecture Gap):
"Architecture design incomplete. Score: 72/100
Gaps identified:
- Scalability not addressed (0/5 points)
→ Design for 10x growth: horizontal scaling strategy, database sharding plan
→ Address: load balancing, caching layers, CDN for static assets
- Security considerations incomplete (1/5 points)
→ Add: authentication mechanism (JWT/OAuth), authorization model (RBAC),
data encryption (at rest and in transit), input validation strategy
- ADRs missing key decisions (2/5 points)
→ Create ADR for: database choice (SQL vs. NoSQL), real-time architecture
(WebSockets vs. polling), deployment platform (cloud provider choice)
→ Format: Status, Context, Decision, Rationale, Consequences, Alternatives
Please regenerate architecture.md and adrs/ addressing these gaps."
For spec-planner (Task Breakdown Gap):
"Task breakdown incomplete. Score: 76/100
Gaps identified:
- Tasks too large and not atomic (4/10 points)
→ Break down: 'Build authentication system' is too broad
→ Should be: 'T2.1: Create user registration API endpoint (4h)',
'T2.2: Implement JWT token generation (3h)', etc.
- Dependencies not clearly identified (2/5 points)
→ Use task IDs: 'Dependencies: T1.3, T2.1' (not 'depends on auth')
→ Ensure topological order (no circular dependencies)
- Risk mitigation incomplete (3/5 points)
→ For each risk, provide concrete mitigation strategy
→ Example: 'Risk: WebSocket scaling' → 'Mitigation: Implement Redis adapter
early in Phase 2, test with 1000 concurrent connections'
Please regenerate tasks.md addressing these gaps."
Step 4: Re-spawn Agent with Feedback
Execute re-spawning process:
- Use Task tool to spawn same agent again
- Provide prompt with:
- Previous output file path (to build upon, not start from scratch)
- Specific feedback with gap list
- Target improvements needed to reach 85% threshold
- Wait for revised output
- Read revised artifact
Example Re-spawn for spec-analyst:
Agent: spec-analyst
Prompt: "Improve requirements.md based on feedback.
Previous version: docs/projects/{project-slug}/planning/requirements.md
Feedback:
[Insert feedback from Step 3]
Please revise requirements.md to address all identified gaps. Focus on:
1. Adding quantitative non-functional requirements
2. Providing measurable acceptance criteria for all user stories
3. Completing stakeholder analysis with needs documentation
Target: 85% quality gate score"
Step 5: Re-validate
Return to Step 5 of Orchestration Workflow (Quality Gate Validation):
- Re-run quality gate checklist on revised artifacts
- Calculate new score
- Compare to previous score (expect improvement)
- Decision:
- If new score ≥ 85%: Proceed to next agent or Step 7 (Deliverable Handoff)
- If new score < 85% AND iterations < 3: Repeat Step 6 (Feedback Loop)
- If iterations = 3: Escalate to user with current artifacts
Iteration Limit Enforcement
Maximum 3 iterations per planning session to prevent infinite loops:
Iteration 1: Initial attempt (typically 60-75% score)
- Agents work from user's initial request
- Common gaps: vague requirements, missing NFRs, incomplete architecture
Iteration 2: Refinement with feedback (typically 75-85% score)
- Agents improve based on specific gap feedback
- Focus on addressing major gaps from Iteration 1
- Most planning sessions reach 85% threshold here
Iteration 3: Final optimization (target 85%+ score)
- Last chance to reach threshold
- Address remaining minor gaps
- If still < 85%: Escalation needed
After 3 iterations, if score < 85%:
Return current artifacts to user with status report:
"Planning quality gate not reached after 3 iterations. Current score: 82/100 Remaining gaps: - [List specific gaps still present] Artifacts available: - requirements.md (mostly complete, minor gaps) - architecture.md (complete) - tasks.md (needs minor refinement) Options: A) Accept current quality level and proceed to development B) Provide manual guidance to close remaining gaps C) Restart planning with clearer initial requirements"User decides next action (orchestrator waits for user input)
Document lessons learned for process improvement:
- What gaps were hardest to close?
- What initial information would have helped?
- Update agent prompts or checklist based on findings
File Organization
Active Project Structure
docs/projects/{project-slug}/planning/*.md: Planning phase outputs (requirements, architecture, tasks)docs/projects/{project-slug}/adrs/*.md: Architecture Decision Records per project- Each project gets its own directory to prevent overwrites across planning sessions
- Handoff ready for development team to implement
Archive Structure (When Refining Existing Projects)
When user chooses "Archive old + fresh start" for an existing project:
docs/projects/{project-slug}/
├── .archive/
│ ├── 20251120-094500/ # Timestamp: YYYYMMDD-HHMMSS
│ │ ├── planning/
│ │ │ ├── requirements.md
│ │ │ ├── architecture.md
│ │ │ └── tasks.md
│ │ └── adrs/
│ │ └── *.md
│ └── 20251118-153000/ # Previous archive (if multiple refinements)
│ └── ...
├── planning/ # Current/active specs
│ ├── requirements.md
│ ├── architecture.md
│ └── tasks.md
└── adrs/ # Current/active ADRs
└── *.md
Archive Benefits:
- Complete history of all planning iterations preserved
- Easy rollback if new specs don't work out
- Compare evolution of planning over time
- No data loss when starting fresh
Best Practices
Project Coordination Principles (Battle-Tested)
These 5 principles from actual spec-orchestrator.md, adapted for planning-only workflow:
Clear Phase Definition
- Planning phase has specific goal: Development-ready specifications
- Success criteria: 85% quality gate score (adapted from 95%)
- Deliverables: requirements.md, architecture.md, tasks.md, adrs/*.md
- Handoff point: Complete specifications ready for implementation team
- Timeline: Typically 2-4 hours for small projects, 1-2 days for complex systems
Quality-First Approach
- Never compromise on 85% threshold for handoff (established quality standard)
- Better to iterate 2-3 times than hand off incomplete planning
- Each iteration should show measurable improvement (+10-15% score)
- Quality gate ensures development team has what they need to succeed
- Incomplete planning = expensive rework during development
Continuous Communication
- Maintain transparent progress reporting using TodoWrite tool
- Update user on agent completion status (✅ spec-analyst → 🔄 spec-architect → ⏳ spec-planner)
- Report quality gate scores with specific gaps identified
- Communicate iteration progress (attempt 1/3, score improvement)
- Set clear expectations about planning timeline and quality requirements
Adaptive Planning
- Adjust planning based on emerging requirements from user
- If user provides new constraints during workflow, incorporate into feedback
- Architecture may need revision if requirements change mid-stream
- Flexibility to restart specific agents if scope changes significantly
- Balance between following process and responding to new information
Risk Management
- Proactively identify technical risks during planning (spec-planner responsibility)
- Document mitigation strategies for each identified risk in tasks.md
- Surface risks to user during handoff (top 3-5 critical risks)
- Don't hide uncertainty; flag unknowns for investigation during development
- Risk assessment is part of quality gate validation (15 points)
Process Improvement Guidelines (Battle-Tested)
From actual spec-orchestrator.md, applicable to planning workflow:
- Document successful patterns for reuse: Save high-quality planning artifacts as templates
- Analyze failures to prevent recurrence: Review failed quality gates to identify common gaps
- Regularly update templates and checklists: Evolve validation criteria based on lessons learned
- Collect feedback from all stakeholders: Ask users what worked/didn't work in planning handoff
- Implement automation where beneficial: Standardize agent prompts, quality gate scoring
Success Factors (Battle-Tested)
From actual spec-orchestrator.md, adapted for planning phase:
- Preparation: Thorough planning prevents poor performance → Clarify scope upfront, gather context
- Communication: Clear, frequent updates keep everyone aligned → Use TodoWrite, report progress
- Flexibility: Adapt to changing requirements while maintaining quality → Iterate with feedback loops
- Documentation: Comprehensive records enable future improvements → Save all artifacts, ADRs
- Validation: Regular quality checks ensure project success → 85% quality gate threshold enforced
Planning Workflow Optimization
Preparation Phase (Before spawning agents)
User Interaction:
- Clarify project scope with user (what's in scope, what's out of scope)
- Identify known constraints (budget, timeline, technical stack requirements)
- Confirm stakeholders and success criteria (who decides if it's good?)
- Elicit domain knowledge (any existing systems, data, APIs to integrate?)
Set Realistic Expectations:
- Planning takes 2-4 hours for small projects (e.g., todo app)
- Complex systems may need 1-2 days (e.g., e-commerce platform)
- Quality gate may require 2-3 iterations (normal, not a failure)
- Development-ready ≠ perfect; specs will evolve during implementation
Execution Phase (During agent spawning)
Provide Clear Prompts:
- Include context from previous agents' outputs (file paths)
- Reference specific files: "Based on requirements.md, design architecture..."
- Specify expected output format and file locations
- Give concrete examples of what "good" looks like
Allow Sufficient Time:
- spec-analyst: 30-60 minutes for requirements analysis
- spec-architect: 45-90 minutes for architecture + ADRs
- spec-planner: 30-60 minutes for task breakdown
- Don't rush agents; thoughtful analysis takes time
Monitor Progress:
- Use TodoWrite tool to track agent spawning and completion
- Read agent outputs immediately after completion (verify before proceeding)
- Check for obv
…(truncated)