Catch bugs before they catch you. AI-powered code review for your uncommitted changes.

GitHub stars
50

Install

/plugin install turingmind@turingmind

Run it inside Claude Code after adding the marketplace with /plugin marketplace add turingmindai/turingmind-code-review.

Contents

Discovered from source

Commands 2

Comprehensive code review with full context analysis. Includes architecture review, test coverage, and impact analysis.

Phase 1: Gather Context (3 Parallel Haiku Agents)

Agent 1A - Change Summary:

1. Run `git status`, `git diff`, `git diff --staged`
2. If no changes β†’ inform user and stop
3. Extract:
   - Files changed (list)
   - Languages detected (from extensions)
   - Line counts (additions/deletions)

Agent 1B - Project Context:

1. Find CLAUDE.md (root + directories with changes)
2. Read dependency files:
   - package.json / requirements.txt / go.mod / Cargo.toml
3. Identify project type and framework

Agent 1C - Related Files:

For each modified file, find:
- Files that import the modified file
- Files that the modified file imports
- Test files (foo.ts β†’ foo.test.ts)

Phase 2: Load Agents (Progressive)

Only load agents relevant to detected context:

ConditionLoad Agent
Always@agents/bugs.md
Always@agents/security.md
Always (deep)@agents/architecture.md
CLAUDE.md exists@agents/compliance.md
.ts/.tsx/.js/.jsx files@agents/language-typescript.md
.py files@agents/language-python.md

See @agents/index.md for full routing logic.

Phase 3: Deep Analysis (Parallel Sonnet Agents)

Launch loaded agents in parallel. Each agent:

  1. Reads full file context + related files from Phase 1C
  2. Analyzes only the diff (not pre-existing code)
  3. Returns structured issues with diff-style fixes

Core Agents (always):

  • @agents/bugs.md - Logic errors, null access, race conditions
  • @agents/security.md - OWASP Top 10, injection, XSS, secrets
  • @agents/architecture.md - Patterns, coupling, dependencies

Conditional Agents:

  • @agents/compliance.md - If CLAUDE.md exists
  • @agents/language-typescript.md - If TS/JS files
  • @agents/language-python.md - If Python files

Additional Deep Analysis:

  • Tests & Documentation Agent:
    • Do test files exist for modified code?
    • Do tests need updating for this change?
    • Are new public APIs missing tests?
    • Do README/docs need updates?

Phase 4: Impact Analysis (Sonnet Agent)

Using Phase 1C results, analyze:

  • What other parts of codebase could be affected?
  • Are there breaking changes to public APIs?
  • Could this affect performance at scale?
  • Are there database/schema implications?
  • What's the blast radius if this has a bug?

Phase 5: Score & Filter (Haiku Agents)

For each issue, score confidence 0-100:

FactorPoints
In the diff (new code)+20
Would cause failure+30
In CLAUDE.md rules+20
Senior engineer would flag+20
Has ignore comment-50

Apply filters from @templates/false-positive-rules.md:

  • Filter issues with score < 70 (lower threshold for deep review)
  • Track filtered count by reason

Phase 6: Present Results

Format output using @templates/output-format.md:

## Deep Code Review

**Summary:** Reviewed X files, Y lines changed

| Found | Reported | Filtered |
|-------|----------|----------|
| total | β‰₯70 score | <70 score |

### Critical (95-100) πŸ”΄
[Issues with diff-style fixes]

### Warning (80-94) 🟠  
[Issues with diff-style fixes]

### Medium (70-79) 🟑
[Issues with diff-style fixes]

### Filtered Issues πŸ”‡
[Count by reason, expandable details]

### Architectural Notes πŸ“
- Pattern consistency: βœ…/⚠️/❌
- Test coverage: βœ…/⚠️/❌
- Documentation: βœ…/⚠️/❌
- Dependencies: βœ…/⚠️/❌

### Impact Analysis πŸ’₯
- Affected files: [list]
- Blast radius: [scope]
- Breaking changes: [yes/no]

Differences from Quick Review

AspectQuick ReviewDeep Review
Thresholdβ‰₯80β‰₯70
ArchitectureβŒβœ…
Impact AnalysisβŒβœ…
Test CoverageβŒβœ…
Related FilesβŒβœ…
Medium PriorityβŒβœ…

Quick code review for uncommitted changes. Fast, focused on critical issues.

Step 1: Gather Context (Haiku Agent)

Detect what needs to be reviewed:

1. Run `git status` and `git diff` / `git diff --staged`
2. If no changes β†’ inform user and stop
3. Extract:
   - Files changed (list)
   - Languages detected (from extensions)
   - Line counts (additions/deletions)
   - Has CLAUDE.md? (root or in changed directories)

Step 2: Load Agents (Progressive)

Only load agents relevant to detected context:

ConditionLoad Agent
Always@agents/bugs.md
Always@agents/security.md
CLAUDE.md exists@agents/compliance.md
.ts/.tsx/.js/.jsx files@agents/language-typescript.md
.py files@agents/language-python.md

See @agents/index.md for full routing logic.

Step 3: Run Review (Parallel Sonnet Agents)

Launch loaded agents in parallel. Each agent:

  1. Reads full file context for changed files
  2. Analyzes only the diff (not pre-existing code)
  3. Returns structured issues with diff-style fixes

Output format per agent (see @agents/bugs.md for example):

### πŸ› {{issue_title}}
**Location:** `{{file}}:{{line}}`
**Confidence:** {{score}}/100

**Problem:** {{reason}}

**Suggested Fix:**
```diff
- {{old_code}}
+ {{new_code}}

## Step 4: Score & Filter (Haiku Agents)

For each issue, score confidence 0-100:

| Factor | Points |
|--------|--------|
| In the diff (new code) | +20 |
| Would cause failure | +30 |
| In CLAUDE.md rules | +20 |
| Senior engineer would flag | +20 |
| Has ignore comment | -50 |

Apply filters from `@templates/false-positive-rules.md`:
- Filter issues with score < 80
- Track filtered count by reason

## Step 5: Present Results

Format output using `@templates/output-format.md`:

Code Review

Summary: Reviewed X files, Y lines changed

FoundReportedFiltered
totalβ‰₯80 score<80 score

Critical (95-100) πŸ”΄

[Issues with diff-style fixes]

Warning (80-94) 🟠

[Issues with diff-style fixes]

Filtered Issues πŸ”‡

[Count by reason, expandable details]


## Output Rules

- **Always** include filtered issues summary (builds trust)
- **Always** use diff-style fixes (actionable)
- **Never** report pre-existing issues (not in diff)
- **Never** report linter territory (ESLint will catch)
- If no issues found, confirm code looks good for commit

Agents 7

Analyze architectural implications of changes. Requires related file context.

Context Required

  • Files that import the modified files
  • Files that the modified files import
  • Existing patterns in the codebase

Checks

Pattern Consistency

  • Does this follow existing patterns in the codebase?
  • Are similar problems solved differently elsewhere?

Abstraction

  • Are there abstraction violations (reaching into private internals)?
  • Is there inappropriate coupling between modules?

Duplication

  • Is there code that should be extracted to shared utilities?
  • Are there near-duplicates that could be consolidated?

Dependencies

  • Are new dependencies justified?
  • Are there circular dependencies introduced?

Separation of Concerns

  • Is business logic mixed with infrastructure?
  • Are there layering violations?

Output

Return observations (not necessarily issues):

  • type: pattern | abstraction | duplication | dependency | separation
  • observation: What was noticed
  • severity: issue | suggestion | note
  • recommendation: What to consider (if applicable)

Focus on significant bugs that would cause runtime failures. Avoid nitpicks.

Checks

  • Null/Undefined Access: Missing guards before accessing properties
  • Off-by-One Errors: Incorrect loop bounds, slice indices
  • Race Conditions: Concurrent access without synchronization
  • Resource Leaks: Unclosed files, connections, subscriptions, event listeners
  • Error Handling Gaps: Unhandled promise rejections, swallowed exceptions
  • Infinite Loops: Missing base cases, unreachable break conditions
  • State Mutation: Unexpected side effects, mutating shared state

Output Format

For each issue, return structured output with diff-style fix:

### πŸ› {{issue_title}}

**Location:** `{{file}}:{{line}}`
**Confidence:** {{score}}/100

**Problem:**
{{reason}}

**Current Code:**
```{{language}}
{{problematic_code}}

Suggested Fix:

- {{old_line}}
+ {{new_line}}

Why this fix works: {{explanation}}


## Example Output

### πŸ› Null reference on user object

**Location:** `src/api/users.ts:45`
**Confidence:** 95/100

**Problem:**
Accessing `user.email` without null check. Will throw if `findUser` returns null.

**Current Code:**
```typescript
const user = await findUser(id);
sendEmail(user.email);  // πŸ’₯ Throws if user is null

Suggested Fix:

  const user = await findUser(id);
+ if (!user) {
+   throw new NotFoundError(`User ${id} not found`);
+ }
  sendEmail(user.email);

Why this fix works: Early return with explicit error prevents runtime crash and provides meaningful error message.

Check adherence to project guidelines defined in CLAUDE.md files.

Context Required

  • Root CLAUDE.md
  • Directory-specific CLAUDE.md files for modified paths

Instructions

  1. Parse CLAUDE.md for actionable coding guidelines
  2. Note: CLAUDE.md is guidance for Claude writing code, so not all instructions apply to review
  3. Focus on rules that would cause issues if violated:
    • Required patterns (e.g., "always use X for Y")
    • Prohibited patterns (e.g., "never use Z")
    • Naming conventions
    • Error handling style
    • Logging/observability requirements

Output

For each violation, return:

  • file: File path
  • line: Line number
  • rule: The CLAUDE.md rule being violated (quote it)
  • violation: What the code does wrong
  • fix: How to comply

Agent Router

This file helps select the right agents based on the code being reviewed. Only load agents that are relevant to reduce context and improve accuracy.

Agent Selection Matrix

DetectedLoad Agents
Any code@agents/bugs.md, @agents/security.md
Has CLAUDE.md@agents/compliance.md
TypeScript/JavaScript@agents/language-typescript.md
Python@agents/language-python.md
Deep review mode@agents/architecture.md

Core Agents (Always Load)

These agents apply to all code reviews:

  1. bugs.md - Logic errors, null access, race conditions
  2. security.md - OWASP Top 10, injection, XSS, secrets

Conditional Agents (Load When Relevant)

Compliance Agent

Load when: CLAUDE.md exists in project root or modified directories

@agents/compliance.md

Language Agents

Load based on file extensions detected in diff:

ExtensionsAgent
.ts, .tsx, .js, .jsx, .mjs@agents/language-typescript.md
.py@agents/language-python.md

Architecture Agent

Load when: Deep review mode (/turingmind-code-review:deep-review)

@agents/architecture.md

Progressive Loading Pattern

Step 1: Detect languages from git diff
        └─ Extract file extensions from changed files

Step 2: Check for CLAUDE.md
        └─ Look in root and directories with changes

Step 3: Load minimum required agents
        └─ Core: bugs + security (always)
        └─ Language: based on Step 1
        └─ Compliance: if Step 2 found CLAUDE.md
        └─ Architecture: only for deep review

Step 4: Run agents in parallel
        └─ Each agent returns structured issues

Step 5: Score and filter
        └─ Apply confidence scoring
        └─ Filter based on threshold

Why Progressive Loading?

ApproachContext SizeAccuracy
Load all agentsLargeLower (noise)
Progressive loadMinimalHigher (focused)

By only loading relevant agents:

  • Faster reviews (less to process)
  • Fewer false positives (no irrelevant checks)
  • Better fixes (language-specific suggestions)

Adding New Agents

To add support for a new language or framework:

  1. Create agents/language-{name}.md or agents/framework-{name}.md
  2. Add entry to the selection matrix above
  3. Update commands/review.md Step 3 with detection logic

Template for new language agent:

---
name: {Language} Issues
model: sonnet
applies_to: ["*.ext"]
---

Language-specific checks for {Language}.

## Checks
- [Check 1]
- [Check 2]

## Output Format
(Use same format as bugs.md with diff-style fixes)

Language-specific checks for Python.

Checks

Type Safety

  • Missing type hints on public function signatures
  • Any type where specific type is known
  • Incorrect Optional handling

Common Pitfalls

  • Mutable default arguments (def foo(x=[]))
  • Bare except: clauses
  • Using is for value comparison
  • Missing if __name__ == "__main__"

Resource Management

  • Missing context managers for files
  • Unclosed connections/cursors
  • Missing finally blocks

Performance

  • String concatenation in loops (use join)
  • Repeated dictionary lookups
  • Loading large files into memory

Output

For each issue, return:

  • file: File path
  • line: Line number
  • issue: Brief description
  • fix: Suggested fix with code

Language-specific checks for TypeScript and JavaScript.

Checks

Type Safety

  • Implicit any types
  • Type assertions without validation (as Type)
  • Missing null checks before property access
  • Non-null assertions (!) without justification

Async/Await

  • Missing try-catch around await
  • Unhandled promise rejections
  • Floating promises (missing await)
  • async function without await

Common Pitfalls

  • == instead of === for non-null checks
  • Mutable default parameters
  • Modifying objects during iteration
  • Missing dependency arrays in hooks

Performance

  • Creating functions/objects in render
  • Missing memoization for expensive computations
  • N+1 queries in loops

Output

For each issue, return:

  • file: File path
  • line: Line number
  • issue: Brief description
  • fix: Suggested fix with code

Check for security vulnerabilities. Focus on issues in the changed code.

Checks

Injection

  • SQL injection (string interpolation in queries)
  • Command injection (user input in exec/spawn)
  • LDAP/XPath injection

XSS

  • Reflected XSS (user input in responses)
  • Stored XSS (unsanitized database content)
  • DOM-based XSS (innerHTML, document.write)

Secrets

  • Hardcoded API keys, passwords, tokens
  • Private keys in source
  • Credentials in comments

Auth

  • Authentication bypass
  • Broken authorization checks
  • Insecure direct object references
  • Missing access control

Data Exposure

  • Sensitive data in logs
  • PII in error messages
  • Verbose stack traces to users

Other

  • Path traversal
  • SSRF (Server-Side Request Forgery)
  • Insecure deserialization
  • Mass assignment vulnerabilities

Output Format

For each issue, return structured output with diff-style fix:

### πŸ” {{issue_title}}

**Location:** `{{file}}:{{line}}`
**Severity:** {{critical|high|medium}} | **CWE:** {{cwe_id}}
**Confidence:** {{score}}/100

**Vulnerability:**
{{description}}

**Current Code:**
```{{language}}
{{vulnerable_code}}

Suggested Fix:

- {{vulnerable_line}}
+ {{secure_line}}

Why this matters: {{impact_explanation}}


## Example Outputs

### πŸ” SQL Injection vulnerability

**Location:** `src/api/auth.ts:23`
**Severity:** critical | **CWE:** CWE-89
**Confidence:** 98/100

**Vulnerability:**
User input directly interpolated into SQL query allows attacker to execute arbitrary SQL.

**Current Code:**
```typescript
const query = `SELECT * FROM users WHERE email = '${email}'`;
const result = await db.query(query);

Suggested Fix:

- const query = `SELECT * FROM users WHERE email = '${email}'`;
- const result = await db.query(query);
+ const query = `SELECT * FROM users WHERE email = $1`;
+ const result = await db.query(query, [email]);

Why this matters: Attacker can input '; DROP TABLE users; -- to delete your database. Parameterized queries prevent this by treating input as data, not code.


πŸ” Hardcoded API key

Location: src/services/payment.ts:12 Severity: critical | CWE: CWE-798 Confidence: 99/100

Vulnerability: API key committed to source code. Anyone with repo access can use your Stripe account.

Current Code:

const stripe = new Stripe('sk_live_abc123xyz');

Suggested Fix:

- const stripe = new Stripe('sk_live_abc123xyz');
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

Also required:

  1. Add to .env: STRIPE_SECRET_KEY=sk_live_abc123xyz
  2. Ensure .env is in .gitignore
  3. Rotate the exposed key immediately

Why this matters: Exposed production keys can lead to unauthorized charges, data theft, and account compromise.

Sponsors

Details

Marketplace
turingmindai/turingmind-code-review
Source
plugins/turingmind
Category
Community