---
name: code-analysis
description: 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.
title: code-analysis
canonical_url: https://skilld.dev/gh/josavicentevw/ai-agent-skills/code-analysis
last_updated: 2026-10-05T11:13:43.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> 34 supporting files sit beside this SKILL.md. When the Skill refers to one, fetch https://skilld.dev/api/skills-raw/josavicentevw/ai-agent-skills/code-analysis/PATH with PATH replaced.
>
> If the user asked to install this Skill, run `npx skilld install josavicentevw/ai-agent-skills/code-analysis`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/code-analysis`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/josavicentevw/ai-agent-skills/code-analysis) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/code-analysis`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/code-analysis --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/code-analysis --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# 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:

```python
# 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`](https://skilld.dev/api/skills-raw/josavicentevw/ai-agent-skills/code-analysis/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)

1. **Open the instructions**: Keep [`code-review-instructions/copilot-instructions.md`](https://skilld.dev/api/skills-raw/josavicentevw/ai-agent-skills/code-analysis/code-review-instructions/copilot-instructions.md) in view.
2. **Identify scope**: List files/diffs included; skip excluded files noted in the instructions.
3. **Assess critical paths first**: Security → reliability → performance/cost → tests → observability → readability/UX.
4. **Apply stack rules**: Pull the relevant concise or full stack rule docs referenced by the instructions.
5. **Report findings**: Start with blocking/important issues, cite file:line, describe impact, and propose the fix.
6. **Close with next steps**: Tests to add/run and any follow-ups required to de-risk.

### Workflow 1: Comprehensive File Analysis

1. **Read the target file**
2. **Parse code structure**: Functions, classes, imports
3. **Calculate metrics**: Complexity, LOC, depth
4. **Detect issues**: Code smells, anti-patterns
5. **Generate report**: Structured findings with priorities
6. **Provide recommendations**: Specific, actionable improvements

### Workflow 2: Multi-File Project Analysis

1. **Scan project structure**
2. **Identify dependencies**
3. **Analyze each file**: Apply single-file workflow
4. **Cross-reference issues**: Duplicate code, circular dependencies
5. **Aggregate findings**: Project-wide statistics
6. **Prioritize improvements**: Impact vs effort matrix

### Workflow 3: Focused Issue Investigation

1. **Receive specific concern**: Performance, security, readability
2. **Deep dive analysis**: Targeted inspection
3. **Identify root causes**
4. **Suggest solutions**: Multiple options with trade-offs
5. **Provide examples**: Before/after code snippets

## Analysis Output Format

Structure your analysis as follows:

```markdown
## 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

1. **Be Specific**: Point to exact line numbers and code sections
2. **Provide Context**: Explain why something is an issue
3. **Offer Solutions**: Don't just identify problems, suggest fixes
4. **Show Examples**: Include code snippets when helpful
5. **Consider Trade-offs**: Acknowledge when recommendations have costs
6. **Prioritize**: Not all issues are equal importance
7. **Be Constructive**: Focus on improvement, not criticism

## Common Patterns to Check

### Anti-Patterns

```python
# 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

```python
# 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

```python
# 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](https://skilld.dev/api/skills-raw/josavicentevw/ai-agent-skills/code-analysis/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](https://skilld.dev/api/skills-raw/josavicentevw/ai-agent-skills/code-analysis/EXAMPLES.md) for detailed analysis examples across different languages and scenarios.

See [EXAMPLES_STACK.md](https://skilld.dev/api/skills-raw/josavicentevw/ai-agent-skills/code-analysis/EXAMPLES_STACK.md) for comprehensive examples with React, TypeScript, Angular, Python, Java, and Kotlin.
