πŸ€– AI-Assisted Software Engineering β€” Deep Dive: Spec-Driven Dev, AI Code Review, Agent Workflow, Toolchain Comparison

Panduan komprehensif workflow software engineering modern dengan AI sebagai pair programmer. Mencakup paradigm shift dari manual-write ke spec-driven development, AI code review (apa yang AI bisa vs tidak bisa deteksi), prompt patterns untuk coding (spec→code, refactor, test-first, explain), perbandingan toolchain (Claude Code, Cursor, Copilot, Aider, Continue.dev), pitfalls AI-generated code, dan workflow rekomendasi untuk solo developer dan team. Vault udah punya clean-code-robert-martin, design-patterns-gof, refactoring-martin-fowler, the-pragmatic-programmer — semua buku klasik tentang software engineering yang tetap relevan. Catatan ini melengkapi dengan bagaimana tools baru (AI) mengubah cara kita menerapkan prinsip-prinsip itu.

Posisi di Vault

Nota ini terkait dengan clean-code-robert-martin (prinsip desain tetap berlaku β€” AI harus ngikut, bukan sebaliknya), design-patterns-gof (AI generate code dengan pattern, lo review), refactoring-martin-fowler (AI refactoring toolchain β€” CodeQL, Semgrep, Copilot), the-pragmatic-programmer (AI adalah new stone ax β€” pragmatic tetap yang utama), architectural-flaw-detection (AI code review sebagai automated gate), agentic-ai-mcp-architecture-deepdive (autonomous coding agent β€” Claude Code, Aider), dan cicd-shiftleft-shiftright (AI code review sebagai Shift-Left security gate).


Daftar Isi


Paradigma Baru β€” Spec-Driven Development

Pergeseran Tanggung Jawab

Dulu (Manual-Write):

Developer: Requirements β†’ Design β†’ Write Code β†’ Test β†’ Debug β†’ Deploy
                               ↓                        ↑
                          (bottleneck)             (loop mahal)

Sekarang (Spec-Driven):

Developer: Requirements β†’ Spec β†’ Review Spec β†’ AI Implement β†’ Review Code β†’ Test β†’ Deploy
                               ↓                             ↑
                    (lo tulis spec, AI tulis kode)   (lo review, bukan nulis)

Prinsip: Lo gak nulis kode lagi. Lo nulis spec, AI nulis implementasi, lo review & approve.

Format Spec Minimal

## Function: validate_api_key(api_key: str) -> bool

Behavior:
- Return True kalau key valid format: "sk-" + 48 karakter alfanumerik
- Return False kalau key kosong / format salah

Edge Cases:
- Key dengan whitespace -> strip dulu?
- Case-sensitive? Ya
- Key dengan karakter Unicode? Tolak

Dependencies:
- Tidak ada (pure function). No network call, no DB access.

Performance:
- Harus selesai < 1ms untuk key 51 karakter

Kenapa Spec-Driven Lebih Cepat?

AktivitasManual-WriteSpec-DrivenEfisiensi
Nulis kode baru30-60 menit2-5 menit (nulis spec) + 30 detik (AI generate)10-20x lebih cepat
Refactor1-3 jam10-15 menit (spec perubahan + AI)6-12x
Debug30 menit - 1 hari5-10 menit (deskripsi bug + spec fix)3-48x
Generate test15-30 menit2-5 menit (review hasil AI)3-6x

Spec yang Buruk = Kode yang Buruk

Garbage in, garbage out. Spec yang ambigu menghasilkan kode yang salah. Semakin detail spec, semakin bagus hasil AI. Lo tetap perlu domain expertise untuk menulis spec yang benar.

AI Code Review & Refactoring

Yang AI Bagus Deteksi

KategoriContohTools
Code smellsDuplicate code, long method, magic numbers, dead codeCopilot review, CodeRabbit
Security flawsSQL injection, XSS, hardcoded credentials, SSRF, command injectionSemgrep, CodeQL
Performance issuesN+1 query, unnecessary allocation, sync-in-asyncCopilot, SonarLint
Style & consistencyFormatting, naming convention, import orderPrettier, ESLint, AI formatter
API misuseWrong API call, deprecated function, wrong paramsCopilot inline, Cursor

Yang AI LEMAH Deteksi (masih perlu human)

KategoriKenapa AI GagalContoh
Business logic correctnessAI tau syntax, gak tau domain rules”Apakah perhitungan diskon ini benar sesuai kebijakan pricing?”
Architectural fitAI gak tau system constraints jangka panjang”Apakah dependency injection di sini akan menyulitkan testing?”
Trade-off judgmentTidak ada konteks prioritas bisnis”Keamanan ekstra vs user experience β€” mana yang dikorbankan?”
Security designAI gak punya threat model untuk system ini”Apakah arsitektur ini memenuhi compliance requirement?”

Golden Rule: Gunakan AI untuk what (apa yang salah) dan how (bagaimana memperbaiki). Jangan gunakan untuk why (kenapa keputusan diambil) β€” itu still human domain.

Prompt Patterns untuk Coding

Pattern 1: Spec β†’ Code

Buat fungsi Python dengan spec berikut:
[tempel spec]
- Gunakan type hints, Google-style docstring
- Handle semua edge cases di spec
- Jangan tambah fitur di luar spec
- Kode minimal β€” no classes, no abstractions untuk 1 fungsi

Pattern 2: Refactor with Constraints

Refactor kode ini dengan constraint:
- Jangan ubah public API signature β€” backward compatible
- Maximum 100 lines per function
- Hapus duplicate code
- Tambah logging (standard library, no external dep)
- Performance: jangan tambah O(n) baru

[tempel kode]

Pattern 3: Test-First

Buat unit test untuk fungsi ini dengan pytest
Coverage requirements:
- Happy path (valid input)
- Edge cases: empty input, None, type mismatch, boundary values
- Error cases (expected exceptions)
- Property-based test untuk validasi format

[tempel kode + spec]

Pattern 4: Explain & Improve

Jelaskan apa yang kode ini lakukan, baris per baris.
Terus kasi saran improvement (prioritas: performance > security > readability).
Jangan rewrite β€” cukup explain + suggest.

[tempel kode]

Pattern 5: Debug with Hypothesis

Kode ini menghasilkan [error/output salah].
Hypothesis: [tebak akar masalah].
Goal: Fix bug tanpa ubah behavior lain.
Kasih 2 opsi solusi sebelum implementasi.

[kode error]
[error message]

Toolchain & IDE Integration

ToolModeBahasaAutonomousKelebihanKekurangan
Claude CodeTerminal agentAllβœ… Full agentMulti-file edit, git-aware, reasoningKadang over-engineering, API cost
AiderTerminalAllβœ… Full agentOpen source, multi-model (local + cloud), map repoCLI-only, no GUI
CursorIDE (VS Code fork)Allβœ… Agent modeInline edit, tab completion, composerProprietary, lock-in
CopilotIDE pluginAll❌ Chat + inlineMature, code review built-inKurang bagus refactor besar
Continue.devIDE pluginAll❌ Chat + inlineOpen source, local model, custom rulesSetup complex
Codex CLITerminalAllβœ… Semi-agentOpenAI, sandboxed executionNew, masih beta
CodeGeminiIDE pluginAll❌ ChatGoogle integration, free tierFitur terbatas

Memilih Tool

Butuh apa?            Pilih
──────────────        ─────
Auto coding task      Claude Code / Aider / Cursor Agent
Code review           Copilot Review / CodeRabbit
Inline completion     Cursor Tab / Copilot
Local model only      Continue.dev + Ollama
Open source + control Aider + Continue.dev
Multi-file refactor   Claude Code / Cursor Composer

Pitfalls β€” Kode yang Terlihat Benar Tapi Salah

1. Halusinasi Dependency

# ❌ AI kadang pake library yang gak exist
from super_fast_library import process_data  # ImportError!
 
# βœ… Selalu test-run setelah AI generate. Minta AI: "Gunakan stdlib first"

2. Security Blindspot

# ❌ AI generate kode tanpa sanitasi
exec(user_input)  # RCE β€” attacker inject perintah OS
 
# βœ… Explicit constraint: "Jangan eval/exec input user. Gunakan whitelist validation."

3. Over-Engineering

# ❌ AI suka bikin abstraksi gak perlu
class AbstractSortingStrategyFactory:
    def create_strategy(self, type): ...
# Padahal cuma perlu: sorted(data)
 
# βœ… Spec: "Kode minimal β€” no classes, no factory, no inheritance untuk use case ini"

4. Context Amnesia

AI lupa constraint di awal setelah beberapa round. Solusi:

  • Simpan spec di file terpisah (spec.md), re-attach tiap prompt
  • Gunakan git commit checkpoint β€” rollback kalau AI ngaco
  • Satu prompt = satu intent (jangan multitask)

5. Hallucinated Security

# ❌ AI generate "security" yang salah
hashlib.md5(password.encode()).hexdigest()  # MD5 untuk password!
# AI tau "hash", tapi gak tau hashing algorithm yang tepat untuk password
 
# βœ… Explicit: "Gunakan bcrypt atau Argon2 untuk password storage"

Workflow Rekomendasi

Solo Developer (1 orang)

1. Tulis spec di .md (5-10 menit)
2. Generate implementasi (30 detik - 2 menit)
3. Test verify (5 menit)
4. AI code review β€” fokus logic & edge case (5 menit)
5. Commit

Total: ~20 menit untuk fitur yang dulu butuh 1 jam.

Security-First Workflow (production)

1. Threat model β†’ spec β†’ AI generate kode
2. SAST scan (Semgrep/CodeQL) β€” automated gate
3. AI code review β€” fokus logic & edge case
4. Human review β€” fokus arsitektur & trade-off
5. Integration test
6. Deploy dengan canary (10% traffic)

Code Review Checklist untuk AI-Generated Code

  • Apakah spec terpenuhi? (tidak kurang, tidak lebih)
  • Apakah ada hallucinated dependency?
  • Apakah ada security issue? (injection, XSS, hardcoded secret)
  • Apakah ada magic number / hardcoded value?
  • Apakah error handling proper? (try/except range, not bare except)
  • Apakah ada race condition? (shared state, timing)
  • Apakah performance acceptable? (O(n), N+1 query)
  • Apakah type hints sesuai dengan spec?

Yang Tetap Sama β€” Prinsip yang Bertahan

PrinsipKenapa Masih RelevanAdaptasi AI
DRY (Don’t Repeat Yourself)AI bisa generate duplicate code β€” lo yang reviewMinta AI: β€œHapus duplicate, extract ke fungsi bersama”
KISS (Keep It Simple)AI suka over-engineer β€” lo yang simplifySpec: β€œMinimal implementation, no patterns”
YAGNI (You Ain’t Gonna Need It)AI suka add feature yang gak dimintaSpec: β€œFitur ini ONLY, jangan tambah prep untuk future”
Single ResponsibilityAI campur logika dalam 1 fungsiSpec: β€œSatu fungsi = satu tanggung jawab”
Separation of ConcernsAI campur business logic + IOSpec: β€œDomain logic pure function, IO di layer terpisah”
TestingAI generate test yang lemahSpec test coverage: happy, edge, error, property-based

Koneksi ke Vault