Skip to content
playbookqualitycode-review

Code Review Loops ​

Systematic, severity-classified code review using AI agents as reviewers. The core idea: treat code review as an iterative feedback loop, not a one-shot gate.


When to Use ​

  • After completing a feature — self-review before opening a PR
  • Before merging a PR — agent-assisted review to catch what humans miss
  • After a refactoring — verify no regressions slipped through structural changes
  • Inheriting unfamiliar code — rapid audit of a codebase you did not write
  • Security-sensitive changes — auth, payments, data handling, API surface changes

The Review Loop ​

The workflow is not "review once and ship." It is an iterative cycle where each pass fixes the highest-severity issues, then a re-review verifies the fixes and catches anything the fixes introduced.

Implementation
    │
    ▼
Code-Reviewer Agent (Phase 1: Security + Correctness)
    │
    ▼
Severity-Classified Findings
    │
    ├── P1 Security / P2 Correctness → Fix immediately
    │       │
    │       ▼
    │   Re-review (verify fixes, catch regressions)
    │
    ├── P3 Performance → Fix before merge or with tracked follow-up
    │
    └── P4 Style → Author's discretion
    │
    ▼
Final Verification Pass
    │
    ▼
Merge

Key Rule

Never skip the re-review after fixing P1/P2 issues. Fixes introduce new code, and new code can introduce new bugs. The re-review is not optional.


The Diff-Based Review Principle ​

Always start from git diff, never by reading whole files cold.

Start here. Reading entire files pulls the reviewer into pre-existing code and buries the actual change in context noise. The diff tells you exactly what changed — that is the scope of the review.

bash
# For uncommitted changes
git diff                    # Unstaged changes
git diff --cached           # Staged changes
git diff HEAD               # Both staged and unstaged

# For a PR / branch
git diff main...HEAD        # Changes on this branch since diverging from main
git log main..HEAD --oneline  # Commits on this branch

# For a GitHub PR
gh pr diff <number>         # View PR diff
gh pr view <number>         # PR description and metadata

# For a specific commit
git show <sha>              # Single commit diff

Every finding in the review must include:

  • File — exact path
  • Line — specific line number
  • Issue — what is wrong, concretely
  • Severity — P1 through P4
  • Suggested fix — a concrete code change, not vague advice

Review Priority Order ​

Review concerns in this strict order. Stop and report critical issues immediately — do not continue to style nits if there is a security vulnerability.

P1: Security (Must fix before merge) ​

CheckWhat to Look For
InjectionSQL strings built with concatenation/interpolation, unsanitized HTML rendering, command injection via exec/eval/subprocess with user input
Auth/authzMissing authentication checks on endpoints, broken authorization (user A can access user B's data), privilege escalation paths
Secrets.env files, API keys, passwords, tokens in committed code — check new files AND diffs
Data exposureStack traces returned to users, verbose error messages with internal details, PII in logs
SSRF/redirectUser-controlled URLs used in server-side requests, open redirects

P2: Correctness (Should fix before merge) ​

CheckWhat to Look For
Logic errorsOff-by-one, wrong comparison operator, inverted conditions, short-circuit evaluation bugs
Null/undefinedAccessing properties on potentially null values without checks, missing nil guards
Race conditionsShared mutable state without synchronization, TOCTOU bugs, concurrent map access
Error handlingSwallowed errors (catch {} with no action), errors that should propagate but don't
Edge casesEmpty arrays/strings, zero values, negative numbers, Unicode, very large inputs

P3: Performance (Fix soon, can merge with follow-up) ​

CheckWhat to Look For
N+1 queriesDatabase query inside a loop — should be batched
Missing indexesNew queries on columns without indexes
Unnecessary allocationsCreating objects in hot loops, loading more data than needed
Memory leaksEvent listeners not cleaned up, growing caches without eviction
Blocking operationsSynchronous I/O on async paths, long-running operations on the main thread

P4: Style (Optional, author's discretion) ​

CheckWhat to Look For
NamingMisleading names (function named getUser that also deletes), non-obvious abbreviations
StructureFunctions doing too many things, deeply nested conditionals that could be early returns
DuplicationSame logic copy-pasted — but only in new code, not pre-existing duplication
Test coverageNew functionality without tests, tests that don't assert anything meaningful

Multi-Phase Review ​

For large changes or security-sensitive code, split the review into separate phases. Each phase can be run as a separate agent for focus and thoroughness.

Phase 1: Security + Correctness ​

The first pass focuses exclusively on P1 and P2 findings. Nothing else. This keeps the reviewer (human or agent) focused on what can cause real damage.

Review this diff for security vulnerabilities and correctness bugs only.
Do not comment on style, naming, or performance.

Focus on:
- Injection, auth/authz, secrets, data exposure, SSRF
- Logic errors, null/undefined, race conditions, error handling

For each finding, provide: file, line, issue, severity (P1 or P2), concrete fix.

Phase 2: Architecture + Design ​

After P1/P2 issues are fixed, a second pass looks at structural concerns.

Review this diff for architectural and design issues.
Assume security and correctness have already been reviewed.

Focus on:
- API design: are the interfaces clean and consistent?
- Separation of concerns: is business logic mixed with infrastructure?
- Error boundaries: are errors handled at the right layer?
- Extensibility: will this design accommodate known future requirements?

Phase 3: Test Coverage ​

The final pass examines whether the changes are adequately tested.

Review this diff for test coverage gaps.

For each changed function or code path:
1. Is there a test that exercises it?
2. Does the test cover the error/edge cases?
3. Are the assertions meaningful (not just "it doesn't throw")?

List untested paths as findings with P4 severity.

Next Step

For systematic test gap analysis after identifying coverage issues in review, see the Test Gap Analysis Playbook.


Cross-Tool Review ​

Running the same review through multiple AI tools surfaces blind spots that no single tool catches alone. This is not about finding the "best" tool — it is about using disagreement between tools as a signal.

  1. Claude Code — Run the code-review skill against the diff. Claude Code's skill system produces severity-classified findings with file/line references.

  2. Codex — Run a separate review with Codex, which may catch different patterns due to its different training and reasoning approach.

  3. Diff the reviews — Compare the two sets of findings. Where both agents agree, confidence is high. Where they disagree, investigate manually.

TIP

Cross-tool review is especially valuable for security reviews, where the cost of a missed finding is high and the marginal effort of a second pass is low.


Tracking & Resolution ​

Every review produces a findings document. Track the status of each finding so nothing falls through the cracks.

Findings Table Format ​

markdown
| #   | Severity | File:Line   | Issue                          | Status   | Notes                          |
| --- | -------- | ----------- | ------------------------------ | -------- | ------------------------------ |
| 1   | P1       | auth.ts:23  | SQL injection in user lookup   | FIXED    | Parameterized in commit abc123 |
| 2   | P2       | api.ts:89   | Missing null check on response | FIXED    | Added guard in commit def456   |
| 3   | P3       | db.ts:45    | N+1 query in user list         | DEFERRED | Tracked in issue #78           |
| 4   | P4       | utils.ts:12 | Misleading function name       | WONTFIX  | Existing convention            |

Status Values ​

StatusMeaning
OPENFinding acknowledged, not yet addressed
FIXEDFix committed, awaiting re-review
VERIFIEDFix confirmed in re-review
DEFERREDAccepted risk, tracked for follow-up
WONTFIXIntentional, with documented reasoning

Real Example: Multi-Phase Review with Tracking ​

In the Jake project, a CODE-REVIEW-CODEX.md document tracked findings across multiple review phases:

  1. Phase 1 ran a Codex-based code review that produced 12 findings across P1-P4 severities
  2. Each finding was logged in the tracking table with file, line, and specific issue
  3. P1/P2 fixes were committed and the status updated to FIXED
  4. A re-review verified the fixes and caught one regression (a new null dereference introduced by the P2 fix)
  5. P3 findings were deferred to follow-up issues with explicit tracking
  6. The final document served as an audit trail showing what was found, what was fixed, and what was accepted

This pattern — findings document as living artifact — turns code review from a conversation into a trackable process.


Review Anti-Patterns ​

Avoid these common mistakes when running agent-assisted reviews:

Anti-PatternWhy It Fails
"LGTM" with no substanceRubber-stamping helps nobody
Reviewing style before correctnessFind the bug first, nit the naming later
Blocking on style preferencesIf it works and is readable, let it go
Reviewing pre-existing codeOnly review what changed in this diff
"I would have done it differently"Different is not wrong — only flag actual issues
Vague feedback ("this seems wrong")Be specific: what is wrong, why, and how to fix it
Skipping re-review after fixesFixes introduce new code. New code can have new bugs.

Example Prompts ​

Launch a Full Code Review Agent ​

Review the diff on this branch against main. Use `git diff main...HEAD`.

Review in priority order:
1. P1 Security: injection, auth/authz, secrets, data exposure, SSRF
2. P2 Correctness: logic errors, null/undefined, race conditions, error handling
3. P3 Performance: N+1, missing indexes, unnecessary allocations
4. P4 Style: naming, structure, test coverage

For each finding, output:
- File and line number
- Issue description
- Severity (P1/P2/P3/P4)
- Concrete suggested fix (code, not prose)

End with a summary table and a verdict: Approve, Request Changes, or Comment.

Launch a Security-Only Review ​

Security audit of the changes on this branch (git diff main...HEAD).

Check every changed line for:
- SQL/NoSQL injection
- Command injection
- XSS / unsanitized output
- Authentication bypass
- Authorization flaws (can user A access user B's data?)
- Hardcoded secrets or credentials
- SSRF / open redirect
- Insecure deserialization

Ignore style, performance, and naming. Only report security findings.
Each finding: file, line, vulnerability type, exploit scenario, fix.

Launch a Re-Review After Fixes ​

Re-review the changes since the last review (commits abc123..HEAD).

1. Verify each fix in the findings table actually resolves the issue
2. Check that fixes did not introduce new problems
3. Update the status column: FIXED → VERIFIED, or note regressions

Output the updated findings table.

Self-Review Before Committing ​

Run `git diff --cached` and review my staged changes.

Apply the standard priority order (P1 Security → P2 Correctness →
P3 Performance → P4 Style). Be strict — I want to catch issues
before they reach a reviewer.

For each finding: file, line, severity, issue, fix.
End with a verdict: safe to commit, or needs changes.

Verification Checklist ​

Before finalizing any review, confirm:

  • [ ] Started from the diff, not from reading whole files
  • [ ] Every finding has a specific file, line number, and concrete suggestion
  • [ ] Severity is assigned to every finding
  • [ ] Security concerns were checked first
  • [ ] No findings about pre-existing code that was not changed in this diff
  • [ ] Summary table and verdict included
  • [ ] Re-review scheduled after P1/P2 fixes

Superpowers Skill Mapping ​

SkillRole in This Playbook
code-reviewThe core skill — producing severity-classified findings from diffs
requesting-code-reviewFraming review requests with context, scope, and focus areas
receiving-code-reviewProcessing findings, triaging severity, updating tracking documents