| name | code-analyzer |
| description | 代码质量分析技能,用于对代码进行全面的质量评估。当用户要求分析代码质量、检查代码规范、评估代码复杂度、查找代码安全隐患、要求代码 review、评估可维护性、或询问代码是否需要重构时,使用此技能。覆盖代码风格、圈复杂度、安全漏洞、可维护性和性能分析等多个维度。即使用户没有明确说'代码质量',只要涉及代码评审、代码改进建议或代码问题排查,也应使用此技能。 |
Code Analyzer Skill
Overview
This skill performs comprehensive code quality analysis across multiple dimensions. It evaluates code quality not just by looking for bugs, but by assessing the overall health of a codebase — style consistency, complexity, security posture, maintainability, and performance characteristics.
The goal is to provide actionable, specific feedback that helps developers improve their code, not just list problems. Every finding should include context, explanation, and a concrete suggestion.
When to Use This Skill
Always load this skill when:
- User asks to "analyze code quality", "review my code", or "check code standards"
- User shares code and asks "what's wrong with this?" or "how can I improve this?"
- User wants to evaluate code complexity, security vulnerabilities, or maintainability
- User asks whether code needs refactoring or restructuring
- User requests a code audit or assessment
- User mentions specific quality concerns like "is this code secure?" or "is this too complex?"
Do NOT load this skill when:
- User asks to write new code (that's code generation, not analysis)
- User asks to debug a specific error (that's debugging, not quality analysis)
- User asks to explain what code does (that's code explanation)
Analysis Workflow
Phase 1: Scope Assessment
Before diving into analysis, understand what you're analyzing:
- Identify the target: Is it a single file, a module, or an entire project?
- Determine the language(s): Check file extensions, package managers, and configuration files
- Understand the context: What is the project's purpose? What frameworks does it use?
- Ask clarifying questions: If the scope is unclear, ask the user what they want analyzed
ls /mnt/user-data/uploads/project-dir/
cat /mnt/user-data/uploads/project-dir/package.json
cat /mnt/user-data/uploads/project-dir/pyproject.toml
cat /mnt/user-data/uploads/project-dir/go.mod
Phase 2: Multi-Dimensional Analysis
Analyze code across these five dimensions. Each dimension has specific checks and patterns to look for.
Dimension 1: Code Style & Consistency
Evaluate adherence to language-specific style conventions:
| Check | What to Look For |
|---|
| Naming conventions | Variables, functions, classes follow language conventions (snake_case for Python, camelCase for JS, PascalCase for classes) |
| Formatting | Consistent indentation, spacing, line length |
| Import organization | Standard library → third-party → local, no unused imports |
| Documentation | Docstrings/comments present for public APIs |
| Consistency | Same patterns used throughout the codebase (e.g., error handling style) |
Common style issues:
- Mixed naming conventions in the same file
- Inconsistent string quote usage (single vs double)
- Missing or inconsistent docstrings
- Inconsistent error handling patterns (sometimes exceptions, sometimes return codes)
Dimension 2: Complexity Analysis
Assess code complexity at function and module levels:
| Metric | Threshold | Risk |
|---|
| Cyclomatic complexity | > 10 per function | Hard to test and understand |
| Lines per function | > 50 | Too much responsibility |
| Nesting depth | > 4 levels | Hard to follow logic |
| Function parameters | > 5 | Consider using options object |
| File length | > 500 lines | Consider splitting |
How to estimate cyclomatic complexity:
- Start at 1 for each function
- Add 1 for each:
if, elif, else, for, while, and, or, except
- Add 1 for each conditional expression or ternary
grep -n "def \|function \|func " <file> | head -20
Dimension 3: Security Analysis
Scan for common security vulnerabilities:
| Category | Pattern to Check | Severity |
|---|
| Injection | SQL string concatenation, shell command with user input, template injection | Critical |
| Authentication | Hardcoded credentials, weak password hashing, missing auth checks | Critical |
| Data exposure | Sensitive data in logs, unencrypted storage, missing input validation | High |
| Dependencies | Known vulnerable packages, outdated versions | High |
| Error handling | Stack traces in responses, verbose error messages | Medium |
| Configuration | Debug mode enabled, CORS misconfigured, insecure defaults | Medium |
Common vulnerability patterns by language:
Python:
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
JavaScript:
element.innerHTML = userInput;
element.textContent = userInput;
Go:
exec.Command("sh", "-c", "ls " + userInput)
exec.Command("ls", userInput)
Dimension 4: Maintainability
Assess how easy the code is to understand, modify, and extend:
| Aspect | Good Sign | Bad Sign |
|---|
| Coupling | Clear interfaces, dependency injection | Direct imports across modules, global state |
| Cohesion | Each module has a single purpose | Modules with unrelated functionality |
| Abstraction | Appropriate level, no leaky abstractions | Over-abstracted or under-abstracted |
| Testability | Pure functions, clear inputs/outputs | Hidden state, external dependencies everywhere |
| DRY | Shared logic extracted | Copy-pasted code with minor variations |
| Error paths | All errors handled explicitly | Errors silently swallowed or ignored |
Red flags for maintainability:
- Functions that do too many things (violating Single Responsibility)
- Deep inheritance hierarchies
- Circular dependencies between modules
- God classes with too many methods
- Magic numbers and hardcoded values without named constants
Dimension 5: Performance
Identify potential performance issues:
| Pattern | Issue | Suggestion |
|---|
| N+1 queries | Database query in a loop | Batch queries or use eager loading |
| Synchronous I/O in handlers | Blocking the event loop | Use async I/O |
| Unbounded collections | Memory growth without limit | Add pagination or streaming |
| Redundant computation | Same result computed multiple times | Cache or memoize results |
| Inefficient data structures | O(n) lookups with lists | Use sets/dicts for O(1) lookups |
| Unnecessary serialization | Serialize-deserialize cycles | Pass objects directly when possible |
Phase 3: Prioritize Findings
Not all findings are equally important. Prioritize using this framework:
| Priority | Label | Criteria |
|---|
| P0 | Critical | Security vulnerabilities, data loss risk, breaking bugs |
| P1 | High | Performance bottlenecks, significant maintainability issues |
| P2 | Medium | Style inconsistencies, moderate complexity, missing docs |
| P3 | Low | Minor style preferences, optimization opportunities |
Phase 4: Generate Report
Output Format
ALWAYS use this exact structure for the analysis report:
# Code Quality Analysis Report
## Summary
| Dimension | Score | Status |
|-----------|-------|--------|
| Style & Consistency | [A-F] | [emoji indicator] |
| Complexity | [A-F] | [emoji indicator] |
| Security | [A-F] | [emoji indicator] |
| Maintainability | [A-F] | [emoji indicator] |
| Performance | [A-F] | [emoji indicator] |
**Overall Grade: [A-F]**
## Critical Issues (P0)
### [Issue Title]
**Location**: `file:line`
**Category**: Security | Complexity | etc.
**Impact**: [What happens if this isn't fixed]
**Current Code:**
```language
// problematic code
Recommended Fix:
// improved code
Explanation: [Why this is a problem and how the fix addresses it]
High Priority Issues (P1)
[Same format as P0]
Medium Priority Issues (P2)
[Brief format — one paragraph per issue with file location and suggestion]
Low Priority Suggestions (P3)
[One-line suggestions with file location]
Positive Findings
[List things the code does well — this is important for balanced feedback]
Refactoring Recommendations
[Suggested structural changes, if any, with rationale]
### Grading Scale
| Grade | Meaning |
|-------|---------|
| A | Excellent — minimal issues, follows best practices |
| B | Good — minor issues only, easy to address |
| C | Acceptable — some issues that should be addressed |
| D | Needs work — significant issues affecting quality |
| F | Critical — major problems requiring immediate attention |
## Example Interactions
### Example 1: Single File Analysis
**User**: "帮我分析一下这个 Python 文件的代码质量"
**Agent approach**:
1. Read the file content
2. Analyze across all five dimensions
3. Calculate complexity metrics
4. Check for security patterns
5. Generate structured report with grade
### Example 2: Focused Analysis
**User**: "这段代码有没有安全问题?"
**Agent approach**:
1. Focus primarily on the Security dimension
2. Scan for vulnerability patterns specific to the language
3. Provide critical and high findings first
4. Still do a quick check of other dimensions for anything obviously related
### Example 3: Project-Level Analysis
**User**: "评估一下这个项目的代码质量"
**Agent approach**:
1. Explore project structure first
2. Identify entry points and core modules
3. Analyze representative files from each module
4. Look for cross-cutting concerns (consistent error handling, logging patterns)
5. Check dependency manifest for known issues
6. Provide project-level summary with module-specific findings
## Tool Usage Patterns
When analyzing code, use these tools effectively:
| Task | Tool | Usage |
|------|------|-------|
| Read source files | `read_file` | Read individual files for detailed analysis |
| Search patterns | `search_code` | Find patterns across the codebase (e.g., all SQL queries) |
| Count metrics | `execute_command` | Use grep/wc/find for quantitative metrics |
| Check dependencies | `read_file` | Read package.json, requirements.txt, go.sum |
| Run static analysis | `execute_command` | Run linters (eslint, flake8, go vet) if available |
## Notes
- Always provide **specific, actionable** feedback — not vague statements like "this could be improved"
- Include **positive findings** — tell the developer what they're doing well, not just what's wrong
- Prioritize by **impact** — a security vulnerability is more important than a style inconsistency
- Consider the **context** — a quick script has different quality expectations than a production service
- Be **language-aware** — different languages have different conventions and best practices
- When uncertain about a finding's severity, explain the **trade-offs** rather than making a hard recommendation
- For large codebases, suggest a **phased approach** — fix critical issues first, then improve incrementally
- Reference specific **industry standards** where applicable (OWASP for security, PEP 8 for Python, etc.)