Spec Validation di CI/CD Golang: Pastikan Kode Sesuai Spesifikasi Otomatis
Integrasi specify audit ke CI pipeline untuk Go. Auto-validate bahwa setiap PR memenuhi acceptance criteria dari spec. Setup GitHub Actions, scoring, dan enforcement strategy.
Spec Validation di CI: Pastikan Kode Selalu Sesuai Spec
Spec validation di CI adalah gerbang terakhir yang menutup loop Specification-Driven Development untuk Golang: setiap pull request otomatis divalidasi terhadap acceptance criteria yang sudah ditulis di spec. Di Topik 1, kita belajar SDD — menulis spec dulu, baru implement. Di Topik 2, kita belajar Spec Kit — tools untuk manage dan audit spec. Sekarang kita jawab pertanyaan praktisnya: bagaimana memastikan setiap PR yang masuk ke codebase sudah comply dengan spec yang sudah ditulis?
Tanpa otomasi, drift antara spec dan implementasi hampir tidak terhindarkan. Developer lupa. Reviewer tidak memeriksa spec. Spec di-update tapi implementasi tidak. CI yang mengintegrasikan spec validation adalah solusi satu-satunya yang scalable untuk tim yang tumbuh.
04.1 Masalah: Spec Drift yang Tidak Terdeteksi
Untuk memahami kenapa spec validation di CI penting, mari lihat skenario nyata yang sering terjadi di tim engineering ketika tidak ada mekanisme deteksi drift. Timeline berikut menunjukkan bagaimana satu perubahan kecil berkembang menjadi bug yang mahal.
1Skenario yang sering terjadi di tim engineering:
2
3Sprint 1: Tim tulis spec untuk CancelOrder
4 AC1: Order PENDING + < 30 menit → cancel → 204
5 AC2: Order bukan PENDING → 409 ORDER_NOT_CANCELLABLE
6 AC3: Order PENDING + > 30 menit → 409 CANCEL_WINDOW_EXPIRED
7 AC4: Order tidak milik user → 404 ORDER_NOT_FOUND
8
9Sprint 1 Developer A implement:
10 ✅ AC1, AC2, AC3, AC4 semua diimplementasi
11 Review: pass
12
13Sprint 3: Developer B perlu modify CancelOrder
14 (ganti 30 menit → 15 menit, per permintaan product)
15
16 Developer B update implementasi tapi LUPA update spec.
17 Review: reviewer tidak cek spec
18
19Sprint 5: Developer C baca spec untuk extend fitur
20 "Spec bilang 30 menit, tapi implementasi 15 menit..."
21 Confusion. Waktu wasted untuk investigate.
22
23Sprint 7: Bug report
24 Customer: "Order saya 18 menit tidak bisa di-cancel, padahal
25 spec bilang 30 menit"
26 Actual: spec tidak diupdate, implementasi benar (15 menit)
27 Waktu fix: 1 hari investigation + meeting
28
29Dengan spec validation di CI:
30 Sprint 3: Developer B ubah implementasi
31 Pipeline: specify audit → "Spec masih menyebut 30 menit,
32 implementasi pakai 15 menit — MISMATCH"
33 Developer B: update spec sekaligus
34 Waktu: 5 menit, bukan 1 hari investigationPerhatikan bahwa masalahnya bukan pada developer yang malas — drift terjadi karena tidak ada yang otomatis memeriksa konsistensi. CI validation mengubah investigasi satu hari menjadi feedback lima menit di saat perubahan dibuat.
04.2 Apa itu specify audit di CI?
Inti dari solusi ini adalah command specify audit dari Spec Kit yang sudah kita bahas di Topik 2. Ringkasan berikut menjelaskan apa yang dilakukan command ini dan bagaimana ia berjalan di dalam pipeline.
1specify audit adalah CLI command dari Spec Kit (Topik 2) yang:
2
31. Membaca semua spec files di .specify/features/
42. Membaca kode implementasi yang terkait
53. Menggunakan AI untuk compare spec vs implementasi
64. Output: compliance score per feature + detail issues
7
8Cara kerja di CI:
9 PR dibuat → pipeline trigger → specify audit run
10 → Score < 80: PR blocked
11 → Score ≥ 80: PR dapat proceed
12 → Issues di-comment ke PR
13
14Contoh output:
15 Feature: cancel-order
16 AC1 ✅ COMPLIANT: Status check + 204 response implemented
17 AC2 ✅ COMPLIANT: 409 for non-PENDING orders
18 AC3 ⚠️ PARTIAL: Timeout check present but uses 15min instead of 30min (spec says 30min)
19 AC4 ✅ COMPLIANT: 404 for unauthorized access
20
21 Score: 87/100
22 Issues: 1 PARTIAL compliance (AC3 timing mismatch)
23
24 Recommendation: Update spec to reflect 15-minute window OR revert to 30 minutesYang membuat audit ini berbeda dari linter biasa adalah kemampuannya membandingkan maksud (spec) dengan realisasi (kode), bukan sekadar mengecek sintaks. Skor per acceptance criteria inilah yang jadi dasar keputusan block atau proceed di pipeline.
04.3 Directory Structure untuk Spec di CI
Agar audit berjalan konsisten, spec dan konfigurasinya perlu tinggal di lokasi yang predictable di dalam repo. Struktur direktori berikut menata spec per feature berdampingan dengan workflow dan konfigurasi Spec Kit.
1santekno-shop/
2├── .specify/
3│ ├── config.yml ← specify configuration
4│ └── features/
5│ ├── cancel-order/
6│ │ ├── spec.md ← feature spec
7│ │ └── implementation/ ← link ke kode yang implement
8│ ├── create-order/
9│ │ └── spec.md
10│ └── list-orders/
11│ └── spec.md
12├── .github/
13│ └── workflows/
14│ └── spec-audit.yml ← workflow yang kita buat
15└── CLAUDE.mdDengan setiap feature punya foldernya sendiri, audit bisa menargetkan hanya feature yang berubah alih-alih men-scan seluruh repo. Selanjutnya, perilaku audit dikendalikan lewat satu file konfigurasi berikut.
1# .specify/config.yml
2version: '1.0'
3project:
4 name: Santekno Shop
5 description: B2C E-Commerce Platform Indonesia
6 language: go
7 framework: echo
8
9audit:
10 threshold: 80 # minimum score untuk pass
11 strict_mode: false # true = block semua non-100% scores
12
13 scope:
14 include:
15 - 'internal/usecase/**' # primary: check usecase layer
16 - 'delivery/http/handler/**' # secondary: check handler
17 exclude:
18 - '**/*_test.go' # skip test files
19 - '**/mock_*.go' # skip generated mocks
20
21 reporting:
22 format: markdown
23 include_suggestions: true
24 post_to_pr: trueKonfigurasi ini menentukan tiga hal penting: ambang lulus (threshold), layer mana yang di-audit (scope.include), dan apa yang di-exclude agar mock dan test tidak mengotori hasil. Sekali di-set, seluruh tim memakai aturan main yang sama.
04.4 Workflow GitHub Actions: Spec Audit
Sekarang kita rangkai audit menjadi workflow GitHub Actions yang berjalan otomatis di setiap PR. Workflow berikut men-trigger audit hanya ketika kode implementasi atau spec berubah, menjalankan specify audit, mem-posting hasil sebagai komentar PR, lalu menegakkan threshold.
1# .github/workflows/spec-audit.yml
2name: Spec Compliance Audit
3
4on:
5 pull_request:
6 branches: [main, develop]
7 types: [opened, synchronize, ready_for_review]
8 paths:
9 # Run jika ada perubahan di kode implementasi
10 - 'internal/usecase/**'
11 - 'delivery/http/handler/**'
12 # ATAU jika ada perubahan di spec itu sendiri
13 - '.specify/**'
14
15jobs:
16 spec-audit:
17 name: Spec Compliance Check
18 runs-on: ubuntu-latest
19 if: "!github.event.pull_request.draft"
20 permissions:
21 pull-requests: write
22 contents: read
23
24 steps:
25 - uses: actions/checkout@v4
26 with:
27 fetch-depth: 0
28
29 - uses: actions/setup-node@v4
30 with:
31 node-version: '20'
32
33 - name: Install Spec Kit CLI
34 run: npm install -g @santekno/spec-kit
35
36 - name: Cache specify results
37 uses: actions/cache@v4
38 with:
39 path: .specify/.cache
40 key: specify-${{ github.base_ref }}-${{ hashFiles('.specify/features/**') }}
41 restore-keys: specify-${{ github.base_ref }}-
42
43 - name: Determine changed features
44 id: changes
45 run: |
46 # Identify features yang berubah
47 CHANGED=$(git diff origin/${{ github.base_ref }}...HEAD \
48 --name-only \
49 -- 'internal/usecase/**' 'delivery/http/handler/**' '.specify/**' \
50 | sed 's|internal/usecase/||' \
51 | sed 's|/.*||' \
52 | sort -u \
53 | tr '\n' ',')
54
55 echo "features=${CHANGED}" >> $GITHUB_OUTPUT
56 echo "Changed feature areas: $CHANGED"
57
58 - name: Run Spec Audit
59 id: audit
60 env:
61 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
62 run: |
63 # Run audit untuk semua features yang berubah
64 # atau semua jika .specify/ berubah
65
66 CHANGED_FEATURES="${{ steps.changes.outputs.features }}"
67
68 if git diff origin/${{ github.base_ref }}...HEAD \
69 --name-only | grep -q '\.specify/'; then
70 echo "Spec files changed — auditing all features"
71 specify audit --output json > /tmp/audit-result.json
72 else
73 echo "Auditing changed features: $CHANGED_FEATURES"
74 specify audit \
75 --features "$CHANGED_FEATURES" \
76 --output json > /tmp/audit-result.json
77 fi
78
79 # Extract overall score
80 SCORE=$(jq '.overall_score' /tmp/audit-result.json)
81 echo "score=$SCORE" >> $GITHUB_OUTPUT
82
83 # Check jika ada critical issues
84 CRITICAL=$(jq '.features[] | .issues[] | select(.severity == "critical") | .description' \
85 /tmp/audit-result.json | wc -l)
86 echo "critical_count=$CRITICAL" >> $GITHUB_OUTPUT
87
88 cat /tmp/audit-result.json
89
90 - name: Generate Audit Report
91 id: report
92 run: |
93 # Convert JSON result ke Markdown untuk PR comment
94 python3 - << 'PYTHON'
95 import json, sys
96
97 with open('/tmp/audit-result.json') as f:
98 result = json.load(f)
99
100 lines = ['## 📋 Spec Compliance Audit', '']
101
102 overall = result['overall_score']
103 emoji = '🟢' if overall >= 90 else '🟡' if overall >= 70 else '🔴'
104 lines.append(f'**Overall Score:** {emoji} {overall}/100')
105 lines.append('')
106
107 for feature in result.get('features', []):
108 fname = feature['name']
109 fscore = feature['score']
110 femoji = '✅' if fscore >= 80 else '⚠️' if fscore >= 60 else '❌'
111 lines.append(f'### {femoji} {fname} ({fscore}/100)')
112 lines.append('')
113
114 for ac in feature.get('acceptance_criteria', []):
115 ac_status = '✅' if ac['status'] == 'compliant' else '⚠️' if ac['status'] == 'partial' else '❌'
116 lines.append(f'- {ac_status} **{ac["id"]}:** {ac["summary"]}')
117 if ac.get('note'):
118 lines.append(f' > 💡 {ac["note"]}')
119
120 lines.append('')
121
122 if result.get('recommendations'):
123 lines.append('### 💡 Recommendations')
124 for rec in result['recommendations']:
125 lines.append(f'- {rec}')
126
127 with open('/tmp/audit-report.md', 'w') as f:
128 f.write('\n'.join(lines))
129
130 print("Report generated")
131 PYTHON
132
133 - name: Post Audit Comment
134 uses: actions/github-script@v7
135 with:
136 script: |
137 const fs = require('fs');
138 const report = fs.readFileSync('/tmp/audit-report.md', 'utf8');
139 const score = parseInt('${{ steps.audit.outputs.score }}');
140 const threshold = 80;
141
142 const statusLine = score >= threshold
143 ? `✅ **PASSED** (${score}/100 ≥ ${threshold} threshold)`
144 : `❌ **FAILED** (${score}/100 < ${threshold} threshold)`;
145
146 const body = [
147 report,
148 '',
149 '---',
150 `**Status:** ${statusLine}`,
151 `*Spec Kit audit | Threshold: ${threshold}/100*`
152 ].join('\n');
153
154 // Find existing audit comment dan update, atau buat baru
155 const { data: comments } = await github.rest.issues.listComments({
156 owner: context.repo.owner,
157 repo: context.repo.repo,
158 issue_number: context.issue.number
159 });
160
161 const existingComment = comments.find(c =>
162 c.body.includes('📋 Spec Compliance Audit')
163 );
164
165 if (existingComment) {
166 await github.rest.issues.updateComment({
167 owner: context.repo.owner,
168 repo: context.repo.repo,
169 comment_id: existingComment.id,
170 body
171 });
172 } else {
173 await github.rest.issues.createComment({
174 owner: context.repo.owner,
175 repo: context.repo.repo,
176 issue_number: context.issue.number,
177 body
178 });
179 }
180
181 - name: Enforce Spec Compliance
182 run: |
183 SCORE=${{ steps.audit.outputs.score }}
184 THRESHOLD=80
185
186 echo "Spec compliance score: $SCORE/100 (threshold: $THRESHOLD)"
187
188 if [ "$SCORE" -lt "$THRESHOLD" ]; then
189 echo "::error::Spec compliance score $SCORE < threshold $THRESHOLD"
190 echo "Please review the spec audit comment above and fix non-compliant ACs"
191 exit 1
192 fi
193
194 echo "✅ Spec compliance passed: $SCORE/100"Perhatikan tiga keputusan desain penting di workflow ini: paths filter menghemat CI run ketika PR tidak menyentuh kode, langkah “Post Audit Comment” memperbarui komentar yang sama alih-alih menumpuk, dan langkah “Enforce” memberi exit code non-nol saat skor di bawah threshold sehingga PR benar-benar terblokir.
04.5 Spec File Format yang Optimal untuk CI
Kualitas audit sangat bergantung pada kualitas spec. Spec yang eksplisit dengan format Given/When/Then jauh lebih mudah di-audit AI daripada prosa bebas. Template berikut menunjukkan format spec yang paling efektif untuk specify audit.
1# .specify/features/cancel-order/spec.md
2# Format yang paling efektif untuk specify audit
3
4## Feature: CancelOrder
5
6### Context
7Customer bisa cancel order yang belum di-proses.
8Business rule: window cancel adalah 30 menit setelah order dibuat.
9
10### Acceptance Criteria
11
12**AC1: Happy Path — Cancel PENDING dalam Window**
13- Given: Order status = PENDING, dibuat < 30 menit yang lalu
14- Given: Request dari user yang punya order ini
15- When: DELETE /orders/{id}
16- Then: Status 204 No Content
17- Then: Order status berubah ke CANCELLED
18- Then: Stock di-restore secara atomic
19- Then: Kafka event ORDER_CANCELLED di-publish
20
21**AC2: Order Status Bukan PENDING**
22- Given: Order status = CONFIRMED, SHIPPED, atau DELIVERED
23- When: DELETE /orders/{id}
24- Then: Status 409 Conflict
25- Then: Error body: {"error": "ORDER_NOT_CANCELLABLE"}
26
27**AC3: Cancel Window Sudah Lewat**
28- Given: Order status = PENDING, dibuat > 30 menit yang lalu
29- When: DELETE /orders/{id}
30- Then: Status 409 Conflict
31- Then: Error body: {"error": "CANCEL_WINDOW_EXPIRED"}
32
33**AC4: Order Tidak Ditemukan atau Bukan Milik User**
34- Given: Order ID tidak ada, atau ada tapi milik user lain
35- When: DELETE /orders/{id}
36- Then: Status 404 Not Found
37- Then: Error body: {"error": "ORDER_NOT_FOUND"}
38
39### Implementation Notes
40- Cancel + stock restore harus dalam satu DB transaction
41- Kafka publish boleh async (tidak block response)
42- 30-menit window dihitung dari Order.CreatedAt
43
44### Links
45- Handler: delivery/http/handler/order_handler.go:CancelOrder
46- UseCase: internal/usecase/order/cancel_order.go
47- Repository: internal/repository/postgres/order_repository.goBagian Links di akhir spec adalah kunci: dari sanalah audit tahu file kode mana yang harus dibandingkan dengan setiap AC. Spec dengan Given/When/Then yang konkret plus Links yang akurat menghasilkan skor audit yang bisa dipercaya.
04.6 Custom Audit Script: Tanpa specify CLI
Jika tim belum setup Spec Kit, kita masih bisa membangun audit sederhana menggunakan Claude API langsung. Script bash berikut meng-iterasi semua spec, memuat file implementasi dari section Links, lalu meminta AI menilai kepatuhan tiap AC.
1#!/bin/bash
2# scripts/simple-spec-audit.sh
3# Simple spec audit menggunakan Claude API langsung
4
5set -euo pipefail
6
7SPEC_DIR=".specify/features"
8PASS_COUNT=0
9FAIL_COUNT=0
10TOTAL_SCORE=0
11FEATURE_COUNT=0
12
13for spec_file in "$SPEC_DIR"/*/spec.md; do
14 feature_name=$(dirname "$spec_file" | xargs basename)
15
16 echo "Auditing: $feature_name..."
17
18 # Load spec
19 SPEC=$(cat "$spec_file")
20
21 # Find implementation files (dari spec Links section)
22 HANDLER_FILE=$(grep "Handler:" "$spec_file" | grep -oP '`[^`]+`' | tr -d '`' || echo "")
23 USECASE_FILE=$(grep "UseCase:" "$spec_file" | grep -oP '`[^`]+`' | tr -d '`' || echo "")
24
25 # Load implementation code
26 IMPL=""
27 if [ -n "$HANDLER_FILE" ] && [ -f "$HANDLER_FILE" ]; then
28 IMPL="$IMPL\n\n=== Handler: $HANDLER_FILE ===\n$(cat "$HANDLER_FILE")"
29 fi
30 if [ -n "$USECASE_FILE" ] && [ -f "$USECASE_FILE" ]; then
31 IMPL="$IMPL\n\n=== UseCase: $USECASE_FILE ===\n$(cat "$USECASE_FILE")"
32 fi
33
34 if [ -z "$IMPL" ]; then
35 echo " ⚠️ No implementation files found for $feature_name, skip"
36 continue
37 fi
38
39 # Build audit prompt
40 PROMPT="You are a spec compliance auditor for a Go e-commerce service.
41
42SPEC:
43$SPEC
44
45IMPLEMENTATION:
46$IMPL
47
48Audit: does the implementation fulfill all Acceptance Criteria?
49
50For each AC, determine:
51- COMPLIANT: implementation clearly satisfies the AC
52- PARTIAL: some aspects satisfied, some missing or different
53- NON_COMPLIANT: implementation does not satisfy the AC
54
55Output format (strict JSON):
56{
57 \"feature\": \"$feature_name\",
58 \"score\": 0-100,
59 \"criteria\": [
60 {\"id\": \"AC1\", \"status\": \"COMPLIANT|PARTIAL|NON_COMPLIANT\", \"note\": \"brief explanation\"}
61 ],
62 \"summary\": \"one line overall assessment\"
63}"
64
65 # Call Claude
66 RESULT=$(./scripts/claude-call.sh "$PROMPT" 600) || {
67 echo " ❌ Claude API call failed for $feature_name"
68 continue
69 }
70
71 # Parse score
72 SCORE=$(echo "$RESULT" | jq -r '.score' 2>/dev/null || echo "0")
73 SUMMARY=$(echo "$RESULT" | jq -r '.summary' 2>/dev/null || echo "Parse error")
74
75 echo " Score: $SCORE/100 — $SUMMARY"
76
77 # Display criteria
78 echo "$RESULT" | jq -r '.criteria[] | " \(.id): \(.status) — \(.note)"' 2>/dev/null || true
79
80 TOTAL_SCORE=$((TOTAL_SCORE + SCORE))
81 FEATURE_COUNT=$((FEATURE_COUNT + 1))
82
83 if [ "$SCORE" -ge 80 ]; then
84 PASS_COUNT=$((PASS_COUNT + 1))
85 else
86 FAIL_COUNT=$((FAIL_COUNT + 1))
87 fi
88
89 echo ""
90done
91
92# Calculate overall
93if [ "$FEATURE_COUNT" -gt 0 ]; then
94 OVERALL=$((TOTAL_SCORE / FEATURE_COUNT))
95else
96 OVERALL=100 # no features to audit = pass
97fi
98
99echo "=========================="
100echo "SPEC AUDIT RESULTS"
101echo "=========================="
102echo "Features audited: $FEATURE_COUNT"
103echo "Pass (≥80): $PASS_COUNT"
104echo "Fail (<80): $FAIL_COUNT"
105echo "Overall score: $OVERALL/100"
106
107# Exit code berdasarkan threshold
108if [ "$OVERALL" -lt 80 ]; then
109 echo "❌ FAILED: Overall score below 80 threshold"
110 exit 1
111fi
112
113echo "✅ PASSED: All features comply with spec"
114exit 0Script ini membuktikan bahwa spec validation tidak wajib menunggu adopsi Spec Kit penuh — dengan satu file bash dan Claude API, tim bisa mulai menegakkan kepatuhan spec hari ini juga, lalu bermigrasi ke specify audit saat siap.
04.7 Handling Perubahan Spec vs Implementasi
Tidak semua perubahan sama artinya. PR yang mengubah spec tanpa mengubah kode punya risiko berbeda dari PR yang mengubah kode tanpa update spec. Langkah berikut mendeteksi tipe perubahan sehingga pipeline bisa memberi feedback yang kontekstual.
1# Deteksi apakah spec atau implementasi yang berubah
2
3- name: Detect change type
4 id: change_type
5 run: |
6 SPEC_CHANGED=$(git diff origin/${{ github.base_ref }}...HEAD \
7 --name-only -- '.specify/**' | wc -l)
8 IMPL_CHANGED=$(git diff origin/${{ github.base_ref }}...HEAD \
9 --name-only -- 'internal/**' 'delivery/**' | wc -l)
10
11 if [ "$SPEC_CHANGED" -gt 0 ] && [ "$IMPL_CHANGED" -eq 0 ]; then
12 echo "type=spec_only" >> $GITHUB_OUTPUT
13 echo "Spec changed without implementation change"
14 elif [ "$SPEC_CHANGED" -eq 0 ] && [ "$IMPL_CHANGED" -gt 0 ]; then
15 echo "type=impl_only" >> $GITHUB_OUTPUT
16 echo "Implementation changed without spec change"
17 elif [ "$SPEC_CHANGED" -gt 0 ] && [ "$IMPL_CHANGED" -gt 0 ]; then
18 echo "type=both" >> $GITHUB_OUTPUT
19 echo "Both spec and implementation changed"
20 else
21 echo "type=none" >> $GITHUB_OUTPUT
22 fi
23
24# Berikan feedback yang kontekstual:
25- name: Contextual audit message
26 run: |
27 case "${{ steps.change_type.outputs.type }}" in
28 "spec_only")
29 echo "::notice::Spec updated without corresponding implementation change."
30 echo "Verify: does the implementation still match the updated spec?"
31 ;;
32 "impl_only")
33 echo "::notice::Implementation changed without spec update."
34 echo "Verify: should the spec be updated to reflect this change?"
35 ;;
36 "both")
37 echo "::notice::Both spec and implementation changed — running full audit."
38 ;;
39 esacDengan membedakan spec_only, impl_only, dan both, pipeline tidak sekadar bilang “ada mismatch” tapi mengarahkan developer ke pertanyaan yang tepat — apakah kode yang perlu menyusul, atau spec yang perlu diperbarui.
04.8 Spec Coverage Report
Selain memeriksa apakah kode sesuai spec, kita juga perlu tahu berapa banyak fitur yang punya spec sama sekali. Script berikut menghitung persentase fitur di internal/usecase yang sudah memiliki spec file.
1#!/bin/bash
2# scripts/spec-coverage.sh
3# Report: berapa % fitur yang punya spec?
4
5FEATURE_DIRS=$(find internal/usecase -mindepth 1 -maxdepth 2 -type d | \
6 xargs -I{} basename {} | sort -u)
7
8TOTAL=0
9WITH_SPEC=0
10WITHOUT_SPEC=()
11
12for feature in $FEATURE_DIRS; do
13 TOTAL=$((TOTAL + 1))
14
15 if [ -d ".specify/features/$feature" ] && \
16 [ -f ".specify/features/$feature/spec.md" ]; then
17 WITH_SPEC=$((WITH_SPEC + 1))
18 else
19 WITHOUT_SPEC+=("$feature")
20 fi
21done
22
23echo "=== SPEC COVERAGE REPORT ==="
24echo "Total features: $TOTAL"
25echo "With spec: $WITH_SPEC"
26echo "Without spec: $((TOTAL - WITH_SPEC))"
27
28if [ "${#WITHOUT_SPEC[@]}" -gt 0 ]; then
29 echo ""
30 echo "Features WITHOUT spec:"
31 for f in "${WITHOUT_SPEC[@]}"; do
32 echo " ⚠️ $f"
33 done
34fi
35
36COVERAGE=$((WITH_SPEC * 100 / TOTAL))
37echo ""
38echo "Coverage: $COVERAGE%"
39
40# Warning jika coverage < 80%
41if [ "$COVERAGE" -lt 80 ]; then
42 echo "::warning::Spec coverage $COVERAGE% below 80% target"
43fiMetrik coverage ini melengkapi skor audit: audit mengukur kualitas kepatuhan pada fitur yang punya spec, sedangkan coverage mengukur cakupan — berapa banyak fitur yang belum tersentuh SDD sama sekali. Target realistis: 80% usecase punya spec.
04.9 Graduated Enforcement Strategy
Menerapkan enforcement keras di hari pertama hampir selalu memicu resistensi tim, apalagi jika spec masih banyak yang belum lengkap. Strategi bertahap berikut memperkenalkan spec audit dalam tiga fase, dari sekadar informational sampai blocking.
1Phase 1 (Minggu 1-2): SHADOW MODE
2 → Spec audit berjalan, hasilnya di-log
3 → Tidak block PR, hanya PR comment
4 → Tujuan: developer familiar dengan format output
5
6 YAML config:
7 continue-on-error: true # pada step Enforce Spec Compliance
8
9Phase 2 (Minggu 3-4): WARNING MODE
10 → Spec audit comment di PR dengan skor
11 → Score < 60: warning yang lebih prominent
12 → Tidak block merge
13 → Tujuan: developer mulai improve spec compliance
14
15Phase 3 (Bulan 2+): ENFORCEMENT MODE
16 → Score < 80: PR blocked
17 → CRITICAL (NON_COMPLIANT AC): block langsung
18 → PARTIAL: informational (tidak block)
19 → Tujuan: systematic quality enforcement
20
21How to configure:
22 Phase 1: continue-on-error: true
23 Phase 2: remove continue-on-error, exit 0 selalu (hanya informational)
24 Phase 3: exit 1 kalau score < thresholdKunci dari strategi ini adalah membangun kepercayaan sebelum menegakkan aturan: tim melihat nilai audit lebih dulu, memperbaiki spec, baru merasakan blocking. Adopsi yang tahan lama datang dari buy-in, bukan paksaan mendadak.
04.10 Spec Audit untuk PR yang Touch Multiple Features
PR besar sering menyentuh banyak feature sekaligus. Meng-audit semua feature setiap kali akan mahal dan memunculkan false fail dari feature yang tidak diubah. Langkah berikut memetakan path yang berubah ke feature yang relevan saja.
1# Jika PR menyentuh banyak feature, audit hanya yang relevan
2# untuk menghindari false fails dari feature yang tidak diubah
3
4- name: Smart feature detection
5 id: features
6 run: |
7 # Mapping: folder path → feature name
8 declare -A FEATURE_MAP
9 FEATURE_MAP["internal/usecase/order"]="cancel-order create-order list-orders"
10 FEATURE_MAP["internal/usecase/payment"]="process-payment refund-payment"
11 FEATURE_MAP["delivery/http/handler"]="all" # all features jika handler berubah
12
13 CHANGED_PATHS=$(git diff origin/${{ github.base_ref }}...HEAD --name-only \
14 -- 'internal/**' 'delivery/**')
15
16 FEATURES_TO_AUDIT=""
17
18 for path in $CHANGED_PATHS; do
19 # Cari feature yang terkait dengan path ini
20 for pattern in "${!FEATURE_MAP[@]}"; do
21 if [[ "$path" == ${pattern}* ]]; then
22 FEATURES_TO_AUDIT="$FEATURES_TO_AUDIT ${FEATURE_MAP[$pattern]}"
23 fi
24 done
25 done
26
27 # Unique dan sort
28 FEATURES=$(echo $FEATURES_TO_AUDIT | tr ' ' '\n' | sort -u | tr '\n' ',')
29 echo "features=$FEATURES" >> $GITHUB_OUTPUT
30 echo "Auditing features: $FEATURES"Mapping path-ke-feature ini menjaga audit tetap fokus dan hemat: PR yang hanya mengubah order tidak akan memicu audit payment, sehingga feedback lebih cepat dan biaya AI lebih terkendali.
04.11 Integration dengan PR Template
Agar spec compliance jadi kebiasaan, bukan sekadar gate otomatis, kita tautkan ke PR template yang wajib diisi developer. Template berikut memaksa penulis PR mencantumkan spec terkait dan AC yang di-address.
1<!-- .github/pull_request_template.md -->
2
3## Description
4[Describe what this PR does]
5
6## Spec Compliance
7<!-- These links will be checked by automated spec audit -->
8- [ ] Spec file updated (if behavior changed): .specify/features/[feature]/spec.md
9- [ ] All Acceptance Criteria addressed
10
11## Related Spec
12<!-- Link to relevant spec files -->
13- Spec: .specify/features/[feature-name]/spec.md
14- AC(s) addressed: AC1, AC2, ...
15
16## Testing
17- [ ] Unit tests added/updated
18- [ ] go test -race ./... ✅
19
20## AI Review
21<!-- Auto-populated by pipeline -->
22AI Review Score: _pending_
23Spec Audit Score: _pending_Template ini menciptakan traceability yang jelas: dari deskripsi PR, reviewer langsung tahu spec mana yang relevan dan AC mana yang disentuh — konteks yang sama yang dipakai audit otomatis, kini juga tersedia untuk reviewer manusia.
04.12 Spec Audit untuk Breaking Changes
Sebagian perubahan implementasi bukan sekadar drift, tapi breaking change terhadap kontrak yang dijanjikan spec. Script berikut menganalisis diff untuk mendeteksi apakah perubahan mengubah response code, error code, atau business rule yang tertulis di spec.
1#!/bin/bash
2# scripts/detect-spec-breaking-change.sh
3# Detect apakah perubahan implementasi merupakan breaking change dari spec
4
5SPEC_FILE=".specify/features/${1}/spec.md"
6IMPL_DIFF="/tmp/impl-diff.txt"
7
8if [ ! -f "$SPEC_FILE" ]; then
9 echo "No spec found for feature: $1"
10 exit 0
11fi
12
13# Load spec ACs
14SPEC_ACS=$(grep "^\*\*AC" "$SPEC_FILE" | sed 's/\*\*//g')
15
16# Check diff untuk potential breaking changes
17DIFF_CONTENT=$(cat "$IMPL_DIFF")
18
19PROMPT="Analyze if these Go code changes are BREAKING relative to this spec.
20
21SPEC (Acceptance Criteria):
22$SPEC_ACS
23
24CODE CHANGES (diff):
25$DIFF_CONTENT
26
27A change is BREAKING if it:
281. Changes HTTP response codes mentioned in spec
292. Changes error codes/messages defined in spec
303. Changes business logic timing/limits in spec
314. Removes functionality required by spec
32
33Output:
34BREAKING: YES|NO
35Reason: [brief explanation]
36Affected ACs: [list if BREAKING=YES]"
37
38RESULT=$(./scripts/claude-call.sh "$PROMPT" 300)
39echo "$RESULT"
40
41if echo "$RESULT" | grep -q "BREAKING: YES"; then
42 echo "::warning::Potential breaking change detected — please update spec"
43fiDeteksi breaking change ini adalah lapis kedua di atas skor kepatuhan: audit biasa mungkin memberi skor tinggi untuk kode yang benar secara teknis, tapi script ini menangkap saat kontrak yang dijanjikan ke konsumen API diam-diam berubah.
04.13 Tips & Gotchas Spec Validation di CI
💡 Tip 1: Spec yang baik = audit yang lebih akurat. Spec dengan Given/When/Then yang explicit lebih mudah di-audit oleh AI daripada spec prosa. Invest di kualitas spec, bukan hanya di tooling.
💡 Tip 2: Audit hanya fitur yang berubah. Running audit untuk semua fitur di setiap PR adalah overkill dan mahal. Detect perubahan secara smart (04.10).
💡 Tip 3: Comment yang updated, bukan ditambahkan. Jika audit berjalan 3 kali (push 3 commit ke satu PR), kita tidak mau 3 comment berbeda. Update comment yang sama (lihat 04.4 — find existing comment).
💡 Tip 4: Fail early untuk CRITICAL. Jika ada AC yang NON_COMPLIANT (bukan PARTIAL), itu mungkin warrant immediate block tanpa menunggu overall score.
⚠️ Gotcha 1: Spec yang terlalu abstrak. Jika spec hanya bilang “handle error correctly” tanpa specify response code, AI tidak bisa audit secara objective. Spec harus konkret.
⚠️ Gotcha 2: Implementation yang jelas dari context. Jika Links section di spec tidak akurat, AI akan audit file yang salah. Maintain Links section dengan benar.
⚠️ Gotcha 3: Large spec = expensive audit. Jika spec file sangat panjang (>200 baris), potong untuk efisiensi. AI perlu token untuk baca spec + implementasi + generate output.
04.14 Spec Audit Metrics
Enforcement yang baik butuh data. Melacak skor audit dari waktu ke waktu memungkinkan kita melihat tren kepatuhan per developer dan per feature. Langkah berikut mencatat metrik audit ke GitHub Step Summary di setiap run.
1# Tambahkan ke workflow untuk tracking:
2- name: Track spec audit metrics
3 if: always()
4 run: |
5 SCORE=${{ steps.audit.outputs.score }}
6 TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)
7 PR_NUMBER=${{ github.event.number }}
8 AUTHOR=${{ github.actor }}
9
10 # Log ke GitHub Step Summary
11 cat >> $GITHUB_STEP_SUMMARY << EOF
12 ## Spec Audit Metrics
13 - Score: $SCORE/100
14 - PR: #$PR_NUMBER
15 - Author: $AUTHOR
16 - Timestamp: $TIMESTAMP
17 - Threshold: 80
18 - Result: $( [ "$SCORE" -ge 80 ] && echo "PASS" || echo "FAIL" )
19 EOF
20
21 # Optional: kirim ke analytics
22 # curl -X POST https://analytics.santekno.com/spec-audit \
23 # -d "{\"score\": $SCORE, \"pr\": $PR_NUMBER, \"author\": \"$AUTHOR\"}"Dengan if: always(), metrik tetap tercatat bahkan saat audit gagal — justru data kegagalan inilah yang paling berharga untuk retro bulanan: fitur mana yang konsisten skor rendah, dan siapa yang mungkin butuh mentoring SDD.
04.15 Workflow Lengkap Terintegrasi
Spec audit bukan gate yang berdiri sendiri — ia satu lapis dari pipeline quality gates berlapis. Workflow berikut mengintegrasikan empat layer: syntactic (build/test/lint), architecture, AI review, dan spec compliance dalam satu file.
1# .github/workflows/quality-gates.yml
2# Workflow yang integrate semua quality gates dari Part 1
3
4name: Quality Gates — Complete Pipeline
5
6on:
7 push:
8 branches: [main, develop]
9 pull_request:
10 branches: [main, develop]
11 types: [opened, synchronize, ready_for_review]
12
13env:
14 GO_VERSION: '1.22'
15
16jobs:
17 # Layer 1: Syntactic
18 go-quality:
19 name: "L1: Go Build, Test & Lint"
20 runs-on: ubuntu-latest
21 timeout-minutes: 10
22 steps:
23 - uses: actions/checkout@v4
24 - uses: actions/setup-go@v5
25 with: { go-version: '${{ env.GO_VERSION }}', cache: true }
26 - run: go build ./...
27 - run: go test -race -count=1 -timeout=5m ./...
28 - run: go vet ./...
29 - uses: golangci/golangci-lint-action@v6
30 - name: Coverage gate
31 run: |
32 go test -coverprofile=cov.out ./...
33 COVERAGE=$(go tool cover -func=cov.out | grep total | awk '{print $3}' | tr -d '%')
34 awk "BEGIN {exit ($COVERAGE >= 70) ? 0 : 1}" || \
35 { echo "::error::Coverage below 70%: ${COVERAGE}%"; exit 1; }
36
37 # Layer 2: Architecture
38 architecture:
39 name: "L2: Architecture Boundaries"
40 runs-on: ubuntu-latest
41 needs: go-quality
42 timeout-minutes: 5
43 steps:
44 - uses: actions/checkout@v4
45 - uses: actions/setup-go@v5
46 with: { go-version: '${{ env.GO_VERSION }}' }
47 - run: go run ./scripts/check-architecture.go ./...
48
49 # Layer 3: AI Review (parallel, PR only)
50 ai-review:
51 name: "L3: AI Semantic Review"
52 runs-on: ubuntu-latest
53 needs: go-quality
54 if: github.event_name == 'pull_request' && !github.event.pull_request.draft
55 timeout-minutes: 5
56 permissions:
57 pull-requests: write
58 contents: read
59 steps:
60 - uses: actions/checkout@v4
61 with: { fetch-depth: 0 }
62 - uses: github/copilot-for-pull-requests@v1
63 with:
64 github-token: ${{ secrets.GITHUB_TOKEN }}
65 review-instructions: |
66 Review per .github/copilot-instructions.md.
67 CRITICAL: error not wrapped, float64 for money, arch violations.
68 REVIEW_SCORE: X/100
69
70 # Layer 4: Spec Compliance (parallel with L3, PR only)
71 spec-compliance:
72 name: "L4: Spec Compliance Audit"
73 runs-on: ubuntu-latest
74 needs: go-quality
75 if: github.event_name == 'pull_request' && !github.event.pull_request.draft
76 timeout-minutes: 5
77 permissions:
78 pull-requests: write
79 contents: read
80 env:
81 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
82 steps:
83 - uses: actions/checkout@v4
84 with: { fetch-depth: 0 }
85 - uses: actions/setup-node@v4
86 with: { node-version: '20' }
87 - run: npm install -g @santekno/spec-kit
88 - name: Run spec audit
89 run: specify audit --output json --fail-on-score-below 80Perhatikan bahwa L3 dan L4 sama-sama needs: go-quality — keduanya berjalan paralel setelah build/test lulus, sehingga PR mendapat review semantik dan audit spec secara bersamaan tanpa memperlambat pipeline.
04.16 Alternatif: Spec Audit Manual via Claude tanpa Spec Kit
Untuk tim yang ingin kontrol penuh atas logika audit, kita bisa menulis tool audit sendiri dalam Go menggunakan Anthropic SDK. Program berikut men-scan direktori spec, memuat implementasi dari section Links, dan meminta Claude menilai kepatuhan tiap feature.
1// cmd/spec-audit/main.go
2// Custom spec audit tool jika tidak pakai Spec Kit
3
4package main
5
6import (
7 "context"
8 "encoding/json"
9 "fmt"
10 "os"
11 "path/filepath"
12 "strings"
13
14 anthropic "github.com/anthropics/anthropic-sdk-go"
15 "github.com/anthropics/anthropic-sdk-go/option"
16)
17
18type AuditResult struct {
19 Feature string `json:"feature"`
20 Score int `json:"score"`
21 Issues []string `json:"issues"`
22 Pass bool `json:"pass"`
23}
24
25func main() {
26 client := anthropic.NewClient(
27 option.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")),
28 )
29
30 specDir := ".specify/features"
31 entries, err := os.ReadDir(specDir)
32 if err != nil {
33 fmt.Fprintln(os.Stderr, "no spec directory found")
34 os.Exit(0)
35 }
36
37 var results []AuditResult
38 totalScore := 0
39
40 for _, entry := range entries {
41 if !entry.IsDir() {
42 continue
43 }
44
45 specFile := filepath.Join(specDir, entry.Name(), "spec.md")
46 spec, err := os.ReadFile(specFile)
47 if err != nil {
48 continue
49 }
50
51 // Find implementation files from spec Links section
52 implCode := extractImplementation(string(spec))
53 if implCode == "" {
54 continue
55 }
56
57 result := auditFeature(context.Background(), client, entry.Name(), string(spec), implCode)
58 results = append(results, result)
59 totalScore += result.Score
60
61 status := "✅"
62 if !result.Pass {
63 status = "❌"
64 }
65 fmt.Printf("%s %s: %d/100\n", status, result.Feature, result.Score)
66 }
67
68 // Output summary
69 if len(results) > 0 {
70 overall := totalScore / len(results)
71 fmt.Printf("\nOverall: %d/100\n", overall)
72
73 if overall < 80 {
74 fmt.Println("❌ Spec compliance failed")
75 os.Exit(1)
76 }
77 }
78
79 fmt.Println("✅ Spec compliance passed")
80}
81
82func extractImplementation(spec string) string {
83 var files []string
84 for _, line := range strings.Split(spec, "\n") {
85 if strings.Contains(line, "Handler:") || strings.Contains(line, "UseCase:") {
86 // Extract path from backticks
87 parts := strings.Split(line, "`")
88 if len(parts) >= 2 {
89 path := parts[1]
90 if content, err := os.ReadFile(path); err == nil {
91 files = append(files, fmt.Sprintf("// %s\n%s", path, string(content)))
92 }
93 }
94 }
95 }
96 return strings.Join(files, "\n\n")
97}
98
99func auditFeature(ctx context.Context, client *anthropic.Client,
100 name, spec, impl string) AuditResult {
101
102 prompt := fmt.Sprintf(`Audit Go implementation vs spec.
103SPEC:
104%s
105
106IMPLEMENTATION:
107%s
108
109Score 0-100. Output JSON:
110{"score": 85, "pass": true, "issues": ["AC3: partial match"]}`, spec, impl)
111
112 msg, err := client.Messages.New(ctx, anthropic.MessageNewParams{
113 Model: anthropic.F(anthropic.ModelClaudeHaiku4_5),
114 MaxTokens: anthropic.F(int64(300)),
115 Messages: anthropic.F([]anthropic.MessageParam{
116 anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),
117 }),
118 })
119 if err != nil {
120 return AuditResult{Feature: name, Score: 0, Pass: false}
121 }
122
123 var result AuditResult
124 result.Feature = name
125 if err := json.Unmarshal([]byte(msg.Content[0].Text), &result); err != nil {
126 result.Score = 50
127 }
128 result.Pass = result.Score >= 80
129 return result
130}Tool Go native ini memberi dua keuntungan: ia bagian dari codebase yang sama sehingga di-version bersama kode, dan logika ekstraksi implementasi (extractImplementation) bisa disesuaikan persis dengan konvensi Links tim kamu tanpa menunggu fitur upstream Spec Kit.
04.17 End-to-End Test: Verifikasi Setup Lengkap
Sebelum mengandalkan pipeline di production, kita perlu membuktikan bahwa mismatch benar-benar terdeteksi. Langkah berikut mensimulasikan siklus penuh: buat spec, jalankan audit lokal, lalu buat PR yang sengaja non-compliant.
1# Test end-to-end spec validation pipeline
2
3# 1. Buat spec untuk fitur yang sudah ada
4mkdir -p .specify/features/cancel-order
5cat > .specify/features/cancel-order/spec.md << 'SPEC'
6## Feature: CancelOrder
7
8### Acceptance Criteria
9
10**AC1: Cancel PENDING dalam 30 menit**
11- Given: Order PENDING + < 30 menit
12- When: DELETE /orders/{id}
13- Then: 204 No Content
14
15**AC2: Order bukan PENDING**
16- When: DELETE /orders/{id}
17- Then: 409 {"error": "ORDER_NOT_CANCELLABLE"}
18
19### Links
20- Handler: delivery/http/handler/order_handler.go
21- UseCase: internal/usecase/order/cancel_order.go
22SPEC
23
24# 2. Run audit lokal
25export ANTHROPIC_API_KEY="sk-ant-xxx"
26specify audit # atau: bash scripts/simple-spec-audit.sh
27
28# 3. Buat PR dengan perubahan yang sengaja non-compliant
29git checkout -b test/spec-audit
30# Edit cancel_order.go untuk pakai 15 menit bukan 30 menit
31# git commit, git push, buat PR
32# Verify: pipeline flag mismatch antara spec (30 menit) dan impl (15 menit)
33
34# 4. Cleanup
35git checkout develop
36git branch -d test/spec-auditTest ini adalah bukti bahwa gate kamu benar-benar berfungsi — bukan sekadar hijau karena tidak pernah menemukan masalah. Selalu verifikasi bahwa audit bisa gagal pada kasus yang memang harus gagal sebelum menyalakan enforcement.
04.18 Penutup Part 1: Fondasi Pipeline AI-Assisted
Dengan menyelesaikan empat artikel di Part 1, kita sekarang punya fondasi yang solid. Ringkasan berikut memetakan kontribusi tiap artikel dan status pipeline yang sudah terbangun.
1Artikel 01: WHY — filosofi dan business case
2Artikel 02: ARCHITECTURE — blueprint 4-layer pipeline
3Artikel 03: SETUP — Claude di GitHub Actions (3 pendekatan)
4Artikel 04: FIRST GATE — spec validation yang menutup loop SDD
5
6PIPELINE STATUS SEKARANG:
7 L1 (Syntactic): ✅ go build, test, lint, gosec
8 L2 (Architecture): ✅ boundary check script
9 L3 (AI Review): ✅ Copilot PR review
10 L4 (Spec): ✅ specify audit
11
12Di Part 2, kita akan memperkuat setiap layer dengan
13quality gates yang lebih sophisticated.Fondasi empat layer ini sudah cukup untuk menjaga kualitas dasar setiap PR. Part 2 tidak menambah layer baru sembarangan, melainkan memperdalam masing-masing agar lebih akurat dan lebih murah dijalankan.
04.19 Checklist Part 1 Selesai
Sebelum melangkah ke Part 2, pastikan seluruh komponen sudah terpasang dan terverifikasi. Checklist berikut memeriksa infrastruktur, spec, secrets, dan verifikasi akhir.
1Pastikan semua ini sudah ada sebelum lanjut ke Part 2:
2
3Infrastructure:
4□ .github/workflows/ci.yml dengan 4-layer structure
5□ .github/copilot-instructions.md
6□ scripts/claude-call.sh (executable)
7□ scripts/claude-review.sh (executable)
8□ scripts/check-architecture.go
9□ CLAUDE.md di root
10
11Spec:
12□ .specify/config.yml
13□ Minimal 1 spec file di .specify/features/
14□ Spec files punya Links section yang akurat
15
16Secrets:
17□ ANTHROPIC_API_KEY di GitHub Secrets
18□ (Optional) SLACK_WEBHOOK
19
20Verification:
21□ Push PR test → semua 4 layers berjalan
22□ PR comment dari Copilot muncul
23□ Spec audit comment muncul
24□ Architecture check script tidak ada violationsJika seluruh kotak sudah tercentang — terutama bagian Verification di mana keempat layer benar-benar berjalan pada satu PR test — fondasi pipeline kamu siap dikembangkan lebih lanjut.
04.20 Ringkasan Part 1
Part 1 Topik 4 sudah selesai. Kita sudah membangun fondasi dari pipeline yang akan terus dikembangkan di Part 2, 3, dan 4:
Artikel 01: Business case yang kuat — AI di pipeline bukan hype, tapi systematic quality enforcement dengan ROI yang terukur.
Artikel 02: Blueprint arsitektur 4-layer yang jelas — dari syntactic ke spec compliance, dengan cost estimasi yang rendah.
Artikel 03: Tiga pendekatan setup Claude di CI — Copilot (paling mudah), Claude API via HTTP (paling fleksibel), Claude Code CLI (paling powerful).
Artikel 04: Spec validation yang menutup loop SDD → Spec Kit → CI — setiap PR sekarang di-audit terhadap spec yang sudah ditulis. Tanpa CI validation, workflow SDD hanya sekuat disiplin developer; dengan CI validation, konsistensi ditegakkan secara sistematis.
Di artikel berikutnya, kita perdalam layer AI review menjadi sistem automated code review yang production-ready — dengan rules eksplisit, scoring objektif, dan enforcement bertahap.