Skill v1.0.1
currentAutomated scan100/1003 files
version: "1.0.1" name: ast-refactor description: This skill should be used when transforming, refactoring, or replacing code patterns across multiple files. Use for renaming functions/classes/variables, migrating API usage patterns, modernizing syntax, or performing bulk code transformations. Prefer ast-grep over sed/awk for syntax-aware replacements that understand language structure. allowed-tools:
- Read
- Glob
- Grep
- Bash
- Edit
- Write
- AskUserQuestion
- TodoWrite
context: fork agent: general-purpose
AST-Aware Code Refactoring
Overview
Transform code patterns systematically using ast-grep, a syntax-aware tool that finds and replaces code based on abstract syntax trees rather than plain text matching.
When to Use
Use this skill when:
- Renaming functions, classes, or variables across the codebase
- Migrating API usage patterns (e.g.,
console.log→logger.info) - Modernizing syntax (e.g.,
var→const,require→import) - Replacing deprecated function calls with new equivalents
- Restructuring code architecture (moving, splitting, combining modules)
- Performing bulk transformations that require syntax awareness
Do NOT use this skill for:
- Searching/exploring code without transformations (use
ast-searchinstead) - Simple text replacements in non-code files (use sed/grep)
- Single-file edits with no pattern repetition (use Edit tool directly)
- Non-structural changes (comments, formatting)
- Bug fixes that don't involve pattern transformation
Quick Reference
# Check if ast-grep is installedwhich ast-grep# Find patternast-grep --pattern 'function $FUNC($$$PARAMS) { $$$ }' --lang javascript# Search and replaceast-grep run -p 'var $VAR = $VAL' -r 'const $VAR = $VAL' -l javascript# Interactive modeast-grep run -p 'PATTERN' -r 'REPLACEMENT' -l LANG --interactive
Pattern Syntax
| Pattern | Matches | |
|---|---|---|
$VAR | Single AST node (variable, expression, etc.) | |
$$$ARGS | Multiple nodes (function arguments) | |
$$$ | Any sequence of nodes within a block |
Workflow
Phase 1: Discovery & Analysis
- Understand the Request: Clarify what structure to refactor
- Find Current Usage: Use ast-grep to discover all instances
- Assess Impact: Count affected files/locations, identify dependencies
# Example: Find all class definitionsast-grep --pattern 'class $CLASS { $$$ }' --lang typescript
Phase 2: Planning
- Design Transformation: Define find pattern and replacement pattern
- Create Plan: Summarize what/why/impact with before/after examples
Plan format:
## Refactoring Plan: [Title]**Goal**: [1-2 sentences]**Impact**: [X files, Y instances]**Pattern Match**:
// Current pattern
**Transform To**:
// New pattern
**Architecture** (if applicable):
Current: New: ┌─────────┐ ┌─────────┐ │ Module │ ──────▶ │ Module │ └─────────┘ └─────────┘
**Additional Steps**: [Manual changes needed]
Phase 3: User Feedback
- Present plan with options if multiple approaches exist
- Gather feedback using AskUserQuestion for architectural decisions
- Confirm approach before proceeding
Phase 4: Execution
- Verify Git State: Ensure clean working tree or user acknowledges changes
- Apply Transformations:
```bash # Simple pattern replacement ast-grep run -p 'console.log($MSG)' -r 'logger.info($MSG)' -l typescript
# Interactive for careful review ast-grep run -p 'PATTERN' -r 'REPLACEMENT' -l LANG --interactive ```
- Verify Changes: Run tests, type checkers, linters
- Document Results: Summarize changes and any remaining manual work
ast-grep Commands
Basic Search
ast-grep --pattern 'useState($$$)' --lang typescriptast-grep -p 'function $F() { $$$ }' -l javascript -A 3 -B 2
Search & Replace
ast-grep run -p 'var $VAR = $VAL' -r 'const $VAR = $VAL' -l javascript
Rule-Based Refactoring
# rule.ymlid: modernize-hasOwnPropertylanguage: typescriptrule:pattern: $OBJ.hasOwnProperty($PROP)fix: Object.hasOwn($OBJ, $PROP)message: Use Object.hasOwn instead
ast-grep scan -r rule.yml --update-all
Supported Languages
JavaScript, TypeScript, Python, Go, Rust, Java, C, C++, C#, Kotlin, Swift, Ruby, PHP, and more.
Common Mistakes
| Mistake | Solution | |
|---|---|---|
| Not checking ast-grep installation | Run which ast-grep first, install with brew install ast-grep | |
| Running on dirty git state | Verify clean state or get user acknowledgment first | |
| Skipping interactive mode for large changes | Use --interactive for 50+ file changes | |
| Pattern doesn't match comments/strings | This is correct behavior - ast-grep is syntax-aware | |
| Not running tests after | Always verify with tests/type-checker after refactoring | |
| Assuming single pass works | Complex refactoring may need multiple ast-grep passes |
Safety Guidelines
- Never run destructive refactoring without user approval
- Always show transformation plan with examples before executing
- Use
--interactiveor--dry-runmodes for significant changes - Verify tests pass after refactoring
- For large refactorings (50+ files), suggest incremental approach
- Work with clean git state, commit refactoring separately from logic changes
Troubleshooting
- Pattern not matching: Verify language flag, check AST structure
- Partial matches: May need multiple patterns for variants
- Syntax errors after refactor: Some edge cases need manual intervention
- Tool not found: Install with
brew install ast-grep