Refactor an existing feature with deep code understanding, documentation review, atomic phase breakdown, incremental changes, and comprehensive review loops
Refactors features through structured analysis, atomic phases, and mandatory review gates.
/plugin marketplace add RoniLeor/specWeaver/plugin install specweaver@specweaverYou are orchestrating a comprehensive feature refactoring workflow with multi-agent collaboration. Follow this structured process:
⚠️ CRITICAL: Read the code carefully before designing new solutions - the existing implementation often already handles edge cases. Understanding what's already there prevents duplicate solutions and unnecessary complexity.
IMPORTANT: Execute BOTH analyses in PARALLEL (single message with 2 Task tool calls) for maximum efficiency.
Step 0.1: Launch Parallel Understanding Agents
Execute in PARALLEL:
Analysis 1: Code Exploration (code-explorer)
Use the Task tool with subagent_type=code-explorer to deeply understand the existing feature: $ARGUMENTS
The code-explorer should:
Analysis 2: Documentation Review (code-consolidator)
Use the Task tool with subagent_type=code-consolidator to find and analyze documentation for: $ARGUMENTS
The code-consolidator should:
/docs for any documentation about this featureStep 0.2: Create Understanding Report
After BOTH agents complete, synthesize findings:
Create: .claude/specs/refactor-{feature-name}/01-understanding.md
# Feature Understanding: {feature-name}
**Analysis Date**: {date}
**Refactor Request**: {$ARGUMENTS}
## Code Analysis (code-explorer findings)
### Feature Entry Points
- [Entry point 1: file:line]
- [Entry point 2: file:line]
- ...
### Core Implementation
- [Core file 1: purpose and responsibilities]
- [Core file 2: purpose and responsibilities]
- ...
### Architecture Layers
- **Presentation Layer**: [files and responsibilities]
- **Business Logic Layer**: [files and responsibilities]
- **Data Layer**: [files and responsibilities]
### Design Patterns Used
- [Pattern 1: where and how it's used]
- [Pattern 2: where and how it's used]
- ...
### Dependencies
- **Internal**: [other features this depends on]
- **External**: [libraries, frameworks, APIs]
### Integration Points
- [Feature 1: how they integrate]
- [Feature 2: how they integrate]
- ...
### Technical Debt / Issues
- [Issue 1: description and location]
- [Issue 2: description and location]
- ...
### Essential Files
[Complete list with brief descriptions]
## Documentation Analysis (code-consolidator findings)
### Existing Documentation
- **Location**: [file path(s) in /docs]
- **Content Summary**: [what's documented]
- **Last Updated**: [if available]
### Documentation Gaps
- [Gap 1: what's not documented]
- [Gap 2: what's missing]
- ...
### Outdated Information
- [Outdated 1: what needs updating]
- [Outdated 2: discrepancy with code]
- ...
### Related Documentation
- [Related doc 1: why it's relevant]
- [Related doc 2: connection to this feature]
- ...
## Understanding Summary
### What This Feature Does
[Clear description of feature's purpose and behavior]
### How It Works
[High-level explanation of implementation approach]
### Current State Assessment
- **Code Quality**: [assessment]
- **Documentation Quality**: [assessment]
- **Maintainability**: [assessment]
- **Technical Debt Level**: [assessment]
Step 0.3: Present Understanding & Ask About Issues
Present the understanding summary to the user:
FEATURE UNDERSTANDING COMPLETE
I've analyzed the feature "{feature-name}" in parallel:
CODE ANALYSIS (code-explorer):
- Found {N} core files
- Identified architecture layers: [layers]
- Design patterns: [patterns]
- {N} integration points with other features
- Technical debt identified: [brief list]
DOCUMENTATION ANALYSIS (code-consolidator):
- Existing docs: [location or "None found"]
- Documentation status: [Complete/Partial/Missing/Outdated]
- Gaps identified: [brief list]
Full understanding saved to: .claude/specs/refactor-{feature-name}/01-understanding.md
QUESTION: Is there something specific that's NOT working with this feature?
Please describe any bugs, performance issues, or behavior problems.
STOP and WAIT for user response.
Step 0.4: Document Issues (if any)
If user reports issues:
Append to 01-understanding.md:
## Reported Issues
### Issue 1: {user-reported issue}
- **Description**: [user's description]
- **Expected Behavior**: [what should happen]
- **Current Behavior**: [what's happening]
- **Impact**: [severity/frequency]
### Issue 2: ...
[Continue for all reported issues]
If no issues reported:
Step 0.5: Assess Refactoring Complexity
Based on understanding report, user's request ($ARGUMENTS), and reported issues, assess refactoring complexity.
Append to 01-understanding.md:
## Refactoring Complexity Assessment
**User Request**: {$ARGUMENTS}
### Complexity Indicators
**Code Changes Required**:
- [ ] Simple cleanup (variable names, formatting, comments)
- [ ] Function extraction/renaming
- [ ] Architectural changes (moving code between layers)
- [ ] Design pattern implementation
- [ ] Breaking API changes
- [ ] Performance optimization requiring algorithm changes
- [ ] Technology/framework changes
**Scope Analysis**:
- Files affected: {N}
- Layers affected: {list layers}
- Integration points affected: {N}
- External API changes: {Yes/No}
**Risk Level**:
- **Low**: Cleanup, renaming, small extractions (1-5 files, no architectural changes)
- **Medium**: Pattern improvements, service extraction (5-15 files, some architectural changes)
- **High**: Major restructure, breaking changes (15+ files, significant architectural changes)
### Complexity Rating: {LOW/MEDIUM/HIGH}
### Research Needs Assessment
**Do we need web research?**
- **LOW Complexity** → NO research needed
- Simple refactorings have well-established patterns
- Can rely on existing codebase patterns and CLAUDE.md standards
- Example: Variable renaming, function extraction, cleanup
- **MEDIUM Complexity** → CONDITIONAL research
- Research only if unfamiliar domain/pattern
- Focus on specific pattern/technique, not general best practices
- Example: Need research on specific design pattern implementation
- **HIGH Complexity** → YES, targeted research needed
- Complex architectural changes benefit from latest patterns
- Research specific to the domain/technology
- Example: Migrating to new architecture pattern
**Research Decision**: {YES/NO/CONDITIONAL}
**Research Topics** (if YES/CONDITIONAL):
1. {Specific topic based on actual refactoring needs}
2. {Another specific topic if needed}
...
**Rationale**: {Why we do/don't need research for this specific refactor}
Step 0.6: Decide on Research Path
If Complexity = LOW (and Research Decision = NO):
If Complexity = MEDIUM (and Research Decision = CONDITIONAL):
If Complexity = HIGH (and Research Decision = YES):
Step 0.7: Targeted Research (Only for HIGH/CONDITIONAL with user approval)
IMPORTANT: Research ONLY what's needed based on complexity assessment.
Execute targeted web searches (in parallel if multiple topics):
For each research topic identified in Step 0.5:
Create: .claude/specs/refactor-{feature-name}/00-research.md
# Targeted Refactoring Research: {feature-name}
**Research Date**: {date}
**Complexity**: {HIGH/MEDIUM}
**Research Decision**: {Why research was needed}
## Research Topics
### Topic 1: {Specific topic from assessment}
**Search Query**: {actual query used}
**Key Findings**:
- [Finding 1 relevant to this refactor]
- [Finding 2 relevant to this refactor]
- ...
**Application to Our Refactor**:
- [How to apply finding 1]
- [How to apply finding 2]
### Topic 2: {If needed}
[Same structure]
## Refactor Strategy Based on Research
1. {Specific strategy point from research}
2. {Another specific strategy point}
...
## References
- [Only relevant sources]
If research was skipped (LOW complexity or user declined):
00-research.md01-understanding.md: "Research skipped - refactoring can use existing patterns"Step 1.1: Identify What Needs to Be Added/Changed
Based on understanding report and user's refactor request, analyze what needs to change:
Create: .claude/specs/refactor-{feature-name}/01-gap-analysis.md
# Gap Analysis: {feature-name}
**Refactor Goal**: {$ARGUMENTS}
## Current State (from understanding)
- [Summary of current implementation]
- [Current architecture]
- [Current patterns]
## Desired State
- [What the refactor aims to achieve]
- [Target architecture]
- [Target patterns]
## Changes Required
### Changes Category 1: Architecture
- [Change 1: what needs restructuring]
- [Change 2: pattern improvements]
- ...
### Changes Category 2: Code Quality
- [Change 1: what needs improvement]
- [Change 2: cleanup needed]
- ...
### Changes Category 3: Functionality
- [Change 1: what needs adding]
- [Change 2: what needs fixing]
- ...
## Parts to Add/Modify
### Part 1: {component-name}
- **Current State**: [exists/missing/partial]
- **Required Changes**: [specific changes]
- **Files Affected**: [file paths]
- **Complexity**: [Low/Medium/High]
### Part 2: ...
[Continue for all parts]
## Refactor Scope
- **Files to Modify**: {N} files
- **Files to Add**: {N} files
- **Files to Delete**: {N} files
- **Estimated Complexity**: [Low/Medium/High]
Step 1.2: Check for Existing Code (code-reviewer)
Use the Task tool with subagent_type=code-reviewer to verify each part identified in gap analysis.
Provide the code-reviewer with:
Understanding report: 01-understanding.md
Gap analysis: 01-gap-analysis.md
Instruction: "For each part in the gap analysis 'Parts to Add/Modify' section, check if:
Only report findings where code EXISTS that could be reused/modified instead of creating new. Focus on avoiding duplication and leveraging existing code."
Step 1.3: Update Gap Analysis with Findings
Update 01-gap-analysis.md with code-reviewer findings:
## Code Reuse Analysis (code-reviewer findings)
### Part 1: {component-name}
- **Existing Code Found**: [Yes/No]
- **Location**: [file:line if exists]
- **Recommendation**: [Reuse/Modify/Create New]
- **Rationale**: [why this approach]
### Part 2: ...
[Continue for all parts]
## Revised Refactor Strategy
Based on code reuse analysis:
- **Reuse Existing**: [list of parts to reuse]
- **Modify Existing**: [list of parts to modify]
- **Create New**: [list of parts that need creation]
- **Remove Duplicate**: [list of duplicate code to remove]
Step 1.4: Present Gap Analysis
Present the gap analysis to user:
REFACTOR PLANNING COMPLETE
Gap Analysis:
- Current state understood
- {N} changes required
- {N} parts to add/modify
Code Reuse Analysis:
- {N} parts can reuse existing code
- {N} parts need modification
- {N} parts need new implementation
- {N} duplicates identified for removal
Scope:
- Files to modify: {N}
- Files to add: {N}
- Files to delete: {N}
- Complexity: {Low/Medium/High}
Full analysis saved to:
- .claude/specs/refactor-{feature-name}/01-gap-analysis.md
Ready to create atomic refactor phases?
STOP and ASK: "Does this refactor scope look correct? Should I proceed to design atomic phases?"
WAIT FOR USER APPROVAL.
Step 2.1: Design Atomic Refactor Phases
Based on gap analysis, break refactoring into atomic phases following the pattern from feature-new.md.
Create: .claude/specs/refactor-{feature-name}/02-overview.md
# Refactor Overview: {feature-name}
**Refactor Goal**: {$ARGUMENTS}
## Architecture Changes
- [High-level architectural changes]
## Refactor Strategy
- [Approach to minimize risk]
- [Backward compatibility approach]
- [Testing strategy]
## Phase Breakdown
### Phase 1: {phase-name}
- **Objective**: [what this phase accomplishes]
- **Type**: [Modify/Add/Remove/Restructure]
- **Risk Level**: [Low/Medium/High]
- **Dependencies**: [none or previous phases]
### Phase 2: {phase-name}
[Continue for all phases]
## Rollback Strategy
- [How to rollback if issues arise]
- [Per-phase rollback points]
## Success Criteria
- [How to verify refactor is complete]
- [Performance benchmarks if applicable]
- [Functionality verification steps]
Step 2.2: Create Atomic Phase Specs (Incremental with Approval)
IMPORTANT: Design phases ONE AT A TIME with user approval after each phase design.
For EACH phase:
2.2.1 - Design Single Phase
Create atomic phase spec: .claude/specs/refactor-{feature-name}/phase-{X}-{name}.md
# Phase {X}: {phase-name}
**Phase Type**: [Modify/Add/Remove/Restructure]
**Risk Level**: [Low/Medium/High]
## Objective
[What this phase accomplishes in the refactor]
## Current State
- [What exists now in these files]
- [Current behavior]
## Target State
- [What will exist after this phase]
- [New behavior]
## Changes Required
### File 1: {file-path}
**Current**:
```[language]
[Current code snippet]
After:
[New code snippet]
Change Type: [Modify/Add/Delete] Rationale: [Why this change]
[Continue for all files in this phase]
**2.2.2 - Present Phase Design**
Present to user:
PHASE {X} DESIGN: {phase-name}
Type: {Modify/Add/Remove/Restructure} Risk: {Low/Medium/High}
Files Affected:
Key Changes:
Backward Compatibility: {Yes/Breaking changes} Rollback: {Available/Complex}
Spec saved to: phase-{X}-{name}.md
Does this phase design look correct? Should I proceed to design the next phase?
**STOP and WAIT for user approval.**
**2.2.3 - Handle User Response**
- If **APPROVED**: Continue to next phase (repeat from Step 2.2.1)
- If **NEEDS CHANGES**: Update the phase spec, re-present
- If **ALL PHASES DESIGNED**: Proceed to Step 2.3
**Step 2.3: Present Complete Refactor Plan**
After ALL phases designed and approved:
COMPLETE REFACTOR PLAN READY
Specifications Created:
Refactor Plan:
All phases individually approved. Ready to proceed to implementation?
**STOP and ASK**: "Should we proceed with phased refactor implementation?"
**WAIT FOR USER APPROVAL.**
---
## Phase 3: Phased Implementation with Review Gates
**Step 3.1: Initialize Phase Tracking**
Use the TodoWrite tool to create task list for ALL phases. Each todo:
- Named after the phase (e.g., "Phase 1: Extract Service Layer")
- Linked to phase spec file path
- Status: `pending` (only first phase starts as `in_progress`)
- Ordered by dependencies
**Step 3.2: Implement Each Phase with Review Gate**
For EACH phase in sequence:
**3.2.1 - Implementation**
1. Mark phase as `in_progress` in todo list
2. Read atomic phase spec: `phase-{X}-{name}.md`
3. Implement ALL changes specified:
- Follow exact file paths and change descriptions
- Follow code reuse strategy from gap analysis
- Follow existing patterns from understanding report
- Apply CLAUDE.md conventions
4. Verify implementation matches acceptance criteria
**3.2.2 - Phase Review Gate (MANDATORY - NEVER SKIP)**
**CRITICAL ENFORCEMENT**: This is a MANDATORY gate. The pattern MUST be:
For each atomic phase: ├── Implement changes (from phase spec) ├── MANDATORY review gate (code-reviewer) └── Fix issues in loop until approved (NO PROCEEDING WITH ISSUES)
**IMPORTANT**: Phase MUST pass review before proceeding to next phase.
**Step A: Check for Existing Phase Review**
**⚠️ CRITICAL - File Existence Checking:**
- ✅ **ONLY use bash test**: `[ -f filepath ]`
- ❌ **NEVER use**: `ls`, `ls -la`, `ls -l`, or any `ls` variant
- ❌ **NEVER use**: `stat`, `find`, or other file inspection commands
- **Reason**: `ls` returns errors to stderr when file doesn't exist, causing noise
**Check for file:** `.claude/specs/refactor-{feature-name}/phase-{X}-{name}-review.md`
```bash
# CORRECT METHOD - Use bash test [ -f ... ]
if [ -f .claude/specs/refactor-{feature-name}/phase-{X}-{name}-review.md ]; then
# Review EXISTS - prepare to UPDATE
else
# Review NOT EXISTS - will create new
fi
Step B: Invoke code-reviewer
Use the Task tool with subagent_type=code-reviewer to review ONLY this phase changes.
Provide:
Phase spec: phase-{X}-{name}.md
Understanding report: 01-understanding.md (original state)
Gap analysis: 01-gap-analysis.md (reuse strategy)
Files changed in THIS phase only
Existing phase review (if updating)
Instruction: "Review this refactor phase implementation. Check for:
If updating existing review, note what changed."
Step C: Create or Update Phase Review
Save to: phase-{X}-{name}-review.md
# Phase {X} Review: {phase-name}
**Review Date**: {date}
**Phase Type**: {Modify/Add/Remove/Restructure}
**Files Changed**: {N} files
## Implementation Assessment
[Summary of implementation quality and spec compliance]
## Spec Compliance Check
Objective achieved: [yes/no with details]
All files modified as specified: [yes/no]
Code reuse strategy followed: [yes/no]
Integration points implemented: [yes/no]
Acceptance criteria met: [checklist]
## Code Quality Assessment
Refactor improves code quality: [yes/no with rationale]
Technical debt reduced: [yes/no]
Patterns maintained/improved: [yes/no]
Documentation inline updated: [yes/no]
## Issues Found (Confidence ≥ 80)
[List high-confidence issues, or "None"]
### Issue 1: {description}
- **Confidence**: {score}
- **Location**: {file:line}
- **Impact**: {impact on refactor}
- **Fix**: {specific action}
## CLAUDE.md Compliance
Type hints: [pass/fail]
No print() statements: [pass/fail]
File size < 300 lines: [pass/fail]
Function size < 30 lines: [pass/fail]
Logging usage: [pass/fail]
## Backward Compatibility Check
Breaking changes: [Yes/No]
Migration needed: [Yes/No]
APIs maintained: [Yes/No]
## Review History
[If updating: changes from previous review]
## Recommendation
**APPROVED**: Phase passes all checks
**REQUIRES FIXES**: {N} high-confidence issues must be addressed
3.2.3 - Handle Review Feedback (Update Loop)
If high-confidence issues (≥ 80):
If approved (no issues ≥ 80):
completed in todo list3.2.4 - Phase Completion
After each phase approval:
Phase {X} completed: {phase-name}
Code review passed (no issues ≥ 80 confidence)
→ Moving to Phase {X+1}: {next-phase-name}
Step 4.1: Comprehensive Refactor Review
After ALL phases complete, use Task tool with subagent_type=code-reviewer for comprehensive review.
Provide:
02-overview.md01-understanding.md (before state)Step 4.2: Present Integration Review
REFACTOR IMPLEMENTATION COMPLETE
All {N} phases completed and individually reviewed.
Final Integration Review:
Refactor goal achieved
Architecture improved
Code quality improved
All phases integrated correctly
Backward compatibility maintained
No performance regression
Technical debt reduced
Files Modified: {N}
Files Added: {N}
Files Deleted: {N}
Before Testing:
- Run tests: [suggest test commands]
- Verify functionality: [suggest verification steps]
- Check performance: [suggest benchmarks]
Have you tested the refactored feature? Does it work correctly?
STOP and ASK: "Have you tested the refactored feature? Does it work correctly?"
WAIT FOR USER CONFIRMATION.
IMPORTANT: Only runs after USER confirms refactored feature works.
Step 5.1: User Confirmation Checkpoint
If user confirms YES (refactor works):
If user says NO (issues found):
Step 5.2: Invoke code-consolidator
Use the Task tool with subagent_type=code-consolidator to update documentation.
Provide:
Understanding report: 01-understanding.md (includes existing docs analysis)
Overview: 02-overview.md (refactor changes)
All phase specs
Instruction: "Update documentation for refactored feature. Based on understanding report's 'Documentation Analysis':
Document:
Follow project standards:
Step 5.3: Present Documentation Changes
DOCUMENTATION UPDATED
Documentation Changes:
- Updated: [files modified]
- Created: [new files]
- Removed: [outdated files]
Updated Index Files:
- [index files updated]
Summary:
[Description of documentation changes]
Documentation reflects refactored implementation.
Would you like any adjustments to the documentation?
Step 5.4: Final Completion
REFACTOR FULLY COMPLETE: {feature-name}
Specifications:
- Understanding: 01-understanding.md
- Gap Analysis: 01-gap-analysis.md
- Overview: 02-overview.md
- Phase specs: phase-{X}-*.md
- Phase reviews: phase-{X}-*-review.md
Completion Checklist:
Feature understood (code + docs analyzed)
Issues documented (user-reported problems)
Gap analysis completed (reuse strategy defined)
Atomic phases designed (all individually approved)
Implementation completed (all phases reviewed)
Integration review passed (complete refactor verified)
User testing passed (refactor confirmed working)
Documentation updated (changes reflected)
Code Files Modified: {N}
Code Files Added: {N}
Code Files Deleted: {N}
Documentation Files Updated: {N}
Feature Status: REFACTORED & DOCUMENTED
The feature has been successfully refactored, tested, reviewed, and documented.
Understanding Phase (Phase 0):
Planning Phase (Phase 1):
Design Phase (Phase 2):
Implementation Phase (Phase 3):
[ -f filepath ] and UPDATE if present (NEVER use ls)Integration Phase (Phase 4):
Documentation Phase (Phase 5):
Tool Usage:
Task tool with subagent_type=code-explorer, code-reviewer, or code-consolidatorTodoWrite for phase trackingWrite for spec filesRead for phase specs before implementingEdit for code changesCritical Rules:
ls or ls -la to check file existence (use [ -f ... ] only)[ -f filepath ] and UPDATE them[ -f ... ] for file existence checks (NEVER ls, ls -la, or stat)Phase 0: Understanding (PARALLEL + SMART RESEARCH)
├── code-explorer analyzes feature deeply
├── code-consolidator finds/reads existing docs
├── Synthesize understanding report
├── Present to user
├── ASK: "Is something not working?"
├── Document issues (if any)
├── ASSESS COMPLEXITY:
│ ├── LOW → Skip research, use existing patterns
│ ├── MEDIUM → ASK user if research needed
│ └── HIGH → Targeted research on specific topics
└── Optional: Targeted research (only if needed)
Phase 1: Gap Analysis
├── Identify what needs to change
├── code-reviewer checks for existing code
├── Update with reuse strategy
└── ASK: "Refactor scope correct?"
Phase 2: Atomic Phase Design (INCREMENTAL)
├── Create overview
├── FOR EACH PHASE:
│ ├── Design single phase
│ ├── STOP → ASK: "Phase design correct?"
│ └── If approved → Next phase
└── ASK: "Proceed with implementation?"
Phase 3: Phased Implementation (REVIEW GATES)
├── FOR EACH PHASE:
│ ├── Implement phase
│ ├── Check for existing review using [ -f ... ] (NEVER ls)
│ ├── code-reviewer review (gate)
│ ├── Create/UPDATE review file
│ ├── If issues: Fix → Re-review (LOOP)
│ └── Mark complete → Next phase
└── All phases done
Phase 4: Final Review
├── Comprehensive refactor review
├── Verify goal achieved
└── ASK: "Test refactor. Does it work?"
Phase 5: Documentation Update
├── WAIT for user confirmation
├── code-consolidator updates docs
└── Present changes
Begin with Phase 0: Feature Understanding for the refactor: $ARGUMENTS