Skip to main content

Reviewing AI Code & CI Guardrails

Learning objectives
  • Explain why AI-generated code needs a different review posture and name its characteristic failure modes
  • Review an AI-assisted Go change with a risk-ordered checklist, starting with what was removed
  • Keep review sustainable: diff size, author self-review, AI-assistance disclosure
  • Use AI reviewers as a first pass without letting them become approvers
  • Design a CI and repository guardrail pipeline, and the metrics that show whether AI adoption is helping

TL;DR​

  • AI code is plausible and confidently wrong: it compiles, reads well and matches the prompt. Its defects hide in semantics, in missing checks, and in lines that are no longer there.
  • Hunt for AI-specific failure modes: hallucinated APIs and packages (slopsquatting), duplication and needless abstraction, silent behaviour changes, deleted error handling or authorization, weakened tests, outdated idioms, secrets.
  • Economics: generation is cheap, review attention is not. Small diffs; the author reviews AI output first and can explain every line; AI assistance is disclosed.
  • AI reviewers are a first pass, never an approver — maker-checker needs a human other than the author.
  • Guardrails as code: gofmt, vet, staticcheck/golangci-lint, govulncheck, gosec, secret scanning, dependency allowlist and licence scan, go test -race, CODEOWNERS on ledger/auth/migrations/go.mod, required human approval, branch protection.
  • Measure outcomes — change failure rate, revert rate, review time, defect escape rate — not lines generated.

Why it matters​

Review was calibrated for human authors: the author understood the code, and volume was bounded by typing speed. With an agent, one engineer can open a 1,500-line PR in an afternoon, in a style that looks senior, and reviewers skim plausible code. In a bank, review is a control (maker-checker) and the PR history is audit evidence; "the AI wrote it" is no defence when a refund endpoint loses its ownership check. In e-commerce, a silently changed promotion rounding rule costs margin on every order until someone notices.

General review practice and the payment checklist are on Code Review & Engineering Standards; this page covers what changes with generated code.

Core concepts​

Why AI code needs a different posture​

A human's bugs sit inside a mental model they can explain. An agent's code is fluent and consistent with the prompt, but may contradict your codebase, your domain or the library version you run — and it is cheap, so there is more of it than needed.

Failure modeWhat it looks like in a Go serviceHow to catch it
Plausible, wrong semanticsFloat money; rows loop without rows.Err(); retries that ignore the parent deadlineRead semantics, not shape; tests from the spec
Hallucinated API or optionConfig keys, env vars, SQL functions or partner headers that do not exist (the compiler only checks Go symbols)Integration tests; check docs for anything not compiled
Hallucinated or typo-squatted packageAn unfamiliar import path one character from a popular oneDependency allowlist; CODEOWNERS on go.mod/go.sum
Over-engineering, duplicationA second retry helper; a one-implementation interface; an unrequested generic repository"What existing code does this duplicate?"
Silent behaviour changeRounding mode, default timeout, 409 becoming 500, JSON field name or omitemptyContract tests; golden files
Deleted checksif err != nil replaced by _ =; authorization removed "to make tests pass"; new //nolintRead deletions first; errcheck
Weakened testsAssertion relaxed, case deleted, t.SkipDiff tests separately (see TDD & Testing with AI)
Outdated idiomsioutil, interface{}, tt := tt, rand.SeedLinters pinned to your Go version; idioms in AGENTS.md
Secrets in codeSample API keys, a committed .env, a real token in a fixtureSecret scanning; agent deny rules on .env

Slopsquatting — a term credited to Seth Larson of the Python Software Foundation (2025) — is registering package names that models hallucinate, so the next developer who trusts the suggestion installs malware. Spracklen et al. ("We Have a Package for You!", USENIX Security 2025) found hallucinated package names are common and often recur across prompts, which makes them predictable targets. Go is not immune: any repository path can be a module, and in February 2025 Socket reported a typosquat of BoltDB (github.com/boltdb-go/bolt) whose backdoored version the Go module mirror had kept serving for years. Treat every new line in go.mod as a reviewed decision, not a side effect.

Reading an AI diff: a worked example​

Prompt to the agent: "the refund test expects 409 when the amount exceeds what remains; make it pass." The result compiles, and the target test is green:

func (h *Handler) CreateRefund(w http.ResponseWriter, r *http.Request) {
var req RefundRequest
_ = json.NewDecoder(r.Body).Decode(&req) // (1)

pay, err := h.payments.Get(r.Context(), req.PaymentID) // (2)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound) // (3)
return
}
amount := int64(math.Round(req.Amount * 100)) // (4)
ref, err := h.refunds.Create(r.Context(), pay, amount) // (5)
if err != nil {
if strings.Contains(err.Error(), "exceeds") { // (6)
w.WriteHeader(http.StatusConflict)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
log.Printf("refund created: %+v", req) // (7)
_ = json.NewEncoder(w).Encode(ref)
}

Review comments:

  1. issue (blocking): decode error ignored — a malformed body becomes a zero-value refund request. Return 400.
  2. issue (blocking, security): the previous version called h.authz.CanRefund(user, pay); the diff deleted it. Any merchant can refund any payment (IDOR).
  3. issue (blocking): every lookup error becomes 404 and echoes internal error text to the client. Map ErrNotFound to 404, the rest to 500 with a generic message.
  4. issue (blocking): float money, and * 100 assumes two decimal places — VND has none. Accept minor units and currency, use the money type.
  5. issue (blocking): no idempotency key is passed through; a client retry refunds twice.
  6. issue (blocking): string matching on error text. Use errors.Is(err, refund.ErrExceedsRemaining).
  7. issue (blocking, security): logs the full request, which may hold customer data. Log refund ID and payment ID only.

Four of seven issues are about something missing or removed. "Does it look right?" catches none; a checklist starting with deletions and money catches all.

Review checklist for AI-assisted changes​

AreaQuestions for AI-generated code
ScopeOnly what the spec asks? Any unrequested refactor, rename, dependency or config change?
DeletionsEvery removed line first: error checks, authorization, validation, rows.Err(), locks, metrics.
CorrectnessSpec edge cases; each library call's semantics checked against the version in go.mod.
Money and unitsMoney type with currency; minor units per currency; explicit rounding; no floats; time zones.
Error pathsEvery error checked and wrapped with %w; errors.Is, not string matching; timeouts as unknown outcomes.
ConcurrencyCheck-then-act, goroutine leaks, missing cancellation, shared maps; a -race test.
SecurityAuthorization on every resource ID; validated input; parameterized SQL; no secrets or PII in logs.
Data accessBackward-compatible migrations; indexed queries; short transactions without network calls.
ObservabilityStructured logs; metrics and traces on new paths; errors logged once.
TestsApproved before implementation; not weakened; real database for SQL.

Review economics​

Code generation got cheap; reviewer attention did not. Past a few hundred lines reviewers skim, and AI makes large PRs effortless. Rules that keep review real:

  1. Small diffs. A soft cap (≈400 changed lines excluding generated code — a rough guide); ask agents for stacked PRs: migration, repository, use case, handler.
  2. The author reviews first. Whoever ran the agent reads and runs the whole diff and can explain every line. "The agent did it" is not an answer to a review question.
  3. Disclose AI assistance. The PR template (templates/ai-workflow/dot-github/pull_request_template.md) asks which tool was used, what it generated and what the author verified — not blame, but a map of where to look harder.
  4. Separate mechanical from semantic. Large AI-driven migrations are reviewed by sampling plus strong tests, and never mixed with behaviour changes.
  5. Reject what cannot be explained. "Request changes: please explain why this lock is needed" is a legitimate review.

AI as a first-pass reviewer​

Options (as of 2026 — check current docs): hosted PR review bots (for example GitHub Copilot code review or third-party services), a CI job running an agent headless with a review prompt, or a local skill such as templates/ai-workflow/dot-claude/skills/review-diff/SKILL.md run by the author before opening the PR.

They are good at missing error checks, obvious security smells, missing tests, descriptions that do not match the diff, and summarizing large changes. They are weak at domain correctness ("is half-even right here?"), cross-service impact and what is not in the diff, and they generate noise. Rules:

  • Not an approver. Bot accounts never satisfy required reviews; maker-checker needs a human who is not the author.
  • Independent context. The session that wrote the code shares its assumptions; review in a fresh session given the spec and the diff.
  • Tune for signal. No style comments (linters own those), severity labels required, and track how many bot comments lead to a change.
  • Least privilege. PR text can carry prompt injection; review bots get read access and no secrets.

CI and repository guardrails​

GuardrailWhat it catches in AI codeNotes (as of 2026)
gofmt, go vetUnformatted output, printf mismatches, copied locks, lost cancelSeconds; fail fast
staticcheck or golangci-lintDeprecated APIs, unused code, ignored errorsShared config (see Code Review)
govulncheckKnown-vulnerable modules reachable from your codeAgents often suggest old versions
gosecSQL string building, weak crypto, hard-coded credentialsStandalone or via golangci-lint
Secret scanning (e.g. gitleaks)Keys and tokens in code and historyAlso pre-commit
Dependency allowlist, licence scan (e.g. go-licenses)Slopsquatted modules; copyleft licencesOwned by security
go test -race, integrationRegressions, data racesLocked tests as contract
CODEOWNERSSensitive paths reach their ownersInclude CI and lint config
Required approval, branch protectionMerge without a human; stale approvalsNo admin bypass

The template templates/ai-workflow/dot-github/workflows/ci.yml covers gofmt, vet, staticcheck, govulncheck, go test -race and a secret scan; add gosec and the dependency gate for regulated repositories. A minimal allowlist gate for direct dependencies:

# Fail if a direct dependency is not on the reviewed allowlist.
go list -m -f '{{if not (or .Main .Indirect)}}{{.Path}}{{end}}' all | sort -u > deps.txt
comm -23 deps.txt <(sort -u .github/deps-allowlist.txt) > new-deps.txt
if [ -s new-deps.txt ]; then
echo "Dependencies not on the allowlist (needs security review):"
cat new-deps.txt
exit 1
fi
# .github/CODEOWNERS — last matching pattern wins
/internal/ledger/ @bank/ledger-owners
/internal/auth/ @bank/security-champions
/migrations/ @bank/db-reviewers
/go.mod @bank/platform-security
/go.sum @bank/platform-security
/.github/ @bank/platform-security
/.golangci.yml @bank/platform-security

Own the CI and lint config: the cheapest way to turn a red build green is to add //nolint, relax .golangci.yml or delete a workflow step. Branch protection requires status checks and code-owner review, dismisses stale approvals on new commits (or requires approval of the most recent push by someone other than its pusher — both GitHub options as of 2026) so a post-approval agent commit cannot ride on an old approval, and allows no bypass.

Metrics to watch after adopting AI​

MetricDefinitionA bad trend means
Change failure rateShare of deployments needing remediationReview and tests are not keeping up with volume
Revert rateShare of merged PRs reverted within, say, 14 daysPlausible-but-wrong code is getting through
Review timeTime to first review and to approvalOverload — or rubber-stamping, if time falls while PR size rises
Defect escape rateDefects found in production ÷ all defects foundTests and review catch less
PR size distributionChanged lines per PRThe leading indicator for all of the above

Baseline before rollout, segment by the disclosure field, and never rank individuals with these (see Big Tech Practices & Team Adoption).

Bank lens: segregation of duties and audit trail​

  • Maker and checker are humans. The engineer who ran the agent is the accountable author; a different, authorized human approves. A bot account is never the checker.
  • Agents hold no merge, deploy or production credentials — otherwise maker and checker collapse into one actor.
  • Attribution. Commits carry the human author, plus an AI trailer such as Co-Authored-By if policy requires; CI service accounts have least privilege.
  • Audit trail. The PR links ticket and spec and records AI disclosure, CI results and approvals, retained per change-management policy. Branch-protection and CODEOWNERS settings are evidence too — export them and review bypass rights periodically.
  • Mapped controls. "Core banking logic changes are approved by a designated owner" is CODEOWNERS plus required review on /internal/ledger/ (see Compliance).

Trade-offs​

PracticeStrengthsWeaknessesChoose when
Line-by-line review of all AI codeThoroughDoes not scale with AI volumeMoney, auth and ledger paths
Risk-based depth via CODEOWNERSFocuses scarce attentionNeeds accurate path ownershipDefault for most repositories
AI first-pass review botFast, tireless, catches mechanical issuesNoise; not accountable; injection riskAdvisory on every PR
Sampling review of mechanical migrationsScales to thousands of filesCan miss outliersCodemods and test migrations with strong tests
Strict dependency allowlistBlocks slopsquatting, licence surprisesFriction for new librariesRegulated codebases

In practice​

A reviewer's first five minutes on an AI-assisted PR:

git diff --stat origin/main...HEAD # size and shape
git diff origin/main...HEAD -- go.mod go.sum # new modules?
git diff origin/main...HEAD -- '*_test.go' '*/testdata/*' # tests weakened?
git diff origin/main...HEAD -- .github .golangci.yml # guardrails touched?
git diff origin/main...HEAD | grep -nE '^-.*(err != nil|authz|rows\.Err|Lock\()' # removed checks
git diff origin/main...HEAD | grep -nE '^\+.*(nolint|t\.Skip|_ = |ioutil\.)' # risky additions

Then read description and disclosure, deletions, tests, core logic and wiring. If the PR is too big to review properly, ask for a split — a valid review outcome.

Common pitfalls​

  • Approving because it looks clean. Symptom: an IDOR or a float-money bug in code that "read like a senior wrote it".
  • Human-sized review budgets for AI-sized PRs. Symptom: review time flat while PR size doubles; failures rise a quarter later.
  • Bot approval counting as review. Symptom: an audit finding that a production change had no human checker.
  • "Fixing" CI by weakening it. Symptom: //nolint and skipped tests creep up unreviewed.
  • Agents with merge or deploy rights. Symptom: no separation of duties in the change record.

Interview angle​

  • Prompts: "How do you review AI-generated code?", "What guardrails would you put in CI for a team using coding agents?", "How do you keep maker-checker intact when AI writes code?"
  • A strong answer: AI code fails differently (deletions, hallucinated dependencies, silent behaviour change); a checklist starting with deletions; small diffs, author self-review and disclosure; AI reviewers advisory only; layered CI with supply-chain gates; CODEOWNERS on money, auth, migrations and the guardrails themselves; outcome metrics against a baseline.
  • Follow-ups: "Isn't AI review enough?", "How do you stop the agent weakening the pipeline?", "What do you show an auditor?"
  • Red flags: "the AI reviews it"; success measured as % of code generated; agents with production access.

Self-check​

1. Why does AI-generated code need a different review posture from human code?

It is fluent and matches the prompt, so it looks correct, but may be inconsistent with the codebase, the domain and the real library versions. Its typical defects — deleted checks, hallucinated packages or options, silent behaviour changes, duplication — do not stand out when you read for shape. And volume rises, so attention per line falls unless diffs stay small.

2. What is slopsquatting, and which controls stop it in a Go repository?

Registering package names that models hallucinate, so whoever trusts the suggestion pulls in malicious code. Controls: a dependency allowlist gate in CI, CODEOWNERS on go.mod and go.sum so a security owner approves any new module, govulncheck, and a private module proxy where policy requires one.

3. Scenario: an agent's PR makes the failing test pass and the code looks clean. What do you check first?

The deletions and what is missing — error checks, authorization, validation, idempotency, locks — then money and units, error mapping and sensitive logging. Agents optimizing for a passing test often remove the obstacle instead of handling it, which is invisible if you read only added lines.

4. Why can an AI review bot not be an approver?

It is not accountable, misses domain and cross-service context, can be prompt-injected through PR content, and maker-checker controls require a human other than the author. Use it as an advisory first pass.

5. Which metrics tell you whether AI adoption is hurting quality?

Change failure rate, revert rate, defect escape rate and review time, read alongside PR size, against a pre-rollout baseline and segmented by the AI-disclosure field. Rising PR size with flat review time is the early warning.

🧠 Flashcards0/8 learned · 0 retries

Exercise​

Build the guardrails and test them with a planted PR:

  1. In a sample Go service, add CI from templates/ai-workflow/dot-github/workflows/ci.yml, plus gosec and the dependency allowlist gate.
  2. Add CODEOWNERS for ledger, auth, migrations, go.mod/go.sum, .github/ and lint config; enable branch protection with code-owner review and stale-approval dismissal.
  3. Have an agent implement a small feature, then plant five defects in its PR: a removed authorization check, an ignored error, float money, an unknown module, a fake API key in a fixture.
  4. Run the review skill (templates/ai-workflow/dot-claude/skills/review-diff/SKILL.md), then review it yourself with the checklist.

Done when: CI blocks the module and the secret, linters flag the ignored error, your own review catches the authorization removal and float money, and you have noted which defects the bot missed.

Further reading​

Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).