AI Code Review Golang: Cara AI Jadi Reviewer yang Efektif untuk Go
Menggunakan AI sebagai code reviewer untuk Golang. Setup pre-PR AI review, custom review rules, integrasi dengan GitHub Actions, dan cara maksimalkan value dari AI review.
AI sebagai Code Reviewer untuk Golang
AI code review golang adalah salah satu use case dengan ROI paling cepat terasa untuk tim Go. Code review sering jadi bottleneck di software development: reviewer yang sibuk, PR yang numpuk, feedback yang lambat. AI tidak menggantikan human review — tapi sangat efektif sebagai first-pass reviewer yang instan menangkap mechanical issue, sehingga human reviewer bisa fokus ke logic dan architecture.
Di artikel ini kita bahas cara menyetel AI review yang benar-benar berguna: batasan yang jelas antara apa yang AI review dengan baik dan apa yang harus tetap ditangani manusia, plus setup praktis dari pre-PR sampai GitHub Actions.
14.1 Apa yang AI Review Lakukan dengan Baik
Sebelum memakai AI sebagai reviewer, penting memahami batasnya: ada hal yang AI tangkap sangat baik, ada yang justru lemah. Peta berikut memisahkan mechanical check yang deterministik dari hal yang butuh domain knowledge.
1AI review sangat efektif untuk:
2
3✅ MECHANICAL CHECKS (deterministic, objective):
4 - Error handling patterns (fmt.Errorf dengan %w?)
5 - Architecture violations (handler import repo impl?)
6 - Type safety (float64 untuk money?)
7 - Context propagation (ctx di-pass ke semua downstream?)
8 - Nil handling (check nil setelah repo call?)
9 - Naming conventions
10 - Import organization
11 - Go idiom violations (panic di non-main, init() abuse)
12
13✅ COMPLETENESS CHECKS:
14 - Test coverage untuk semua error paths
15 - Missing error codes
16 - Incomplete interface implementation
17 - Missing godoc comments
18
19⚠️ AI review KURANG EFEKTIF untuk:
20 - Business logic correctness (AI tidak tahu domain rules)
21 - Security vulnerability yang complex
22 - Performance implications di high-traffic scenarios
23 - Architecture decision yang butuh context business luas
24 - Subtle concurrency bugs yang butuh domain knowledgePrinsipnya jelas: serahkan pekerjaan mekanis dan berpola ke AI, tapi jangan berharap AI menggantikan penilaian manusia soal benar-salahnya business logic.
14.2 Setup Pre-PR AI Review dengan Claude Code
Cara paling cepat merasakan manfaatnya adalah menjalankan review sebelum PR dibuat. Dua pendekatan berikut menunjukkan prompt review terstruktur dan cara memipe git diff langsung ke Claude Code.
1# Approach 1: Manual pre-PR review
2
3claude
4> Review semua perubahan di working directory ini:
5> [atau: "Review PR diff dari main ke HEAD"]
6>
7> Check untuk:
8>
9> CRITICAL (harus fix sebelum PR):
10> 1. Error handling: semua error di-wrap dengan fmt.Errorf?
11> 2. Repository: return nil, nil untuk not-found?
12> 3. Architecture: tidak ada cross-layer imports yang violate?
13> 4. Types: tidak ada float64 untuk monetary values?
14> 5. Context: ctx di-pass ke semua downstream calls?
15> 6. Nil checks: semua repo return di-check nil sebelum use?
16>
17> SUGGESTION (nice to have):
18> 7. Test coverage untuk semua error paths?
19> 8. Godoc untuk exported functions?
20> 9. Error messages yang helpful?
21>
22> Format output:
23> CRITICAL: [issue] at [file:line] — [explanation + fix]
24> SUGGESTION: [improvement] at [file:line]
25> SCORE: [X]/100
26>
27> Mulai dari yang paling critical.
28
29# Approach 2: AI review dari git diff
30git diff main..HEAD -- '*.go' | claude
31> Review diff ini. Check: error handling, architecture, types, nil checks.
32> Format: CRITICAL/SUGGESTION/SCOREKunci kualitas review ada di format output yang terstruktur (CRITICAL/SUGGESTION/SCORE): ini memaksa AI memberikan feedback yang bisa langsung ditindaklanjuti, bukan komentar naratif yang mengambang.
14.3 GitHub Actions AI Review dengan Copilot
Setelah pre-PR review manual terbukti bermanfaat, langkah berikutnya adalah mengotomasinya di CI. Workflow berikut menjalankan Copilot review otomatis pada setiap PR Go dengan review-instructions yang eksplisit.
1# .github/workflows/ai-code-review.yml
2
3name: AI Code Review
4
5on:
6 pull_request:
7 types: [opened, synchronize, ready_for_review]
8 paths: ['**.go']
9
10jobs:
11 ai-review:
12 runs-on: ubuntu-latest
13 if: github.event.pull_request.draft == false
14 permissions:
15 pull-requests: write
16 contents: read
17
18 steps:
19 - uses: actions/checkout@v4
20 with:
21 fetch-depth: 0
22
23 - name: Copilot Go Review
24 uses: github/copilot-for-pull-requests@v1
25 with:
26 github-token: ${{ secrets.GITHUB_TOKEN }}
27 review-type: "code-review"
28 review-instructions: |
29 Review Go code untuk Santekno Shop production service.
30
31 CRITICAL CHECK (comment sebagai "CRITICAL: ..."):
32 1. Error wrap: SEMUA error harus fmt.Errorf("pkg.Method: %w", err)
33 Jika ada: return err (tanpa wrap) → CRITICAL
34
35 2. Repository not-found: HARUS return nil, nil
36 Jika ada: return nil, pgx.ErrNoRows → CRITICAL
37
38 3. Monetary type: HARUS int64 cents
39 Jika ada: float64 atau float32 untuk price/amount → CRITICAL
40
41 4. Architecture: handler tidak boleh import repository impl
42 Jika ada cross-layer import → CRITICAL
43
44 5. Context: ctx harus di-pass ke semua downstream calls
45 Jika ada DB/cache call tanpa ctx → CRITICAL
46
47 SUGGESTION CHECK (comment sebagai "SUGGESTION: ..."):
48 6. Test coverage untuk semua error paths
49 7. Godoc untuk exported functions dan types
50 8. Interface methods tidak lebih dari 5 (split jika lebih)
51
52 Untuk setiap issue: berikan exact code fix, bukan hanya description.
53 Prioritaskan CRITICAL sebelum SUGGESTION.
54 Akhiri dengan: REVIEW_SCORE: [X]/100Dengan workflow ini, review mekanis berjalan otomatis di setiap PR tanpa mengandalkan reviewer mengingat semua aturan — konvensi tim tertanam langsung di CI.
14.4 AI Review sebagai PR Template
Agar hasil AI review terdokumentasi di setiap PR, tempelkan bagian khusus di deskripsi PR. Template berikut menyediakan tempat untuk output AI review beserta status CRITICAL dan manual test.
1<!-- .github/pull_request_template.md -->
2
3## Summary
4[Describe what this PR does]
5
6## Changes
7- [ ] Domain changes
8- [ ] Usecase changes
9- [ ] Repository changes
10- [ ] Handler changes
11- [ ] Tests
12
13## AI Pre-Review Checklist
14Copy-paste output dari AI review di sini:
15
16```
17[AI Review Output]
18CRITICAL: [list]
19SUGGESTION: [list]
20SCORE: __/100
21```
22
23Status: ✅ Semua CRITICAL sudah di-fix | ⚠️ Ada CRITICAL yang masih outstanding
24
25## Manual Test
26- [ ] go test -race ./... ✅
27- [ ] go build ./... ✅
28- [ ] go vet ./... ✅
29
30## Spec Compliance
31- [ ] specify audit score: __/100Template ini membuat AI review jadi bagian resmi dari proses PR, bukan langkah opsional yang mudah dilewati saat sedang buru-buru.
14.5 Review Rules yang Comprehensive untuk Go
Semakin eksplisit aturan yang kamu berikan, semakin konsisten hasil review-nya. Prompt komprehensif berikut mendefinisikan aturan CRITICAL dan SUGGESTION lengkap dengan penalti skor untuk setiap pelanggaran.
1# Claude Code review rules yang comprehensive:
2
3claude
4> Review ini dengan rules berikut:
5>
6> === CRITICAL RULES (score penalty: -10 each) ===
7>
8> C1. ERROR WRAPPING
9> All errors must use: fmt.Errorf("packageName.MethodName: %w", err)
10> Violations: "return err", errors.New() in non-domain code, wrap tanpa %w
11>
12> C2. REPOSITORY NOT-FOUND
13> Must return (nil, nil) for not-found, never an error
14> Violation: return nil, pgx.ErrNoRows, return nil, sql.ErrNoRows
15>
16> C3. MONETARY TYPES
17> Must use int64 (cents), never float64/float32
18> Violation: Price float64, Amount float32, any decimal for money
19>
20> C4. ARCHITECTURE LAYERS
21> handler: only import usecase interfaces
22> usecase: only import domain + repository interfaces
23> repository: only import domain + drivers
24> domain: zero external imports
25>
26> C5. CONTEXT PROPAGATION
27> ctx must be first parameter and passed to ALL downstream
28> Violation: DB query without ctx, HTTP call without ctx
29>
30> C6. NIL CHECKS
31> After every repo/cache call: check error, then check nil
32> Violation: use result without nil check
33>
34> C7. ERROR IGNORE
35> Never use _ for errors in non-test code
36> Violation: result, _ := db.Query(...)
37>
38> === SUGGESTION RULES (score penalty: -3 each) ===
39>
40> S1. TEST COVERAGE
41> Error paths should have corresponding test cases
42>
43> S2. GODOC
44> Exported functions, types, constants need godoc
45>
46> S3. INTERFACE SIZE
47> Interface methods > 5: suggest split
48>
49> S4. CONTEXT TIMEOUT
50> External calls should have context with timeout
51>
52> === OUTPUT FORMAT ===
53> [CRITICAL|SUGGESTION] [rule-code]: [description] at [file:line]
54> Fix: [exact code fix]
55>
56> Final: SCORE: [X]/100 (100 - sum of penalties)Aturan dengan kode (C1, C2, …) dan penalti terukur membuat review menjadi reproducible dan mudah di-audit — kamu bisa lacak pelanggaran mana yang paling sering muncul dari waktu ke waktu.
14.6 AI Review untuk Security Issues di Go
Selain kualitas kode, AI juga bisa jadi lapisan pertama untuk isu keamanan yang umum. Prompt berikut mengarahkan review ke delapan kategori kerentanan Go yang sering luput, dari SQL injection hingga concurrency issue.
1# Security-focused review prompt:
2claude
3> Review code ini untuk common Go security issues:
4>
5> 1. SQL INJECTION
6> Parameterized queries? Tidak ada string concatenation di SQL?
7>
8> 2. PATH TRAVERSAL
9> User-controlled file paths yang tidak di-sanitize?
10>
11> 3. RATE LIMITING
12> Endpoints yang bisa di-abuse tanpa rate limit?
13>
14> 4. AUTHENTICATION CHECK
15> Protected endpoints yang lupa auth middleware?
16>
17> 5. INFORMATION DISCLOSURE
18> Error messages yang expose internal details?
19> Stack trace yang di-return ke client?
20>
21> 6. INSECURE DEFAULTS
22> TLS config yang insecure?
23> Hardcoded secrets?
24>
25> 7. INTEGER OVERFLOW
26> Arithmetic yang bisa overflow untuk financial data?
27> (int64 untuk price ok, tapi multiplication harus careful)
28>
29> 8. CONCURRENCY ISSUES
30> Shared state yang tidak di-protect?
31> Channel yang bisa deadlock?
32>
33> Mark setiap issue sebagai: CRITICAL (exploit potential) atau WARNINGPerlu diingat: AI review keamanan adalah first-pass, bukan pengganti security audit — ia menangkap pola umum, tapi kerentanan yang kompleks tetap butuh mata manusia yang paham konteks.
14.7 AI Review untuk Performance Issues
AI juga bisa menandai potensi masalah performa yang baru terasa di traffic tinggi. Prompt berikut memfokuskan review pada tujuh pola performa klasik seperti N+1 query, unbounded query, dan goroutine leak.
1# Performance-focused review:
2claude
3> Review code ini untuk potential performance issues di high-traffic scenario:
4>
5> 1. N+1 QUERIES
6> Loop yang contain DB queries?
7> → Seharusnya batch query atau JOIN
8>
9> 2. MISSING INDEX
10> Query tanpa index yang obvious? (filter by non-PK column di large table)
11>
12> 3. UNBOUNDED QUERY
13> SELECT * tanpa LIMIT untuk potentially large table?
14>
15> 4. MISSING CACHE
16> Data yang sering di-read dan jarang berubah tapi tidak di-cache?
17>
18> 5. EXPENSIVE OPERATION IN HOT PATH
19> JSON serialization yang expensive di loop?
20> String concatenation di loop?
21>
22> 6. GOROUTINE LEAK POTENTIAL
23> Goroutine yang tidak punya cancellation mechanism?
24>
25> 7. MEMORY ALLOCATION
26> Large struct yang di-pass by value (harusnya pointer)?
27> Append dalam loop yang bisa grow significantly?
28>
29> Mark: HIGH (akan ketara di production) / MEDIUM / LOWPenandaan HIGH/MEDIUM/LOW membantu memprioritaskan: tidak semua temuan performa perlu diperbaiki sekarang, tapi yang ber-flag HIGH biasanya layak ditangani sebelum merge.
14.8 Self-Review Workflow: AI sebelum Human
Agar AI dan human review saling melengkapi, susun urutan yang jelas: developer self-review, AI otomatis, baru human. Alur empat tahap berikut menunjukkan pembagian fokus di tiap tahap.
1Workflow yang efektif untuk code review:
2
31. DEVELOPER SELF-REVIEW (dengan AI):
4 Sebelum push PR:
5
6 claude > "Review perubahan yang saya buat hari ini"
7 → Fix semua CRITICAL
8 → Evaluate SUGGESTIONS
9 → Score target: > 90/100
10
11 go test -race ./...
12 golangci-lint run ./...
13
14 Commit dengan message yang informative
15
162. AI AUTOMATED REVIEW (di GitHub Actions):
17 PR dibuat → Copilot otomatis review
18 → Fix issues yang di-flag
19 → Update PR
20
213. HUMAN REVIEW (setelah AI pre-filter):
22 Reviewer tidak perlu check:
23 - Error handling format
24 - Architecture violations
25 - Type safety
26 (AI sudah catch ini)
27
28 Reviewer fokus ke:
29 - Business logic correctness
30 - Architecture decisions (bukan violations)
31 - Code clarity dan maintainability
32 - Edge cases yang AI miss
33 - Security implications yang domain-specific
34
354. MERGE:
36 All CRITICAL issues resolved
37 AI score: > 85/100
38 Human reviewer approvedInti alur ini adalah pembagian kerja: AI menyaring hal mekanis di tahap 1-2, sehingga human reviewer di tahap 3 bisa mencurahkan energinya ke hal yang benar-benar butuh penilaian manusia.
14.9 Metrics: AI Review Effectiveness
Untuk membuktikan AI review benar-benar bernilai, ukur dampaknya dengan metrik konkret. Empat metrik berikut menunjukkan cara membandingkan kondisi sebelum dan sesudah AI review diadopsi.
1Cara mengukur value dari AI review:
2
3Metric 1: Mechanical review comments per PR
4 Before AI review: [X] comments tentang error handling, types, dll.
5 After AI review (AI catch first): [Y] comments
6 Target: Y < X * 30% (AI catch 70%+ mechanical issues)
7
8Metric 2: Time spent in human review per PR
9 Before: [X] menit average
10 After: [Y] menit average
11 Target: Y < X * 50% (reviewer lebih fokus)
12
13Metric 3: Post-merge bug rate
14 Before: [X] bugs/sprint yang discovered post-merge
15 After: [Y] bugs/sprint
16 Target: Y < X * 60% (AI catches more before merge)
17
18Metric 4: PR cycle time (open to merge)
19 Before: [X] hari average
20 After: [Y] hari average
21 Target: Y < X (faster feedback loop)
22
23Track ini semua di spreadsheet, evaluate quarterly.Dengan metrik ini, keputusan mempertahankan atau menyetel ulang AI review jadi berbasis data, bukan sekadar kesan bahwa “review terasa lebih cepat”.
14.10 Common AI Review Limitations dan Mitigations
AI review punya keterbatasan yang nyata, tapi sebagian besar bisa dimitigasi dengan prompt yang lebih baik. Tabel mental berikut memasangkan tiap keterbatasan dengan mitigasinya.
1Limitation 1: AI tidak tahu business context
2 Example: "ini harus idempotent karena Kafka delivery"
3 AI tidak tahu Kafka delivery semantics kamu
4
5 Mitigation: Include domain context di review prompt
6 "Review ini. Context: ini adalah Kafka consumer handler.
7 Idempotency adalah CRITICAL requirement karena at-least-once delivery."
8
9Limitation 2: False positives
10 AI kadang flag code yang actually correct
11
12 Mitigation: Include exceptions di review rules
13 "Note: test files boleh ignore errors dengan _"
14 "Note: domain error types boleh return errors.New()"
15
16Limitation 3: False negatives (miss yang seharusnya caught)
17 Untuk complex business logic bugs, AI bisa miss
18
19 Mitigation: Human review untuk business logic
20 AI review untuk mechanical, human review untuk logic
21
22Limitation 4: Inconsistency antar runs
23 Same code bisa dapat review yang sedikit berbeda tiap run
24
25 Mitigation: Structured prompts dengan explicit rules
26 → More rules = more consistent resultsPola mitigasinya konsisten: semakin banyak konteks dan aturan eksplisit yang kamu berikan, semakin sedikit false positive dan semakin stabil hasil review antar run.
14.11 Review Rules yang Bisa Dipakai di Semua Tools
Aturan review yang baik seharusnya portable antar tool. Prompt universal berikut bisa dipakai di Claude Code, Cursor, Copilot Chat, maupun Windsurf tanpa perubahan.
1# Universal review prompt yang work untuk Claude Code, Cursor, Copilot Chat
2
3REVIEW_PROMPT="Review perubahan ini untuk Go production code:
4
5CRITICAL (stop PR kalau ada ini):
6□ Error tanpa wrap (return err, bukan fmt.Errorf)
7□ Repository return error untuk not-found (bukan nil, nil)
8□ Float64 untuk monetary values
9□ Architecture layer violations
10□ Error yang di-ignore dengan _
11
12IMPORTANT (fix recommended):
13□ Context tidak di-propagate ke downstream
14□ Nil tidak di-check setelah repo call
15□ Interface > 5 methods
16
17NICE TO HAVE:
18□ Missing godoc untuk exported symbols
19□ Missing test untuk error paths
20
21Output: list issues dengan file:line, severity, dan exact fix.
22End dengan: OVERALL: APPROVE / REQUEST_CHANGES / NEEDS_REVIEW"
23
24# Gunakan prompt ini di:
25# Claude Code: claude > "$REVIEW_PROMPT"
26# Cursor: Composer atau Chat dengan prompt
27# Copilot: Chat dengan @workspace + prompt
28# Windsurf: Chat dengan promptMenyimpan satu prompt review sebagai variabel yang tool-agnostic membuat tim konsisten: aturan yang sama diterapkan siapa pun developernya dan apa pun tool favoritnya.
14.12 Team Review Workflow dengan AI
Untuk tim, AI review perlu dijadikan norma bersama, bukan kebiasaan individu. Alur berikut merangkum setup awal, workflow per-PR, ritual bulanan, dan anti-pattern yang harus dihindari untuk tim 5-10 developer.
1Recommended workflow untuk tim 5-10 developer:
2
3SETUP:
4 □ Setup GitHub Actions Copilot review (14.3)
5 □ Semua developer install AI tool (Claude Code / Cursor)
6 □ Share pre-PR review prompt (14.2) ke semua developer
7 □ Add AI review section ke PR template (14.4)
8
9PER PR WORKFLOW:
10 Developer → self AI review (< 5 menit) → push PR
11 GitHub Actions → Copilot review (auto, < 5 menit)
12 Reviewer → human review (focus: logic, tidak mechanical)
13
14 PR tidak boleh di-review human tanpa AI review complete
15
16MONTHLY:
17 Review AI review effectiveness metrics (14.9)
18 Update review rules berdasarkan issues yang sering muncul
19 Update CLAUDE.md/copilot-instructions jika ada pattern baru
20
21ANTI-PATTERN:
22 "AI review sudah cukup, tidak perlu human review"
23 → WRONG. AI sebagai filter, bukan replacementAnti-pattern di akhir adalah yang paling penting diingat: AI review adalah filter yang mempercepat human review, bukan alasan untuk menghapusnya.
14.13 Review untuk Database Migration
File migration database punya risiko khusus yang berbeda dari kode aplikasi biasa. Prompt review berikut mengecek tujuh aspek migration yang berbahaya, dari operasi destructive hingga locking table besar.
1# Special review untuk migration files:
2claude
3> Review migration file ini (SQL):
4> @migrations/20250701_cancel_order_index.sql
5>
6> Check:
7> 1. DESTRUCTIVE: apakah ada DROP atau DELETE tanpa backup strategy?
8> 2. LOCKING: apakah ada operation yang lock table besar?
9> (ALTER TABLE di PostgreSQL bisa lock production table)
10> 3. REVERSIBLE: apakah ada down migration yang sesuai?
11> 4. INDEX: apakah tidak ada index yang missing untuk column yang sering di-query?
12> 5. DEFAULT VALUES: apakah new NOT NULL column punya default yang benar?
13> 6. FK CONSTRAINT: apakah foreign key ada index?
14> 7. DATA MIGRATION: apakah data migration yang safe (tidak truncate tanpa backup)?
15>
16> Mark sebagai: BLOCKING (jangan deploy sampai fix) / WARNING / OKReview migration wajib memakai kategori BLOCKING karena kesalahan di sini bisa mengunci production table atau menghapus data — konsekuensinya jauh lebih besar daripada bug kode biasa.
14.14 Menggabungkan AI Review dengan specify audit
AI mechanical review menjadi makin kuat ketika digabung dengan audit spec compliance. Alur berikut menggabungkan skor AI review dan skor kepatuhan spec menjadi satu combined score yang jadi gate merge.
1# Combine AI review dengan Spec Kit audit:
2
3# Step 1: AI mechanical review
4claude > "Review perubahan saya dari perspektif Go conventions dan architecture"
5
6# Step 2: Spec compliance audit
7specify audit --feature cancel-order --compare-to spec.md
8# → Check apakah implementation match semua ACs
9
10# Step 3: Combined score
11# AI review score: 92/100
12# Spec compliance: 95/100
13# Combined: (92 + 95) / 2 = 93.5/100
14
15# Target untuk PR: combined score > 85/100
16
17# Automatic di CI:
18# .github/workflows/quality-gates.yml
19# Step 1: go test + lint (standard)
20# Step 2: specify audit (spec compliance)
21# Step 3: Copilot review (AI mechanical review)
22# All must pass untuk mergeCombined score menyatukan dua pertanyaan penting sekaligus: “apakah kodenya bersih?” (AI review) dan “apakah kodenya sesuai spec?” (specify audit) — keduanya harus lulus sebelum merge.
14.15 Tips & Gotchas
💡 Tip 1: Review prompt yang spesifik selalu lebih baik dari generic
“Review code ini” → terlalu generic, AI akan review semua hal. “Review untuk error handling violations dan architecture issues” → targeted, actionable.
💡 Tip 2: Update review rules setelah setiap sprint
Jika ada issue yang tidak tertangkap AI review dan lolos ke production, tambahkan ke review rules segera.
💡 Tip 3: Pre-review diri sendiri dengan AI sebelum request human review
“Saya malu kalau reviewer nemuin mechanical issues yang bisa AI catch” — ini adalah motivasi yang bagus untuk pre-review.
💡 Tip 4: Track false positive rate
Jika AI flagging too many things yang actually correct: refine rules untuk reduce noise. Review harus actionable, bukan overwhelming.
⚠️ Gotcha 1: Review yang terlalu panjang
AI review yang memberikan 30+ issues sering diabaikan. Target: max 10-15 issues yang most important. Gunakan scoring (CRITICAL/SUGGESTION) untuk prioritisasi.
⚠️ Gotcha 2: Developer yang bypass AI review
“Ini PR kecil, skip AI review dulu.” — tidak ada PR yang terlalu kecil untuk 5 menit AI review. Policy: semua PR dapat AI review.
14.16 Advanced: Custom Review Bot untuk Internal Tools
Kalau tim butuh review yang lebih ter-custom, kamu bisa membangun review bot sendiri memakai Claude API. Kode Go berikut mengambil git diff PR, mengirimkannya ke Claude, lalu keluar dengan exit code 1 jika ada CRITICAL issue agar CI gagal.
1// Jika tim butuh review yang lebih customized: build custom review bot
2
3// cmd/review-bot/main.go
4package main
5
6import (
7 "context"
8 "fmt"
9 "os"
10 "os/exec"
11 "strings"
12
13 "github.com/anthropics/anthropic-sdk-go"
14)
15
16func main() {
17 // Get git diff dari PR
18 diff, err := getGitDiff()
19 if err != nil {
20 fmt.Fprintf(os.Stderr, "Error getting diff: %v\n", err)
21 os.Exit(1)
22 }
23
24 // Review dengan Claude API
25 review, score, err := reviewWithClaude(diff)
26 if err != nil {
27 fmt.Fprintf(os.Stderr, "Review error: %v\n", err)
28 os.Exit(1)
29 }
30
31 fmt.Println(review)
32
33 // Exit dengan code 1 jika ada CRITICAL issues
34 if score < 70 || strings.Contains(review, "CRITICAL:") {
35 os.Exit(1) // CI akan fail
36 }
37}
38
39func getGitDiff() (string, error) {
40 cmd := exec.Command("git", "diff", "main..HEAD", "--", "*.go")
41 out, err := cmd.Output()
42 return string(out), err
43}
44
45func reviewWithClaude(diff string) (string, int, error) {
46 client := anthropic.NewClient()
47
48 prompt := fmt.Sprintf(`Review Go code diff untuk production service.
49
50Rules:
51CRITICAL (exit 1 if found):
52- Error not wrapped with fmt.Errorf("pkg.Method: %%w", err)
53- Repository returns error for not-found (must nil, nil)
54- float64 for monetary values
55- Architecture layer violations
56
57SUGGESTION (warning only):
58- Missing tests for error paths
59- Interface > 5 methods
60
61Diff:
62%s
63
64Output: list issues + SCORE:[0-100]`, diff)
65
66 msg, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
67 Model: anthropic.F(anthropic.ModelClaudeSonnet4_6),
68 MaxTokens: anthropic.F(int64(2000)),
69 Messages: anthropic.F([]anthropic.MessageParam{
70 anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),
71 }),
72 })
73 if err != nil {
74 return "", 0, fmt.Errorf("claude api: %w", err)
75 }
76
77 result := msg.Content[0].Text
78
79 // Extract score dari result
80 score := 80 // default
81 fmt.Sscanf(result, "SCORE:%d", &score)
82
83 return result, score, nil
84}Dengan bot ini, kamu punya kontrol penuh atas aturan dan gate: exit code 1 saat menemukan CRITICAL membuat review AI menjadi quality gate yang benar-benar memblokir merge, bukan sekadar komentar.
14.17 Review untuk Concurrent Go Code
Kode konkuren adalah area di mana bug paling sulit terdeteksi mata biasa. Prompt review khusus berikut mengarahkan AI ke lima kategori masalah konkuren Go: data race, channel, context cancellation, errgroup, dan WaitGroup.
1# Special review rules untuk concurrent code:
2claude
3> Review concurrent code ini dengan fokus ke:
4>
5> 1. DATA RACES
6> Shared variable yang di-access concurrent tanpa sync?
7> → Solusi: sync.Mutex, sync.RWMutex, atau atomic
8>
9> 2. CHANNEL CORRECTNESS
10> Channel yang bisa deadlock?
11> Goroutine yang tidak exit (goroutine leak)?
12> Close channel yang nil?
13>
14> 3. CONTEXT CANCELLATION
15> Goroutine yang tidak respect context cancellation?
16> → Setiap goroutine harus select case ctx.Done()
17>
18> 4. ERRGROUP USAGE
19> Error dari goroutine yang tidak di-propagate?
20> → Pakai errgroup.WithContext untuk goroutine management
21>
22> 5. WAITGROUP
23> wg.Add() sebelum go? (bukan di dalam goroutine)
24> wg.Done() dijamin terpanggil? (defer wg.Done())
25>
26> Mark: RACE_CONDITION (critical) / LEAK (critical) / WARNINGUntuk kode konkuren, AI review paling efektif dipadukan dengan go test -race: AI menandai pola berbahaya secara statis, sementara race detector membuktikannya secara runtime.
14.18 Dashboard AI Review Quality
Efektivitas AI review perlu dipantau berkelanjutan, bukan sekali evaluasi. Kerangka tracking berikut menyediakan ritual mingguan, retrospektif bulanan, dan metrik dashboard sederhana.
1Tracking AI review effectiveness di tim:
2
3Weekly standup addition (5 menit):
4 "AI review caught X issues yang tidak ada di pre-review"
5 "Human review caught Y issues yang AI miss"
6 "Top 3 issue types yang paling sering: ___"
7
8Monthly review retrospective:
9 PR sample dari bulan lalu (5 PRs)
10 Count: mechanical issues yang lolos ke human review
11 Count: issues yang AI catch dan developer fix sebelum push
12
13 Goal: ratio AI-catch / total-mechanical > 80%
14
15Dashboard metrics (spreadsheet sederhana):
16 Tanggal | PR ID | AI Score | CRITICAL count | Time-to-merge | Post-deploy bugsTarget rasio AI-catch di atas 80% memberi patokan konkret: kalau angkanya turun, itu sinyal bahwa review rules perlu diperbarui mengikuti pola bug terbaru.
14.19 Ringkasan Extended: ROI AI Code Review
Untuk meyakinkan manajemen, angka ROI berbicara lebih keras daripada narasi. Kalkulasi berikut membandingkan overhead review mekanis tanpa dan dengan AI untuk tim 5 developer, lengkap dengan estimasi biaya dan ROI.
1Kalkulasi ROI AI Code Review untuk tim 5 developer:
2
3TANPA AI REVIEW:
4 Average mechanical review comments per PR: 8
5 Time reviewer spend per mechanical comment: 5 menit
6 Time developer spend fix + re-push: 10 menit
7 Total per PR: 8 × (5+10) = 120 menit = 2 jam
8 PR per week per dev: 3
9 Total mechanical review overhead per week: 5 × 3 × 2 jam = 30 jam/minggu
10
11DENGAN AI REVIEW:
12 AI catch 70% mechanical issues before human review
13 Remaining mechanical comments: 8 × 30% = 2.4 per PR
14 Total per PR: 2.4 × 15 = 36 menit = 0.6 jam
15 Total per week: 5 × 3 × 0.6 = 9 jam/minggu
16
17SAVINGS:
18 30 - 9 = 21 jam/minggu
19 = 84 jam/bulan
20
21 Jika hourly rate tim = Rp 100,000/jam:
22 Value = 84 × 100,000 = Rp 8,400,000/bulan
23
24COST:
25 Copilot Business: $19 × 5 = $95/bulan ≈ Rp 1,500,000/bulan
26
27ROI = (8,400,000 - 1,500,000) / 1,500,000 × 100 = 460%
28
29Dan ini belum include value dari: kurang post-merge bugs,
30faster PR cycle, reviewer yang lebih fokus.Angka ROI 460% ini pun konservatif karena belum menghitung penghematan dari berkurangnya bug production dan siklus PR yang lebih cepat — argumen bisnis untuk AI review sangat kuat.
14.20 Integrasi dengan Pull Request Checklist
Agar AI review benar-benar tertanam, jadikan bagian dari checklist PR baik untuk developer maupun reviewer. Template checklist berikut memisahkan tanggung jawab keduanya dengan jelas.
1# PR Checklist yang Include AI Review
2
3## Developer Checklist (before requesting review)
4- [ ] AI pre-review dilakukan: `claude > "review changes"`
5- [ ] AI review score: ___/100
6- [ ] Semua CRITICAL dari AI sudah di-fix
7- [ ] go test -race ./... ✅
8- [ ] go vet ./... ✅
9- [ ] golangci-lint run ./... ✅
10
11## Reviewer Checklist (human review)
12- [ ] AI review score acceptable (> 85/100)
13- [ ] Business logic benar (AI tidak bisa check ini)
14- [ ] Edge cases yang AI mungkin miss
15- [ ] Architecture decision yang tepat
16- [ ] Code clarity yang acceptable untuk maintainabilityPemisahan checklist ini memperkuat pembagian peran: developer memastikan hal mekanis beres lewat AI, reviewer manusia fokus pada hal yang hanya bisa dinilai manusia.
14.21 Sample Review Session: End-to-End
Untuk menutup, mari lihat satu sesi review nyata dari awal sampai akhir. Transkrip berikut memperlihatkan developer menjalankan pre-review, mendapat skor 72, memperbaiki CRITICAL, lalu naik ke 92.
1# Real session: developer baru implement CancelOrder
2# Sebelum push PR, jalankan pre-review:
3
4cd santekno-shop
5git diff main..HEAD -- '*.go' | head -100
6# [shows 5 files changed]
7
8claude
9> Review perubahan yang ada di git diff main..HEAD.
10> Fokus: error handling, architecture, types, nil checks.
11> Output: CRITICAL/SUGGESTION + SCORE
12
13# Claude output:
14# CRITICAL: cancel_order.go:45 — error tidak di-wrap
15# return err (WRONG)
16# Should be: return fmt.Errorf("cancelOrder.Execute: %w", err)
17#
18# CRITICAL: order_handler.go:89 — float64 untuk monetary
19# Amount float64 (WRONG)
20# Should be: AmountIDR int64
21#
22# SUGGESTION: cancel_order.go:60 — missing nil check
23# order mungkin nil setelah repo call, check dulu
24#
25# SCORE: 72/100
26
27# Developer fix CRITICAL issues
28# Re-run review:
29
30claude
31> Review lagi setelah fix
32
33# Claude output:
34# ✅ Error wrapping: OK
35# ✅ Monetary types: OK
36# SUGGESTION: missing nil check masih ada
37#
38# SCORE: 92/100
39
40# Developer decide: fix suggestion atau push dengan note
41# Push PR dengan AI review hasil di-paste di descriptionSesi ini menunjukkan nilai nyata AI review: dua CRITICAL yang memalukan (error tanpa wrap dan float64 untuk uang) tertangkap dan diperbaiki dalam hitungan menit, jauh sebelum reviewer manusia harus melihatnya.