refactor
Refactor code for quality and maintainability without changing behavior; improves structure, naming, and JSDoc. Triggers when: "refactor this", "clean up this code", "rename these variables", "improve readability", "add JSDoc comments". Also use when: simplifying complex functions, extracting helpers, standardizing naming across a module. Examples: "refactor src/utils", "clean up this file", "add JSDoc to all exports".
What this skill does
# Refactor Code
Refactors implementation for quality and maintainability without changing functionality, improving structure, readability, naming, and JSDoc while keeping every test green. **Coherence Mandate.** Every edit must produce one continuous, deliberate work. Rewrite over restructure, restructure over integrate, never append. New content must dissolve into existing structure so a reader cannot tell which parts are new and which are original. Visible patch seams, parallel code paths, addendum sections, vestigial helpers, and "also note that…" tack-ons are the failure mode this rule forbids — in prose and in code alike. That standard is why refactoring exists: it is the discipline by which earlier compromises are absorbed into the current shape of the code, not the act of layering new niceties on top — and the Two-Stage Rule below is its concrete application to file size.
## Purpose & Scope
**What this command does NOT do**:
- Change functionality or behavior of existing code
- Add new features or business logic
- Fix failing tests (use `/coding:fix` instead)
- Create new test cases
- Modify project configuration
**When to REJECT**:
- Request is for new feature development (use `/coding:write-code`)
- Request is to fix bugs or failing tests (use `/coding:fix`)
- Area path is invalid or no files found
- Code has failing tests (fix tests first before refactoring)
## Applicable Standards
When executing this skill, the following standards apply:
| Standard | Purpose |
|---|---|
| `universal/write` | General code authoring conventions |
| `typescript/write` | TypeScript patterns and type safety |
| `function/write` | Function design, signatures, and complexity |
| `documentation/write` | JSDoc, inline comments, usage examples |
| `naming/write` | Naming conventions for variables, functions, files |
## Workflow
ultrathink: you'd perform the following steps
### Step 1: Analyze Current State
1. **Parse Arguments**
- Extract area path from $ARGUMENTS
- Parse `--focus` flag (naming, structure, docs, all; default: all)
- Determine if running as standalone or as part of composite (`--from-composite`)
2. **Pre-flight Check**
- Run existing tests to confirm they all pass before refactoring
- If any tests fail, reject with guidance to use `/coding:fix` first
- Read files in the target area to understand current structure
3. **Identify Refactoring Opportunities**
- Code structure improvements (extract functions, reduce complexity)
- Readability enhancements (clearer variable names, better flow)
- Naming convention violations
- Missing or incomplete JSDoc documentation
- Inline comment gaps for complex logic
- Pattern inconsistencies with the rest of the codebase
### Step 2: Refactor Implementation
1. **Improve Code Structure**
- Apply proper design patterns following standards
- Reduce function complexity where possible
- Extract reusable utilities and helpers
- Ensure code follows all established patterns in the codebase
- Run tests continuously to ensure no functionality is broken
2. **Split Long Files (Two-Stage Rule)**
- When a file exceeds the project's `max-lines` threshold, apply the two-stage rule before making any ad-hoc splits:
- **Stage 1 — Extract shared helpers:** Look for logic that can live in another file (existing or new) as a genuinely reusable helper. Prefer this when the extracted code is shared by more than one caller.
- **Stage 2 — Folder split:** If the file still exceeds `max-lines` after extraction, split it into a folder using the `<base>.ts` + `<base>/*.ts` pattern. The entry file `<base>.ts` stays as a thin re-exports/orchestrator; helpers move into `<base>/*.ts` with short names (the folder already provides the context).
- Do NOT split a file into arbitrary sibling files (e.g. `foo.schema.ts`, `foo.parse.ts`) unless that naming is already an established project convention; prefer the folder pattern.
- See `constitution/standards/file-structure.md` → "Splitting Long Files" for the full rule and examples.
3. **Enhance Readability**
- Apply proper naming conventions per naming standards
- Improve code flow and logical grouping
- Simplify complex expressions
- Remove dead code and unnecessary comments
### Step 3: Add Documentation
1. **Add JSDoc Comments**
- Document all public functions, classes, and interfaces
- Include parameter descriptions, return types, and behavior
- Add `@example` blocks where appropriate
- Follow documentation standards for format and content
2. **Add Inline Comments**
- Explain complex algorithms and non-obvious logic
- Document "why" decisions, not "what" the code does
- Add TODO/FIXME markers for known limitations (if any)
### Step 4: Validate Quality
1. **Run Full Test Suite**
- Execute all related tests to verify no regressions
- Confirm coverage is maintained at expected levels
2. **Run Quality Checks**
- Execute linting to ensure standards compliance
- Run type checker to verify TypeScript correctness
- Verify all quality gates pass
3. **Final Assessment**
- Confirm refactoring improved code quality metrics
- Verify documentation completeness
- Ensure production readiness
### Step 5: Reporting
**Output Format**:
```
[OK/FAIL] Command: refactor $ARGUMENTS
## Summary
- Area: [path]
- Focus: [naming|structure|docs|all]
- Files refactored: [count]
- Documentation added: [count] JSDoc blocks
- Quality improvements: [list]
## Actions Taken
1. Refactored [N] files for [improvements]
2. Added [M] JSDoc documentation blocks
3. Applied naming convention fixes to [K] identifiers
4. Verified all tests still pass
## Quality Results
- Tests: PASS ([X] passing, [Y] coverage)
- Types: PASS ([N] errors)
- Lint: PASS ([N] warnings)
## Improvements Applied
- [file:line] - [improvement description]
- [file:line] - [improvement description]
## Next Steps
1. Review refactored code
2. Run full test suite
3. Commit with /coding:commit
```
## Examples
### Refactor All Aspects
```bash
/refactor "src/services/auth/"
# Improves structure, naming, and documentation
# Runs tests continuously to verify no regressions
```
### Focus on Documentation
```bash
/refactor "src/utils/" --focus=docs
# Adds JSDoc to all public functions
# Adds inline comments for complex logic
```
### Focus on Naming
```bash
/refactor "src/models/" --focus=naming
# Applies naming convention standards
# Renames variables, functions, and files
```
### Error Case
```bash
/refactor "src/broken-tests/"
# Error: 3 tests failing in target area
# Fix tests first with /coding:fix, then refactor
```
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.