| name | refactor |
| description | Intelligent refactoring with LSP, AST-grep, parallel codebase analysis, test assessment, plan generation, and continuous verification. 6-phase deterministic workflow. |
Intelligent Refactor Command
Usage
/refactor <refactoring-target> [--scope=<file|module|project>] [--strategy=<safe|aggressive>]
Arguments:
refactoring-target: What to refactor. Can be:
- File path: src/auth/handler.ts
- Symbol name: "AuthService class"
- Pattern: "all functions using deprecated API"
- Description: "extract validation logic into separate module"
Options:
--scope: Refactoring scope (default: module)
- file: Single file only
- module: Module/directory scope
- project: Entire codebase
--strategy: Risk tolerance (default: safe)
- safe: Conservative, maximum test coverage required
- aggressive: Allow broader changes with adequate coverage
What This Command Does
Performs intelligent, deterministic refactoring with full codebase awareness:
- Understands your intent - Analyzes what you actually want to achieve
- Maps the codebase - Builds a definitive codemap before touching anything
- Assesses risk - Evaluates test coverage and determines verification strategy
- Plans meticulously - Creates a detailed refactoring plan
- Executes precisely - Step-by-step refactoring with LSP and AST-grep
- Verifies constantly - Runs tests after each change to ensure zero regression
PHASE 0: INTENT GATE (MANDATORY FIRST STEP)
BEFORE ANY ACTION, classify and validate the request.
Step 0.1: Parse Request Type
| Signal | Classification | Action |
|---|
| Specific file/symbol | Explicit | Proceed to codebase analysis |
| "Refactor X to Y" | Clear transformation | Proceed to codebase analysis |
| "Improve", "Clean up" | Open-ended | MUST ask: "What specific improvement?" |
| Ambiguous scope | Uncertain | MUST ask: "Which modules/files?" |
| Missing context | Incomplete | MUST ask: "What's the desired outcome?" |
Step 0.2: Validate Understanding
Before proceeding, confirm:
If ANY of above is unclear, ASK CLARIFYING QUESTION.
Step 0.3: Create Initial Todos
IMMEDIATELY after understanding the request, create todos for all 6 phases.
PHASE 1: CODEBASE ANALYSIS (PARALLEL EXPLORATION)
1.1: Launch Parallel Explore Agents (BACKGROUND)
Fire ALL of these simultaneously:
- Find the refactoring target: All occurrences and definitions of [TARGET]. Report file paths, line numbers, usage patterns.
- Find related code: All code that imports, uses, or depends on [TARGET]. Report dependency chains, import graphs.
- Find similar patterns: Similar code patterns to [TARGET] in the codebase. Report analogous implementations, established conventions.
- Find tests: All test files related to [TARGET]. Report test file paths, test case names, coverage indicators.
- Architecture context: Architectural patterns and module organization around [TARGET]. Report module boundaries, layer structure, design patterns.
1.2: Direct Tool Exploration (WHILE AGENTS RUN)
While background agents are running, use direct tools:
LSP Tools for Precise Analysis:
goto_definition - Where is it defined?
find_references - ALL usages across workspace
document_symbols - File structure
workspace_symbols - Search by name
diagnostics - Current errors/warnings before we start
AST-Grep for Pattern Analysis:
ast_grep_search - Find structural patterns
ast_grep_replace with dryRun=true - Preview refactoring
1.3: Collect Background Results
Collect all agent results and merge findings.
PHASE 2: BUILD CODEMAP (DEPENDENCY MAPPING)
Based on Phase 1 results, build:
## CODEMAP: [TARGET]
### Core Files (Direct Impact)
- path/to/file.ts:L10-L50 - Primary definition
- path/to/file2.ts:L25 - Key usage
### Dependency Graph
[TARGET]
imports from: module-a (types), module-b (utils)
imported by: consumer-1.ts, consumer-2.ts, consumer-3.ts
used by: handler.ts (direct call), service.ts (dependency injection)
### Impact Zones
| Zone | Risk Level | Files Affected | Test Coverage |
| Core | HIGH | 3 files | 85% covered |
| Consumers | MEDIUM | 8 files | 70% covered |
| Edge | LOW | 2 files | 50% covered |
### Established Patterns
- Pattern A: [description] - used in N places
- Pattern B: [description] - established convention
Identify refactoring constraints:
- MUST follow: existing patterns identified
- MUST NOT break: critical dependencies
- Safe to change: isolated code zones
- Requires migration: breaking changes impact
PHASE 3: TEST ASSESSMENT (VERIFICATION STRATEGY)
3.1: Detect Test Infrastructure
Check for test commands in package.json, pytest.ini, etc.
3.2: Analyze Test Coverage
Find all tests related to target. What test cases exist? Integration tests? Edge cases? Estimated coverage?
3.3: Determine Verification Strategy
| Coverage Level | Strategy |
|---|
| HIGH (>80%) | Run existing tests after each step |
| MEDIUM (50-80%) | Run tests + add safety assertions |
| LOW (<50%) | PAUSE: Propose adding tests first |
| NONE | BLOCK: Refuse aggressive refactoring |
If coverage is LOW or NONE, ask user for risk tolerance.
3.4: Document Verification Plan
- Test Commands (unit, integration, type check)
- Verification Checkpoints (diagnostics, tests, type check after each step)
- Regression Indicators (specific tests, behaviors, API contracts)
PHASE 4: PLAN GENERATION
Create a detailed refactoring plan incorporating:
- The codemap from Phase 2
- The verification plan from Phase 3
- Constraints and patterns identified
Requirements:
- Break down into atomic refactoring steps
- Each step must be independently verifiable
- Order steps by dependency (what must happen first)
- Specify exact files and line ranges for each step
- Include rollback strategy for each step
- Define commit checkpoints
Convert plan into granular todos with alternating refactor/verify steps.
PHASE 5: EXECUTE REFACTORING (DETERMINISTIC EXECUTION)
For EACH refactoring step:
Pre-Step
- Mark step todo as
in_progress
- Read current file state
- Verify diagnostics are at baseline
Execute Step
For Symbol Renames:
prepare_rename (validate rename is possible)
rename (execute rename across workspace)
For Pattern Transformations:
ast_grep_replace with dryRun=true first
- If preview looks good, execute with
dryRun=false
For Structural Changes:
- Use edit tool for precise changes
Post-Step Verification (MANDATORY)
- Check diagnostics - Must be clean or same as baseline
- Run tests - All must pass
- Type check - Must be clean
Step Completion
- If verification passes: Mark step todo as
completed
- If verification fails: STOP AND FIX
Failure Recovery Protocol
If ANY verification fails:
- STOP immediately
- REVERT the failed change
- DIAGNOSE what went wrong
- OPTIONS: Fix and retry, skip step, consult oracle, ask user
NEVER proceed to next step with broken tests.
Commit Checkpoints
After each logical group of changes, create an atomic commit.
PHASE 6: FINAL VERIFICATION (REGRESSION CHECK)
- Full test suite
- Full type check
- Lint check
- Build verification (if applicable)
- Diagnostics on all changed files
- Generate summary of changes, files modified, verification results
CRITICAL RULES
NEVER DO
- Skip diagnostics check after changes
- Proceed with failing tests
- Make changes without understanding impact
- Use
as any, @ts-ignore, @ts-expect-error
- Delete tests to make them pass
- Commit broken code
- Refactor without understanding existing patterns
ALWAYS DO
- Understand before changing
- Preview before applying (ast_grep dryRun=true)
- Verify after every change
- Follow existing codebase patterns
- Keep todos updated in real-time
- Commit at logical checkpoints
- Report issues immediately
ABORT CONDITIONS
If any of these occur, STOP and consult user:
- Test coverage is zero for target code
- Changes would break public API
- Refactoring scope is unclear
- 3 consecutive verification failures
Tool Usage
LSP Tools
- Understand before changing: goto_definition to grasp context
- Impact analysis: find_references to map all usages before modification
- Safe refactoring: prepare_rename then rename for symbol renames
- Continuous verification: diagnostics after every change
AST-Grep
ast_grep_search and ast_grep_replace for structural transformations
- Critical: Always
dryRun=true first, review, then execute
Agents
- explore: Parallel codebase pattern discovery
- librarian: Use proactively for deprecated methods or library migration tasks
- oracle: Read-only consultation for complex architectural decisions
Deprecated Code & Library Migration
When encountering deprecated methods/APIs during refactoring:
- Use librarian to find the recommended modern alternative
- DO NOT auto-upgrade to latest version unless user explicitly requests migration
- If user requests library migration, use librarian to fetch latest API docs before changes
Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.