Spec Validation in Golang CI/CD: Automatically Ensure Code Matches the Spec
Integrate specify audit into a CI pipeline for Go. Auto-validate that every PR meets the acceptance criteria from the spec. GitHub Actions setup, scoring, and enforcement strategy.
Spec Validation in CI: Ensure Code Always Matches the Spec
Spec validation in CI is the final gate that closes the Specification-Driven Development loop for Golang: every pull request is automatically validated against the acceptance criteria already written in the spec. In Topic 1, we learned SDD — write the spec first, then implement. In Topic 2, we learned Spec Kit — the tools to manage and audit specs. Now we answer the practical question: how do we ensure every PR that lands in the codebase already complies with the spec that was written?
Without automation, drift between spec and implementation is almost unavoidable. Developers forget. Reviewers don’t check the spec. The spec is updated but the implementation isn’t. A CI pipeline that integrates spec validation is the only scalable solution for a growing team.
04.1 The Problem: Undetected Spec Drift
To understand why spec validation in CI matters, let’s look at a real scenario that often happens in engineering teams when there’s no mechanism to detect drift. The timeline below shows how one small change grows into an expensive bug.
1A scenario that often happens in engineering teams:
2
3Sprint 1: Team writes a spec for CancelOrder
4 AC1: Order PENDING + < 30 minutes → cancel → 204
5 AC2: Order not PENDING → 409 ORDER_NOT_CANCELLABLE
6 AC3: Order PENDING + > 30 minutes → 409 CANCEL_WINDOW_EXPIRED
7 AC4: Order not owned by user → 404 ORDER_NOT_FOUND
8
9Sprint 1 Developer A implements:
10 ✅ AC1, AC2, AC3, AC4 all implemented
11 Review: pass
12
13Sprint 3: Developer B needs to modify CancelOrder
14 (change 30 minutes → 15 minutes, per product request)
15
16 Developer B updates the implementation but FORGETS to update the spec.
17 Review: reviewer doesn't check the spec
18
19Sprint 5: Developer C reads the spec to extend a feature
20 "The spec says 30 minutes, but the implementation says 15 minutes..."
21 Confusion. Time wasted investigating.
22
23Sprint 7: Bug report
24 Customer: "My order at 18 minutes couldn't be cancelled, even though
25 the spec says 30 minutes"
26 Actual: spec was not updated, implementation is correct (15 minutes)
27 Time to fix: 1 day of investigation + meeting
28
29With spec validation in CI:
30 Sprint 3: Developer B changes the implementation
31 Pipeline: specify audit → "Spec still says 30 minutes,
32 implementation uses 15 minutes — MISMATCH"
33 Developer B: updates the spec at the same time
34 Time: 5 minutes, not a 1-day investigationNotice that the problem isn’t a lazy developer — the drift happens because nothing automatically checks for consistency. CI validation turns a one-day investigation into five-minute feedback exactly when the change is made.
04.2 What is specify audit in CI?
The core of this solution is the specify audit command from Spec Kit, which we covered in Topic 2. The summary below explains what this command does and how it runs inside the pipeline.
1specify audit is a CLI command from Spec Kit (Topic 2) that:
2
31. Reads all spec files in .specify/features/
42. Reads the related implementation code
53. Uses AI to compare spec vs implementation
64. Output: compliance score per feature + detailed issues
7
8How it works in CI:
9 PR created → pipeline triggered → specify audit runs
10 → Score < 80: PR blocked
11 → Score ≥ 80: PR may proceed
12 → Issues commented onto the PR
13
14Example 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 minutesWhat makes this audit different from an ordinary linter is its ability to compare intent (the spec) with realization (the code), rather than merely checking syntax. That per-acceptance-criteria score is the basis for the block-or-proceed decision in the pipeline.
04.3 Directory Structure for Specs in CI
For the audit to run consistently, the spec and its configuration need to live in a predictable location inside the repo. The directory structure below organizes the spec per feature alongside the workflow and Spec Kit configuration.
1santekno-shop/
2├── .specify/
3│ ├── config.yml ← specify configuration
4│ └── features/
5│ ├── cancel-order/
6│ │ ├── spec.md ← feature spec
7│ │ └── implementation/ ← link to the implementing code
8│ ├── create-order/
9│ │ └── spec.md
10│ └── list-orders/
11│ └── spec.md
12├── .github/
13│ └── workflows/
14│ └── spec-audit.yml ← the workflow we'll build
15└── CLAUDE.mdWith every feature having its own folder, the audit can target only the features that changed instead of scanning the whole repo. Next, the audit behavior is controlled through a single configuration file below.
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 to pass
11 strict_mode: false # true = block all 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: trueThis configuration decides three important things: the pass threshold (threshold), which layers are audited (scope.include), and what’s excluded so mocks and tests don’t pollute the results. Once set, the whole team plays by the same rules.
04.4 GitHub Actions Workflow: Spec Audit
Now we wire the audit into a GitHub Actions workflow that runs automatically on every PR. The workflow below triggers the audit only when implementation code or the spec changes, runs specify audit, posts the result as a PR comment, then enforces the 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 if there are changes in implementation code
10 - 'internal/usecase/**'
11 - 'delivery/http/handler/**'
12 # OR if there are changes in the spec itself
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 that changed
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 for all changed features
64 # or all of them if .specify/ changed
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 if there are 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 to Markdown for 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 an existing audit comment and update it, or create a new one
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"Notice three important design decisions in this workflow: the paths filter saves CI runs when a PR doesn’t touch code, the “Post Audit Comment” step updates the same comment instead of stacking new ones, and the “Enforce” step returns a non-zero exit code when the score is below threshold so the PR is genuinely blocked.
04.5 The Optimal Spec File Format for CI
Audit quality depends heavily on spec quality. An explicit spec in Given/When/Then format is far easier for the AI to audit than free-form prose. The template below shows the most effective spec format for specify audit.
1# .specify/features/cancel-order/spec.md
2# The most effective format for specify audit
3
4## Feature: CancelOrder
5
6### Context
7Customers can cancel an order that hasn't been processed.
8Business rule: the cancel window is 30 minutes after the order is created.
9
10### Acceptance Criteria
11
12**AC1: Happy Path — Cancel PENDING within the Window**
13- Given: Order status = PENDING, created < 30 minutes ago
14- Given: Request from the user who owns this order
15- When: DELETE /orders/{id}
16- Then: Status 204 No Content
17- Then: Order status changes to CANCELLED
18- Then: Stock is restored atomically
19- Then: Kafka event ORDER_CANCELLED is published
20
21**AC2: Order Status Not PENDING**
22- Given: Order status = CONFIRMED, SHIPPED, or DELIVERED
23- When: DELETE /orders/{id}
24- Then: Status 409 Conflict
25- Then: Error body: {"error": "ORDER_NOT_CANCELLABLE"}
26
27**AC3: Cancel Window Has Passed**
28- Given: Order status = PENDING, created > 30 minutes ago
29- When: DELETE /orders/{id}
30- Then: Status 409 Conflict
31- Then: Error body: {"error": "CANCEL_WINDOW_EXPIRED"}
32
33**AC4: Order Not Found or Not Owned by User**
34- Given: Order ID doesn't exist, or exists but belongs to another user
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 must be in a single DB transaction
41- Kafka publish may be async (does not block the response)
42- The 30-minute window is computed from 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.goThe Links section at the end of the spec is the key: that’s how the audit knows which code files to compare against each AC. A spec with concrete Given/When/Then plus accurate Links produces an audit score you can trust.
04.6 Custom Audit Script: Without the specify CLI
If the team hasn’t set up Spec Kit yet, we can still build a simple audit using the Claude API directly. The bash script below iterates over all specs, loads the implementation files from the Links section, then asks the AI to score compliance for each AC.
1#!/bin/bash
2# scripts/simple-spec-audit.sh
3# Simple spec audit using the Claude API directly
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 (from the 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 based on 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 0This script proves that spec validation doesn’t have to wait for full Spec Kit adoption — with one bash file and the Claude API, a team can start enforcing spec compliance today, then migrate to specify audit when ready.
04.7 Handling Spec vs Implementation Changes
Not all changes mean the same thing. A PR that changes the spec without changing code carries a different risk than a PR that changes code without updating the spec. The step below detects the change type so the pipeline can give contextual feedback.
1# Detect whether the spec or the implementation changed
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# Give contextual feedback:
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 esacBy distinguishing spec_only, impl_only, and both, the pipeline doesn’t just say “there’s a mismatch” but points the developer to the right question — is it the code that needs to catch up, or the spec that needs updating?
04.8 Spec Coverage Report
Beyond checking whether code matches the spec, we also need to know how many features have a spec at all. The script below computes the percentage of features in internal/usecase that already have a spec file.
1#!/bin/bash
2# scripts/spec-coverage.sh
3# Report: what % of features have a 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 if coverage < 80%
41if [ "$COVERAGE" -lt 80 ]; then
42 echo "::warning::Spec coverage $COVERAGE% below 80% target"
43fiThis coverage metric complements the audit score: the audit measures the quality of compliance for features that have a spec, while coverage measures the breadth — how many features SDD hasn’t touched at all. A realistic target: 80% of usecases have a spec.
04.9 Graduated Enforcement Strategy
Applying hard enforcement on day one almost always triggers team resistance, especially when many specs are still incomplete. The graduated strategy below introduces spec audit in three phases, from informational to blocking.
1Phase 1 (Weeks 1-2): SHADOW MODE
2 → Spec audit runs, results are logged
3 → Doesn't block the PR, only a PR comment
4 → Goal: developers get familiar with the output format
5
6 YAML config:
7 continue-on-error: true # on the Enforce Spec Compliance step
8
9Phase 2 (Weeks 3-4): WARNING MODE
10 → Spec audit comments on the PR with a score
11 → Score < 60: a more prominent warning
12 → Doesn't block merge
13 → Goal: developers start improving spec compliance
14
15Phase 3 (Month 2+): ENFORCEMENT MODE
16 → Score < 80: PR blocked
17 → CRITICAL (NON_COMPLIANT AC): immediate block
18 → PARTIAL: informational (doesn't block)
19 → Goal: systematic quality enforcement
20
21How to configure:
22 Phase 1: continue-on-error: true
23 Phase 2: remove continue-on-error, always exit 0 (informational only)
24 Phase 3: exit 1 if score < thresholdThe key to this strategy is building trust before enforcing rules: the team sees the audit’s value first, improves the spec, and only then feels the blocking. Durable adoption comes from buy-in, not sudden coercion.
04.10 Spec Audit for PRs that Touch Multiple Features
Large PRs often touch many features at once. Auditing every feature each time is expensive and produces false failures from features that weren’t changed. The step below maps changed paths to only the relevant features.
1# If the PR touches many features, audit only the relevant ones
2# to avoid false fails from features that weren't changed
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 if handler changed
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 # Find the feature related to this path
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 and sort
28 FEATURES=$(echo $FEATURES_TO_AUDIT | tr ' ' '\n' | sort -u | tr '\n' ',')
29 echo "features=$FEATURES" >> $GITHUB_OUTPUT
30 echo "Auditing features: $FEATURES"This path-to-feature mapping keeps the audit focused and economical: a PR that only changes order won’t trigger an audit of payment, so feedback is faster and AI cost stays under control.
04.11 Integration with the PR Template
To make spec compliance a habit rather than just an automated gate, we tie it into a PR template that developers must fill out. The template below forces the PR author to list the related spec and the ACs addressed.
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_This template creates clear traceability: from the PR description, a reviewer immediately knows which spec is relevant and which ACs were touched — the same context the automated audit uses, now also available to the human reviewer.
04.12 Spec Audit for Breaking Changes
Some implementation changes aren’t mere drift, but a breaking change to the contract the spec promised. The script below analyzes the diff to detect whether a change alters a response code, error code, or business rule written in the spec.
1#!/bin/bash
2# scripts/detect-spec-breaking-change.sh
3# Detect whether an implementation change is a breaking change from the 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 the diff for 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"
43fiThis breaking-change detection is a second layer on top of the compliance score: an ordinary audit might give a high score for code that’s technically correct, but this script catches when the contract promised to API consumers silently changes.
04.13 Tips & Gotchas for Spec Validation in CI
💡 Tip 1: A good spec = a more accurate audit. A spec with explicit Given/When/Then is easier for the AI to audit than a prose spec. Invest in spec quality, not just tooling.
💡 Tip 2: Audit only changed features. Running the audit for all features on every PR is overkill and expensive. Detect changes smartly (04.10).
💡 Tip 3: Update the comment, don’t add. If the audit runs 3 times (3 commits pushed to one PR), we don’t want 3 different comments. Update the same comment (see 04.4 — find existing comment).
💡 Tip 4: Fail early for CRITICAL. If there’s an AC that’s NON_COMPLIANT (not PARTIAL), that may warrant an immediate block without waiting for the overall score.
⚠️ Gotcha 1: A spec that’s too abstract. If the spec only says “handle error correctly” without specifying a response code, the AI can’t audit objectively. The spec must be concrete.
⚠️ Gotcha 2: Implementation that’s clear from context. If the Links section in the spec isn’t accurate, the AI will audit the wrong file. Maintain the Links section correctly.
⚠️ Gotcha 3: A large spec = an expensive audit. If the spec file is very long (>200 lines), trim it for efficiency. The AI needs tokens to read the spec + implementation + generate output.
04.14 Spec Audit Metrics
Good enforcement needs data. Tracking audit scores over time lets us see compliance trends per developer and per feature. The step below records audit metrics into the GitHub Step Summary on every run.
1# Add to the workflow for 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 to 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: send to analytics
22 # curl -X POST https://analytics.santekno.com/spec-audit \
23 # -d "{\"score\": $SCORE, \"pr\": $PR_NUMBER, \"author\": \"$AUTHOR\"}"With if: always(), metrics are recorded even when the audit fails — and that failure data is precisely what’s most valuable for a monthly retro: which features consistently score low, and who might need SDD mentoring.
04.15 The Full Integrated Workflow
The spec audit isn’t a standalone gate — it’s one layer of a layered quality-gates pipeline. The workflow below integrates four layers: syntactic (build/test/lint), architecture, AI review, and spec compliance in a single file.
1# .github/workflows/quality-gates.yml
2# Workflow that integrates all quality gates from 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 80Notice that L3 and L4 both needs: go-quality — they run in parallel after build/test passes, so the PR gets semantic review and spec audit simultaneously without slowing down the pipeline.
04.16 Alternative: Manual Spec Audit via Claude without Spec Kit
For teams that want full control over the audit logic, we can write our own audit tool in Go using the Anthropic SDK. The program below scans the spec directory, loads implementations from the Links section, and asks Claude to score compliance for each feature.
1// cmd/spec-audit/main.go
2// Custom spec audit tool if not using 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}This native Go tool gives two advantages: it’s part of the same codebase so it’s versioned alongside the code, and the implementation-extraction logic (extractImplementation) can be tailored exactly to your team’s Links conventions without waiting for an upstream Spec Kit feature.
04.17 End-to-End Test: Verify the Full Setup
Before relying on the pipeline in production, we need to prove that a mismatch is actually detected. The steps below simulate the full cycle: create a spec, run a local audit, then open a deliberately non-compliant PR.
1# Test the end-to-end spec validation pipeline
2
3# 1. Create a spec for an existing feature
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 within 30 minutes**
11- Given: Order PENDING + < 30 minutes
12- When: DELETE /orders/{id}
13- Then: 204 No Content
14
15**AC2: Order not 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 a local audit
25export ANTHROPIC_API_KEY="sk-ant-xxx"
26specify audit # or: bash scripts/simple-spec-audit.sh
27
28# 3. Open a PR with a deliberately non-compliant change
29git checkout -b test/spec-audit
30# Edit cancel_order.go to use 15 minutes instead of 30 minutes
31# git commit, git push, open a PR
32# Verify: the pipeline flags the mismatch between spec (30 min) and impl (15 min)
33
34# 4. Cleanup
35git checkout develop
36git branch -d test/spec-auditThis test is proof that your gate actually works — not just green because it never found a problem. Always verify that the audit can fail on a case that should fail before turning on enforcement.
04.18 Closing Part 1: The AI-Assisted Pipeline Foundation
By completing the four articles in Part 1, we now have a solid foundation. The summary below maps each article’s contribution and the status of the pipeline built so far.
1Article 01: WHY — philosophy and business case
2Article 02: ARCHITECTURE — the 4-layer pipeline blueprint
3Article 03: SETUP — Claude in GitHub Actions (3 approaches)
4Article 04: FIRST GATE — spec validation that closes the SDD loop
5
6PIPELINE STATUS NOW:
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
12In Part 2, we'll strengthen each layer with
13more sophisticated quality gates.This four-layer foundation is enough to protect the basic quality of every PR. Part 2 doesn’t add new layers arbitrarily; instead it deepens each one to be more accurate and cheaper to run.
04.19 Part 1 Completion Checklist
Before moving on to Part 2, make sure every component is installed and verified. The checklist below covers infrastructure, specs, secrets, and final verification.
1Make sure all of this exists before moving on to Part 2:
2
3Infrastructure:
4□ .github/workflows/ci.yml with a 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 at root
10
11Spec:
12□ .specify/config.yml
13□ At least 1 spec file in .specify/features/
14□ Spec files have an accurate Links section
15
16Secrets:
17□ ANTHROPIC_API_KEY in GitHub Secrets
18□ (Optional) SLACK_WEBHOOK
19
20Verification:
21□ Push a test PR → all 4 layers run
22□ PR comment from Copilot appears
23□ Spec audit comment appears
24□ Architecture check script has no violationsIf every box is checked — especially the Verification section where all four layers actually run on a single test PR — your pipeline foundation is ready to be developed further.
04.20 Part 1 Summary
Part 1 of Topic 4 is complete. We’ve built the foundation of a pipeline that will keep evolving in Parts 2, 3, and 4:
Article 01: A strong business case — AI in the pipeline isn’t hype, but systematic quality enforcement with measurable ROI.
Article 02: A clear 4-layer architecture blueprint — from syntactic to spec compliance, with a low cost estimate.
Article 03: Three approaches to setting up Claude in CI — Copilot (easiest), Claude API via HTTP (most flexible), Claude Code CLI (most powerful).
Article 04: Spec validation that closes the SDD → Spec Kit → CI loop — every PR is now audited against the spec that was written. Without CI validation, an SDD workflow is only as strong as developer discipline; with CI validation, consistency is enforced systematically.
In the next article, we’ll deepen the AI review layer into a production-ready automated code review system — with explicit rules, objective scoring, and graduated enforcement.