ast-refactor
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.
Best use case
ast-refactor is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
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.
Teams using ast-refactor should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/ast-refactor/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How ast-refactor Compares
| Feature / Agent | ast-refactor | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
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.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
# 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-search` instead)
- 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
```bash
# Check if ast-grep is installed
which ast-grep
# Find pattern
ast-grep --pattern 'function $FUNC($$$PARAMS) { $$$ }' --lang javascript
# Search and replace
ast-grep run -p 'var $VAR = $VAL' -r 'const $VAR = $VAL' -l javascript
# Interactive mode
ast-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
1. **Understand the Request**: Clarify what structure to refactor
2. **Find Current Usage**: Use ast-grep to discover all instances
3. **Assess Impact**: Count affected files/locations, identify dependencies
```bash
# Example: Find all class definitions
ast-grep --pattern 'class $CLASS { $$$ }' --lang typescript
```
### Phase 2: Planning
1. **Design Transformation**: Define find pattern and replacement pattern
2. **Create Plan**: Summarize what/why/impact with before/after examples
Plan format:
```markdown
## Refactoring Plan: [Title]
**Goal**: [1-2 sentences]
**Impact**: [X files, Y instances]
**Pattern Match**:
```typescript
// Current pattern
```
**Transform To**:
```typescript
// New pattern
```
**Architecture** (if applicable):
```
Current: New:
┌─────────┐ ┌─────────┐
│ Module │ ──────▶ │ Module │
└─────────┘ └─────────┘
```
**Additional Steps**: [Manual changes needed]
```
### Phase 3: User Feedback
1. Present plan with options if multiple approaches exist
2. Gather feedback using AskUserQuestion for architectural decisions
3. Confirm approach before proceeding
### Phase 4: Execution
1. **Verify Git State**: Ensure clean working tree or user acknowledges changes
2. **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
```
3. **Verify Changes**: Run tests, type checkers, linters
4. **Document Results**: Summarize changes and any remaining manual work
## ast-grep Commands
### Basic Search
```bash
ast-grep --pattern 'useState($$$)' --lang typescript
ast-grep -p 'function $F() { $$$ }' -l javascript -A 3 -B 2
```
### Search & Replace
```bash
ast-grep run -p 'var $VAR = $VAL' -r 'const $VAR = $VAL' -l javascript
```
### Rule-Based Refactoring
```yaml
# rule.yml
id: modernize-hasOwnProperty
language: typescript
rule:
pattern: $OBJ.hasOwnProperty($PROP)
fix: Object.hasOwn($OBJ, $PROP)
message: Use Object.hasOwn instead
```
```bash
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 `--interactive` or `--dry-run` modes 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`Related Skills
tdd-workflows-tdd-refactor
Use when working with tdd workflows tdd refactor
skill-refactor
Reviews and refactors an existing skill against quality standards. Use when asked to review, audit, improve, or refactor a skill. Triggers on phrases like "refactor this skill", "review my skill", "improve skill quality", "audit skill-name", "clean up my skill". Do NOT use to create a new skill from scratch.
refactorer-view
A front end staff engineer and UX designer, who refactors and simplifies the user interfaces with the best of user experience patterns.
refactor
Plan vault restructuring from config changes. Compares config.yaml against derivation.md, identifies dimension shifts, shows restructuring plan, executes on approval. Triggers on "/refactor", "restructure vault".
refactor-skill
Assess and refactor oversized or multi-domain skills. First determines whether splitting or references/ extraction is appropriate — then executes the correct action. Use when a skill exceeds token thresholds (SK006/SK007) or covers multiple independent domains. Performs candidate assessment before any structural changes; cohesive single-intent skills are redirected to references/ extraction instead of splitting. When splitting is warranted — domain analysis gate, split plan, new SKILL.md generation, validation, and backwards-compatible facade conversion.
refactor-html
Refactor HTML/TSX files to use existing UI components, DaisyUI classes, and semantic colors. Use when (1) refactoring React/TSX page components to use reusable UI components, (2) replacing raw HTML elements with component library equivalents, (3) converting primitive Tailwind colors to semantic DaisyUI colors, (4) extracting repeated styling patterns into components.
moonbit-refactoring
Refactor MoonBit code to be idiomatic: shrink public APIs, convert functions to methods, use pattern matching with views, add loop invariants, and ensure test coverage without regressions.
dotnet-to-react-python-refactor
Agent skill for refactoring .NET applications into a React frontend + Python backend. Use for migrating/modernizing .NET apps (ASP.NET MVC, Web API, Blazor, Web Forms) to React + Python, or analyzing .NET codebases for migration planning.
code-refactoring-tech-debt
You are a technical debt expert specializing in identifying, quantifying, and prioritizing technical debt in software projects. Analyze the codebase to uncover debt, assess its impact, and create acti
code-refactoring-context-restore
Use when working with code refactoring context restore
52-execute-refactor-150
[52] EXECUTE. Three-stage refactoring workflow: (1) iterative research of refactor/modularization options, (2) plan + risk/edge-case analysis + Scope150 validation, then implement with tests after user confirmation, and (3) apply Scout105 cleanup protocol. Use when asked to refactor, modularize, or restructure code safely.
refactoring-ui
Practical UI design system based on Adam Wathan & Steve Schoger's "Refactoring UI". Use when you need to: (1) fix visual hierarchy problems, (2) choose consistent spacing and typography scales, (3) build color palettes with proper contrast, (4) add depth with shadows and layering, (5) design in grayscale first and add color last, (6) style components in Tailwind CSS, (7) make UI look professional without a designer.