Code Quality Checker
Analyzes Done implementation tasks with quantitative Code Quality Score based on metrics, MCP Ref validation, and issue penalties.
Purpose & Scope
- Load Story and Done implementation tasks (exclude test tasks)
- Calculate Code Quality Score using metrics and issue penalties
- MCP Ref validation: Verify optimality, best practices, and performance via external sources
- Check for DRY/KISS/YAGNI violations, architecture boundary breaks, security issues
- Produce quantitative verdict with structured issue list; never edits Linear or kanban
Code Metrics
| Metric |
Threshold |
Penalty |
| Cyclomatic Complexity |
≤10 OK, 11-20 warning, >20 fail |
-5 (warning), -10 (fail) per function |
| Function size |
≤50 lines OK, >50 warning |
-3 per function |
| File size |
≤500 lines OK, >500 warning |
-5 per file |
| Nesting depth |
≤3 OK, >3 warning |
-3 per instance |
| Parameter count |
≤4 OK, >4 warning |
-2 per function |
Code Quality Score
Formula: Code Quality Score = 100 - metric_penalties - issue_penalties
Issue penalties by severity:
| Severity |
Penalty |
Examples |
| high |
-20 |
Security vulnerability, O(n²)+ algorithm, N+1 query |
| medium |
-10 |
DRY violation, suboptimal approach, missing config |
| low |
-3 |
Naming convention, minor code smell |
Score interpretation:
| Score |
Status |
Verdict |
| 90-100 |
Excellent |
PASS |
| 70-89 |
Acceptable |
CONCERNS |
| <70 |
Below threshold |
ISSUES_FOUND |
Issue Prefixes
| Prefix |
Category |
Default Severity |
MCP Ref |
| SEC- |
Security (auth, validation, secrets) |
high |
— |
| PERF- |
Performance (algorithms, configs, bottlenecks) |
medium/high |
✓ Required |
| MNT- |
Maintainability (DRY, SOLID, complexity, dead code) |
medium |
— |
| ARCH- |
Architecture (layers, boundaries, patterns) |
medium |
— |
| BP- |
Best Practices (implementation differs from recommended) |
medium |
✓ Required |
| OPT- |
Optimality (better approach exists for this goal) |
medium |
✓ Required |
PERF- subcategories:
| Prefix |
Category |
Severity |
| PERF-ALG- |
Algorithm complexity (Big O) |
high if O(n²)+ |
| PERF-CFG- |
Package/library configuration |
medium |
| PERF-PTN- |
Architectural pattern performance |
high |
| PERF-DB- |
Database queries, indexes |
high |
MNT- subcategories:
| Prefix |
Category |
Severity |
| MNT-DC- |
Dead code: replaced implementations, unused exports/re-exports, backward-compat wrappers, deprecated aliases |
medium (high if public API) |
| MNT-DRY- |
DRY violations: duplicate logic across files |
medium |
When to Use
- Invoked by ln-500-story-quality-gate Pass 1 (first gate)
- All implementation tasks in Story status = Done
- Before regression testing (ln-503) and test planning (ln-510)
Workflow (concise)
- Load Story (full) and Done implementation tasks (full descriptions) via Linear; skip tasks with label "tests".
- Collect affected files from tasks (Affected Components/Existing Code Impact) and recent commits/diffs if noted.
- Calculate code metrics:
- Cyclomatic Complexity per function (target ≤10)
- Function size (target ≤50 lines)
- File size (target ≤500 lines)
- Nesting depth (target ≤3)
- Parameter count (target ≤4)
3.5) MCP Ref Validation (MANDATORY for code changes):
Level 1 — OPTIMALITY (OPT-):
- Extract goal from task (e.g., "user authentication", "caching", "API rate limiting")
- Research alternatives:
ref_search_documentation("{goal} approaches comparison {tech_stack} 2026")
- Compare chosen approach vs alternatives for project context
- Flag suboptimal choices as OPT- issues
Level 2 — BEST PRACTICES (BP-):
- Research:
ref_search_documentation("{chosen_approach} best practices {tech_stack} 2026")
- For libraries:
query-docs(library_id, "best practices implementation patterns")
- Flag deviations from recommended patterns as BP- issues
Level 3 — PERFORMANCE (PERF-):
- PERF-ALG: Analyze algorithm complexity (detect O(n²)+, research optimal via MCP Ref)
- PERF-CFG: Check library configs (connection pooling, batch sizes, timeouts) via
query-docs
- PERF-PTN: Research pattern pitfalls:
ref_search_documentation("{pattern} performance bottlenecks")
- PERF-DB: Check for N+1, missing indexes via
query-docs(orm_library_id, "query optimization")
Triggers for MCP Ref validation:
- New dependency added (package.json/requirements.txt changed)
- New pattern/library used
- API/database changes
- Loops/recursion in critical paths
- ORM queries added
Analyze code for static issues (assign prefixes):
- SEC-: hardcoded creds, unvalidated input, SQL injection, race conditions
- MNT-: DRY violations (MNT-DRY: duplicate logic), dead code (MNT-DC: per
shared/references/clean_code_checklist.md — 4 categories: unreachable, unused, commented-out, backward-compat), complex conditionals, poor naming
- ARCH-: layer violations, circular dependencies, guide non-compliance
Calculate Code Quality Score:
- Start with 100
- Subtract metric penalties (see Code Metrics table)
- Subtract issue penalties (see Issue penalties table)
Output verdict with score and structured issues. Add Linear comment with findings.
Agent Review (Delegated to ln-502):
Invoke Skill(skill="ln-502-agent-reviewer", args="{storyId}").
- ln-502 loads Story/Done Tasks from Linear, materializes content to
.agent-review/ files, runs agents, cleans up.
- Merge returned suggestions into issues list (same prefixes: SEC-, PERF-, MNT-, ARCH-, BP-, OPT-).
- If verdict =
SUGGESTIONS with area=security or area=correctness → escalate PASS → CONCERNS.
- If verdict =
SKIPPED → Self-Review fallback (native Claude reviews code).
- Display: agent stats from ln-502 output.
Critical Rules
- Read guides mentioned in Story/Tasks before judging compliance.
- MCP Ref validation: For ANY architectural change, MUST verify via ref_search_documentation before judging.
- Context7 for libraries: When reviewing library usage, query-docs to verify correct patterns.
- Language preservation in comments (EN/RU).
- Do not create tasks or change statuses; caller decides next actions.
Definition of Done
- Story and Done implementation tasks loaded (test tasks excluded).
- Code metrics calculated (Cyclomatic Complexity, function/file sizes).
- MCP Ref validation completed:
- OPT-: Optimality checked (is chosen approach the best for the goal?)
- BP-: Best practices verified (correct implementation of chosen approach?)
- PERF-: Performance analyzed (algorithms, configs, patterns, DB)
- Issues identified with prefixes and severity, sources from MCP Ref/Context7.
- Code Quality Score calculated.
- Agent review: ln-502 invoked; suggestions merged into issues (or SKIPPED/Self-Review fallback).
- Output format:
verdict: PASS | CONCERNS | ISSUES_FOUND
code_quality_score: {0-100}
metrics:
avg_cyclomatic_complexity: {value}
functions_over_50_lines: {count}
files_over_500_lines: {count}
issues:
# OPTIMALITY
- id: "OPT-001"
severity: medium
file: "src/auth/index.ts"
goal: "User session management"
finding: "Suboptimal approach for session management"
chosen: "Custom JWT with localStorage"
recommended: "httpOnly cookies + refresh token rotation"
reason: "httpOnly cookies prevent XSS token theft"
source: "ref://owasp-session-management"
# BEST PRACTICES
- id: "BP-001"
severity: medium
file: "src/api/routes.ts"
finding: "POST for idempotent operation"
best_practice: "Use PUT for idempotent updates (RFC 7231)"
source: "ref://api-design-guide#idempotency"
# PERFORMANCE - Algorithm
- id: "PERF-ALG-001"
severity: high
file: "src/utils/search.ts:42"
finding: "Nested loops cause O(n²) complexity"
current: "O(n²) - nested filter().find()"
optimal: "O(n) - use Map/Set for lookup"
source: "ref://javascript-performance#data-structures"
# PERFORMANCE - Config
- id: "PERF-CFG-001"
severity: medium
file: "src/db/connection.ts"
finding: "Missing connection pool config"
current_config: "default (pool: undefined)"
recommended: "pool: { min: 2, max: 10 }"
source: "context7://pg#connection-pooling"
# PERFORMANCE - Database
- id: "PERF-DB-001"
severity: high
file: "src/repositories/user.ts:89"
finding: "N+1 query pattern detected"
issue: "users.map(u => u.posts) triggers N queries"
solution: "Use eager loading: include: { posts: true }"
source: "context7://prisma#eager-loading"
# MAINTAINABILITY - Dead Code
- id: "MNT-DC-001"
severity: medium
file: "src/auth/legacy-adapter.ts"
finding: "Backward-compatibility wrapper kept after migration"
dead_code: "legacyLogin() wraps newLogin() — callers already migrated"
action: "Delete legacy-adapter.ts, remove re-export from index.ts"
# MAINTAINABILITY - DRY
- id: "MNT-DRY-001"
severity: medium
file: "src/service.ts:42"
finding: "DRY violation: duplicate validation logic"
suggested_action: "Extract to shared validator"
- Linear comment posted with findings.
Reference Files
- Code metrics:
references/code_metrics.md (thresholds and penalties)
- Guides:
docs/guides/
- Templates for context:
shared/templates/task_template_implementation.md
- Agent review prompt:
shared/agents/prompt_templates/code_review.md
- Agent review schema:
shared/agents/schemas/code_review_schema.json
- Clean code checklist:
shared/references/clean_code_checklist.md
- Agent delegation:
shared/references/agent_delegation_pattern.md
Version: 5.0.0 (Added 3-level MCP Ref validation: Optimality, Best Practices, Performance with PERF-ALG/CFG/PTN/DB subcategories)
Last Updated: 2026-01-29
1---2name: ln-501-code-quality-checker3description: Worker that checks DRY/KISS/YAGNI/architecture compliance with quantitative Code Quality Score. Validates architectural decisions via MCP Ref: (1) Optimality - is chosen approach the best? (2) Compliance - does it follow best practices? (3) Performance - algorithms, configs, bottlenecks. Reports issues with SEC-, PERF-, MNT-, ARCH-, BP-, OPT- prefixes.4---56# Code Quality Checker78Analyzes Done implementation tasks with quantitative Code Quality Score based on metrics, MCP Ref validation, and issue penalties.910## Purpose & Scope11- Load Story and Done implementation tasks (exclude test tasks)12- Calculate Code Quality Score using metrics and issue penalties13- **MCP Ref validation:** Verify optimality, best practices, and performance via external sources14- Check for DRY/KISS/YAGNI violations, architecture boundary breaks, security issues15- Produce quantitative verdict with structured issue list; never edits Linear or kanban1617## Code Metrics1819| Metric | Threshold | Penalty |20|--------|-----------|---------|21| **Cyclomatic Complexity** | ≤10 OK, 11-20 warning, >20 fail | -5 (warning), -10 (fail) per function |22| **Function size** | ≤50 lines OK, >50 warning | -3 per function |23| **File size** | ≤500 lines OK, >500 warning | -5 per file |24| **Nesting depth** | ≤3 OK, >3 warning | -3 per instance |25| **Parameter count** | ≤4 OK, >4 warning | -2 per function |2627## Code Quality Score2829Formula: `Code Quality Score = 100 - metric_penalties - issue_penalties`3031**Issue penalties by severity:**3233| Severity | Penalty | Examples |34|----------|---------|----------|35| **high** | -20 | Security vulnerability, O(n²)+ algorithm, N+1 query |36| **medium** | -10 | DRY violation, suboptimal approach, missing config |37| **low** | -3 | Naming convention, minor code smell |3839**Score interpretation:**4041| Score | Status | Verdict |42|-------|--------|---------|43| 90-100 | Excellent | PASS |44| 70-89 | Acceptable | CONCERNS |45| <70 | Below threshold | ISSUES_FOUND |4647## Issue Prefixes4849| Prefix | Category | Default Severity | MCP Ref |50|--------|----------|------------------|---------|51| SEC- | Security (auth, validation, secrets) | high | — |52| PERF- | Performance (algorithms, configs, bottlenecks) | medium/high | ✓ Required |53| MNT- | Maintainability (DRY, SOLID, complexity, dead code) | medium | — |54| ARCH- | Architecture (layers, boundaries, patterns) | medium | — |55| BP- | Best Practices (implementation differs from recommended) | medium | ✓ Required |56| OPT- | Optimality (better approach exists for this goal) | medium | ✓ Required |5758**PERF- subcategories:**5960| Prefix | Category | Severity |61|--------|----------|----------|62| PERF-ALG- | Algorithm complexity (Big O) | high if O(n²)+ |63| PERF-CFG- | Package/library configuration | medium |64| PERF-PTN- | Architectural pattern performance | high |65| PERF-DB- | Database queries, indexes | high |6667**MNT- subcategories:**6869| Prefix | Category | Severity |70|--------|----------|----------|71| MNT-DC- | Dead code: replaced implementations, unused exports/re-exports, backward-compat wrappers, deprecated aliases | medium (high if public API) |72| MNT-DRY- | DRY violations: duplicate logic across files | medium |7374## When to Use75- **Invoked by ln-500-story-quality-gate** Pass 1 (first gate)76- All implementation tasks in Story status = Done77- Before regression testing (ln-503) and test planning (ln-510)787980## Workflow (concise)811) Load Story (full) and Done implementation tasks (full descriptions) via Linear; skip tasks with label "tests".822) Collect affected files from tasks (Affected Components/Existing Code Impact) and recent commits/diffs if noted.833) **Calculate code metrics:**84 - Cyclomatic Complexity per function (target ≤10)85 - Function size (target ≤50 lines)86 - File size (target ≤500 lines)87 - Nesting depth (target ≤3)88 - Parameter count (target ≤4)89903.5) **MCP Ref Validation (MANDATORY for code changes):**9192 **Level 1 — OPTIMALITY (OPT-):**93 - Extract goal from task (e.g., "user authentication", "caching", "API rate limiting")94 - Research alternatives: `ref_search_documentation("{goal} approaches comparison {tech_stack} 2026")`95 - Compare chosen approach vs alternatives for project context96 - Flag suboptimal choices as OPT- issues9798 **Level 2 — BEST PRACTICES (BP-):**99 - Research: `ref_search_documentation("{chosen_approach} best practices {tech_stack} 2026")`100 - For libraries: `query-docs(library_id, "best practices implementation patterns")`101 - Flag deviations from recommended patterns as BP- issues102103 **Level 3 — PERFORMANCE (PERF-):**104 - **PERF-ALG:** Analyze algorithm complexity (detect O(n²)+, research optimal via MCP Ref)105 - **PERF-CFG:** Check library configs (connection pooling, batch sizes, timeouts) via `query-docs`106 - **PERF-PTN:** Research pattern pitfalls: `ref_search_documentation("{pattern} performance bottlenecks")`107 - **PERF-DB:** Check for N+1, missing indexes via `query-docs(orm_library_id, "query optimization")`108109 **Triggers for MCP Ref validation:**110 - New dependency added (package.json/requirements.txt changed)111 - New pattern/library used112 - API/database changes113 - Loops/recursion in critical paths114 - ORM queries added1151164) **Analyze code for static issues (assign prefixes):**117 - SEC-: hardcoded creds, unvalidated input, SQL injection, race conditions118 - MNT-: DRY violations (MNT-DRY: duplicate logic), dead code (MNT-DC: per `shared/references/clean_code_checklist.md` — 4 categories: unreachable, unused, commented-out, backward-compat), complex conditionals, poor naming119 - ARCH-: layer violations, circular dependencies, guide non-compliance1201215) **Calculate Code Quality Score:**122 - Start with 100123 - Subtract metric penalties (see Code Metrics table)124 - Subtract issue penalties (see Issue penalties table)1251266) Output verdict with score and structured issues. Add Linear comment with findings.1277) **Agent Review (Delegated to ln-502):**128 Invoke `Skill(skill="ln-502-agent-reviewer", args="{storyId}")`.129 - ln-502 loads Story/Done Tasks from Linear, materializes content to `.agent-review/` files, runs agents, cleans up.130 - Merge returned suggestions into issues list (same prefixes: SEC-, PERF-, MNT-, ARCH-, BP-, OPT-).131 - If verdict = `SUGGESTIONS` with `area=security` or `area=correctness` → escalate PASS → CONCERNS.132 - If verdict = `SKIPPED` → Self-Review fallback (native Claude reviews code).133 - **Display:** agent stats from ln-502 output.134135## Critical Rules136- Read guides mentioned in Story/Tasks before judging compliance.137- **MCP Ref validation:** For ANY architectural change, MUST verify via ref_search_documentation before judging.138- **Context7 for libraries:** When reviewing library usage, query-docs to verify correct patterns.139- Language preservation in comments (EN/RU).140- Do not create tasks or change statuses; caller decides next actions.141142## Definition of Done143- Story and Done implementation tasks loaded (test tasks excluded).144- Code metrics calculated (Cyclomatic Complexity, function/file sizes).145- **MCP Ref validation completed:**146 - OPT-: Optimality checked (is chosen approach the best for the goal?)147 - BP-: Best practices verified (correct implementation of chosen approach?)148 - PERF-: Performance analyzed (algorithms, configs, patterns, DB)149- Issues identified with prefixes and severity, sources from MCP Ref/Context7.150- Code Quality Score calculated.151- Agent review: ln-502 invoked; suggestions merged into issues (or SKIPPED/Self-Review fallback).152- **Output format:**153 ```yaml154 verdict: PASS | CONCERNS | ISSUES_FOUND155 code_quality_score: {0-100}156 metrics:157 avg_cyclomatic_complexity: {value}158 functions_over_50_lines: {count}159 files_over_500_lines: {count}160 issues:161 # OPTIMALITY162 - id: "OPT-001"163 severity: medium164 file: "src/auth/index.ts"165 goal: "User session management"166 finding: "Suboptimal approach for session management"167 chosen: "Custom JWT with localStorage"168 recommended: "httpOnly cookies + refresh token rotation"169 reason: "httpOnly cookies prevent XSS token theft"170 source: "ref://owasp-session-management"171172 # BEST PRACTICES173 - id: "BP-001"174 severity: medium175 file: "src/api/routes.ts"176 finding: "POST for idempotent operation"177 best_practice: "Use PUT for idempotent updates (RFC 7231)"178 source: "ref://api-design-guide#idempotency"179180 # PERFORMANCE - Algorithm181 - id: "PERF-ALG-001"182 severity: high183 file: "src/utils/search.ts:42"184 finding: "Nested loops cause O(n²) complexity"185 current: "O(n²) - nested filter().find()"186 optimal: "O(n) - use Map/Set for lookup"187 source: "ref://javascript-performance#data-structures"188189 # PERFORMANCE - Config190 - id: "PERF-CFG-001"191 severity: medium192 file: "src/db/connection.ts"193 finding: "Missing connection pool config"194 current_config: "default (pool: undefined)"195 recommended: "pool: { min: 2, max: 10 }"196 source: "context7://pg#connection-pooling"197198 # PERFORMANCE - Database199 - id: "PERF-DB-001"200 severity: high201 file: "src/repositories/user.ts:89"202 finding: "N+1 query pattern detected"203 issue: "users.map(u => u.posts) triggers N queries"204 solution: "Use eager loading: include: { posts: true }"205 source: "context7://prisma#eager-loading"206207 # MAINTAINABILITY - Dead Code208 - id: "MNT-DC-001"209 severity: medium210 file: "src/auth/legacy-adapter.ts"211 finding: "Backward-compatibility wrapper kept after migration"212 dead_code: "legacyLogin() wraps newLogin() — callers already migrated"213 action: "Delete legacy-adapter.ts, remove re-export from index.ts"214215 # MAINTAINABILITY - DRY216 - id: "MNT-DRY-001"217 severity: medium218 file: "src/service.ts:42"219 finding: "DRY violation: duplicate validation logic"220 suggested_action: "Extract to shared validator"221 ```222- Linear comment posted with findings.223224## Reference Files225- Code metrics: `references/code_metrics.md` (thresholds and penalties)226- Guides: `docs/guides/`227- Templates for context: `shared/templates/task_template_implementation.md`228- Agent review prompt: `shared/agents/prompt_templates/code_review.md`229- Agent review schema: `shared/agents/schemas/code_review_schema.json`230- **Clean code checklist:** `shared/references/clean_code_checklist.md`231- Agent delegation: `shared/references/agent_delegation_pattern.md`232233---234**Version:** 5.0.0 (Added 3-level MCP Ref validation: Optimality, Best Practices, Performance with PERF-ALG/CFG/PTN/DB subcategories)235**Last Updated:** 2026-01-29