Skip to content

notque/vexjoy-agent / skills/programming/programming

programming

Flagged

Language rules, workflows, and tooling: Go, Python, Rust, Kotlin, Swift, PHP, TypeScript type checks and debugging, OpenStack Python, MCP local-docs servers, Node.js backend APIs.

FileKindSize
SKILL.mdskill md19.3 KB
references/go/code-review.mdmarkdown12.0 KB
references/go/code-review/common-review-comments.mdmarkdown6.6 KB
references/go/concurrency.mdmarkdown11.5 KB
references/go/concurrency/concurrency-patterns.mdmarkdown5.7 KB
references/go/error-handling.mdmarkdown10.8 KB
references/go/error-handling/patterns.mdmarkdown4.2 KB
references/go/google-style-guide/SHA256SUMSother313 B
references/go/google-style-guide/UPSTREAM_REVISIONother41 B
references/go/google-style-guide/best-practices/part-01.mdmarkdown10.0 KB
references/go/google-style-guide/best-practices/part-02.mdmarkdown15.0 KB
references/go/google-style-guide/best-practices/part-03.mdmarkdown14.1 KB
references/go/google-style-guide/best-practices/part-04.mdmarkdown13.5 KB
references/go/google-style-guide/best-practices/part-05.mdmarkdown10.5 KB
references/go/google-style-guide/best-practices/part-06.mdmarkdown14.4 KB
references/go/google-style-guide/best-practices/part-07.mdmarkdown16.1 KB
references/go/google-style-guide/best-practices/part-08.mdmarkdown11.4 KB
references/go/google-style-guide/best-practices/part-09.mdmarkdown13.7 KB
references/go/google-style-guide/best-practices/part-10.mdmarkdown16.9 KB
references/go/google-style-guide/decisions/part-01.mdmarkdown15.0 KB
references/go/google-style-guide/decisions/part-02.mdmarkdown12.5 KB
references/go/google-style-guide/decisions/part-03.mdmarkdown11.5 KB
references/go/google-style-guide/decisions/part-04.mdmarkdown8.4 KB
references/go/google-style-guide/decisions/part-05.mdmarkdown9.8 KB
references/go/google-style-guide/decisions/part-06.mdmarkdown14.7 KB
references/go/google-style-guide/decisions/part-07.mdmarkdown13.3 KB
references/go/google-style-guide/decisions/part-08.mdmarkdown14.3 KB
references/go/google-style-guide/decisions/part-09.mdmarkdown15.3 KB
references/go/google-style-guide/decisions/part-10.mdmarkdown8.3 KB
references/go/google-style-guide/guide/part-01.mdmarkdown16.3 KB
references/go/google-style-guide/guide/part-02.mdmarkdown3.0 KB
references/go/google-style-guide/index.mdmarkdown8.4 KB
references/go/preferred-patterns.mdmarkdown12.5 KB
references/go/preferred-patterns/code-examples.mdmarkdown11.6 KB
references/go/quality-gate.mdmarkdown7.3 KB
references/go/quality-gate/common-lint-errors.jsonconfig7.6 KB
references/go/quality-gate/examples.mdmarkdown11.0 KB
references/go/quality-gate/makefile-targets.jsonconfig5.1 KB
references/go/sapcc-conventions.mdmarkdown34.6 KB
references/go/sapcc-conventions/api-design-detailed.mdmarkdown22.7 KB
references/go/sapcc-conventions/architecture-patterns.mdmarkdown18.6 KB
references/go/sapcc-conventions/build-ci-detailed.mdmarkdown18.7 KB
references/go/sapcc-conventions/error-handling-detailed.mdmarkdown20.1 KB
references/go/sapcc-conventions/extended-patterns.mdmarkdown7.1 KB
references/go/sapcc-conventions/go-bits-philosophy-detailed.mdmarkdown24.5 KB
references/go/sapcc-conventions/library-reference.mdmarkdown14.0 KB
references/go/sapcc-conventions/pr-mining-insights.mdmarkdown17.5 KB
references/go/sapcc-conventions/review-standards.mdmarkdown10.5 KB
references/go/sapcc-conventions/sapcc-code-patterns.mdmarkdown46.2 KB
references/go/testing.mdmarkdown9.7 KB
references/go/testing/go-benchmark-and-concurrency.mdmarkdown5.6 KB
references/go/testing/go-test-patterns.mdmarkdown9.0 KB
references/golang-general.mdmarkdown8.9 KB
references/golang-general/go-modern-code.mdmarkdown17.2 KB
references/golang-general/go-verification-workflow.mdmarkdown5.0 KB
references/golang-general/go-version-idioms.mdmarkdown6.8 KB
references/kotlin-general.mdmarkdown7.5 KB
references/kotlin-general/kotlin-patterns.mdmarkdown7.9 KB
references/kotlin-general/kotlin-security-testing.mdmarkdown4.4 KB
references/kotlin-general/kotlin-security.mdmarkdown11.1 KB
references/kotlin/concurrency-patterns.mdmarkdown5.4 KB
references/kotlin/kotlin-testing.mdmarkdown7.9 KB
references/mcp-local-docs.mdmarkdown6.9 KB
references/mcp-local-docs/mcp-patterns.mdmarkdown9.6 KB
references/mcp-local-docs/mcp-preferred-patterns.mdmarkdown6.9 KB
references/mcp-local-docs/server-templates.mdmarkdown4.4 KB
references/mcp-local-docs/typescript-async-patterns.mdmarkdown8.9 KB
references/nodejs-api.mdmarkdown7.3 KB
references/nodejs-api/auth-patterns.mdmarkdown10.0 KB
references/nodejs-api/middleware-patterns.mdmarkdown10.5 KB
references/nodejs-api/nodejs-security.mdmarkdown12.3 KB
references/nodejs-api/webhook-patterns.mdmarkdown9.9 KB
references/php-general.mdmarkdown4.7 KB
references/php-general/php-behaviors.mdmarkdown5.2 KB
references/php-general/php-conventions.mdmarkdown5.8 KB
references/php/modern-php-features.mdmarkdown4.4 KB
references/php/testing-patterns.mdmarkdown7.5 KB
references/python-general.mdmarkdown7.7 KB
references/python-general/flask-jinja-webapp.mdmarkdown5.7 KB
references/python-general/python-local-gates.mdmarkdown4.4 KB
references/python-general/python-modern-code.mdmarkdown23.1 KB
references/python-openstack.mdmarkdown5.2 KB
references/python-openstack/error-handling.mdmarkdown658 B
references/python-openstack/hacking-rules.mdmarkdown4.1 KB
references/python-openstack/openstack-patterns.mdmarkdown1.2 KB
references/python-openstack/oslo-patterns.mdmarkdown6.4 KB
references/python-openstack/output-format.mdmarkdown2.4 KB
references/python-openstack/preferred-patterns.mdmarkdown1.9 KB
references/python-openstack/rpc-versioning.mdmarkdown5.3 KB
references/rust-general.mdmarkdown8.2 KB
references/rust-general/rust-modern-code.mdmarkdown13.4 KB
references/rust-general/rust-verification-workflow.mdmarkdown5.5 KB
references/rust-general/rust-version-idioms.mdmarkdown7.0 KB
references/swift-general.mdmarkdown5.7 KB
references/swift-general/swift-patterns.mdmarkdown6.7 KB
references/swift-general/swift-security-testing.mdmarkdown6.6 KB
references/swift-general/swift-security.mdmarkdown13.3 KB
references/swift/preferred-patterns.mdmarkdown2.4 KB
references/swift/swift-testing.mdmarkdown6.6 KB
references/swift/task-patterns.mdmarkdown3.6 KB
references/typescript-debugging.mdmarkdown9.3 KB
references/typescript-debugging/debugging-workflows-async-memory.mdmarkdown5.8 KB
references/typescript-debugging/debugging-workflows.mdmarkdown5.6 KB
scripts/bench-compare.shscript7.1 KB
scripts/check-errors.shscript7.1 KB
scripts/check-interface-compliance.shscript6.4 KB
scripts/check-sapcc-auth-ordering.shscript5.5 KB
scripts/check-sapcc-httptest.shscript4.4 KB
scripts/check-sapcc-identify-endpoint.shscript5.8 KB
scripts/check-sapcc-json-strict.shscript4.9 KB
scripts/check-sapcc-time-now.shscript4.2 KB
scripts/check-sapcc-todo-format.shscript4.1 KB
scripts/gen-table-test.shscript4.2 KB
scripts/quality_checker.pyscript16.2 KB
scripts/sync-google-style-guide.pyscript2.5 KB
scripts/validate.pyscript6.3 KB

references/go/sapcc-conventions/architecture-patterns.md

View on GitHub
# SAP CC Architecture Patterns

Complete architectural patterns from `sapcc/keppel` with 102 rules. Organized by concern area.

---

## 1. Directory Structure

```
project/
  main.go                         # Root entry point, Cobra root command
  go.mod / go.sum
  Makefile / Dockerfile
  cmd/                            # Cobra subcommands, one dir per component
    api/main.go                   # Server: keppel-api
    janitor/main.go               # Server: background worker
    healthmonitor/main.go         # Server: health monitoring
    validate/main.go              # CLI: validate images
    test/main.go                  # CLI: test driver harness
  internal/
    api/                          # HTTP handlers by API surface
      auth/                       # Token/auth endpoint
      keppel/                     # Keppel v1 API (CRUD)
      peer/                       # Peer API (replication)
      registry/                   # Registry v2 API (push/pull)
    auth/                         # Authorization logic
    client/                       # Outbound HTTP clients
    drivers/                      # Pluggable driver implementations
      basic/                      # Simple/static drivers
      filesystem/                 # Filesystem storage
      multi/                      # Multi-backend federation
      openstack/                  # Keystone auth + Swift storage
      redis/                      # Redis federation
      trivial/                    # In-memory test doubles
    keppel/                       # Core domain: interfaces, config, DB, errors
    models/                       # Database models (pure data, no logic)
    processor/                    # Business logic (DB + Storage coordination)
    tasks/                        # Background jobs
    test/                         # Test infrastructure, doubles, helpers
  docs/drivers/                   # Driver documentation
  LICENSES/                       # REUSE-compliant license files
  vendor/                         # Vendored dependencies
```

### Rules

- **R1**: Use `internal/` to prevent external imports of all application code
- **R2**: Each `cmd/<component>/main.go` defines one Cobra subcommand via `AddCommandTo(parent *cobra.Command)`
- **R3**: Root `main.go` assembles all subcommands and blank-imports all driver packages
- **R4**: Model structs: `internal/models/` (pure data, `db:` tags, no business logic)
- **R5**: Core interfaces and config: `internal/keppel/` (the domain package)
- **R6**: API handlers: `internal/api/<surface>/` with separate packages per API
- **R7**: Background tasks: `internal/tasks/`
- **R8**: Business logic: `internal/processor/` (coordinates DB and storage)
- **R9**: Test doubles: `internal/test/`
- **R10**: Drivers: `internal/drivers/<driver-name>/`
- **R11**: Fixtures: `fixtures/` subdirectories adjacent to test files

---

## 2. Package Naming

| Directory | Package Name | Convention |
|-----------|-------------|------------|
| `cmd/api/` | `apicmd` | `<name>cmd` suffix for command packages |
| `cmd/janitor/` | `janitorcmd` | Same pattern |
| `internal/api/keppel/` | `keppelv1` | Version-suffixed for versioned APIs |
| `internal/api/registry/` | `registryv2` | Same pattern |
| `internal/api/auth/` | `auth` | Plain name when unambiguous |
| `internal/drivers/openstack/` | `openstack` | Plain name matching directory |
| `internal/keppel/` | `keppel` | Matches module name's last segment |
| `internal/models/` | `models` | Plain name |

- **R12**: Command packages use `<name>cmd` suffix to avoid collisions
- **R13**: API handler packages use `<name>v<N>` suffix for versioned APIs
- **R14**: Test packages use `_test` suffix for black-box tests

---

## 3. Pluggable Driver Architecture

The defining architectural pattern of keppel. 6 driver types, all identical structure.

### Interface Definition

```go
// internal/keppel/storage_driver.go
type StorageDriver interface {
    pluggable.Plugin    // requires PluginTypeID() string
    Init(AuthDriver, Configuration) error
    // domain-specific methods...
    AppendToBlob(ctx context.Context, account models.Account, storageID string, ...) error
    ReadBlob(ctx context.Context, account models.Account, storageID string) (io.ReadCloser, uint64, error)
}

var StorageDriverRegistry pluggable.Registry[StorageDriver]

func NewStorageDriver(configJSON string, ad AuthDriver, cfg Configuration) (StorageDriver, error) {
    callInit := func(d StorageDriver) error { return d.Init(ad, cfg) }
    return newDriver("KEPPEL_DRIVER_STORAGE", StorageDriverRegistry, configJSON, callInit)
}
```

### Implementation Registration

```go
// internal/drivers/openstack/swift.go
func init() {
    keppel.StorageDriverRegistry.Add(func() keppel.StorageDriver { return &swiftDriver{} })
}

type swiftDriver struct {
    ContainerName string `json:"container_name"`  // Config from JSON
    client        *schwift.Account `json:"-"`      // Runtime state excluded from JSON
}

func (d *swiftDriver) PluginTypeID() string { return "swift" }
func (d *swiftDriver) Init(ad keppel.AuthDriver, cfg keppel.Configuration) error { ... }
```

### Activation in main.go

```go
import (
    _ "github.com/sapcc/keppel/internal/drivers/basic"
    _ "github.com/sapcc/keppel/internal/drivers/filesystem"
    _ "github.com/sapcc/keppel/internal/drivers/openstack"
    _ "github.com/sapcc/keppel/internal/drivers/trivial"
)
```

### Driver Configuration Flow

Environment variable contains JSON: `KEPPEL_DRIVER_STORAGE={"type":"swift","params":{"container_name":"keppel"}}`

1. Parse JSON to extract `type` and `params`
2. Look up plugin in registry by `type`
3. `json.Unmarshal` `params` into driver struct
4. Call `Init()` on the driver

### Rules

- **R21**: Every driver interface embeds `pluggable.Plugin`
- **R22**: Every driver has a corresponding `XxxDriverRegistry` var
- **R23**: Every driver has a `NewXxxDriver()` factory function
- **R24**: Implementations register via `init()` functions
- **R25**: Blank-imported in `main.go` to trigger registration
- **R26**: Config is JSON via struct tags on the driver struct
- **R27**: Runtime state uses `json:"-"` to exclude from config
- **R28**: `Init()` validates driver compatibility
- **R29**: Implementation comments: `// MethodName implements the keppel.XxxDriver interface.`

---

## 4. Cobra Command Pattern

### Root Command

```go
func main() {
    logg.ShowDebug = osext.GetenvBool("KEPPEL_DEBUG")
    keppel.SetupHTTPClient()

    rootCmd := &cobra.Command{
        Use:     "keppel",
        Short:   "Multi-tenant Docker registry",
        Version: bininfo.VersionOr("unknown"),
        Args:    cobra.NoArgs,
        Run:     func(cmd *cobra.Command, args []string) { cmd.Help() },
    }

    validatecmd.AddCommandTo(rootCmd)
    testcmd.AddCommandTo(rootCmd)

    serverCmd := &cobra.Command{Use: "server <subcommand>", ...}
    apicmd.AddCommandTo(serverCmd)
    janitorcmd.AddCommandTo(serverCmd)
    rootCmd.AddCommand(serverCmd)

    must.Succeed(rootCmd.Execute())
}
```

### Subcommand Pattern

```go
package apicmd

func AddCommandTo(parent *cobra.Command) {
    cmd := &cobra.Command{
        Use:   "api",
        Short: "Run the keppel-api server component.",
        Long:  "... Configuration is read from environment variables.",
        Args:  cobra.NoArgs,
        Run:   run,
    }
    parent.AddCommand(cmd)
}

func run(cmd *cobra.Command, args []string) {
    keppel.SetTaskName("api")
    cfg := keppel.ParseConfiguration()
    ctx := httpext.ContextWithSIGINT(cmd.Context(), 10*time.Second)
    // ... bootstrap drivers, DB, handlers ...
}
```

### Rules

- **R30**: Each `cmd/<name>/` exports only `AddCommandTo(parent *cobra.Command)`
- **R31**: `run()` is unexported, handles all bootstrapping
- **R32**: `keppel.SetTaskName(name)` called first in each server command
- **R33**: Graceful shutdown via `httpext.ContextWithSIGINT(cmd.Context(), timeout)`

---

## 5. Bootstrap Sequence

Every server command follows this order:

```
1. SetTaskName()           -- configure component identity
2. ParseConfiguration()    -- read env vars into Configuration struct
3. Context setup           -- ContextWithSIGINT for graceful shutdown
4. InitAuditTrail()        -- optional audit event pipeline
5. Database connection     -- easypg.Connect + InitORM
6. Driver initialization   -- NewAuthDriver, NewFederationDriver, etc.
7. API/handler setup       -- httpapi.Compose(apis...)
8. Background goroutines   -- go job.Run(ctx) for janitor tasks
9. HTTP server             -- httpext.ListenAndServeContext
```

- **R34**: Config is env-var-driven. `osext.MustGetenv()` for required, `GetenvOrDefault()` for optional
- **R35**: `must.Return()` / `must.Succeed()` for fatal bootstrap errors (not at request time)
- **R36**: Drivers initialized in dependency order: Auth first, then Storage, Federation, etc.

---

## 6. Configuration Pattern

All configuration via environment variables prefixed with `KEPPEL_`:

| Category | Variables | Pattern |
|----------|-----------|---------|
| API identity | `KEPPEL_API_PUBLIC_FQDN` | Required string |
| Database | `KEPPEL_DB_HOSTNAME`, `KEPPEL_DB_PORT`, etc. | With defaults |
| Drivers | `KEPPEL_DRIVER_AUTH`, `KEPPEL_DRIVER_STORAGE`, etc. | JSON config string |
| Feature flags | `KEPPEL_DEBUG`, `KEPPEL_INSECURE` | Boolean via `GetenvBool()` |

- **R37**: All config via env vars. No config files, no CLI flags for config
- **R38**: `Configuration` struct contains only non-driver-specific settings
- **R39**: `ParseConfiguration()` is the single entry point
- **R40**: Use osext helpers: `MustGetenv()`, `GetenvOrDefault()`, `GetenvBool()`

---

## 7. Database Patterns

### ORM: gorp v3 with PostgreSQL

```go
type DB struct { gorp.DbMap }

func InitORM(dbConn *sql.DB) *DB {
    result := &DB{DbMap: gorp.DbMap{Db: dbConn, Dialect: gorp.PostgresDialect{}}}
    result.DbMap.AddTableWithName(models.Account{}, "accounts").SetKeys(false, "name")
    return result
}
```

### Query Pattern

```go
var reducedAccountGetByNameQuery = sqlext.SimplifyWhitespace(`
    SELECT auth_tenant_id, upstream_peer_hostname
      FROM accounts
     WHERE name = $1
`)
```

- **R41**: Model structs use `db:"column_name"` tags
- **R42**: Models are pure data (no business logic methods)
- **R43**: DB helpers accept `gorp.SqlExecutor` (works with `*DB` and `*Transaction`)
- **R44**: PostgreSQL `$1`, `$2` placeholders (not `?`)
- **R45**: Migrations use sequential numbering with `.up.sql`/`.down.sql`
- **R46**: Migrations embedded as Go string constants
- **R47**: `FindXxx()` returns `nil, nil` for "not found"
- **R48**: Complex SQL in package-level `var` with `SimplifyWhitespace()`

---

## 8. API Handler Pattern

```go
type API struct {
    cfg        keppel.Configuration
    authDriver keppel.AuthDriver
    db         *keppel.DB
    timeNow    func() time.Time      // injectable for tests
}

func NewAPI(...) *API { return &API{...} }
func (a *API) OverrideTimeNow(f func() time.Time) *API { a.timeNow = f; return a }

func (a *API) AddTo(r *mux.Router) {
    r.Methods("GET").Path("/keppel/v1/accounts").HandlerFunc(a.handleGetAccounts)
    r.Methods("PUT").Path("/keppel/v1/accounts/{account:[a-z0-9][a-z0-9-]{0,47}}").HandlerFunc(a.handlePutAccount)
}
```

- **R49**: API structs hold all deps as unexported fields
- **R50**: `NewAPI()` constructor; `OverrideTimeNow()` for test doubles
- **R51**: `httpapi.IdentifyEndpoint(r, pattern)` FIRST in every handler
- **R52**: Route patterns use gorilla/mux regex constraints inline
- **R53**: Handler methods unexported, named `handle<Verb><Resource>`
- **R54**: Auth done inline at top of handler (not middleware)
- **R55**: Errors written directly, function returns immediately
- **R56**: JSON responses via `respondwith.JSON(w, status, body)`
- **R57**: Request decoding uses `DisallowUnknownFields()`
- **R58**: API composition via `httpapi.Compose(apis...)`

---

## 9. Error Response System

### RegistryV2Error Builder

```go
keppel.ErrBlobUnknown.With("blob does not exist in this repository")
keppel.ErrDenied.With("access denied").WithStatus(http.StatusForbidden)
keppel.ErrTooManyRequests.With("").WithHeader("Retry-After", retryAfterStr)
keppel.AsRegistryV2Error(err).WithStatus(http.StatusUnprocessableEntity).WithDetail(msg)
```

### Three Output Methods

| Method | API | Format |
|--------|-----|--------|
| `WriteAsRegistryV2ResponseTo(w, r)` | Registry v2 | JSON `{"errors": [...]}` |
| `WriteAsAuthResponseTo(w)` | Auth | JSON `{"details": "..."}` |
| `WriteAsTextTo(w)` | Keppel v1 | Plain text |

### Guard Clause Pattern

```go
if respondWithError(w, r, err) { return }         // Registry v2
if respondwith.ObfuscatedErrorText(w, err) { return }  // Keppel v1
```

- **R59**: Typed error codes with HTTP status mappings
- **R60**: Fluent builder: `.With()`, `.WithStatus()`, `.WithDetail()`, `.WithHeader()`
- **R61**: `AsRegistryV2Error(err)` wraps unknown errors in `ErrUnknown`
- **R62**: 5xx errors use `ObfuscatedErrorText` (UUID-masked response, real error logged)

---

## 10. Processor Pattern (Business Logic)

```go
type Processor struct {
    cfg     keppel.Configuration
    db      *keppel.DB
    sd      keppel.StorageDriver
    timeNow func() time.Time
    generateStorageID func() string
}
```

- **R63**: Wraps DB + StorageDriver to keep them in lockstep
- **R64**: Non-deterministic functions are injectable struct fields
- **R65**: Both API handlers and Janitor tasks create Processor instances
- **R66**: `WithLowlevelAccess()` provides escape hatch for direct DB/storage

---

## 11. Background Job Pattern

```go
type Janitor struct {
    cfg     keppel.Configuration
    db      *keppel.DB
    timeNow func() time.Time
    addJitter func(time.Duration) time.Duration
}

// Starting jobs
go janitor.BlobSweepJob(nil).Run(ctx)
go janitor.ManifestGarbageCollectionJob(nil).Run(ctx)
```

- **R67**: Each task is a separate method returning a runnable job
- **R68**: Jobs started as goroutines in `run()`
- **R69**: Jitter applied to scheduled intervals
- **R70**: Test doubles can disable jitter and inject deterministic time

---

## 12. Test Infrastructure

```go
s := test.NewSetup(t,
    test.WithKeppelAPI,
    test.WithQuotas,
    test.WithAccount(models.Account{Name: "test1", AuthTenantID: "tenant1"}),
    test.WithRepo(models.Repository{AccountName: "test1", Name: "foo"}),
)
```

- **R71**: Functional options for test setup
- **R72**: `TestMain` with `easypg.WithTestDB` required for DB packages
- **R73**: Test doubles register as regular drivers via `init()`
- **R74**: Time injectable via `mock.Clock`
- **R75**: SQL fixtures use raw INSERT statements
- **R76**: In-memory `RoundTripper` for testing peer communication

---

## 13. Type Conventions

```go
// Typed string enums
type Permission string
const CanViewAccount Permission = "view"

// Typed int enums
type ClaimResult int
const ClaimSucceeded ClaimResult = iota

// Newtype for IDs
type AccountName string

// Option type for nullable fields
NextBlobSweepedAt Option[time.Time] `db:"next_blob_sweep_at"`
```

- **R81**: String enums: `type X string` with `const` block
- **R82**: Integer enums: `type X int` with `iota`
- **R83**: Semantic newtypes for IDs: `type AccountName string`
- **R84**: `Option[T]` instead of `*T` for nullable DB fields
- **R85**: Error sentinels: `var ErrXxx = errors.New(...)`

---

## 14. Comment Conventions

```go
// Interface methods: detailed godoc
// AuthenticateUser authenticates the user identified by the given username
// and password. Note that usernames may not contain colons.
AuthenticateUser(ctx context.Context, userName, password string) (UserIdentity, *RegistryV2Error)

// Implementation comments
// PluginTypeID implements the keppel.AuthDriver interface.
func (d *driver) PluginTypeID() string { return "keystone" }

// Section separators
////////////////////////////////////////////////////////////////////////////////
// section title
```

- **R88**: Interface methods have detailed godoc
- **R89**: Implementations use `// Method implements the pkg.Interface interface.`
- **R90**: Section separators: `////////////////////////////////////////////////////////////////////////////////`

---

## 15. File Naming

| Pattern | Example | Usage |
|---------|---------|-------|
| `<entity>.go` | `account.go` | Model or domain type |
| `<entity>_driver.go` | `auth_driver.go` | Driver interface |
| `<entity>s.go` | `accounts.go` | API handlers or task implementations |
| `shared_test.go` | `shared_test.go` | Test infrastructure (TestMain) |
| `api.go` | `api.go` | API struct, constructor, router |
| `config.go` | `config.go` | Configuration parsing |
| `database.go` | `database.go` | Schema, ORM setup, migrations |
| `errors.go` | `errors.go` | Package-wide error types only (interface-specific sentinels live with their interface per §36) |

- **R77**: One file per major entity
- **R78**: Driver interface files named `<concern>_driver.go`
- **R79**: Shared test setup in `shared_test.go`
- **R80**: Constants live adjacent to their types, not in `constants.go`
- **R80a**: **Contract cohesion** (§36): The file defining an interface/contract type also contains its constants, error sentinels, and validation functions. If you can name which interface owns an artifact, that artifact lives in the interface's file, not in `util.go` or `constants.go`. See sapcc-code-patterns.md §36 for the full rule with keppel evidence.

---

## 16. Dependency Injection

```go
type API struct {
    timeNow func() time.Time  // default: time.Now
}

func (a *API) OverrideTimeNow(f func() time.Time) *API {
    a.timeNow = f
    return a
}
```

- **R91**: Non-deterministic functions are struct fields with production defaults
- **R92**: `OverrideXxx()` methods return `*Self` for chaining
- **R93**: Defaults use stdlib: `time.Now`, `keppel.GenerateStorageID`

---

## 17. SPDX License Headers

```go
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company
// SPDX-License-Identifier: Apache-2.0
```

- **R86**: Every `.go` file must have SPDX headers as first two comment lines
- **R87**: Year reflects file creation or last substantial modification

---

## 18. API Response Patterns

### DB Model vs API Model

```go
// DB model (internal/models/)
type Account struct {
    Name           AccountName `db:"name"`
    GCPoliciesJSON string      `db:"gc_policies_json"`  // JSON string in DB
}

// API model (internal/keppel/)
type Account struct {
    Name       models.AccountName `json:"name"`
    GCPolicies []GCPolicy         `json:"gc_policies,omitempty"`  // Parsed in API
}

// Conversion
func RenderAccount(dbAccount models.Account) (Account, error) { ... }
```

- **R99**: DB models use `db:` tags; API models use `json:` tags. Separate structs.
- **R100**: `RenderXxx()` functions convert DB to API models
- **R101**: JSON responses wrap in named keys: `{"account": {...}}`, `{"accounts": [...]}`
- **R102**: Empty collections: `[]`, never `null`
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 198kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 198kUpdated Claude CodeCodexVerifiedInstall