Reviewing AI Code & CI Guardrails
- 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 mode | What it looks like in a Go service | How to catch it |
|---|---|---|
| Plausible, wrong semantics | Float money; rows loop without rows.Err(); retries that ignore the parent deadline | Read semantics, not shape; tests from the spec |
| Hallucinated API or option | Config 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 package | An unfamiliar import path one character from a popular one | Dependency allowlist; CODEOWNERS on go.mod/go.sum |
| Over-engineering, duplication | A second retry helper; a one-implementation interface; an unrequested generic repository | "What existing code does this duplicate?" |
| Silent behaviour change | Rounding mode, default timeout, 409 becoming 500, JSON field name or omitempty | Contract tests; golden files |
| Deleted checks | if err != nil replaced by _ =; authorization removed "to make tests pass"; new //nolint | Read deletions first; errcheck |
| Weakened tests | Assertion relaxed, case deleted, t.Skip | Diff tests separately (see TDD & Testing with AI) |
| Outdated idioms | ioutil, interface{}, tt := tt, rand.Seed | Linters pinned to your Go version; idioms in AGENTS.md |
| Secrets in code | Sample API keys, a committed .env, a real token in a fixture | Secret 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:
- issue (blocking): decode error ignored — a malformed body becomes a zero-value refund request. Return 400.
- issue (blocking, security): the previous version called
h.authz.CanRefund(user, pay); the diff deleted it. Any merchant can refund any payment (IDOR). - issue (blocking): every lookup error becomes 404 and echoes internal error text to the client. Map
ErrNotFoundto 404, the rest to 500 with a generic message. - issue (blocking): float money, and
* 100assumes two decimal places — VND has none. Accept minor units and currency, use the money type. - issue (blocking): no idempotency key is passed through; a client retry refunds twice.
- issue (blocking): string matching on error text. Use
errors.Is(err, refund.ErrExceedsRemaining). - 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
| Area | Questions for AI-generated code |
|---|---|
| Scope | Only what the spec asks? Any unrequested refactor, rename, dependency or config change? |
| Deletions | Every removed line first: error checks, authorization, validation, rows.Err(), locks, metrics. |
| Correctness | Spec edge cases; each library call's semantics checked against the version in go.mod. |
| Money and units | Money type with currency; minor units per currency; explicit rounding; no floats; time zones. |
| Error paths | Every error checked and wrapped with %w; errors.Is, not string matching; timeouts as unknown outcomes. |
| Concurrency | Check-then-act, goroutine leaks, missing cancellation, shared maps; a -race test. |
| Security | Authorization on every resource ID; validated input; parameterized SQL; no secrets or PII in logs. |
| Data access | Backward-compatible migrations; indexed queries; short transactions without network calls. |
| Observability | Structured logs; metrics and traces on new paths; errors logged once. |
| Tests | Approved 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:
- Small diffs. A soft cap (≈400 changed lines excluding generated code — a rough guide); ask agents for stacked PRs: migration, repository, use case, handler.
- 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.
- 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. - Separate mechanical from semantic. Large AI-driven migrations are reviewed by sampling plus strong tests, and never mixed with behaviour changes.
- 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
| Guardrail | What it catches in AI code | Notes (as of 2026) |
|---|---|---|
gofmt, go vet | Unformatted output, printf mismatches, copied locks, lost cancel | Seconds; fail fast |
| staticcheck or golangci-lint | Deprecated APIs, unused code, ignored errors | Shared config (see Code Review) |
govulncheck | Known-vulnerable modules reachable from your code | Agents often suggest old versions |
gosec | SQL string building, weak crypto, hard-coded credentials | Standalone or via golangci-lint |
| Secret scanning (e.g. gitleaks) | Keys and tokens in code and history | Also pre-commit |
| Dependency allowlist, licence scan (e.g. go-licenses) | Slopsquatted modules; copyleft licences | Owned by security |
go test -race, integration | Regressions, data races | Locked tests as contract |
| CODEOWNERS | Sensitive paths reach their owners | Include CI and lint config |
| Required approval, branch protection | Merge without a human; stale approvals | No 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
| Metric | Definition | A bad trend means |
|---|---|---|
| Change failure rate | Share of deployments needing remediation | Review and tests are not keeping up with volume |
| Revert rate | Share of merged PRs reverted within, say, 14 days | Plausible-but-wrong code is getting through |
| Review time | Time to first review and to approval | Overload — or rubber-stamping, if time falls while PR size rises |
| Defect escape rate | Defects found in production ÷ all defects found | Tests and review catch less |
| PR size distribution | Changed lines per PR | The 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-Byif 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
| Practice | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Line-by-line review of all AI code | Thorough | Does not scale with AI volume | Money, auth and ledger paths |
| Risk-based depth via CODEOWNERS | Focuses scarce attention | Needs accurate path ownership | Default for most repositories |
| AI first-pass review bot | Fast, tireless, catches mechanical issues | Noise; not accountable; injection risk | Advisory on every PR |
| Sampling review of mechanical migrations | Scales to thousands of files | Can miss outliers | Codemods and test migrations with strong tests |
| Strict dependency allowlist | Blocks slopsquatting, licence surprises | Friction for new libraries | Regulated 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:
//nolintand 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.
Exercise
Build the guardrails and test them with a planted PR:
- In a sample Go service, add CI from
templates/ai-workflow/dot-github/workflows/ci.yml, plus gosec and the dependency allowlist gate. - 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. - 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.
- 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
- Google Engineering Practices: Code Review
- Joseph Spracklen et al., "We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs" (USENIX Security 2025).
- Socket research blog, report on the typo-squatted BoltDB module served by the Go module mirror (February 2025).
- Go vulnerability management (govulncheck)
- golangci-lint documentation
- GitHub Docs: About protected branches
Related
- Code Review & Engineering Standards — general review practice and the payment checklist.
- TDD & Testing with AI — locked tests and the oracle problem.
- Setting Up a Repo for AI Agents — permissions, hooks and the templates referenced here.
- Big Tech Practices & Team Adoption — measurement and rollout.
- Security for Architects — supply chain, secrets, least privilege.
- LLM Security, Privacy & Governance — prompt injection and data handling.
- Compliance: PCI DSS, KYC/AML, Data Protection — why change controls are non-negotiable in banks.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).