Files
gh-ronileor-specweaver-plug…/commands/feature-refactor.md
2025-11-30 08:52:54 +08:00

1079 lines
30 KiB
Markdown

---
description: Refactor an existing feature with deep code understanding, documentation review, atomic phase breakdown, incremental changes, and comprehensive review loops
---
You are orchestrating a comprehensive feature refactoring workflow with multi-agent collaboration. Follow this structured process:
## Core Principle
**⚠️ 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.
## Phase 0: Feature Understanding (Parallel Analysis)
**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:
- Find ALL files related to this feature (entry points, core logic, utilities, tests)
- Trace execution paths from entry to data storage
- Map architecture layers (presentation, business logic, data)
- Identify design patterns and abstractions currently in use
- Document all dependencies (internal and external)
- Find integration points with other features
- Note any technical debt or improvement areas
- List ALL essential files for understanding this feature
**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:
- Search `/docs` for any documentation about this feature
- Identify documentation location(s) if exists
- Read and summarize existing documentation
- Note any gaps in documentation
- Identify related documentation that might need updates
- Check if documentation matches current implementation
- Flag any outdated or incorrect documentation
**Step 0.2: Create Understanding Report**
After BOTH agents complete, synthesize findings:
Create: `.claude/specs/refactor-{feature-name}/01-understanding.md`
```markdown
# 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`:
```markdown
## 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:
- Note: "No functional issues reported. This is a code quality/architecture refactoring."
**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`:
```markdown
## 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)**:
- Skip research phase entirely
- Proceed directly to Phase 1: Refactor Planning
**If Complexity = MEDIUM (and Research Decision = CONDITIONAL)**:
- Ask user: "This is a medium-complexity refactor. Would you like me to research {specific-topic} before planning, or should we proceed with existing patterns?"
- If user says NO or "proceed": Skip to Phase 1
- If user says YES: Execute Step 0.7 with targeted searches
**If Complexity = HIGH (and Research Decision = YES)**:
- Proceed to Step 0.7 for targeted research
**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:
- Search: "{specific-topic} {language/framework} best practices 2025"
- Focus: ONLY information relevant to this specific refactoring need
Create: `.claude/specs/refactor-{feature-name}/00-research.md`
```markdown
# 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)**:
- Do NOT create `00-research.md`
- Note in `01-understanding.md`: "Research skipped - refactoring can use existing patterns"
---
## Phase 1: Refactor Planning (Gap Analysis)
**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`
```markdown
# 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:
1. This code already exists somewhere in the codebase (might be duplicated)
2. Similar functionality exists that could be reused
3. This conflicts with existing code patterns
4. Small changes to existing code would achieve the same goal
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:
```markdown
## 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.**
---
## Phase 2: Atomic Phase Design
**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`
```markdown
# 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`
```markdown
# 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**:
```[language]
[New code snippet]
```
**Change Type**: [Modify/Add/Delete]
**Rationale**: [Why this change]
### File 2: ...
[Continue for all files in this phase]
## Code Reuse
- [Existing code being reused]: [location]
- [Existing patterns being followed]: [pattern name]
## Integration Points
- [How this phase affects other features]
- [APIs/interfaces that change]
## Backward Compatibility
- [Breaking changes if any]
- [Migration steps if needed]
## Testing Requirements
- [Unit tests to update/add]
- [Integration tests needed]
- [Manual verification steps]
## Rollback Procedure
- [How to undo this phase if needed]
- [Files to revert]
## Acceptance Criteria
1. [Criterion 1]
2. [Criterion 2]
...
## Dependencies
- [Previous phases that must be complete]
- [External dependencies]
```
**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:
- {file1} ({change-type})
- {file2} ({change-type})
- ...
Key Changes:
- [Brief description 1]
- [Brief description 2]
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:
- Understanding: 01-understanding.md
- Gap Analysis: 01-gap-analysis.md
- Overview: 02-overview.md
- Phase 1 spec: phase-1-{name}.md (approved)
- Phase 2 spec: phase-2-{name}.md (approved)
- ... (all phases listed)
Refactor Plan:
- {N} atomic phases
- {N} files to modify
- {N} files to add
- {N} files to delete
- Risk level: {Low/Medium/High}
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
```
- If EXISTS: Read it, note previous issues, prepare to UPDATE
- If NOT EXISTS: Proceed to create new review
**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:
1. **Spec Compliance**: Matches phase spec exactly?
2. **Acceptance Criteria**: All criteria fulfilled?
3. **Code Reuse**: Used existing code as planned in gap analysis?
4. **Pattern Consistency**: Follows patterns from understanding report?
5. **CLAUDE.md Compliance**: Project standards met?
6. **Backward Compatibility**: Breaking changes handled as specified?
7. **Refactor Quality**: Code quality improved, not degraded?
8. **Bugs/Issues**: Any high-confidence problems (≥ 80)?
If updating existing review, note what changed."
**Step C: Create or Update Phase Review**
Save to: `phase-{X}-{name}-review.md`
```markdown
# 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):
1. **DO NOT PROCEED** to next phase
2. Present issues to user (brief)
3. Fix each issue
4. Re-run code-reviewer (LOOP)
5. Update phase review file
6. Repeat until approved
If approved (no issues ≥ 80):
1. Update phase review with APPROVED status
2. Mark phase as `completed` in todo list
3. Proceed to next phase (return to Step 3.2.1)
**3.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}
```
---
## Phase 4: Final Integration Review
**Step 4.1: Comprehensive Refactor Review**
After ALL phases complete, use Task tool with `subagent_type=code-reviewer` for comprehensive review.
Provide:
- Overview: `02-overview.md`
- Understanding: `01-understanding.md` (before state)
- All modified/created files
- Instruction: "Perform comprehensive refactor review. Focus on:
1. **Complete Refactor Goal**: Was the refactor goal achieved?
2. **Architecture Improvement**: Is architecture better than before?
3. **Code Quality**: Is code quality improved overall?
4. **Integration**: Do all phases work together correctly?
5. **Backward Compatibility**: Are compatibility guarantees maintained?
6. **Performance**: Any performance regression?
7. **Technical Debt**: Was technical debt reduced?
8. **Cross-Phase Issues**: Any issues spanning multiple phases?"
**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.**
---
## Phase 5: Documentation Update (Only after USER confirms refactor works)
**IMPORTANT**: Only runs after USER confirms refactored feature works.
**Step 5.1: User Confirmation Checkpoint**
If user confirms YES (refactor works):
- Proceed to Step 5.2
If user says NO (issues found):
- Return to Phase 3 for fixes
- Do NOT proceed to documentation
**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':
1. If existing docs found: UPDATE them with refactor changes
2. If docs outdated: REFRESH with current implementation
3. If gaps identified: FILL gaps with missing information
4. If no docs existed: CREATE new documentation
Document:
- What changed in the refactor
- New architecture/patterns
- Updated usage examples
- Migration guide if breaking changes
- Deprecated features if any
Follow project standards:
- Lowercase filenames
- Update index files
- Cross-reference related docs
- Zero duplication"
**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.
```
---
## Important Guidelines
**Understanding Phase (Phase 0)**:
- ALWAYS run code-explorer and code-consolidator in PARALLEL
- code-explorer provides deep code understanding
- code-consolidator finds and analyzes existing documentation
- Ask user about issues BEFORE planning refactor
- ASSESS COMPLEXITY before any web research
- Research ONLY if HIGH complexity or user approves MEDIUM complexity
- Skip research for LOW complexity - use existing patterns
**Planning Phase (Phase 1)**:
- Gap analysis identifies what needs to change
- code-reviewer checks for existing code to reuse
- Avoid duplication by finding existing implementations
- Update gap analysis with reuse strategy
- Get user approval before designing phases
**Design Phase (Phase 2)**:
- Design atomic phases ONE AT A TIME
- Each phase independently testable and reviewable
- Include rollback procedures per phase
- Get user approval after EACH phase design
- Maintain backward compatibility strategy
**Implementation Phase (Phase 3)**:
- Use TodoWrite for phase tracking
- Implement ONE phase at a time
- MANDATORY review gate after each phase
- Check for existing review using `[ -f filepath ]` and UPDATE if present (NEVER use `ls`)
- Fix all issues ≥ 80 confidence before next phase
- Follow code reuse strategy from gap analysis
**Integration Phase (Phase 4)**:
- Comprehensive review of complete refactor
- Verify refactor goal achieved
- Check architecture and quality improvements
- ASK user to test before documentation
**Documentation Phase (Phase 5)**:
- ONLY after user confirms refactor works
- UPDATE existing docs (don't create duplicates)
- Reflect architecture and pattern changes
- Include migration guide if breaking changes
**Tool Usage**:
- `Task tool` with `subagent_type=code-explorer`, `code-reviewer`, or `code-consolidator`
- `TodoWrite` for phase tracking
- `Write` for spec files
- `Read` for phase specs before implementing
- `Edit` for code changes
**Critical Rules**:
- NEVER skip understanding phase (must understand before refactoring)
- NEVER do blind web research (assess complexity first)
- NEVER skip gap analysis (must know what to reuse)
- NEVER skip phase review gates
- NEVER proceed with unresolved high-confidence issues (≥ 80)
- NEVER create duplicate code (check for existing first)
- NEVER use `ls` or `ls -la` to check file existence (use `[ -f ... ]` only)
- ALWAYS assess complexity before deciding on research
- ALWAYS design phases incrementally with user approval
- ALWAYS check for existing reviews using `[ -f filepath ]` and UPDATE them
- ALWAYS use bash test `[ -f ... ]` for file existence checks (NEVER `ls`, `ls -la`, or `stat`)
- ALWAYS ask user to test before documentation
- ALWAYS update existing docs rather than create new ones
---
## Execution Flow Summary
```
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**