Code Analysis
A comprehensive code analysis skill that helps evaluate code quality, identify potential issues, and provide actionable recommendations for improvement.
Quick Start
Basic code analysis workflow:
# Read the code file
with open("target_file.py", "r") as f:
code = f.read()
# Run an LLM code review following code-review-instructions/copilot-instructions.md
# Summarize findings by severity with clear, actionable recommendations
LLM Code Review Mode (Preferred)
Use the LLM (no scripts) to perform reviews guided by code-review-instructions/copilot-instructions.md:
- Keep the instructions open; follow the severity model (Blocking, Important, Suggestions) and priority order (Security → Reliability → Performance/Cost → Testing → Observability → Readability).
- Make the review scope explicit (files/diff) and skip excluded assets like generated/vendor/lock files unless instructed otherwise.
- Pull the relevant stack rules and checklists referenced in the instructions; cite them when flagging issues.
- Report findings first with file:line, impact, and the specific fix or test to add before closing with positives.
Review Checklists and Stack Rules
- Start with general review lists:
docs/review/code-conventions.md, docs/review/readability-checklist.md, docs/review/reliability-checklist.md, docs/review/security-checklist.md, docs/review/performance-checklist.md, docs/review/testing-checklist.md.
- Apply stack-specific rules:
docs/stack-rules/react-typescript-rules.md, docs/stack-rules/angular-rules.md, docs/stack-rules/python-rules.md, docs/stack-rules/java-rules.md, docs/stack-rules/java-kotlin-rules.md, docs/stack-rules/scala-rules.md, docs/stack-rules/go-rules.md.
- Report with references: Link findings to the checklist/rule anchor that was violated for fast remediation.
Core Capabilities
1. Code Quality Assessment
Evaluate overall code quality across multiple dimensions:
- Readability: Variable naming, function clarity, code organization
- Maintainability: Code complexity, coupling, cohesion
- Performance: Potential bottlenecks, inefficient patterns
- Security: Common vulnerabilities, input validation
- Best Practices: Language-specific conventions and idioms
2. Code Smell Detection
Identify common code smells:
- Long Method: Functions exceeding reasonable length
- Large Class: Classes with too many responsibilities
- Duplicate Code: Similar code patterns across files
- Dead Code: Unused variables, functions, imports
- Magic Numbers: Hardcoded values without explanation
- Deep Nesting: Excessive indentation levels
- God Object: Classes doing too much
3. Complexity Metrics
Calculate and interpret:
- Cyclomatic Complexity: Number of independent paths
- Cognitive Complexity: How difficult code is to understand
- Lines of Code: Total, comment, and blank lines
- Function/Method Count: Per class or module
- Dependency Analysis: Import structure and coupling
4. Language-Specific Analysis
React + TypeScript
- Reference:
docs/stack-rules/react-typescript-rules.md
- Component patterns (functional vs class)
- Hooks usage and custom hooks
- Props validation and typing
- State management patterns
- Performance optimization (memo, useMemo, useCallback)
- Key prop usage in lists
- Event handling best practices
- Accessibility (a11y) compliance
Angular + TypeScript
- Reference:
docs/stack-rules/angular-rules.md
- Component lifecycle hooks
- RxJS observable patterns
- Dependency injection
- Change detection strategies
- Template syntax and bindings
- Service architecture
- Module organization
- TypeScript strict mode compliance
Python
- Reference:
docs/stack-rules/python-rules.md
- PEP 8 compliance
- Type hints usage (Python 3.8+)
- Async/await patterns
- Exception handling patterns
- List/dict comprehensions
- Generator vs list usage
- FastAPI/Django best practices
- Pydantic model validation
Java + Spring Boot
- Reference:
docs/stack-rules/java-rules.md
- SOLID principles adherence
- Design pattern opportunities
- Spring annotations usage
- JPA/Hibernate patterns
- Exception handling (@ControllerAdvice)
- Bean validation
- Lombok usage
- Transaction management
- REST API design
Kotlin
- Reference:
docs/stack-rules/java-kotlin-rules.md
- Idiomatic Kotlin patterns
- Coroutines and Flow
- Null safety
- Data classes and sealed classes
- Extension functions
- Scope functions (let, run, with, apply, also)
- Companion objects
- Destructuring declarations
Scala
- Reference:
docs/stack-rules/scala-rules.md
- Option/Either/Try usage instead of null
- Immutability and collection best practices
- Pattern matching exhaustiveness and for-comprehensions
- Concurrency with Future/IO and resource safety
- Controlled use of implicits/givens and type classes
Go
- Reference:
docs/stack-rules/go-rules.md
- Explicit error handling and wrapping with context
- Context propagation and cancellation
- Concurrency correctness with goroutines/channels
- Interface-oriented design and zero-value-safe structs
- Database/HTTP patterns with proper resource management
Workflows
Workflow 0: LLM Code Review (Copilot Instructions)
- Open the instructions: Keep
code-review-instructions/copilot-instructions.md in view.
- Identify scope: List files/diffs included; skip excluded files noted in the instructions.
- Assess critical paths first: Security → reliability → performance/cost → tests → observability → readability/UX.
- Apply stack rules: Pull the relevant concise or full stack rule docs referenced by the instructions.
- Report findings: Start with blocking/important issues, cite file:line, describe impact, and propose the fix.
- Close with next steps: Tests to add/run and any follow-ups required to de-risk.
Workflow 1: Comprehensive File Analysis
- Read the target file
- Parse code structure: Functions, classes, imports
- Calculate metrics: Complexity, LOC, depth
- Detect issues: Code smells, anti-patterns
- Generate report: Structured findings with priorities
- Provide recommendations: Specific, actionable improvements
Workflow 2: Multi-File Project Analysis
- Scan project structure
- Identify dependencies
- Analyze each file: Apply single-file workflow
- Cross-reference issues: Duplicate code, circular dependencies
- Aggregate findings: Project-wide statistics
- Prioritize improvements: Impact vs effort matrix
Workflow 3: Focused Issue Investigation
- Receive specific concern: Performance, security, readability
- Deep dive analysis: Targeted inspection
- Identify root causes
- Suggest solutions: Multiple options with trade-offs
- Provide examples: Before/after code snippets
Analysis Output Format
Structure your analysis as follows:
## Code Analysis Report
### Summary
- File: [filename]
- Language: [language]
- Lines of Code: [total]
- Overall Quality: [High/Medium/Low]
### Metrics
- Cyclomatic Complexity: [average] (functions: [list high-complexity ones])
- Maintainability Index: [score]
- Code Smells Detected: [count]
### Critical Issues (Priority: High)
1. [Issue description]
- Location: Line [X]
- Impact: [explanation]
- Recommendation: [specific fix]
### Moderate Issues (Priority: Medium)
[Similar structure]
### Minor Improvements (Priority: Low)
[Similar structure]
### Positive Aspects
- [What's done well]
- [Good patterns observed]
### Actionable Recommendations
1. [Priority 1 action]
2. [Priority 2 action]
3. [Priority 3 action]
Best Practices for Analysis
- Be Specific: Point to exact line numbers and code sections
- Provide Context: Explain why something is an issue
- Offer Solutions: Don't just identify problems, suggest fixes
- Show Examples: Include code snippets when helpful
- Consider Trade-offs: Acknowledge when recommendations have costs
- Prioritize: Not all issues are equal importance
- Be Constructive: Focus on improvement, not criticism
Common Patterns to Check
Anti-Patterns
# Anti-pattern: God Object
class UserManager:
def authenticate(self): pass
def send_email(self): pass
def generate_report(self): pass
def process_payment(self): pass
# Too many responsibilities!
# Better: Single Responsibility
class Authenticator:
def authenticate(self): pass
class EmailService:
def send_email(self): pass
Performance Issues
# Inefficient: Multiple iterations
data = [process(x) for x in items]
filtered = [x for x in data if x > 0]
result = [transform(x) for x in filtered]
# Efficient: Single pass
result = [transform(process(x)) for x in items if process(x) > 0]
Security Concerns
# Vulnerable: SQL Injection
query = f"SELECT * FROM users WHERE id = {user_id}"
# Safe: Parameterized query
query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))
Integration with Other Tools
This skill can reference:
- Linting tools: pylint, eslint, golangci-lint
- Testing: pytest, jest, JUnit results
- Coverage: Code coverage reports
- Profiling: Performance profiler output
For detailed language-specific guidelines, see LANGUAGE_GUIDES.md.
- Prefer LLM-driven review; do not call scripts like
scripts/analyze.py unless explicitly requested.
Limitations
- Cannot execute code for dynamic analysis
- Limited to static code analysis
- May miss runtime-only issues
- Context-dependent recommendations require human judgment
When to Use This Skill
Use this skill when:
- Reviewing pull requests
- Auditing legacy code
- Planning refactoring efforts
- Conducting code quality assessments
- Training team members on best practices
- Investigating specific code issues
- Preparing for production deployment
Examples
See EXAMPLES.md for detailed analysis examples across different languages and scenarios.
See EXAMPLES_STACK.md for comprehensive examples with React, TypeScript, Angular, Python, Java, and Kotlin.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: code-analysis-33description: Analyze code quality, detect code smells, identify bugs, and provide improvement recommendations. Use when reviewing code, checking quality, analyzing complexity, or when user mentions code review, refactoring suggestions, or quality assessment. Use when this capability is needed.4---56# Code Analysis78A comprehensive code analysis skill that helps evaluate code quality, identify potential issues, and provide actionable recommendations for improvement.910## Quick Start1112Basic code analysis workflow:1314```python15# Read the code file16with open("target_file.py", "r") as f:17 code = f.read()1819# Run an LLM code review following code-review-instructions/copilot-instructions.md20# Summarize findings by severity with clear, actionable recommendations21```2223## LLM Code Review Mode (Preferred)2425Use the LLM (no scripts) to perform reviews guided by [`code-review-instructions/copilot-instructions.md`](code-review-instructions/copilot-instructions.md):26- Keep the instructions open; follow the severity model (Blocking, Important, Suggestions) and priority order (Security → Reliability → Performance/Cost → Testing → Observability → Readability).27- Make the review scope explicit (files/diff) and skip excluded assets like generated/vendor/lock files unless instructed otherwise.28- Pull the relevant stack rules and checklists referenced in the instructions; cite them when flagging issues.29- Report findings first with file:line, impact, and the specific fix or test to add before closing with positives.3031## Review Checklists and Stack Rules3233- **Start with general review lists**: `docs/review/code-conventions.md`, `docs/review/readability-checklist.md`, `docs/review/reliability-checklist.md`, `docs/review/security-checklist.md`, `docs/review/performance-checklist.md`, `docs/review/testing-checklist.md`.34- **Apply stack-specific rules**: `docs/stack-rules/react-typescript-rules.md`, `docs/stack-rules/angular-rules.md`, `docs/stack-rules/python-rules.md`, `docs/stack-rules/java-rules.md`, `docs/stack-rules/java-kotlin-rules.md`, `docs/stack-rules/scala-rules.md`, `docs/stack-rules/go-rules.md`.35- **Report with references**: Link findings to the checklist/rule anchor that was violated for fast remediation.3637## Core Capabilities3839### 1. Code Quality Assessment4041Evaluate overall code quality across multiple dimensions:4243- **Readability**: Variable naming, function clarity, code organization44- **Maintainability**: Code complexity, coupling, cohesion45- **Performance**: Potential bottlenecks, inefficient patterns46- **Security**: Common vulnerabilities, input validation47- **Best Practices**: Language-specific conventions and idioms4849### 2. Code Smell Detection5051Identify common code smells:5253- **Long Method**: Functions exceeding reasonable length54- **Large Class**: Classes with too many responsibilities55- **Duplicate Code**: Similar code patterns across files56- **Dead Code**: Unused variables, functions, imports57- **Magic Numbers**: Hardcoded values without explanation58- **Deep Nesting**: Excessive indentation levels59- **God Object**: Classes doing too much6061### 3. Complexity Metrics6263Calculate and interpret:6465- **Cyclomatic Complexity**: Number of independent paths66- **Cognitive Complexity**: How difficult code is to understand67- **Lines of Code**: Total, comment, and blank lines68- **Function/Method Count**: Per class or module69- **Dependency Analysis**: Import structure and coupling7071### 4. Language-Specific Analysis7273#### React + TypeScript74- Reference: `docs/stack-rules/react-typescript-rules.md`75- Component patterns (functional vs class)76- Hooks usage and custom hooks77- Props validation and typing78- State management patterns79- Performance optimization (memo, useMemo, useCallback)80- Key prop usage in lists81- Event handling best practices82- Accessibility (a11y) compliance8384#### Angular + TypeScript85- Reference: `docs/stack-rules/angular-rules.md`86- Component lifecycle hooks87- RxJS observable patterns88- Dependency injection89- Change detection strategies90- Template syntax and bindings91- Service architecture92- Module organization93- TypeScript strict mode compliance9495#### Python96- Reference: `docs/stack-rules/python-rules.md`97- PEP 8 compliance98- Type hints usage (Python 3.8+)99- Async/await patterns100- Exception handling patterns101- List/dict comprehensions102- Generator vs list usage103- FastAPI/Django best practices104- Pydantic model validation105106#### Java + Spring Boot107- Reference: `docs/stack-rules/java-rules.md`108- SOLID principles adherence109- Design pattern opportunities110- Spring annotations usage111- JPA/Hibernate patterns112- Exception handling (@ControllerAdvice)113- Bean validation114- Lombok usage115- Transaction management116- REST API design117118#### Kotlin119- Reference: `docs/stack-rules/java-kotlin-rules.md`120- Idiomatic Kotlin patterns121- Coroutines and Flow122- Null safety123- Data classes and sealed classes124- Extension functions125- Scope functions (let, run, with, apply, also)126- Companion objects127- Destructuring declarations128129#### Scala130- Reference: `docs/stack-rules/scala-rules.md`131- Option/Either/Try usage instead of null132- Immutability and collection best practices133- Pattern matching exhaustiveness and for-comprehensions134- Concurrency with Future/IO and resource safety135- Controlled use of implicits/givens and type classes136137#### Go138- Reference: `docs/stack-rules/go-rules.md`139- Explicit error handling and wrapping with context140- Context propagation and cancellation141- Concurrency correctness with goroutines/channels142- Interface-oriented design and zero-value-safe structs143- Database/HTTP patterns with proper resource management144145## Workflows146147### Workflow 0: LLM Code Review (Copilot Instructions)1481491. **Open the instructions**: Keep [`code-review-instructions/copilot-instructions.md`](code-review-instructions/copilot-instructions.md) in view.1502. **Identify scope**: List files/diffs included; skip excluded files noted in the instructions.1513. **Assess critical paths first**: Security → reliability → performance/cost → tests → observability → readability/UX.1524. **Apply stack rules**: Pull the relevant concise or full stack rule docs referenced by the instructions.1535. **Report findings**: Start with blocking/important issues, cite file:line, describe impact, and propose the fix.1546. **Close with next steps**: Tests to add/run and any follow-ups required to de-risk.155156### Workflow 1: Comprehensive File Analysis1571581. **Read the target file**1592. **Parse code structure**: Functions, classes, imports1603. **Calculate metrics**: Complexity, LOC, depth1614. **Detect issues**: Code smells, anti-patterns1625. **Generate report**: Structured findings with priorities1636. **Provide recommendations**: Specific, actionable improvements164165### Workflow 2: Multi-File Project Analysis1661671. **Scan project structure**1682. **Identify dependencies**1693. **Analyze each file**: Apply single-file workflow1704. **Cross-reference issues**: Duplicate code, circular dependencies1715. **Aggregate findings**: Project-wide statistics1726. **Prioritize improvements**: Impact vs effort matrix173174### Workflow 3: Focused Issue Investigation1751761. **Receive specific concern**: Performance, security, readability1772. **Deep dive analysis**: Targeted inspection1783. **Identify root causes**1794. **Suggest solutions**: Multiple options with trade-offs1805. **Provide examples**: Before/after code snippets181182## Analysis Output Format183184Structure your analysis as follows:185186```markdown187## Code Analysis Report188189### Summary190- File: [filename]191- Language: [language]192- Lines of Code: [total]193- Overall Quality: [High/Medium/Low]194195### Metrics196- Cyclomatic Complexity: [average] (functions: [list high-complexity ones])197- Maintainability Index: [score]198- Code Smells Detected: [count]199200### Critical Issues (Priority: High)2011. [Issue description]202 - Location: Line [X]203 - Impact: [explanation]204 - Recommendation: [specific fix]205206### Moderate Issues (Priority: Medium)207[Similar structure]208209### Minor Improvements (Priority: Low)210[Similar structure]211212### Positive Aspects213- [What's done well]214- [Good patterns observed]215216### Actionable Recommendations2171. [Priority 1 action]2182. [Priority 2 action]2193. [Priority 3 action]220```221222## Best Practices for Analysis2232241. **Be Specific**: Point to exact line numbers and code sections2252. **Provide Context**: Explain why something is an issue2263. **Offer Solutions**: Don't just identify problems, suggest fixes2274. **Show Examples**: Include code snippets when helpful2285. **Consider Trade-offs**: Acknowledge when recommendations have costs2296. **Prioritize**: Not all issues are equal importance2307. **Be Constructive**: Focus on improvement, not criticism231232## Common Patterns to Check233234### Anti-Patterns235236```python237# Anti-pattern: God Object238class UserManager:239 def authenticate(self): pass240 def send_email(self): pass241 def generate_report(self): pass242 def process_payment(self): pass243 # Too many responsibilities!244245# Better: Single Responsibility246class Authenticator:247 def authenticate(self): pass248249class EmailService:250 def send_email(self): pass251```252253### Performance Issues254255```python256# Inefficient: Multiple iterations257data = [process(x) for x in items]258filtered = [x for x in data if x > 0]259result = [transform(x) for x in filtered]260261# Efficient: Single pass262result = [transform(process(x)) for x in items if process(x) > 0]263```264265### Security Concerns266267```python268# Vulnerable: SQL Injection269query = f"SELECT * FROM users WHERE id = {user_id}"270271# Safe: Parameterized query272query = "SELECT * FROM users WHERE id = ?"273cursor.execute(query, (user_id,))274```275276## Integration with Other Tools277278This skill can reference:279280- **Linting tools**: pylint, eslint, golangci-lint281- **Testing**: pytest, jest, JUnit results282- **Coverage**: Code coverage reports283- **Profiling**: Performance profiler output284285For detailed language-specific guidelines, see [LANGUAGE_GUIDES.md](LANGUAGE_GUIDES.md).286287- Prefer LLM-driven review; do not call scripts like `scripts/analyze.py` unless explicitly requested.288289## Limitations290291- Cannot execute code for dynamic analysis292- Limited to static code analysis293- May miss runtime-only issues294- Context-dependent recommendations require human judgment295296## When to Use This Skill297298Use this skill when:299- Reviewing pull requests300- Auditing legacy code301- Planning refactoring efforts302- Conducting code quality assessments303- Training team members on best practices304- Investigating specific code issues305- Preparing for production deployment306307## Examples308309See [EXAMPLES.md](EXAMPLES.md) for detailed analysis examples across different languages and scenarios.310311See [EXAMPLES_STACK.md](EXAMPLES_STACK.md) for comprehensive examples with React, TypeScript, Angular, Python, Java, and Kotlin.312313---314> Converted and distributed by [TomeVault](https://tomevault.io/claim/josavicentevw) — claim your Tome and manage your conversions.315<!-- tomevault:4.0:skill_md:2026-04-13 -->