Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
03 Aug 2026 · 13 min read ·Article 14 / 208
Go

Code Review with AI: Verifying Golang Code Against the Spec

Use Claude Code for code review that focuses on verifying Golang code against its specification. SDD techniques to guarantee the implementation truly matches the spec.

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Code Review with AI: Verifying Code Against Specification

Traditional code review focuses on code quality: are there bugs? is it idiomatic? is the architecture correct? All valid questions. But AI code review in Golang SDD adds a second, critical dimension: does this code implement what the spec actually says? That is a different question entirely — code can be qualitatively excellent yet still wrong because it drifts from the spec. This article shows how Claude Code becomes a review partner that verifies implementation against specification, both before and after human review.


14.1 Two Dimensions of Code Review in SDD

Code review in SDD runs along two axes that are equally important but rarely treated equally. The list below separates the familiar quality checks from the spec-compliance checks that SDD adds.

  • Dimension 1 — Code Quality Review (standard review): Go idioms and best practices, error handling, performance, security vulnerabilities, maintainability and readability.
  • Dimension 2 — Spec Compliance Review (the SDD addition): are all ACs implemented? are all ECs handled? does the response format match the spec? do error codes match? are NFR considerations implemented?

AI is especially effective on Dimension 2 — cross-referencing code against a spec document is tedious work humans tend to do superficially, and it is exactly the kind of systematic matching a model does well.


14.2 A Prompt for Spec Compliance Review

The most effective compliance review feeds the spec and the implementation into one prompt and asks for a structured, per-criterion verdict. The template below does that.

text
 1Do a spec compliance review for the cancel order implementation.
 2
 3SPEC (specs/order/cancel-order.md v1.3):
 4@specs/order/cancel-order.md
 5
 6IMPLEMENTATION:
 7File 1: internal/usecase/order/cancel_order.go       @internal/usecase/order/cancel_order.go
 8File 2: internal/repository/postgres/order_repository.go  @internal/repository/postgres/order_repository.go
 9File 3: internal/delivery/http/handler/order_handler.go   @internal/delivery/http/handler/order_handler.go
10
11Review checklist:
121. For each AC (AC1-AC10): is it implemented? Where?
132. For each EC (EC1-EC4): is it handled? How?
143. Does the response format match spec?
154. Is error mapping from usecase to handler complete?
165. Any missing AC/EC?
17
18Output: a compliance table with Covered / Not Covered / Partial status

The instruction to output a table is what makes this reusable — you get the same shape every time, so results are comparable across features and easy to paste into a PR.


14.3 Sample Compliance Review Output

When the prompt runs, Claude returns a criterion-by-criterion table with a location for each verdict. This is what a typical result looks like.

text
 1| Item | Status | Location      | Notes                                        |
 2|------|--------|---------------|----------------------------------------------|
 3| AC1  | OK     | handler.go:45 | DELETE /api/v1/orders/:id — path param parsed |
 4| AC4  | OK     | entity.go:35  | time.Since(CreatedAt) <= 15*time.Minute — INCLUSIVE boundary: an order exactly 15 min 00 sec old can still be cancelled |
 5| AC6  | OK     | handler.go:89 | c.NoContent(http.StatusNoContent)            |
 6| AC8  | OK     | repo.go:89    | Returns nil,nil for security                 |
 7| EC1  | OK     | repo.go:98    | SELECT FOR UPDATE in transaction             |
 8| EC2  | OK     | usecase.go:65 | Best effort + slog.WarnContext               |
 9| EC3  | WARN   | -             | No DB timeout. Consider context.WithTimeout  |
10| EC4  | OK     | repo.go:~110  | defer tx.Rollback, order stays PENDING       |
11
12Issues Found
13WARN EC3: No explicit timeout for DB operations during lock wait
14Recommendation: cancelCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
15
16Overall Compliance Score: 13/14 items covered, 3/4 ECs fully handled

The rows above are an excerpt — the full table covers all 14 items (AC1-AC10 plus EC1-EC4). The value is in the “location” column and the single WARN row: the review does not just say “looks good,” it names the exact gap (EC3, no DB timeout) and hands you a concrete fix.


14.4 Code Quality Review with Spec Context

Compliance is not the only use. You can also ask for a classic quality review, but grounded in the spec’s NFRs so the feedback stays relevant to your constraints.

text
 1Review CancelOrderUseCase.Execute as a senior Go engineer.
 2
 3Spec context:
 4- NFR-P2: p95 latency < 500ms
 5- NFR-S4: audit log for all order state changes
 6- NFR-O3: INFO log for every state change
 7
 8Review:
 91. Is error handling idiomatic Go?
102. Any potential panic or nil dereference?
113. Is logging per NFR-S4 and NFR-O3?
124. Any performance concern for NFR-P2?
135. Any readability improvements?

Anchoring the review to named NFRs keeps it actionable — feedback like “add a log here” carries the weight of NFR-O3 behind it rather than being a matter of taste.


14.5 Red / Yellow / Green Feedback Classification

Not every finding is equally urgent, so classify feedback by severity before acting. The scheme below tells contributors what blocks a merge and what is merely a suggestion.

text
 1RED — Must fix before merge:
 2- Unimplemented spec AC
 3- Security vulnerability
 4- Data corruption risk
 5
 6YELLOW — Needs discussion:
 7- Pattern inconsistency with existing codebase
 8- Performance below NFR target but still acceptable
 9- Missing "nice to have" audit log
10
11GREEN — Optional suggestion:
12- Readability refactoring
13- Alternative approach (not better, just different)
14- Additional clarifying comments

With this triage in place, a review with twenty comments still has a clear merge decision — only the RED items block, and everyone knows it up front.


14.6 Automated Spec Compliance Script

Some compliance checks are cheap enough to automate outright. A small shell script can grep for the exact status codes and error codes the spec mandates, failing CI when they go missing.

bash
 1#!/bin/bash
 2# scripts/check-spec-compliance.sh
 3
 4# Check AC6: 204 No Content response
 5if ! grep -r "StatusNoContent" "internal/delivery/http/handler/"; then
 6    echo "AC6: StatusNoContent (204) not found in handler"; exit 1
 7fi
 8
 9# Check required error codes
10for code in "ORDER_NOT_FOUND" "ORDER_NOT_CANCELLABLE" "CANCEL_WINDOW_EXPIRED"; do
11    if ! grep -r "\"$code\"" "internal/delivery/http/handler/"; then
12        echo "Error code $code missing from handler"; exit 1
13    fi
14done
15
16echo "Basic spec compliance check passed"

This script catches the crude regressions — a deleted error code, a wrong status — before a human reviewer even opens the PR, freeing the AI and human passes to focus on subtler logic.


14.7 Pre-Merge Checklist

For consistency across every PR, wrap the review in a reusable checklist that spans spec, quality, security, and the AI review itself. Paste this into each pull request.

markdown
 1## Pre-Merge Checklist
 2
 3### Spec Compliance
 4- [ ] All ACs (AC1-AC10) implemented
 5- [ ] All ECs (EC1-EC4) handled
 6- [ ] Response format matches spec
 7- [ ] NFR considerations implemented
 8
 9### Code Quality
10- [ ] go build ./... passes
11- [ ] go test -race ./... passes
12- [ ] golangci-lint run ./... passes
13- [ ] Coverage >= 85% for the usecase layer
14
15### Security
16- [ ] No sensitive data in logs
17- [ ] All SQL uses parameterized queries
18- [ ] Auth check via middleware
19
20### AI Review
21- [ ] Spec compliance review done
22- [ ] All RED issues resolved
23- [ ] YELLOW issues acknowledged or discussed

A checklist like this turns “definition of done” from tribal knowledge into an artifact — the RED-issue line in particular makes the merge gate explicit.


14.8 Responding to Review Feedback

AI feedback is a conversation, not a verdict. There are three legitimate responses, and each has a shape worth practicing.

text
 1Accept and Fix:
 2Good catch on EC3 timeout. Will add context.WithTimeout(ctx, 3s) before the DB call.
 3Question: spec NFR-M4 says 2-second timeout. Should we use 2s instead of 3s?
 4
 5Acknowledge and Defer:
 6Audit log (NFR-S12) valid. Out of initial scope — creating a ticket for next sprint.
 7Acceptable to merge without it given the ticket tracking?
 8
 9Disagree with Justification:
10Not adding context.WithTimeout in the usecase layer. Reason: HTTP middleware already
11sets a 30s context deadline, and context propagation handles client-disconnect
12cancellation. A second deadline could cause hard-to-debug partial state.
13Is there a specific concern driving this suggestion?

Treating AI findings as claims to evaluate — accept, defer, or rebut with reasoning — keeps the developer in control and turns review into design discussion rather than blind compliance.


14.9 AI as Third Reviewer in Small Teams

On a small team you may only have one human reviewer, so let the AI play a structured “third reviewer” that hunts for what a tired human misses. The prompt below frames that role.

text
 1This is a PR ready for merge:
 2[paste diff or file changes]
 3
 4As third reviewer:
 51. Anything human reviewers might miss?
 62. Subtle security or performance concerns?
 73. Consistent with existing codebase patterns?
 84. Missing tests that should be there?
 9
10Context: spec at specs/order/cancel-order.md, conventions at CLAUDE.md

Pointing the model at both the spec and CLAUDE.md gives it the same context a senior teammate would have — so its “third opinion” reflects your conventions, not generic best practice.


14.10 Interface Change Review

Interface changes ripple across implementers and tests, so review them for blast radius before committing. The prompt asks specifically about breakage and migration.

text
1Interface OrderRepository has been modified:
2BEFORE: [2 methods]
3AFTER:  [4 methods — 2 new added]
4
51. Is this a breaking change?
62. Which files implement this interface and need updating?
73. Which tests will break?
84. Any deprecation period needed?

Framing the review around “who else implements this” catches the mock and the second adapter you forgot existed — the classic source of a broken build after an interface grows.


14.11 Performance Review with Spec NFRs

Performance review is meaningful only against a target and real data volumes, so hand the model both alongside the SQL. The prompt below grounds the analysis in NFR-P2.

text
 1Review the CancelWithStockRestore SQL queries for performance:
 2@internal/repository/postgres/order_repository.go
 3
 4Context: 5M orders, 20M order_items, 500K products
 5NFR target: p95 < 500ms
 6
 71. Are all queries using the correct indexes?
 82. Any hidden N+1 queries?
 93. Can SELECT FOR UPDATE lock contention become a bottleneck?
104. Estimated query time at normal load?

Supplying row counts and the p95 target turns vague “is this fast?” into a concrete analysis — the model can reason about index selectivity and lock contention against numbers that match production.


14.12 Building a Review Culture with AI

Beyond individual PRs, AI review can be woven into team process. A standard PR template captures the full traceability chain so every merge tells the same story:

  • a link to the spec being implemented,
  • a spec-compliance self-review checklist,
  • the AI compliance review output (as a collapsible section),
  • the issues found and how each was handled.

Making this the default template means every merged feature carries its own audit trail — spec → implementation → review → merge — without anyone having to reconstruct it later.


14.13 Verifying AI Review Findings

AI review is a first layer, not an oracle, and it can be confidently wrong. When it claims “AC X is not implemented,” run this three-step verification before acting: check the specific line the AI references, check whether there is an indirect implementation it missed, and check whether it misread the spec or the code. Trusting a false negative wastes time; trusting a false positive can make you “fix” correct code. Always verify against the source before you change anything.


14.14 Limitations of AI Code Review

Knowing where AI review falls short keeps you from over-trusting it. Four limitations matter most: false positives and negatives (it can miss indirect implementations or flag correct code), no runtime insight (it reviews source, so load and integration tests remain mandatory), degradation with large context (per-file review beats dumping the whole codebase), and no business intuition (it only knows what the spec states). Human review therefore stays essential for business-logic judgment and architectural decisions.


14.15 Diff-Based Review for Changes

For an incremental change, review the diff rather than the whole file so the model’s attention stays on what actually changed. The prompt shows a before/after and asks the pointed questions.

text
 1Here's a recent change to cancel_order.go:
 2
 3BEFORE:
 4if err != nil || order == nil { return ErrOrderNotFound }
 5
 6AFTER:
 7if err != nil { return fmt.Errorf("get order: %w", err) }
 8if order == nil { return ErrOrderNotFound }
 9
10Review this change:
111. Is the change correct? (DB errors are no longer silently ignored)
122. Any side effects?
133. Does this match spec AC7/AC8?

A tight diff yields a tight review — the model can reason precisely about the one behavioral change (DB errors now surface) instead of re-reviewing code that did not move.


14.16 Database Migration Review

Migrations run against live data, so review them for production safety, not just correctness. The prompt below checks for downtime risk and index design.

sql
1-- Review this migration
2CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_user_id_status
3ON orders(user_id, status) WHERE deleted_at IS NULL;

Ask the model: is it safe without downtime, is the index optimal for GetByIDAndUserID, are there CONCURRENTLY caveats on PostgreSQL 15, is the partial WHERE correct, and does it overlap an existing index? On a table with ~5M rows, the CONCURRENTLY clause is the difference between a safe deploy and a locking incident — which is exactly the kind of production risk this review exists to surface.


14.17 Security Review with Spec Context

Security review is sharpest when it is checked against named security NFRs rather than a generic checklist. Feed the spec’s security requirements alongside the code.

text
 1Review the cancel order implementation from a security perspective:
 2
 3Spec security requirements:
 4- NFR-S1: JWT Bearer authentication required
 5- NFR-S3: rate limit 5 cancels per user per hour
 6- NFR-S12: audit log for all order-modifying operations
 7
 8Review:
 91. Can an unauthenticated user reach the usecase layer?
102. Is the audit log present and sufficient?
113. Any information leakage (e.g. revealing order existence to an unauthorized user)?
124. Is rate limiting tested?
135. Any SQL injection vulnerability?

Tying each question to an NFR turns “is this secure?” into a set of verifiable checks — information leakage in particular (question 3) is the subtle one, and naming NFR-S12 keeps it from being overlooked.


14.18 Tips & Gotchas

The habits below decide whether AI review sharpens your process or lulls you into false confidence:

Tip 1: Review spec and code simultaneously — paste the content directly, never describe the spec from memory.

Tip 2: Request actionable feedback — “identify spec compliance gaps with specific fixes” beats “review this code.”

Tip 3: Verify AI findings — always check manually when the AI says something isn’t implemented.

Tip 4: Use AI review as a sanity check, not an oracle — human judgment stays essential for business logic and architecture.

Gotcha 1: AI review can produce false positives — verify before acting.

Gotcha 2: Too-large context reduces review quality — review per-file or per-feature.

Gotcha 3: AI can’t review runtime behavior — load and integration tests are still required.

Gotcha 4: Review without a spec reference yields only quality feedback, not compliance — always include the spec.


14.19 The Complete SDD Review Pipeline

Individual techniques come together in one repeatable pipeline. The sequence below is the full path from finished code to a confident merge.

text
11. Implementation complete
22. AI spec compliance review → fix RED issues
33. Developer self-review with checklist
44. PR created with spec link + AI review output
55. Human code review (focus: business context, architecture)
66. Address human review feedback
77. Optional: AI final check for remaining concerns
88. Merge with confidence

Following this pipeline guarantees every merged feature is both quality-reviewed and spec-compliance-verified — the two dimensions are no longer left to chance.


14.20 Summary

Code review in SDD has two dimensions: code quality (as in any review) and spec compliance (SDD-specific). AI is highly effective at the second thanks to systematic cross-referencing.

Effective workflow: implementation → AI spec compliance review → handle issues → self-review → PR → human review → merge.

Effective prompts: include spec and code together, request structured output (a Covered/Not/Partial table), and ask for actionable suggestions.

AI review limitations: it can be wrong, cannot review runtime behavior, and degrades with very large context — so human review remains essential.

Team culture: integrate AI review into the PR template and make spec compliance part of the standard definition of done.

In the next article we cover refactoring with Claude Code — how to perform safe, structured refactoring with a strong safety net drawn from spec and tests.

Related Articles

💬 Comments