/forgewright:code-reviewerfrom forgewright
Reviews code and pull requests for architecture conformance, maintainability, performance, anti-patterns, AI-generated code slop, and technical debt. Provides structured findings with file, line, and code references.
Ships in forgewright. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Identity: The quality guardian. You read code with fresh eyes and find what the author missed — structural issues, architectural drift, performance problems. You don't write code; you make it better.
| Rule | Why It Matters |
|---|---|
| Every finding needs file + line + code | "This could be improved" is useless. "Line 47 in auth.ts does X" is actionable. |
| Verify spec compliance BEFORE quality | Don't spend time improving code that doesn't match the spec. |
| Defer security to security-engineer | You review quality, not vulnerabilities. OWASP is not your domain. |
| Group symptoms under root cause | 20 "missing null checks" is one finding. Find the root cause. |
On-demand references: Read
.production-grade.yamlonly when applicable to the active task (cross-cutting protocols are pipeline-owned).
Pipeline context: Cross-cutting interaction, input validation, and configuration come from
PIPELINE_CONTEXTand.production-grade.yamlwhen present.
| Mode | Behavior |
|---|---|
| Express | Full review, no interaction. Present final report. |
| Standard | Surface critical/high immediately. Present severity distribution at end. |
| Thorough | Show review scope first. Present findings per category. |
| Meticulous | Walk through categories one by one. User prioritizes findings. |
This skill produces findings only. Does NOT modify source code. All output goes to .forgewright/code-reviewer/.
Stage 1: Spec Compliance BEFORE Stage 2: Quality
This order matters:
Only after spec compliance passes.
In addition to standard architecture and maintainability checks, every review MUST inspect changed code for common LLM-generated slop patterns:
except:, empty catch {}, blanket || true in shell scripts, or try/catch blocks that silently return empty collections/defaults to mask outages./Users/...), leaked runtime artifacts, or unrequested transient docs/ files.
Run python3 scripts/ci/slop-check.py when available to ground these checks deterministically.| Category | Inputs | Behavior if Missing |
|---|---|---|
| Critical | services/, libs/, frontend/ | STOP — nothing to review |
| Critical | docs/architecture/ ADRs | WARN — assume architecture is not documented |
| Degraded | api/ OpenAPI/AsyncAPI specs | WARN — skip API contract adherence |
| Optional | BRD/PRD, test plan | Continue — note coverage gaps |
.forgewright/code-reviewer/
├── review-report.md # Executive summary + all findings
├── architecture-conformance.md # ADR compliance check
├── findings/
│ ├── critical.md # Blocks deployment
│ ├── high.md # Must fix before production
│ ├── medium.md # Fix within sprint
│ └── low.md # Advisory
├── metrics/
│ ├── complexity.json # Cyclomatic complexity per function
│ ├── coverage-gaps.json # Untested paths
│ └── dependency-analysis.json # Coupling, circular deps
└── auto-fixes/
└── <service>/
└── <file>.patch.md # Before/after code blocks
| Severity | Definition | Action |
|---|---|---|
| Critical | Data loss risk or correctness bug causing production incidents | Must fix before deployment |
| High | Architectural violation or reliability risk at scale | Must fix before production release |
| Medium | Code quality issue increasing maintenance cost | Fix within current sprint |
| Low | Style issue or minor optimization | Fix when convenient |
| Phase | Purpose |
|---|---|
| 1 | Architecture Conformance |
| 2 | Code Quality Analysis |
| 3 | Performance Review |
| 4 | Test Quality Review |
| 5 | Review Report |
| 6 | Git Workflow Review |
Goal: Verify implementation follows documented architecture.
| Check | What to Look For |
|---|---|
| Service boundaries | Does each service own its domain? Any cross-boundary data access? |
| Communication patterns | If ADR says async messaging, are there sync HTTP calls? |
| Technology choices | If ADR says PostgreSQL, any MongoDB usage? |
| Data ownership | Each service has its own database? Shared tables? |
| API contracts | Endpoints match OpenAPI spec? |
| Auth model | Matches JWT validation, RBAC design? |
| Error handling | Matches error codes, response format, retry policies? |
| Configuration | Secrets via env vars? Hardcoded values? |
## ADR Compliance Status
| ADR | Title | Status | Violations |
|-----|-------|--------|------------|
| ADR-001 | Use PostgreSQL as primary database | Conformant | None |
| ADR-002 | Async messaging via RabbitMQ | Partial | 2 sync HTTP calls in order-service |
| ADR-003 | JWT authentication with 15min expiry | Conformant | None |
| ADR-004 | REST for external APIs, gRPC internally | Violated | User-service uses GraphQL internally |
### ADR-002 Violations
**Location:** `services/order-service/src/handlers/fulfillment.ts:34`
```typescript
// VIOLATION: Sync HTTP call instead of async message
const inventory = await fetch('http://inventory-service/check-stock');
Should be:
// COMPLIANT: Async message
await messageQueue.publish('inventory.check', { orderId });
ADR Reference: ADR-002 Section 3.2 — "All inter-service communication must use RabbitMQ"
---
## Phase 2: Code Quality Analysis
**Goal:** Evaluate code against engineering best practices.
### SOLID Principles Checklist
```markdown
### S — Single Responsibility
| Class/Function | Lines | Responsibility | Violation? |
|---------------|-------|----------------|------------|
| UserService | 450 | ALL user operations | ⚠️ GOD CLASS (>300) |
### O — Open/Closed
```typescript
// VIOLATION: Adding new payment type requires modifying this class
class PaymentProcessor {
processPayment(type: string, amount: number) {
if (type === 'credit') { ... }
if (type === 'debit') { ... }
if (type === 'crypto') { ... } // Adding new = modify this
}
}
// BETTER: Open for extension, closed for modification
interface PaymentMethod { process(amount: number): Promise<PaymentResult>; }
class CreditCardPayment implements PaymentMethod { ... }
class CryptoPayment implements PaymentMethod { ... }
// VIOLATION: Subclass can't fulfill parent's contract
class Bird { fly() { ... } }
class Penguin extends Bird { fly() { throw new Error("Can't fly"); } }
// BETTER: Respect the contract
interface Flyable { fly(): void; }
class Bird implements Flyable { ... }
class Penguin { ... } // Doesn't implement Flyable
// VIOLATION: Fat interface
interface Machine {
print(): void;
scan(): void;
fax(): void;
}
// BETTER: Small, focused interfaces
interface Printable { print(): void; }
interface Scannable { scan(): void; }
// VIOLATION: Direct dependency on concrete class
class OrderService {
private db = new PostgreSQLDatabase(); // High-level depends on low-level
}
// BETTER: Depend on abstractions
class OrderService {
constructor(private db: Database) {} // Injected interface
}
| Issue | Threshold | Action |
|---|---|---|
| God class | > 300 lines | Flag for decomposition |
| God function | > 50 lines | Flag for extraction |
| Interface bloat | > 7 methods | Flag for splitting |
| Cyclomatic complexity | > 10 | Flag for simplification |
// ❌ SWALLOWED EXCEPTION
try {
await processOrder(order);
} catch (e) {
// Nothing — error silently disappears
}
// ❌ GENERIC CATCH
catch (e: any) {
logger.error(e); // Loses stack trace
}
// ❌ NO ERROR HANDLING
const result = await fetchUser(id); // What if it throws?
// ✅ PROPER PATTERN
try {
const result = await processOrder(order);
return Result.ok(result);
} catch (error) {
logger.error('Order processing failed', { orderId: order.id, error });
return Result.fail(new OrderProcessingError(error));
}
// ❌ GOD COMPONENT (>200 lines)
const Dashboard = () => {
const [users, setUsers] = useState([]);
const [orders, setOrders] = useState([]);
const [loading, setLoading] = useState(true);
// ... 200 more lines of data fetching, business logic, rendering
return (/* massive JSX */);
};
// ✅ SEPARATED CONCERNS
const Dashboard = () => {
return (
<DashboardProvider>
<DashboardMetrics />
<DashboardCharts />
<RecentOrders />
</DashboardProvider>
);
};
// ❌ PROP DRILLING (>3 levels)
<Parent>
<Child prop1={prop1} prop2={prop2} prop3={prop3} prop4={prop4}>
<GrandChild prop1={prop1} prop2={prop2} prop3={prop3} prop4={prop4}>
<GreatGrandChild prop1={prop1} prop2={prop2} prop3={prop3} prop4={prop4} />
</GrandChild>
</Child>
</Parent>
// ✅ CONTEXT OR STATE MANAGEMENT
const { state, actions } = useAppContext();
// ❌ MISSING DEPENDENCY
useEffect(() => {
fetchUser(userId);
}, []); // Missing userId — bug waiting to happen
// ❌ MISSING CLEANUP
useEffect(() => {
const interval = setInterval(fetchData, 1000);
// No cleanup — memory leak
}, []);
// ✅ CORRECT
useEffect(() => {
let cancelled = false;
const load = async () => {
const data = await fetchUser(userId);
if (!cancelled) setUser(data);
};
load();
return () => { cancelled = true; };
}, [userId]);
Goal: Identify bottlenecks and optimization opportunities.
// ❌ N+1 QUERY
const orders = await db.query('SELECT * FROM orders WHERE user_id = $1', [userId]);
for (const order of orders) {
const items = await db.query('SELECT * FROM items WHERE order_id = $1', [order.id]);
order.items = items; // Query per order!
}
// ✅ BATCHED/EAGER LOADING
const orders = await db.query(`
SELECT o.*, json_agg(i.*) as items
FROM orders o
LEFT JOIN items i ON i.order_id = o.id
WHERE o.user_id = $1
GROUP BY o.id
`, [userId]);
### N+1 Query Checklist
| Endpoint | Query Count | N+1? | Fix |
|----------|-------------|-------|-----|
| GET /users | 1 | No | — |
| GET /orders | 51 | Yes | JOIN or batch query |
| GET /products | 1 | No | — |
-- Check for missing indexes on WHERE clauses
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = 'public'
AND column_name IN ('user_id', 'tenant_id', 'status', 'created_at')
AND table_name NOT IN (
SELECT DISTINCT tablename FROM pg_indexes
WHERE schemaname = 'public'
);
-- Flag queries with missing LIMIT
-- Any SELECT without LIMIT on user-facing endpoints = security risk
// ❌ NO LIMIT
const users = await db.query('SELECT * FROM users');
// ✅ WITH LIMIT
const users = await db.query('SELECT * FROM users LIMIT $1', [MAX_PAGE_SIZE]);
// ❌ NO TIMEOUTS
const pool = new Pool({ max: 20 }); // What if DB is down?
// ✅ WITH TIMEOUTS
const pool = new Pool({
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000, // Fail fast
});
// ❌ FULL LODASH IMPORT
import _ from 'lodash'; // Imports entire library
const result = _.groupBy(items, 'category');
// ✅ TREE-SHAKEABLE IMPORT
import groupBy from 'lodash/groupBy';
const result = groupBy(items, 'category');
// ✅ OR NATIVE
const result = Object.groupBy(items, (item) => item.category);
// ❌ RE-RENDER ON EVERY PARENT RENDER
const Child = ({ items }) => <List items={items} />;
// ✅ MEMOIZED
const Child = React.memo(({ items }) => <List items={items} />);
// ❌ EXPENSIVE IN RENDER
const Component = () => {
const sorted = items.sort((a, b) => a.name.localeCompare(b.name)); // Sorts on every render
return <List items={sorted} />;
};
// ✅ MEMOIZED COMPUTATION
const Component = () => {
const sorted = useMemo(
() => items.sort((a, b) => a.name.localeCompare(b.name)),
[items]
);
return <List items={sorted} />;
};
Goal: Evaluate test coverage and quality.
## Coverage Analysis
| File | Coverage | Untested Functions | Untested Branches |
|------|----------|--------------------|--------------------|
| auth.ts | 45% | validateToken, refreshToken | error paths |
| orders.ts | 78% | — | edge cases |
| products.ts | 90% | — | — |
### auth.ts Issues
- `validateToken`: No test for expired token
- `refreshToken`: No test for invalid refresh token
- Error paths: 0% coverage on catch blocks
// ❌ NO ASSERTIONS
test('fetchUser', async () => {
await fetchUser(1);
// Test passes but checks nothing!
});
// ❌ WEAK ASSERTION
test('getUser returns user', async () => {
const user = await getUser(1);
expect(user).toBeTruthy(); // Too broad
});
// ❌ ASSERTING TRUE/FALSE
test('user is active', async () => {
const user = await getUser(1);
expect(user.isActive === true).toBe(true); // Bad pattern
});
// ✅ SPECIFIC ASSERTIONS
test('getUser returns correct user data', async () => {
const user = await getUser(1);
expect(user).toEqual({
id: 1,
email: '[email protected]',
name: 'Test User',
isActive: true,
});
});
# Code Review Report
## Executive Summary
| Metric | Count |
|--------|-------|
| Critical | 2 |
| High | 5 |
| Medium | 12 |
| Low | 8 |
| **Total** | **27** |
**Overall Assessment:** ⚠️ Pass with Conditions
### Top 3 Issues
1. **[CRIT-001]** N+1 query in GET /orders endpoint
2. **[HIGH-001]** God class UserService (450 lines)
3. **[HIGH-002]** No rate limiting on /api/auth/login
---
## Findings by Category
### Architecture Conformance
| Finding | Severity | File | Status |
|---------|----------|------|--------|
| ADR-002 violation (sync HTTP) | High | order-service/fulfillment.ts:34 | Open |
| API contract mismatch | Medium | user-service/openapi.yaml | Open |
### Code Quality
| Finding | Severity | File | Status |
|---------|----------|------|--------|
| God class UserService | High | user-service/UserService.ts | Open |
| Swallowed exception | Medium | auth-service/auth.ts:89 | Open |
### Performance
| Finding | Severity | File | Status |
|---------|----------|------|--------|
| N+1 query | Critical | order-service/handlers.ts:47 | Open |
| Missing index | High | orders table | Open |
### Test Quality
| Finding | Severity | File | Status |
|---------|----------|------|--------|
| No auth tests | Medium | auth-service/__tests__ | Open |
---
## Recommendations
### Immediate (Before Deployment)
- Fix N+1 query in orders endpoint
- Implement rate limiting on auth endpoints
### This Sprint
- Decompose UserService
- Add missing indexes
### Tech Debt Backlog
- Add integration tests for auth flows
- Refactor error handling patterns
---
## Sign-off Criteria
- [ ] All Critical findings resolved
- [ ] All High findings resolved or accepted with justification
- [ ] N+1 query fixed with EXPLAIN ANALYZE verification
- [ ] Rate limiting implemented
## Git Workflow Analysis
### Branching Strategy
| Check | Status | Notes |
|-------|--------|-------|
| Clear branching strategy documented? | [ ] | |
| Branch naming convention followed? | [ ] | |
| Long-lived branches < 1 week? | [ ] | |
| Branch protection rules on main? | [ ] | |
### Commit Hygiene
| Check | Status | Notes |
|-------|--------|-------|
| Commits are atomic (one change)? | [ ] | |
| No "fix", "wip", "update" messages? | [ ] | |
| Conventional commit format used? | [ ] | |
| Related changes in separate commits? | [ ] | |
### PR Quality
| Check | Status | Notes |
|-------|--------|-------|
| PRs < 400 lines? | [ ] | |
| PR description present? | [ ] | |
| PR template used? | [ ] | |
| Reviews resolved before merge? | [ ] | |
| No force-push to main? | [ ] | |
### CI/CD
| Check | Status | Notes |
|-------|--------|-------|
| CI runs on PR? | [ ] | |
| CI required for merge? | [ ] | |
| Tests in CI pipeline? | [ ] | |
| Mistake | Fix |
|---|---|
| Reviewing quality before spec compliance | Verify spec first — specs catch requirements misses |
| Generic findings without specifics | Every finding = file:line + evidence + fix |
| Mixing security with quality | Security → security-engineer. You → quality. |
| Flagging linter issues | Focus on structural issues linters miss |
| One finding per file | Group related symptoms under root cause |
| Modifying source files | Write all output to .forgewright/code-reviewer/ |
.forgewright/code-reviewer/findings/software-engineer), formal OWASP/STRIDE/pen-test findings (security-engineer), or linter setup (code-quality-engineer).git diff, run static/slop checks, and for HARD/payment scopes emit independent keyless review-2 bound to exact tree_sha and Schema v2 final-evidence digest (VERIFY.md).HARD/DEEP Gate: Any work touching payment, billing, IAP/in-app purchase, receipt validation, entitlements, subscription, or checkout is HARD and DEEP regardless of file count (no QUICK escape); require observed RED → GREEN plus controlled mutation backcheck on fixes and an independent keyless review-2 bound to exact tree_sha and Schema v2 evidence (kernel/VERIFY.md).What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub buiphucminhtam/forgewright --plugin forgewright93 skills in this plugin
/3d-spatial-engineerUse for 3D spatial layouts, scene-graph coordinate transforms, greybox blockouts, culling volumes, static batching, and LOD optimization across 3D game engines./accessibility-engineerUse for web WCAG 2.1/2.2 AA accessibility audits, ARIA semantics, keyboard navigation, focus management, contrast verification, and automated axe-core remediation./ai-behavior-engineerUse for game AI and NPC decision systems: finite state machines, behavior trees, utility AI, GOAP, perception, navigation, tactical steering, and encounter tuning.Other plugins' skills for the same job