refactor
Detects code smells, suggests design pattern improvements, and restructures code while preserving existing behavior. Use when the user says "refactor this", "clean up this code", "this code is messy", "improve code quality", "reduce complexity", "simplify this", "make this more maintainable", "code smells", or "this function is too long".
What this skill does
# Refactor Skill
When refactoring code, follow this structured process. The golden rule: change structure without changing behavior. Every refactoring should be verifiable by existing tests โ if there are no tests, write them first.
## 1. Pre-Refactor Analysis
Before changing anything, understand the current state:
### Read and Map the Code
```bash
# Understand the file and its dependencies
cat [target-file]
# Find what imports this file (who depends on it)
grep -rn "import.*from.*[filename]" --include="*.ts" --include="*.js" --include="*.py" src/ 2>/dev/null
grep -rn "require.*[filename]" --include="*.js" src/ 2>/dev/null
# Find what this file imports (what it depends on)
grep -E "^import|^from|require\(" [target-file]
# Check for existing tests
find . -name "*[filename]*test*" -o -name "*[filename]*spec*" -o -name "test_*[filename]*" 2>/dev/null
```
### Measure Current Complexity
```bash
# Line count per function (rough estimate)
grep -n "function\|const.*=.*=>\|def \|func \|fn \|pub fn\|class " [target-file]
# File line count
wc -l [target-file]
# Nesting depth (count indentation levels)
awk '{ match($0, /^[[:space:]]*/); print RLENGTH/2, $0 }' [target-file] | sort -rn | head -10
```
### Verify Test Coverage
```bash
# Run existing tests to establish a baseline
npm test -- --coverage --testPathPattern=[filename] 2>/dev/null
python -m pytest --cov=[module] tests/test_[filename].py 2>/dev/null
go test -cover ./[package]/ 2>/dev/null
# If no tests exist, flag this immediately
```
**CRITICAL**: If no tests cover the code being refactored, the FIRST step is to add characterization tests that capture the current behavior. Never refactor untested code.
## 2. Code Smell Detection
Scan for these common smells, grouped by severity:
### ๐ด Critical Smells โ Refactor First
#### Long Functions / Methods
```
Symptom: Function > 30 lines or does more than one thing
Detection: Count lines, look for multiple levels of abstraction
```
```bash
# Find long functions (rough heuristic)
awk '/^[[:space:]]*(export )?(async )?(function|const.*=>|def |func |fn |pub fn)/{name=$0; count=0} {count++} /^[[:space:]]*\}/{if(count>30) print count, name}' [target-file]
```
#### God Class / God Module
```
Symptom: File > 500 lines, class with 10+ methods, module that does everything
Detection: Line count, method count, number of imports
```
```bash
# Count methods in classes
grep -c "^\s*\(public\|private\|protected\|async\)\?\s*\w\+\s*(" [target-file]
# Count imports (high import count = too many responsibilities)
grep -c "^import\|^from.*import\|require(" [target-file]
```
#### Deeply Nested Code
```
Symptom: 4+ levels of indentation, nested if/else/for/try
Detection: Indentation analysis
// ๐ด SMELL โ deeply nested
function processOrder(order) {
if (order) {
if (order.items.length > 0) {
for (const item of order.items) {
if (item.quantity > 0) {
if (item.inStock) {
// actual logic buried 5 levels deep
}
}
}
}
}
}
// โ
REFACTORED โ early returns + extracted functions
function processOrder(order) {
if (!order) return;
if (order.items.length === 0) return;
const validItems = order.items.filter(item => item.quantity > 0 && item.inStock);
validItems.forEach(processItem);
}
```
#### Duplicated Code
```
Symptom: Same logic copy-pasted in multiple places
Detection: Similar code blocks, only differing in small details
```
```bash
# Find duplicate lines (rough detection)
sort [target-file] | uniq -d | grep -v "^$\|^import\|^//\|^#\|^\s*$" | head -20
# Find similar functions across files
grep -rn "function.*validate\|def.*validate\|func.*Validate" --include="*.ts" --include="*.py" --include="*.go" src/ 2>/dev/null
```
#### Primitive Obsession
```
Symptom: Using raw strings/numbers instead of domain types
// ๐ด SMELL โ raw strings everywhere
function createUser(name: string, email: string, role: string, status: string) { ... }
function sendEmail(to: string, subject: string, body: string, priority: string) { ... }
// โ
REFACTORED โ domain types
function createUser(input: CreateUserInput): User { ... }
function sendEmail(message: EmailMessage): void { ... }
interface CreateUserInput {
name: string;
email: Email; // validated email type
role: UserRole; // 'admin' | 'editor' | 'viewer'
status: UserStatus; // 'active' | 'inactive' | 'suspended'
}
```
### ๐ก Warning Smells โ Refactor Soon
#### Feature Envy
```
Symptom: A function that uses more data from another class/module than its own
// ๐ด SMELL โ OrderPrinter knows too much about Order internals
class OrderPrinter {
print(order: Order) {
const subtotal = order.items.reduce((sum, i) => sum + i.price * i.quantity, 0);
const tax = subtotal * order.taxRate;
const shipping = order.weight > 10 ? 15.99 : 5.99;
const total = subtotal + tax + shipping;
// ...
}
}
// โ
REFACTORED โ move calculation to Order
class Order {
get subtotal() { return this.items.reduce((sum, i) => sum + i.price * i.quantity, 0); }
get tax() { return this.subtotal * this.taxRate; }
get shippingCost() { return this.weight > 10 ? 15.99 : 5.99; }
get total() { return this.subtotal + this.tax + this.shippingCost; }
}
class OrderPrinter {
print(order: Order) {
// Just use order.total, order.subtotal, etc.
}
}
```
#### Long Parameter Lists
```
Symptom: Function with 4+ parameters
// ๐ด SMELL
function createUser(name, email, role, department, manager, startDate, salary, location) { ... }
// โ
REFACTORED โ parameter object
function createUser(input: CreateUserInput) { ... }
```
#### Switch/If-Else Chains
```
Symptom: Long switch or if/else chains that map types to behavior
// ๐ด SMELL
function calculateDiscount(customerType: string, amount: number): number {
if (customerType === 'gold') return amount * 0.2;
if (customerType === 'silver') return amount * 0.1;
if (customerType === 'bronze') return amount * 0.05;
if (customerType === 'employee') return amount * 0.3;
return 0;
}
// โ
REFACTORED โ strategy map
const DISCOUNT_RATES: Record<string, number> = {
gold: 0.2,
silver: 0.1,
bronze: 0.05,
employee: 0.3,
};
function calculateDiscount(customerType: string, amount: number): number {
return amount * (DISCOUNT_RATES[customerType] ?? 0);
}
```
#### Boolean Blindness
```
Symptom: Functions that take boolean flags to change behavior
// ๐ด SMELL โ what does `true` mean here?
processOrder(order, true, false, true);
// โ
REFACTORED โ named options
processOrder(order, {
expedited: true,
giftWrap: false,
sendNotification: true,
});
```
#### Magic Numbers and Strings
```
Symptom: Unexplained literal values in code
// ๐ด SMELL
if (retryCount > 3) { ... }
if (user.role === 'admin') { ... }
const timeout = 30000;
// โ
REFACTORED
const MAX_RETRIES = 3;
const ROLES = { ADMIN: 'admin', EDITOR: 'editor' } as const;
const REQUEST_TIMEOUT_MS = 30_000;
```
#### Dead Code
```
Symptom: Unreachable code, unused variables, commented-out blocks
```
```bash
# Find unused exports (TypeScript)
npx ts-prune 2>/dev/null
# Find unused variables
npx eslint --rule '{"no-unused-vars": "error"}' [target-file] 2>/dev/null
# Find commented-out code blocks
grep -n "^\s*//.*function\|^\s*//.*const\|^\s*//.*class\|^\s*#.*def " [target-file]
```
### ๐ข Minor Smells โ Refactor When Convenient
#### Inconsistent Naming
```
Symptom: Mixed conventions in the same codebase
// ๐ด SMELL โ mixed naming
const user_name = getUserName();
const userEmail = get_user_email();
const UserRole = fetchRole();
// โ
REFACTORED โ consistent camelCase
const userName = getUserName();
const userEmail = getUserEmail();
const userRole = fetchRole();
```
#### Comments That Should Be Code
```
Symptom: Comments explaining WHAT, not WHY
// ๐ด SMELL โ comment restates the code
// Check if user is admin
if (user.role === 'admin') { ... }
// โ
REFACTORED โ self-documenting code
if (user.isAdmin()) { ... }
// ๐ด SMELL โ comment as sectioRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context โ no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes โ information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development โ guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.