| name | analyze-code |
| description | Analyze code modules and files for refactoring opportunities, code smells, and architectural pattern violations in any language or framework. Use this skill when the user asks to "analyze code smells", "find refactoring opportunities", "check for code quality issues", or "review architecture" for a specific module or file. |
Refactoring Analyzer
Overview
Systematically analyze code for refactoring opportunities by checking against comprehensive checklists and architectural principles. This skill identifies code smells, architectural violations, design pattern misuse, and improvement opportunities in any language or framework.
When to Use This Skill
Use this skill when the user requests:
- "Analyze code smells in [module/file]"
- "Find refactoring opportunities in [module/file]"
- "Check [module/file] for architecture violations"
- "Review code quality in [module/file]"
- "What can be improved in [module/file]?"
- "Look for code duplication in [module/file]"
Important: This skill analyzes specific modules or files, NOT the entire codebase. The user should specify the scope.
Analysis Workflow
Step 1: Determine Scope
Identify what needs to be analyzed from the user's request:
Module-Level Analysis (directory with related files):
- A feature module, package, or namespace
- A domain/service layer
- A shared/utility library
File-Level Analysis:
- A specific source file
- A specific test file
- A configuration file
If the scope is unclear, ask the user to specify the module or file path.
Step 2: Detect Language & Context
Before analyzing, identify the project's technology stack:
- Language: Look at file extensions (
.swift, .ts, .py, .go, .rs, .java, .kt, etc.)
- Framework: Check imports/dependencies (React, SwiftUI, Django, Spring, etc.)
- Architecture: Check for
CLAUDE.md, .claude/rules/, .github/instructions/, or other project docs describing the architecture
- Conventions: Check for linter configs (
.eslintrc, .swiftlint.yml, pyproject.toml, etc.)
This context shapes which checklist items are most relevant and what patterns to validate against.
Step 3: Read the Target Code
Use appropriate tools to read the code being analyzed:
For Module Analysis:
- Use
Glob to find all source files in the module directory
- Use
Read to load each file in the module
- Note the module's purpose and dependencies
For File Analysis:
- Use
Read to load the specific file
- Check related files (e.g., if analyzing a view, also read its controller/model/service)
Context Gathering:
- Understand the code's purpose and responsibility
- Identify dependencies and relationships
- Note patterns and conventions used
- Check
.claude/rules/ and .github/instructions/ for project-specific knowledge
Step 4: Apply Refactoring Checklist
Load and apply the comprehensive refactoring checklist from references/refactoring-checklist.md.
How to use the checklist:
-
Read the checklist: Use the Read tool to load references/refactoring-checklist.md into context
-
Scan systematically: Go through each category relevant to the code type:
- For UI/View code: Focus on Presentation Layer, State Management, Component Reuse
- For Business Logic: Focus on Architecture, Code Organization, Error Handling
- For Data/API code: Focus on API Integration, Error Handling, Async Patterns
- For Tests: Focus on Testing & Testability, Code Clarity
- For All code: Always check Architecture, Duplication, Security, Performance
-
Document findings: For each issue found, note:
- Issue category and specific checklist item
- File and line number (if applicable)
- Code snippet demonstrating the issue
- Severity (Critical, High, Medium, Low)
Severity Guidelines:
- Critical: Security vulnerabilities, data loss risks, crashes, resource leaks
- High: Architectural violations, major pattern violations, significant maintainability issues
- Medium: Code duplication, missing best practices, moderate complexity
- Low: Naming inconsistencies, minor style issues, documentation gaps
False Positive Avoidance: Only flag issues you are CERTAIN about from the visible code. If you cannot see the full context (e.g., an extension method defined in another file, the reason behind a keyword like nonisolated), do NOT flag it as a problem. When flagging potential issues in code you cannot fully verify (e.g., unused enum cases that may be used elsewhere), explicitly qualify with "verify before acting" language. Speculative future advice ("you could migrate to X someday") is NOT an issue — omit it. When assessing lifecycle/memory issues, consider whether the runtime already handles the scenario (e.g., a Task holding self strongly is not a "leak" if the task completes or is cancelled — it just extends lifetime). Do not flag working dependency imports as potential risks ("what if this dependency is removed someday").
Step 5: Validate Against Architecture
Load and validate against architectural principles from references/architecture-patterns.md.
How to validate:
-
Read architecture guide: Use the Read tool to load references/architecture-patterns.md into context
-
Discover the project's architecture: Check CLAUDE.md, .claude/rules/, .github/instructions/, and project docs for declared boundaries, dependency rules, and conventions. Do NOT assume a specific architecture style — use whatever the project declares.
-
Identify the code's role: Determine what role this code plays within the project's own architecture. What module does it belong to? What is that module responsible for? What should it depend on?
-
Validate against universal principles:
- Single Responsibility: Does each unit have one clear purpose?
- Dependency Direction: Do dependencies flow in the direction the project declares?
- Boundary Compliance: Does the code respect the boundaries between modules?
- Separation of Concerns: Are distinct concerns in distinct modules?
-
Document violations: For each architectural violation, note:
- What boundary or principle was violated
- File and location
- What the project's architecture expects instead
- Suggested refactoring approach
Step 6: Identify Refactoring Opportunities
Beyond checklist items, look for higher-level refactoring opportunities:
Extract and Consolidate:
- Duplicate code that should be extracted to shared utilities
- Custom implementations where framework/library solutions exist
- Repeated logic that should be helper functions or shared modules
- Similar structures that could share a base component or abstraction
Architectural Improvements:
- Code in wrong layer that should be moved
- Missing abstractions (interfaces, protocols, base classes)
- Tight coupling that should be loosened
- Missing error handling or edge case handling
Modern Language Adoption:
- Old patterns that have modern replacements in the language
- Manual implementations of things the standard library provides
- Imperative code that could be declarative/functional
- Callback/promise chains that could use async/await
Performance Optimizations:
- Unnecessary re-computation or re-rendering
- Missing lazy evaluation or caching
- Inefficient algorithms or data structures
- Blocking operations that should be async
Step 6.5: Virtue Scorecard
Score the analyzed code against the 7 Code Virtues (see skills/_references/virtues/code-virtues.md). This provides a positive quality assessment alongside the issue-based findings.
For each virtue, assign 1-5 stars based on evidence:
| Virtue | What to Measure | Evidence Sources |
|---|
| Working | Test coverage, CI status, known bugs | Test files, coverage reports, issue trackers |
| Unique | Duplication level, copy-paste patterns | Duplication analysis from Step 4 |
| Simple | Cyclomatic complexity, entity count, nesting depth | Complexity metrics from Step 4 |
| Clear | Naming quality, self-documenting structure, magic values | Code Clarity checks from Step 4 |
| Easy | How many files/layers a typical change touches | Grain analysis, coupling assessment |
| Developed | Type maturity, abstraction quality, API design | Architecture validation from Step 5 |
| Brief | Verbosity, boilerplate ratio, unnecessary code | Code Organization checks from Step 4 |
Scoring guide:
- ★☆☆☆☆ — Significant problems, this virtue is actively violated
- ★★☆☆☆ — Below expectations, notable issues
- ★★★☆☆ — Adequate, some room for improvement
- ★★★★☆ — Good, minor issues only
- ★★★★★ — Excellent, this virtue is well-served
Evidence MUST be concrete: Each virtue's evidence cell must cite specific line numbers, metrics, or issue references — not vague prose. Bad: "Some complexity issues." Good: "save() at line 127 is 44 lines with 3 nesting levels; setupPlayerPerformances at line 207 uses imperative loop where filter() would suffice."
The scorecard highlights what to protect (high scores) as well as what to improve (low scores). This is especially valuable when prioritizing refactoring work — fix the lowest-scoring virtue that has the highest priority number first (Working before Unique before Simple, etc.).
Step 7: Generate Report
Create a comprehensive, actionable report with the following structure.
Non-Negotiable Output Rules (the report MUST satisfy all of these):
- The Virtue Scorecard must use exactly these 7 virtue names in this order: Working, Unique, Simple, Clear, Easy, Developed, Brief. Use ★ star ratings (1-5). Do NOT substitute other dimensions.
- Every issue must include a Location with
file_path:line_number — never use step names or vague references instead of line numbers.
- Every Critical and High severity issue must include a Suggested Fix section with a concrete code snippet — not just a prose description of what to change.
- The Architecture Validation section is MANDATORY — never skip it. You MUST discover the project's declared architecture (from
CLAUDE.md, .claude/rules/, .github/instructions/, or project docs) and validate the code against those specific boundaries. If no project architecture docs exist, state that explicitly and validate against universal principles only.
Report Template
# Refactoring Analysis: [Module/File Name]
## Summary
- **Language/Framework**: [detected stack]
- **Total Issues Found**: [count]
- **Critical**: [count]
- **High**: [count]
- **Medium**: [count]
- **Low**: [count]
## Virtue Scorecard
| Virtue | Score | Evidence |
|-------------|-------|----------|
| Working | [★☆☆☆☆ - ★★★★★] | [brief evidence] |
| Unique | [★☆☆☆☆ - ★★★★★] | [brief evidence] |
| Simple | [★☆☆☆☆ - ★★★★★] | [brief evidence] |
| Clear | [★☆☆☆☆ - ★★★★★] | [brief evidence] |
| Easy | [★☆☆☆☆ - ★★★★★] | [brief evidence] |
| Developed | [★☆☆☆☆ - ★★★★★] | [brief evidence] |
| Brief | [★☆☆☆☆ - ★★★★★] | [brief evidence] |
**Lowest-priority virtue to fix first:** [virtue name — why]
## Critical Issues
### 1. [Issue Title]
**Category**: [Category from checklist]
**Severity**: Critical
**Location**: `[File]:[Line]`
**Description**: [What's wrong and why it's critical]
**Current Code**:
[Code snippet showing the issue]
**Suggested Fix**:
[Code snippet showing the solution]
**Impact**: [Why this matters]
---
## High Priority Issues
[Same format as Critical]
---
## Medium Priority Issues
[Same format as Critical]
---
## Low Priority Issues
[Same format as Critical]
---
## Architecture Validation
### Principle Compliance
- [ ] Single Responsibility: each unit has one clear purpose
- [ ] Dependency Direction: dependencies flow in the direction the project declares
- [ ] Boundary Compliance: module boundaries are respected
- [ ] Separation of Concerns: distinct concerns live in distinct modules
- [ ] Naming Conventions: consistent naming throughout
### Violations Found
[List any architectural violations with references]
---
## Refactoring Opportunities
### Extract to Shared Code
[List code that should be extracted with suggestions]
### Existing Solutions to Adopt
[List framework/library features that could replace custom code]
### Modernization Opportunities
[List areas where modern language/framework features could be adopted]
---
## Positive Observations
[List things done well - proper patterns, good practices, etc.]
---
## Recommended Action Plan
1. **Immediate** (Critical/High issues):
- [Action item]
- [Action item]
2. **Short-term** (Medium issues):
- [Action item]
- [Action item]
3. **Long-term** (Low issues + optimizations):
- [Action item]
- [Action item]
Report Guidelines
Be Specific:
- Always include file paths and line numbers
- Show actual code snippets, not descriptions
- Provide concrete fix suggestions in the project's language
Be Actionable:
- Prioritize issues clearly
- Explain why each issue matters
- Provide working code examples for fixes
Be Balanced:
- Include positive observations
- Don't overwhelm with minor issues
- Focus on impactful improvements
Be Contextual:
- Consider the code's purpose and constraints
- Acknowledge tradeoffs
- Respect the project's existing conventions and style
- Adapt recommendations to the language/framework idioms
Tips for Effective Analysis
Focus on Impact
Prioritize issues that:
- Affect security or stability
- Violate core architectural principles
- Create maintenance burden
- Impact performance noticeably
Provide Context
For each finding:
- Explain why it's an issue
- Show how to fix it
- Describe the impact of fixing it
Be Constructive
- Frame issues as opportunities
- Acknowledge good practices when present
- Suggest incremental improvements
- Consider team coding style and constraints
Use References
- Point to specific checklist items in
refactoring-checklist.md
- Reference principles in
architecture-patterns.md
- Check
.claude/rules/ and .github/instructions/ for project-specific knowledge
- Link to relevant language/framework documentation when helpful
Common Analysis Patterns
For Any Module With a Clear Responsibility
- Check that the module only does what its declared responsibility says
- Validate that dependencies flow in the direction the project expects
- Review error handling completeness for the module's operations
- Check for proper abstractions at the module's boundaries
- Verify no concerns from other modules leak in
For Code That Coordinates Other Modules
- Check it delegates rather than implements (orchestration, not business logic)
- Validate it doesn't depend on implementation details of the modules it coordinates
- Review that state management is appropriate for the coordination scope
- Check for proper separation between coordination logic and the work being coordinated
For Code That Provides a Public API (library, SDK, shared module)
- Verify the API surface is intentional (no accidental exposure of internals)
- Check reusability and API design consistency
- Review for unnecessary dependencies that consumers would inherit
- Check for proper error handling and documentation
- Validate that internal implementation details don't leak through the API
Limitations
- This skill analyzes code structure and patterns, not runtime behavior
- Cannot detect all performance issues without profiling
- Cannot validate business logic correctness
- Cannot verify against proprietary external APIs
- Recommendations are based on universal best practices but may need adjustment for specific project contexts
- Language-specific deep analysis may require additional domain knowledge
References
This skill uses three reference documents:
-
refactoring-checklist.md: 15 categories covering universal refactoring opportunities
- Architecture & Design Patterns
- Code Organization & Structure
- Presentation / UI Layer
- State Management
- Asynchronous Programming
- API & External Integration
- Code Duplication
- Error Handling & Edge Cases
- Performance & Efficiency
- Testing & Testability
- Documentation & Code Clarity
- Security & Privacy
- Language Idioms & Modern Features
- Observability & Monitoring
- Build, Configuration & Dependencies
-
architecture-patterns.md: Universal architectural principles and validation methodology
- Universal design principles (SOLID, DRY, YAGNI, etc.)
- Project-specific architecture validation methodology (discover, identify role, validate boundaries)
- Dependency management principles
- Universal refactoring strategies (Extract, Move, Replace, Simplify, Introduce)
- Architecture smell summary
-
skills/_references/virtues/code-virtues.md: The 7 Code Virtues positive quality framework
- Priority-ordered virtues: Working, Unique, Simple, Clear, Easy, Developed, Brief
- Virtue Scorecard methodology for balanced code assessment
- Trade-off resolution when virtues conflict
These references are loaded into context during analysis to ensure comprehensive and accurate findings.