一键导入
arib-dev-review
Dev | Code review with quality gates — function length, duplication, security, tests
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Dev | Code review with quality gates — function length, duplication, security, tests
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Memory | Code-graph subsystem — a native lightweight IMPORT graph (which file imports which, god-node candidates) built with ripgrep/grep, so a large monorepo can be navigated by structure instead of re-grepping every session. build/refresh/query. Honest scope: structural import graph, NOT semantic (no call-graph/type resolution); no Graphify dependency. Loads ON DEMAND only (zero always-on tokens). ADR-034.
Dev | Over-engineering review — reads a diff/module and returns a delete-list of bloat (single-use abstractions, premature generalization, speculative config, dead options) WITHOUT stripping legitimate structure. Advisory: returns recommendations, never auto-deletes. The on-demand companion to the ponytail-lite tripwire hook. Authored natively (no Ponytail dependency). ADR-033.
Wave | Pre-wave requirement lock — Act 1 derives the requirements from the codebase + memory (an honest grill, not guesswork), Act 2 hands the locked plan to an independent model (Codex) to tear apart until sign-off. Produces waves/<id>/PLAN.md + PLAN-REVIEW-LOG.md. Auto-chained idempotently from /arib-wave-start. If Act 2 can't run (no Codex), the wave proceeds but HOLDS MERGE for a human. Absorbs grill-me-codex (ADR-032).
Wave | Start a multi-session delivery wave — branch, plan, parallel architect+planner
Engine | Command the engineering team to deliver a known goal — dispatches the engineer-manager to decompose → dispatch specialists (parallel where safe) → integrate → reconcile (verification-agent) → merge gate. Scales its own reach: runs inline for a bounded goal, escalates to a parallel Workflow for a broad one, and paces under /loop for a multi-turn campaign — only when it needs to. Use when a goal needs a coordinated TEAM, not one specialist. Sibling of /arib-engine: the engine DISCOVERS its own backlog; /arib-build EXECUTES a goal you hand it.
Stack | NestJS architecture & patterns reference — modules/providers/DI, DTO+validation, guards/interceptors/pipes/filters, config, async lifecycle, testing, and the security + performance pitfalls that bite at scale. Use when building or reviewing a NestJS backend. Composes with security-auditor (OWASP), database-guardian (TypeORM/Prisma migrations), and performance (N+1). Authored natively (the ECC graft was unsourceable; this is CCM's own, MIT).
| name | arib-dev-review |
| argument-hint | <target-branch-or-path> |
| description | Dev | Code review with quality gates — function length, duplication, security, tests |
A code review is your last gate before merge. It's the moment to catch bugs, security issues, poor design decisions, and undocumented code before they hit your codebase. This skill transforms Claude into a CODE REVIEWER agent that applies eight quality gates systematically.
Why this matters: Code reviews prevent cascading failures. A 10-minute review that catches a security vulnerability saves hours of incident response later. A review that enforces function length limits prevents the 500-line monoliths that slow down future developers. This methodology ensures every merge maintains standards.
Claude Code acts as the CODE REVIEWER during this skill — thorough, specific, and fair.
For non-trivial diffs (>5 files, or any change touching auth/payment/data boundaries), open the review by dispatching three subagents in a single message — all in parallel — instead of running the gates sequentially.
Task(code-reviewer) — runs Gates 1-4 (structure, maintainability)
Task(security-auditor) — runs Gate 5 (security) deeper than this skill alone
Task(test-engineer, mode=report-only)
— runs Gate 7 (tests) deeper than this skill alone
All three are read-only on the diff and write nothing to disk. Per
architecture/AGENT_ARCHITECTURE.md, this fan-out is parallel-safe.
Merge their findings: wait for all three reports, then write the unified review report yourself. Conflicts (one agent says ship, another blocks) are resolved by the more conservative call — when in doubt, block.
Wall-clock: ~90 seconds parallel vs. ~5–10 minutes sequential.
When NOT to fan out:
Use the skill with different targets:
# Review all changes on a branch vs develop
/arib-dev-review feature/user-auth
# Review a specific file
/arib-dev-review src/auth/login.ts
# Review all uncommitted changes
/arib-dev-review .
# Review a specific commit range
/arib-dev-review develop..HEAD
Each gate is a checkpoint. Gates 1–4 focus on structure and maintainability. Gates 5–7 focus on safety and reliability. Gate 8 is your final verdict.
Before diving into code, understand what changed.
Scope creep is the enemy of good reviews. If a PR changes 50 files and 2000 lines, it's hard to review carefully. Scope assessment tells you whether this is focused work or something that needs splitting.
Commands to run:
# For branch review
git diff develop...[branch] --stat
git log develop...[branch] --oneline
# For file review
git diff HEAD -- [file] --stat
# For uncommitted changes
git status --short
git diff --stat
Assessment matrix:
| Files Changed | Lines Changed | Verdict | Action |
|---|---|---|---|
| 1–5 | <200 | ✅ Focused | Proceed with full review |
| 5–15 | 200–500 | ⚠️ Moderate | Section-by-section review |
| 15–30 | 500–1000 | 🔶 Large | Review in logical groups, flag for splitting if not necessary |
| 30+ | 1000+ | ❌ Too Large | Request developer to split PR into smaller, logical units |
Example verdict: "This branch changes 8 files with 350 lines added. This is a focused, reviewable change. Proceeding with full review."
Scan all changed and new functions for excessive length.
Long functions are a code smell. They do too much, are hard to test, hard to understand, and hard to reuse. This gate enforces function length discipline.
How to check:
Length thresholds:
| Length | Verdict | Action |
|---|---|---|
| ≤30 lines | ✅ Excellent | No action needed |
| 31–50 lines | ⚠️ Acceptable | Note in review; acceptable if well-structured |
| 51–100 lines | 🔶 Needs Justification | Require comment explaining complexity; suggest refactor plan |
| >100 lines | ❌ Blocking | Cannot merge; must refactor into smaller functions |
Bad example — 120-line function:
// ❌ Too long — does validation, processing, and logging all at once
function processUserRegistration(userData, emailService, database) {
// ... 120 lines of mixed concerns ...
}
Good refactor — broken into focused functions:
// ✅ Each function has one clear job
function validateUserData(userData) { /* 12 lines */ }
function createUserRecord(userData, database) { /* 18 lines */ }
function sendWelcomeEmail(user, emailService) { /* 15 lines */ }
function processUserRegistration(userData, emailService, database) {
const validated = validateUserData(userData);
const user = createUserRecord(validated, database);
sendWelcomeEmail(user, emailService);
}
Note: If a function is long but justified (e.g., complex parsing algorithm), require an inline comment: // This is 85 lines because it handles 7 different document formats. Refactoring would harm readability.
Check if individual files are growing too large.
Large files are hard to navigate, test, and maintain. If a file exceeds 1000 lines, it's doing too much. Split it.
How to check:
wc -l)Length thresholds:
| File Size | Verdict | Action |
|---|---|---|
| ≤300 lines | ✅ Excellent | No action |
| 301–500 lines | ⚠️ Acceptable | Monitor; watch for future growth |
| 501–1000 lines | 🔶 Needs Justification | Require split plan; suggest refactoring |
| >1000 lines | ❌ Blocking | Must split into logical modules before merge |
Example split plan:
src/auth.ts (800 lines) → Split into:
├─ auth/tokens.ts (140 lines) — token generation/validation
├─ auth/login.ts (160 lines) — login flow
├─ auth/password.ts (120 lines) — password reset/hashing
└─ auth/index.ts (30 lines) — exports
Find copy-pasted code and repeated patterns.
Duplication violates DRY (Don't Repeat Yourself). When you fix a bug in duplicated code, you have to fix it in five places. Duplication compounds maintenance cost. This gate finds and eliminates it.
What to look for:
formatDate, parseQuery, etc.)Search strategy:
utils/, helpers/, lib/) for existing solutionsBad duplication example:
// File: src/payment/stripe.ts
function formatPrice(cents) {
return '$' + (cents / 100).toFixed(2);
}
// File: src/invoice/generator.ts
function formatPrice(amt) {
return '$' + (amt / 100).toFixed(2);
}
// File: src/reports/export.ts
const formatPrice = (p) => '$' + (p / 100).toFixed(2);
Good fix — extract to shared utility:
// File: src/utils/format.ts
export function formatPrice(cents) {
return '$' + (cents / 100).toFixed(2);
}
// Now import in all three files:
import { formatPrice } from '../utils/format';
Verdict format: "Found 3 instances of date formatting logic. Extract to utils/format.ts and import."
Verify that code doesn't introduce security vulnerabilities.
Security is not optional. This gate checks for hardcoded secrets, input validation gaps, auth bypass, and injection vulnerabilities.
Checklist by category:
apiKey: "sk-...").env files not checked in; use .env.example insteadSearch for:
password = "
apiKey: "
secret: "
token = "
-----BEGIN PRIVATE KEY
credentials: {
AWS_SECRET_ACCESS_KEY
DATABASE_PASSWORD
❌ query("SELECT * FROM users WHERE id = " + userId)✅ query("SELECT * FROM users WHERE id = ?", [userId])dangerouslySetInnerHTML with user dataVulnerability severity reference:
| Vulnerability | Example | Severity |
|---|---|---|
| SQL Injection | SELECT * FROM users WHERE id = " + userId | CRITICAL |
| Hardcoded Secret | apiKey: "sk-live-abc123" | CRITICAL |
| XSS via innerHTML | element.innerHTML = userInput | HIGH |
| Missing Auth | GET /admin/users with no auth check | HIGH |
| Path Traversal | readFile(userPath) without validation | HIGH |
| CSRF missing | POST /api/transfer with no token | MEDIUM-HIGH |
| Known CVE | npm audit shows dependency with CVE | MEDIUM-HIGH |
| Information Leak | Stack trace in API response | MEDIUM |
Example verdict: "Found hardcoded API key on line 42 of services/payment.ts. CRITICAL — move to .env and use process.env.STRIPE_KEY. Cannot merge until fixed."
Ensure new code is tested and tests are meaningful.
Untested code breaks in production. But tests can be fake (tests that don't actually test anything). This gate verifies coverage is real.
Checklist:
npm test or equivalentTest quality rules:
| Pattern | Verdict |
|---|---|
expect(result).toBeDefined() | ❌ Doesn't test anything meaningful |
expect(() => func()).not.toThrow() | ⚠️ Minimal; tests existence not correctness |
expect(result).toBe(42) | ✅ Tests actual behavior |
should handle null input gracefully | ✅ Good test name |
test('should work') | ❌ Vague; what should work? |
| Mocking external API in unit test | ✅ Correct |
| Mocking internal helper function | ❌ Tests are too tightly coupled |
Example assessment:
// ❌ Bad test — doesn't verify correct behavior
test('calculateTotal works', () => {
const result = calculateTotal([10, 20, 30]);
expect(result).toBeDefined();
});
// ✅ Good test — verifies correctness and edge case
test('calculateTotal sums array of numbers', () => {
expect(calculateTotal([10, 20, 30])).toBe(60);
});
test('calculateTotal returns 0 for empty array', () => {
expect(calculateTotal([])).toBe(0);
});
Verdict format: "Test coverage for new authMiddleware function is incomplete. Missing: expired token case, invalid signature case. Require additional tests before merge."
Verify that code changes are documented.
Undocumented code forces future readers to reverse-engineer your intent. This gate ensures code is self-explanatory and documentation is updated.
Checklist:
API_ENDPOINTS.md (if applicable)Good vs. bad comments:
// ❌ Bad — just states what the code does (reader can see that)
const users = data.filter(x => x.active); // Filter active users
// ✅ Good — explains why and the business context
// Filter to active users only; inactive accounts lose access after 90 days (compliance req)
const users = data.filter(x => x.active);
// ❌ Bad — comment doesn't help
x = x + 1; // Increment x
// ✅ Good — explains the non-obvious logic
// Retry 3x because the payment API returns transient 503 errors during peak hours (4-6 PM PT)
const maxRetries = 3;
for (let i = 0; i < maxRetries; i++) {
try {
return await chargeCard(amount);
} catch (err) {
if (i === maxRetries - 1) throw err;
await sleep(1000 * (i + 1)); // Exponential backoff
}
}
JSDoc template:
/**
* Validates user registration data.
* @param {Object} userData - User data to validate
* @param {string} userData.email - User email address
* @param {string} userData.password - Password (min 8 chars, must include number)
* @returns {Object} { isValid: boolean, errors: string[] }
* @throws {TypeError} If userData is null or not an object
*/
function validateUser(userData) { }
Verdict format: "New calculateShippingCost function lacks JSDoc and has complex multi-step calculation without explanation. Require documentation before merge."
After all gates, render one of two verdicts.
Use when ALL gates pass, or only have minor, non-blocking suggestions.
## Review: APPROVED ✅
**Branch**: feature/user-auth
**Files Changed**: 6 files, +142 lines / -8 lines
**Tests**: All passing (18 tests, 100% coverage for new code)
### Strengths
- Clean separation of concerns — validation, auth logic, and storage are in separate modules
- Comprehensive test coverage including edge cases (expired tokens, invalid signatures, malformed requests)
- Excellent use of environment variables for secrets; no hardcoded API keys
- Clear inline comments explaining the retry logic for external API calls
- Password hashing uses industry-standard bcrypt with salt rounds = 12
### Suggestions (non-blocking)
- Consider extracting token validation logic to `auth/validate.ts`; currently mixed with refresh logic
- Add `@deprecated` notice to old `authenticateUser` function; consumers should migrate to new `authenticate` within 2 releases
**Recommendation**: Ready to merge into develop. No blockers.
Use when ANY gate has blocking issues. List them specifically with file:line references.
## Review: NEEDS CHANGES ❌
**Branch**: feature/user-auth
**Blocking Issues**: 4 issues found
### Required Fixes (must address before merge)
1. **Gate 5 — Security | Hardcoded API Key**
Location: `src/services/stripe.ts:17`
Issue: Stripe secret key hardcoded as `const API_KEY = "sk-live-abc123"`. This will be exposed in version control and built artifacts.
Fix: Move to `.env` file and load via `process.env.STRIPE_SECRET_KEY`
2. **Gate 6 — Testing | Missing Error Case**
Location: `src/auth/login.ts` + tests
Issue: `login()` function tests happy path but not "user not found" or "wrong password" cases. These are critical flows.
Fix: Add tests for invalid credentials, account locked scenarios, and database connection failures.
3. **Gate 2 — Function Length**
Location: `src/auth/register.ts:34–152` (118 lines)
Issue: `registerUser()` function exceeds 100-line limit. Currently handles validation, user creation, email sending, and logging all in one function.
Fix: Refactor into: `validateRegistration()`, `createUser()`, `sendWelcomeEmail()`, `logSignup()`. Each should be <50 lines.
4. **Gate 4 — Duplication**
Location: `src/auth/login.ts:45` and `src/auth/passwordReset.ts:82`
Issue: Identical password hashing logic appears twice. Should be extracted.
Fix: Create `src/utils/crypto.ts` with `hashPassword()` and `verifyPassword()` functions. Import in both files.
### Suggestions (non-blocking)
- Add JSDoc comments to `verifyToken()` function; currently lacks parameter documentation
- Consider adding rate limiting to `/api/login` endpoint to prevent brute force attacks (not critical but recommended)
**Next Step**: Fix the 4 blocking issues, commit, and request re-review.
Use this scale when rating issues:
| Level | Meaning | Action |
|---|---|---|
| 🔴 CRITICAL | Security vulnerability, data loss risk, or impossible to use | Block merge — fix immediately, no exceptions |
| 🟠 HIGH | Bug, missing security check, fails constraints, untested code | Block merge — must be fixed before merging |
| 🟡 MEDIUM | Code quality issue, missing docs, should refactor | Should fix — can merge with written plan to address soon |
| 🟢 LOW | Style preference, minor suggestion, polish | Optional — mention in feedback, up to developer |
Code that passes tests but violates architecture:
TECH_STACK.md)Tests that look good but test nothing meaningful:
test('should work', () => {
const result = doSomething();
expect(result).toBeDefined(); // Proves nothing
});
Tests that pass regardless of correctness:
Code that works now but creates implicit coupling:
Code that optimizes something that isn't slow:
When Claude Code reviews code it produced earlier in same session:
You have context (you helped write it), but review objectively:
If PR adds a new library:
TECH_STACK.md (approved)?npm audit)?/arib-dev-feature — The skill that produces code for review/arib-check-perf — Performance-specific review gate/arib-check-a11y — Accessibility-specific review gate/arib-check-deps — Dependency security and audit reviewGate sequence order:
Common blocking issues:
Non-blocking but recommend: