Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
16 Oct 2026 · 21 min read ·Article 68 / 208
Go

Architecture Linting in Golang CI: Enforce Clean Architecture Automatically

Implement architecture linting for Go in CI/CD. Custom rules for Clean Architecture, depguard configuration, import graph analysis, and AI-powered architecture review.

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Architecture Linting: Enforce Clean Architecture via the Pipeline

Architecture linting in golang CI is the only sustainable way to keep Clean Architecture clean over the long run. Clean Architecture is a powerful pattern but easily eroded over time. Developers in a hurry take shortcuts. Tired reviewers miss the wrong import. In six months, a tidy architecture can become a big ball of mud.

The solution is enforcing the architecture rules in CI: every PR is checked against the architecture rules, and violations are blocked before they enter the codebase. In this article we build layered enforcement, from depguard to AI review.


08.1 The Real Problem: Architecture Drift

Before talking about the solution, let’s see how an architecture “rots” silently. The chronology below illustrates how one small shortcut piles up into months of technical debt.

text
 1Sprint 1: The team implements Clean Architecture well
 2  handler → usecase (interface) → repository (interface) → domain
 3
 4Sprint 4: A new developer joins, unfamiliar with the architecture
 5  shortcut: handler calls the repository implementation directly
 6  reviewer: misses it because code review focuses on the logic
 7
 8Sprint 8: The CI/CD analyst looks at the import graph
 9  handler → usecase → repository ✅
10  handler → repository (direct!) ❌
11  usecase → pgx driver (direct!) ❌
12  domain → echo framework ❌
13
14  Refactoring now takes 2 sprints because dependencies must be untangled
15
16With architecture linting from Sprint 1:
17  Sprint 1: violations are caught → the developer fixes them before merge
18  Sprint 8: the import graph is still clean, no refactoring burden
19
20  Prevention cost: 5 minutes fix per PR
21  Remediation cost: 2 sprints = ~2 weeks × 5 developers = 400 hours

The comparison is stark: 5 minutes of prevention per PR versus 400 hours of remediation. Automatic enforcement from the start is far cheaper than cleaning up the mess later.


08.2 Three Layers of Architecture Enforcement

Comprehensive enforcement doesn’t rely on a single tool, but on three layers with different trade-offs. The summary below maps each layer, its scope, and its cost.

text
 1LAYER 1: golangci-lint with depguard (easiest to set up)
 2  → Catch explicitly forbidden imports
 3  → Rule-based, configured in .golangci.yml
 4  → Zero AI cost
 5
 6LAYER 2: Custom Go script (more flexible)
 7  → Catch cross-layer imports with path matching
 8  → Can detect subtler violations
 9  → Zero AI cost
10
11LAYER 3: AI Architecture Review (most sophisticated)
12  → Catch violations that need semantic understanding
13  → "Does this handler properly delegate to the usecase, or bypass it?"
14  → Low AI cost

The three complement each other: Layers 1 and 2 are free and deterministic for explicit violations, while Layer 3 handles the cases that need contextual understanding. We’ll go through each in turn.


08.3 Layer 1: depguard Configuration

The easiest layer is depguard, which is just configured in YAML without writing code. The configuration below defines the forbidden imports per layer — handler, usecase, and domain.

yaml
 1# .golangci.yml — add depguard rules
 2
 3linters-settings:
 4  depguard:
 5    rules:
 6      # Rule: handler layer must not import repository impl
 7      handler-no-repo:
 8        files:
 9          - "!**/delivery/http/handler/**"  # handler files only
10          - "!**/*_test.go"
11        deny:
12          - pkg: "github.com/santekno/santekno-shop/internal/repository"
13            desc: "Handler must use usecase interfaces, not repository directly"
14          - pkg: "github.com/jackc/pgx"
15            desc: "Handler must not import database drivers"
16          - pkg: "github.com/redis/go-redis"
17            desc: "Handler must not import cache drivers"
18
19      # Rule: usecase layer must not import a framework
20      usecase-no-framework:
21        files:
22          - "!**/internal/usecase/**"
23          - "!**/*_test.go"
24        deny:
25          - pkg: "github.com/labstack/echo"
26            desc: "Usecase must not import an HTTP framework"
27          - pkg: "github.com/jackc/pgx"
28            desc: "Usecase must use repository interfaces, not the DB directly"
29          - pkg: "github.com/redis/go-redis"
30            desc: "Usecase must not import cache directly"
31
32      # Rule: domain layer — zero external imports
33      domain-pure:
34        files:
35          - "!**/internal/domain/**"
36          - "!**/*_test.go"
37        deny:
38          - pkg: "github.com/labstack/echo"
39            desc: "Domain must have zero framework dependencies"
40          - pkg: "github.com/jackc/pgx"
41            desc: "Domain must have zero infrastructure dependencies"
42          - pkg: "github.com/redis/go-redis"
43            desc: "Domain must have zero infrastructure dependencies"
44          - pkg: "github.com/confluentinc/confluent-kafka-go"
45            desc: "Domain must have zero infrastructure dependencies"
46
47      # Rule: test files may import anything
48      test-files:
49        files:
50          - "**/*_test.go"
51        allow:
52          - $all  # allow everything in test files

The advantage of depguard is maintainability: rules are simply added in YAML, and every deny includes a desc that explains to the developer why the import is forbidden.


08.4 Layer 2: Custom Architecture Check Script

depguard can’t express every rule. For more complex patterns, we write a Go script that traverses the file tree, parses the imports, and matches them against the per-layer rules.

go
  1// scripts/check-architecture.go
  2// Comprehensive architecture boundary enforcement
  3// Run: go run scripts/check-architecture.go ./...
  4
  5//go:build ignore
  6
  7package main
  8
  9import (
 10    "fmt"
 11    "go/parser"
 12    "go/token"
 13    "os"
 14    "path/filepath"
 15    "strings"
 16)
 17
 18// LayerRule defines what may / may not be imported per layer
 19type LayerRule struct {
 20    Name        string
 21    PathPattern string   // pattern to identify a file's layer
 22    ForbiddenImports []ForbiddenImport
 23}
 24
 25type ForbiddenImport struct {
 26    Pattern     string // forbidden import path
 27    Description string // why it's forbidden
 28    Severity    string // CRITICAL | WARNING
 29}
 30
 31var architectureRules = []LayerRule{
 32    {
 33        Name:        "handler",
 34        PathPattern: "delivery/http/handler",
 35        ForbiddenImports: []ForbiddenImport{
 36            {
 37                Pattern:     "internal/repository",
 38                Description: "Handler must depend on usecase interfaces, not repository",
 39                Severity:    "CRITICAL",
 40            },
 41            {
 42                Pattern:     "github.com/jackc/pgx",
 43                Description: "Handler must not touch the database directly",
 44                Severity:    "CRITICAL",
 45            },
 46            {
 47                Pattern:     "github.com/redis/go-redis",
 48                Description: "Handler must not touch the cache directly",
 49                Severity:    "CRITICAL",
 50            },
 51        },
 52    },
 53    {
 54        Name:        "usecase",
 55        PathPattern: "internal/usecase",
 56        ForbiddenImports: []ForbiddenImport{
 57            {
 58                Pattern:     "delivery/",
 59                Description: "Usecase must not import from the delivery layer (circular dep risk)",
 60                Severity:    "CRITICAL",
 61            },
 62            {
 63                Pattern:     "github.com/jackc/pgx",
 64                Description: "Usecase must use a repository interface, not the DB driver",
 65                Severity:    "CRITICAL",
 66            },
 67            {
 68                Pattern:     "github.com/labstack/echo",
 69                Description: "Usecase must not depend on the HTTP framework",
 70                Severity:    "CRITICAL",
 71            },
 72        },
 73    },
 74    {
 75        Name:        "domain",
 76        PathPattern: "internal/domain",
 77        ForbiddenImports: []ForbiddenImport{
 78            {
 79                Pattern:     "github.com/",  // any github package
 80                Description: "Domain must have zero external dependencies (stdlib only)",
 81                Severity:    "CRITICAL",
 82                // Exception: github.com/google/uuid is allowed
 83            },
 84        },
 85    },
 86}
 87
 88// Domain UUID exception
 89var domainAllowedExceptions = []string{
 90    "github.com/google/uuid",
 91    "github.com/santekno/santekno-shop/shared/", // shared domain packages
 92}
 93
 94type Violation struct {
 95    File        string
 96    Layer       string
 97    Import      string
 98    Description string
 99    Severity    string
100}
101
102func main() {
103    var violations []Violation
104    fset := token.NewFileSet()
105
106    err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
107        if err != nil || info.IsDir() {
108            return err
109        }
110        if !strings.HasSuffix(path, ".go") {
111            return nil
112        }
113        if strings.HasSuffix(path, "_test.go") {
114            return nil // skip test files
115        }
116        // Skip generated files
117        if strings.Contains(path, "mock_") || strings.Contains(path, ".pb.go") {
118            return nil
119        }
120
121        // Determine which layer this file belongs to
122        var matchedRule *LayerRule
123        for i := range architectureRules {
124            if strings.Contains(path, architectureRules[i].PathPattern) {
125                matchedRule = &architectureRules[i]
126                break
127            }
128        }
129        if matchedRule == nil {
130            return nil
131        }
132
133        // Parse imports
134        f, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
135        if err != nil {
136            return nil
137        }
138
139        for _, imp := range f.Imports {
140            importPath := strings.Trim(imp.Path.Value, `"`)
141
142            for _, forbidden := range matchedRule.ForbiddenImports {
143                if !strings.Contains(importPath, forbidden.Pattern) {
144                    continue
145                }
146
147                // Check exception list
148                isException := false
149                for _, exc := range domainAllowedExceptions {
150                    if strings.HasPrefix(importPath, exc) {
151                        isException = true
152                        break
153                    }
154                }
155                if isException {
156                    continue
157                }
158
159                violations = append(violations, Violation{
160                    File:        path,
161                    Layer:       matchedRule.Name,
162                    Import:      importPath,
163                    Description: forbidden.Description,
164                    Severity:    forbidden.Severity,
165                })
166            }
167        }
168        return nil
169    })
170
171    if err != nil {
172        fmt.Fprintf(os.Stderr, "walk error: %v\n", err)
173        os.Exit(2)
174    }
175
176    if len(violations) == 0 {
177        fmt.Println("Architecture check PASSED — all layer boundaries respected")
178        os.Exit(0)
179    }
180
181    // Print violations
182    criticalCount := 0
183    warningCount := 0
184
185    fmt.Printf("Architecture violations found: %d\n\n", len(violations))
186    for _, v := range violations {
187        marker := "[X]"
188        if v.Severity == "WARNING" {
189            marker = "[!]"
190        }
191        fmt.Printf("%s [%s] %s\n", marker, v.Layer, v.File)
192        fmt.Printf("   Imports: %s\n", v.Import)
193        fmt.Printf("   Reason:  %s\n\n", v.Description)
194
195        if v.Severity == "CRITICAL" {
196            criticalCount++
197        } else {
198            warningCount++
199        }
200    }
201
202    fmt.Printf("CRITICAL: %d | WARNING: %d\n", criticalCount, warningCount)
203
204    if criticalCount > 0 {
205        os.Exit(1) // block pipeline
206    }
207
208    os.Exit(0) // warnings only, do not block
209}

This script gives full control: severity per rule, an exception list for uuid, and exit code 1 only if there’s a CRITICAL violation. That flexibility is exactly what depguard alone can’t achieve.


08.5 Layer 3: AI Architecture Review

Some violations need semantic understanding, not mere path matching. The script below gives the AI a full architecture description plus the diff, then asks it to judge whether there’s a hidden violation.

bash
 1#!/bin/bash
 2# scripts/ai-architecture-review.sh
 3# AI review for violations that need semantic understanding
 4
 5set -euo pipefail
 6
 7DIFF_FILE="${1}"
 8
 9# Load architecture description
10ARCH_DESC=$(cat << 'ARCH'
11Clean Architecture for Santekno Shop:
12
13LAYERS (outer to inner):
141. delivery/http/handler/ — HTTP request/response only
15   - Parse request, call usecase, format response
16   - MUST depend on usecase interfaces only
17   - MUST NOT access DB, cache, or messaging directly
18
192. internal/usecase/ — Business logic
20   - Orchestrate business rules
21   - MUST depend on repository interfaces only
22   - MUST NOT import HTTP framework or DB drivers
23
243. internal/repository/ — Data access
25   - Implement repository interfaces from domain
26   - CAN import database drivers (pgx, redis)
27   - MUST NOT import usecase or handler
28
294. internal/domain/ — Pure domain
30   - Entities, value objects, errors, interfaces
31   - MUST NOT import anything external except stdlib
32   - Exception: github.com/google/uuid
33
34RED FLAGS to detect:
35- Handler calling repository directly (bypassing usecase)
36- Usecase importing pgx, echo, or redis packages
37- Domain importing any github.com/* except uuid
38- Any circular dependency pattern
39ARCH
40)
41
42DIFF=$(cat "$DIFF_FILE" | head -400)
43
44PROMPT="You are an architecture reviewer for a Go Clean Architecture project.
45
46ARCHITECTURE:
47$ARCH_DESC
48
49CODE DIFF:
50$DIFF
51
52Review for architecture violations. Be specific about:
531. Does any handler directly access repository without going through usecase?
542. Does any usecase import infrastructure packages (pgx, echo, redis)?
553. Does any domain type import external frameworks?
564. Are there any circular dependency patterns?
57
58Output:
59VIOLATION: [yes/no]
60Details (if violation):
61  CRITICAL: [description] at [file:line]
62  Fix: [specific change needed]
63
64ARCHITECTURE_SCORE: [0-100]
65(100=perfect, 80=minor issues, 60=violations, <60=serious problems)"
66
67RESULT=$(./scripts/claude-call.sh "$PROMPT" 600)
68echo "$RESULT"
69
70if echo "$RESULT" | grep -q "^  CRITICAL:"; then
71  echo ""
72  echo "::error::Architecture violations detected"
73  exit 1
74fi
75
76SCORE=$(echo "$RESULT" | grep "ARCHITECTURE_SCORE:" | grep -oP '\d+' || echo "85")
77if [ "$SCORE" -lt 70 ]; then
78  echo "::warning::Architecture score $SCORE — review architecture concerns"
79fi

The strength of Layer 3 is catching cases like a handler that technically only imports the usecase interface, but where that usecase itself quietly imports pgx — a violation that slips past simple path matching.


08.6 Workflow: Architecture Linting in CI

The three layers are combined into a single workflow that runs in sequence. The configuration below runs depguard, the custom script, then the AI review that only executes if the two earlier layers pass.

yaml
  1# .github/workflows/architecture.yml
  2
  3name: Architecture Linting
  4
  5on:
  6  pull_request:
  7    paths:
  8      - '**.go'
  9      - 'go.mod'
 10      - 'go.sum'
 11
 12jobs:
 13  layer1-depguard:
 14    name: "L1: depguard Import Rules"
 15    runs-on: ubuntu-latest
 16    steps:
 17      - uses: actions/checkout@v4
 18      - uses: actions/setup-go@v5
 19        with: { go-version: '1.22', cache: true }
 20      - uses: golangci/golangci-lint-action@v6
 21        with:
 22          args: --enable depguard --disable-all
 23          # Only run depguard, not the full lint suite
 24
 25  layer2-custom-script:
 26    name: "L2: Custom Architecture Check"
 27    runs-on: ubuntu-latest
 28    steps:
 29      - uses: actions/checkout@v4
 30      - uses: actions/setup-go@v5
 31        with: { go-version: '1.22' }
 32      - name: Run architecture check
 33        run: |
 34          go run scripts/check-architecture.go ./...
 35
 36  layer3-ai-review:
 37    name: "L3: AI Architecture Review"
 38    runs-on: ubuntu-latest
 39    needs: [layer1-depguard, layer2-custom-script]
 40    # Only runs if L1 and L2 pass (don't waste AI tokens on a broken arch)
 41    if: success()
 42    permissions:
 43      pull-requests: write
 44      contents: read
 45    env:
 46      ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
 47    steps:
 48      - uses: actions/checkout@v4
 49        with: { fetch-depth: 0 }
 50
 51      - name: Get diff
 52        run: |
 53          git diff origin/${{ github.base_ref }}...HEAD -- '*.go' \
 54            | head -400 > /tmp/arch-diff.txt
 55
 56      - name: AI Architecture Review
 57        id: arch_review
 58        continue-on-error: true
 59        run: |
 60          chmod +x scripts/ai-architecture-review.sh
 61          RESULT=$(./scripts/ai-architecture-review.sh /tmp/arch-diff.txt 2>&1) || true
 62
 63          echo "result<<EOF" >> $GITHUB_OUTPUT
 64          echo "$RESULT" >> $GITHUB_OUTPUT
 65          echo "EOF" >> $GITHUB_OUTPUT
 66
 67          SCORE=$(echo "$RESULT" | grep "ARCHITECTURE_SCORE:" | grep -oP '\d+' || echo "85")
 68          echo "score=$SCORE" >> $GITHUB_OUTPUT
 69
 70      - name: Post architecture review
 71        if: steps.arch_review.outputs.result != ''
 72        uses: actions/github-script@v7
 73        with:
 74          script: |
 75            const result = `${{ steps.arch_review.outputs.result }}`;
 76            const score = parseInt('${{ steps.arch_review.outputs.score }}') || 85;
 77            const emoji = score >= 80 ? '🟢' : score >= 60 ? '🟡' : '🔴';
 78
 79            const body = [
 80              `## 🏗️ Architecture Review`,
 81              `**Score:** ${emoji} ${score}/100`,
 82              ``,
 83              result,
 84              `---`,
 85              `*Layer boundaries: handler → usecase → repository → domain*`
 86            ].join('\n');
 87
 88            // Find or update existing arch comment
 89            const { data: comments } = await github.rest.issues.listComments({
 90              owner: context.repo.owner,
 91              repo: context.repo.repo,
 92              issue_number: context.issue.number
 93            });
 94
 95            const existing = comments.find(c => c.body.includes('🏗️ Architecture Review'));
 96
 97            if (existing) {
 98              await github.rest.issues.updateComment({
 99                owner: context.repo.owner,
100                repo: context.repo.repo,
101                comment_id: existing.id,
102                body
103              });
104            } else {
105              await github.rest.issues.createComment({
106                owner: context.repo.owner,
107                repo: context.repo.repo,
108                issue_number: context.issue.number,
109                body
110              });
111            }

Note the needs: [layer1-depguard, layer2-custom-script] and if: success() on Layer 3 — AI tokens aren’t wasted reviewing code that already clearly violates the deterministic rules.


08.7 Import Graph Visualization

Sometimes a problem is easier to see through a graph than a list. The script below uses goda to produce an import graph and checks whether the repository is imported by a layer that shouldn’t.

bash
 1#!/bin/bash
 2# scripts/generate-import-graph.sh
 3# Generate an import graph for architecture visualization
 4
 5go install golang.org/x/tools/cmd/callgraph@latest
 6go install github.com/loov/goda@latest
 7
 8# Generate import graph for internal packages
 9goda graph "github.com/santekno/santekno-shop/internal/..." | \
10  grep -v "_test" > /tmp/import-graph.dot
11
12# Convert to a readable format
13echo "Package dependencies:"
14goda list "github.com/santekno/santekno-shop/internal/..." 2>/dev/null | \
15  grep -v "_test" | \
16  sort
17
18# Check for cross-layer imports that shouldn't exist
19echo ""
20echo "Checking for forbidden cross-layer dependencies..."
21goda list -f "{{.ImportedBy}}" "github.com/santekno/santekno-shop/internal/repository/..." | \
22  grep -E "(delivery|usecase)" && \
23  echo "Repository imported by a non-allowed layer" || \
24  echo "Repository layer isolation: OK"

The ImportedBy check on the repository is a quick way to detect an architecture leak: if delivery or usecase appears in the list, a layer is violating the boundary.


08.8 Architecture Rules as Tests

The most elegant approach is to encode the architecture rules as ordinary Go tests — no special CI step needed. The test below verifies that the handler doesn’t import forbidden packages and that the domain only imports stdlib plus uuid.

go
 1// internal/architecture_test.go
 2// Architecture rules encoded as Go tests
 3
 4package architecture_test
 5
 6import (
 7    "go/build"
 8    "testing"
 9
10    "github.com/stretchr/testify/assert"
11    "golang.org/x/tools/go/packages"
12)
13
14// TestHandlerLayerDependencies verifies the handler only imports what's allowed
15func TestHandlerLayerDependencies(t *testing.T) {
16    pkgs, err := packages.Load(&packages.Config{
17        Mode: packages.NeedImports,
18        Dir:  "../",
19    }, "github.com/santekno/santekno-shop/delivery/http/handler/...")
20
21    if err != nil {
22        t.Skip("Cannot load packages:", err)
23    }
24
25    forbiddenInHandler := []string{
26        "github.com/jackc/pgx",
27        "github.com/redis/go-redis",
28        "github.com/santekno/santekno-shop/internal/repository",
29    }
30
31    for _, pkg := range pkgs {
32        for importPath := range pkg.Imports {
33            for _, forbidden := range forbiddenInHandler {
34                assert.NotContains(t, importPath, forbidden,
35                    "Handler %s imports forbidden package %s",
36                    pkg.PkgPath, importPath)
37            }
38        }
39    }
40}
41
42// TestDomainLayerPurity verifies the domain only imports stdlib
43func TestDomainLayerPurity(t *testing.T) {
44    pkgs, err := packages.Load(&packages.Config{
45        Mode: packages.NeedImports,
46    }, "github.com/santekno/santekno-shop/internal/domain/...")
47
48    if err != nil {
49        t.Skip("Cannot load packages:", err)
50    }
51
52    allowedExternalInDomain := []string{
53        "github.com/google/uuid", // only exception
54    }
55
56    for _, pkg := range pkgs {
57        for importPath := range pkg.Imports {
58            if !isStdlibOrAllowed(importPath, allowedExternalInDomain) {
59                t.Errorf("Domain package %s imports external package %s",
60                    pkg.PkgPath, importPath)
61            }
62        }
63    }
64}
65
66func isStdlibOrAllowed(importPath string, allowed []string) bool {
67    // Check stdlib
68    if !strings.Contains(importPath, ".") {
69        return true
70    }
71    // Check allowed list
72    for _, a := range allowed {
73        if strings.HasPrefix(importPath, a) {
74            return true
75        }
76    }
77    return false
78}

The beauty of this approach: the architecture rules run every time go test does, so a violation fails instantly without any extra tooling or separate CI job.


08.9 Handling Architecture Exceptions

Not every “violation” is bad — there are legitimate exceptions that need documenting. The example below shows how to document an exception with a nolint comment plus an allowlist in depguard.

go
 1// Sometimes there are legitimate exceptions that need documenting
 2
 3// Example: the repository layer needs to return domain.ErrNotFound
 4// which should only be known to the domain
 5// But this is acceptable because the repository implements the domain interface
 6
 7// How to document an exception:
 8// 1. Add a comment explaining why
 9// 2. Add it to golangci-lint nolint or the allowlist
10
11// In the code:
12// repository/postgres/order_repository.go
13// nolint:depguard -- using domain.ErrOrderNotFound is intentional:
14// repository implements the domain.OrderRepository interface
15import "github.com/santekno/santekno-shop/internal/domain"

The key to healthy exceptions is that every nolint always comes with a reason. “Conscious technical debt” is far better than “undetected technical debt.” The configuration side is set up in depguard as follows.

yaml
1# In .golangci.yml:
2linters-settings:
3  depguard:
4    rules:
5      repo-domain-exception:
6        files:
7          - "internal/repository/**"
8        allow:
9          - "github.com/santekno/santekno-shop/internal/domain"  # implementing domain interfaces

With this explicit allowlist, the repository may import the domain because it genuinely implements its interfaces — a documented exception, not a loophole that slips through silently.


08.10 Architecture Documentation via AI

Hand-written architecture documentation quickly goes stale. The script below generates documentation directly from the actual import graph, so it’s always in sync with the code.

bash
 1#!/bin/bash
 2# scripts/generate-arch-doc.sh
 3# AI generates architecture documentation from actual code
 4
 5set -euo pipefail
 6
 7# Collect import relationships
 8IMPORT_ANALYSIS=$(go list -f '{{.ImportPath}} imports: {{range .Imports}}{{.}} {{end}}' \
 9  ./internal/... 2>/dev/null | grep "santekno" | head -50)
10
11LAYER_COUNT=$(find internal -mindepth 1 -maxdepth 1 -type d | wc -l)
12
13PROMPT="Generate architecture documentation for this Go project.
14
15Import relationships (internal packages only):
16$IMPORT_ANALYSIS
17
18Write:
191. Architecture overview (2-3 paragraphs)
202. Layer descriptions with responsibilities
213. Dependency rules (what can depend on what)
224. Known violations or concerns (if any from the import analysis)
23
24Format as Markdown. Technical but readable for new developers."
25
26RESULT=$(./scripts/claude-call.sh "$PROMPT" 1000)
27
28# Save to docs
29mkdir -p docs
30echo "# Architecture Documentation" > docs/architecture.md
31echo "*Auto-generated from codebase — $(date -u +%Y-%m-%d)*" >> docs/architecture.md
32echo "" >> docs/architecture.md
33echo "$RESULT" >> docs/architecture.md
34
35echo "Architecture documentation generated: docs/architecture.md"

Because the input is the real import graph, the documentation produced reflects the code’s current state — not the architectural intent that may have long since drifted.


08.11 Architecture Linting Tips & Gotchas

💡 Tip 1: Start with depguard, not a custom script. depguard is easier to maintain because the configuration is in YAML. Use a custom script for the edge cases depguard can’t handle.

💡 Tip 2: Architecture rules as tests. An architecture_test.go that tests import rules can run with go test — no special CI step needed.

💡 Tip 3: Exceptions must be explicit and documented. Every nolint or allowlist entry must have a comment explaining why the exception is valid. “Conscious technical debt” is better than “undetected technical debt.”

💡 Tip 4: Run the architecture check in pre-commit. It’s far faster to get feedback locally than to wait for CI. Add it to the pre-commit hook.

⚠️ Gotcha 1: Path-based detection can miss files. A custom script that detects “if the path contains ‘handler’” can miss a case where a developer puts a file in the wrong directory. Pair it with golangci-lint, which is more robust.

⚠️ Gotcha 2: Third-party wrappers. If the usecase wraps a pgx error, that’s acceptable. If the usecase imports the pgx package, that’s a violation. Distinguish between a type assertion and a direct import.

⚠️ Gotcha 3: Shared packages can become a loophole. A package in shared/ imported by all layers must be truly pure (types and interfaces only). Don’t put infrastructure code in a shared package.


08.12 Architecture Health Metrics

Enforcement alone isn’t enough; we also want to monitor the trend of architecture health. The script below counts the number of violations, the import depth, and the packages with the most dependents as weekly metrics.

bash
 1# Weekly architecture health check
 2
 3# 1. Count architecture violations
 4VIOLATIONS=$(go run scripts/check-architecture.go ./... 2>&1 | \
 5  grep "^\[X\]" | wc -l || echo "0")
 6
 7# 2. Import depth (deeper = more complex)
 8MAX_DEPTH=$(go list -f '{{len .Imports}}' ./... | sort -n | tail -1)
 9
10# 3. Packages with the most dependents
11MOST_DEPENDED=$(go list -f '{{.ImportedBy}}' ./internal/... | \
12  sort | uniq -c | sort -rn | head -5)
13
14echo "Architecture Health Report"
15echo "=========================="
16echo "Violations: $VIOLATIONS (target: 0)"
17echo "Max import count: $MAX_DEPTH (target: < 20)"
18echo ""
19echo "Most depended packages:"
20echo "$MOST_DEPENDED"

Metrics like “max import count” and “most depended packages” give an early signal about packages that are too complex or becoming a dependency bottleneck — before they become a big problem.


08.13 Case Study: Migration from Monolith to Clean Architecture

Enforcement theory looks different when applied to a 50K-line legacy codebase. The chronology below shows how one team used architecture linting to track the migration’s progress incrementally.

text
 1Santekno team, an old service with 50K lines and no clear layers.
 2Using architecture linting to track migration progress.
 3
 4Phase 1 (Sprint 1-3): Set up linting with severity=warning
 5  Day 1: 847 violations detected
 6  Action: prioritize per layer and severity
 7
 8Phase 2 (Sprint 4-8): Fix per feature
 9  Sprint 4: 847 → 612 violations
10  Sprint 6: 612 → 341 violations
11  Sprint 8: 341 → 89 violations
12
13Phase 3 (Sprint 9-10): Hard enforcement
14  Sprint 10: 0 violations
15  Architecture linting: fully enforced
16
17Lessons: soft enforcement first is the key to buy-in.

The main lesson: starting with severity=warning let the team bring 847 violations down gradually without immediately blocking every PR — hard enforcement was only switched on once the number approached zero.


08.14 Import Graph Analysis

For deeper dependency analysis, tooling from golang.org/x/tools can be used. The commands below produce an import graph and check forbidden cross-layer dependencies concisely.

bash
 1# golang.org/x/tools/cmd/callgraph to analyze dependencies
 2go install golang.org/x/tools/cmd/callgraph@latest
 3
 4# Generate an import graph for internal packages
 5goda graph "github.com/santekno/santekno-shop/internal/..." > /tmp/import-graph.dot
 6
 7# Check forbidden cross-layer deps
 8goda list -f "{{.ImportedBy}}" \
 9  "github.com/santekno/santekno-shop/internal/repository/..." | \
10  grep -E "(delivery|usecase)" && echo "VIOLATION" || echo "OK"

This binary “VIOLATION” or “OK” output is easy to integrate into the pipeline as a fast gate before the more expensive analysis runs.


08.15 Enforcement Levels per Environment

Enforcement doesn’t have to be uniform across all branches. The configuration below applies strict rules (zero violations) on main, but only warnings on develop.

yaml
 1# Different enforcement for different contexts
 2- name: Architecture check
 3  run: |
 4    VIOLATIONS=$(go run scripts/check-architecture.go ./... 2>&1 | \
 5      grep "^VIOLATION" | wc -l)
 6
 7    # main branch: strict (zero violations)
 8    if [ "${{ github.ref }}" == "refs/heads/main" ]; then
 9      [ "$VIOLATIONS" -gt 0 ] && exit 1
10    fi
11
12    # develop: warning only
13    if [ "${{ github.ref }}" == "refs/heads/develop" ]; then
14      [ "$VIOLATIONS" -gt 0 ] && echo "::warning::$VIOLATIONS architecture violations"
15    fi

This tiered approach gives room to maneuver on development branches while keeping main clean — the highest standard applies to the code that actually ships.


08.16 Architecture Linting Summary

Architecture linting with three layers provides comprehensive coverage:

depguard (Layer 1): Easy-to-maintain YAML configuration, catches explicitly forbidden imports.

Custom script (Layer 2): More flexible, can detect more complex patterns, generates detailed violation reports with exact file:line.

AI review (Layer 3): Semantic understanding for violations that need context — “is this really a bypass or a legitimate wrapper?”

Architecture tests (bonus): Encode the rules as Go tests that run with go test, zero infrastructure overhead.

The key insight: good architecture is architecture that is enforced automatically — not just the kind written neatly in a document but never guarded.


08.17 Transition to the Next Article

We now have four independent quality gates — AI code review, security audit, coverage enforcement, and architecture linting. But all four can still be ignored if a developer forces the merge. The next question: how do we make all these gates a hard requirement that can’t be bypassed?

The answer is GitHub Branch Protection with required status checks and an aggregate quality gate, which unites all the gates into a single coherent enforcement system.

Related Articles

💬 Comments