go-ai-ready-boilerplate / rules
Cursor rule1 starsChanged 4 months agoMITView on GitHub
Go coding standards: formatting, naming, errors, DB, context
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 4,371 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository40 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/01-project-overview.mdcCursor rule
- .cursor/rules/02-architecture.mdcCursor rule
- .cursor/rules/03-workflow.mdcCursor rule
- .cursor/rules/04-testing.mdcCursor rule
- .cursor/rules/06-commit-protocol.mdcCursor rule
- .cursor/rules/07-documentation.mdcCursor rule
- .cursor/rules/08-testing-standards.mdcCursor rule
- .cursor/rules/karpathy-guidelines.mdcCursor rule
- openspec-apply-changeSkill
- openspec-archive-changeSkill
- openspec-bulk-archive-changeSkill
- openspec-continue-changeSkill
- openspec-exploreSkill
- openspec-ff-changeSkill
- openspec-new-changeSkill
- openspec-onboardSkill
- openspec-sync-specsSkill
- openspec-verify-changeSkill
- openspec-apply-changeSkill
- openspec-archive-changeSkill
- openspec-bulk-archive-changeSkill
- openspec-continue-changeSkill
- openspec-exploreSkill
- openspec-ff-changeSkill
- openspec-new-changeSkill
- openspec-onboardSkill
- openspec-sync-specsSkill
- openspec-verify-changeSkill
- openspec-apply-changeSkill
- openspec-archive-changeSkill
- openspec-bulk-archive-changeSkill
- openspec-continue-changeSkill
- openspec-exploreSkill
- openspec-ff-changeSkill
- openspec-new-changeSkill
- openspec-onboardSkill
- openspec-sync-specsSkill
- openspec-verify-changeSkill
The file
Show its rules and text
We split this 05-coding-standards.mdc into the rules it gives an agent
42 rules. About 0 are common, 22 are distinctive, and 20 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈22
Distinctive · estimate
This author's own choices. Worth a look.
20
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 12
Run gofmt -w . before committing
- Very specific: line 13
Use go fmt ./... for entire packages
- Distinctive: line 14
Never argue about formatting - let the machine decide
- Distinctive: line 18
Use tabs for indentation (gofmt default)
- Distinctive: line 19
No line length limit - wrap when lines feel too long
- Very specific: line 20
No parentheses in control structures (if, for, switch)
- Distinctive: line 40
No underscores or mixedCaps in package names
- Distinctive: line 42
Keep it brief - everyone typing it will import it
- Very specific: line 54
Use MixedCaps for multi-word names
- Very specific: line 63
Don't use Get prefix for getters
- Distinctive: line 64
Use field name directly, capitalized
- Distinctive: line 80
Use canonical method names when possible
- Distinctive: line 129
Never ignore error returns
- Distinctive: line 130
Check errors immediately after calls
- Distinctive: line 131
Use "comma ok" idiom for type assertions
- Very specific: line 149
No unnecessary else after error return
- Distinctive: line 280
Prefer slices in most cases
- Distinctive: line 326
Avoid explicit mutexes when possible
- Distinctive: line 333
Use pointer receivers when method needs to mutate
- Distinctive: line 334
Use value receivers for immutable operations
- Distinctive: line 355
Before marking work complete:
- Distinctive: line 389
No blank line between comment and declaration
- Distinctive: line 441
Test files MUST match implementation file names
- Very specific: line 469
Use fmt.Errorf with %w verb for error wrapping
- Distinctive: line 471
Add context to errors before returning
- Distinctive: line 489
Always check errors immediately
- Very specific: line 495
Always pass context.Context as first parameter
- Very specific: line 496
Use context.Background() for tests or CLI entry points
- Very specific: line 497
Use ctx.Value() for request-scoped data when needed
- Very specific: line 499
If a parameter is required by convention but unused in the body (e.g.
- Very specific: line 535
Use ExecContext for INSERT, UPDATE, DELETE
- Very specific: line 536
Use QueryRowContext for single-row SELECT
- Very specific: line 537
Use QueryContext for multi-row SELECT
- Very specific: line 538
Always defer rows.Close() for QueryContext
- Very specific: line 539
Check rows.Err() after iteration
- Distinctive: line 564
Use meaningful error messages
- Very specific: line 570
Use setupTestDB(t *testing.T) helper for consistent test database creation
- Very specific: line 571
Always cleanup temporary resources in defer
- Very specific: line 572
Use t.Fatal for setup failures, t.Error for test failures
- Distinctive: line 578
Use descriptive test names that explain what is being tested
- Very specific: line 595
Never write if dep != nil guards inside method bodies.
- Distinctive: line 596
If a dependency is truly optional, model it explicitly with a no-op implementation (Null Object pattern) and inject that instead.
≈ “Common” is an estimate: at least 1 in 5 of the 7,324 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: "Go coding standards: formatting, naming, errors, DB, context"
globs:
alwaysApply: true
---
# Coding standards
## Formatting (CRITICAL)
**Always use `gofmt`**: Go's canonical formatting tool
- Run `gofmt -w .` before committing
- Use `go fmt ./...` for entire packages
- Never argue about formatting - let the machine decide
**Formatting rules:**
- Use **tabs** for indentation (gofmt default)
- No line length limit - wrap when lines feel too long
- No parentheses in control structures (`if`, `for`, `switch`)
- Opening brace on same line as declaration (never on next line)
```go
// CORRECT
if x > 0 {
return y
}
// WRONG - brace on next line causes semicolon insertion
if x > f()
{ // wrong!
g()
}
```
## Package Names
**Short, lowercase, single-word names:**
- No underscores or mixedCaps in package names
- Package name matches base directory name
- Keep it brief - everyone typing it will import it
```go
package buffer // NOT buf_util or BufferUtil
package http // NOT httpserver or HTTPServer
```
## Naming Conventions
**Exported names** (visible outside package):
- First character **uppercase** = exported
- Use `MixedCaps` for multi-word names
**Unexported names** (package-private):
- First character **lowercase** = unexported
- Use `mixedCaps` for multi-word names
**Getters/Setters:**
- Don't use `Get` prefix for getters
- Use field name directly, capitalized
```go
// WRONG
func (u *User) GetID() string { return u.id }
func (u *User) SetID(id string) { u.id = id }
// CORRECT
func (u *User) ID() string { return u.id }
func (u *User) SetID(id string) { u.id = id }
```
**Interface names:**
- One-method interfaces: method name + `-er` suffix
- `Reader`, `Writer`, `Formatter`, `CloseNotifier`
- Use canonical method names when possible
```go
type Reader interface {
Read(p []byte) (n int, err error)
}
type Stringer interface {
String() string
}
```
## File Organization
**MANY SMALL FILES > FEW LARGE FILES:**
- One file per type or related group
- 200-400 lines typical, 800 max
- High cohesion, low coupling
- Organize by feature/domain, not by type
**SEPARATE CONTRACT, TYPES, AND IMPLEMENTATION (one concern per file):**
- `types.go` — domain models / DTOs only (row structs, request/response)
- one file per interface — the interface + factory signatures only, **no implementation** (e.g. `store.go`, `adapter.go`, `keymanager.go`)
- impl files — concrete implementations only (e.g. `sqlite.go`, `stub.go`, `registry.go`, `*_impl.go`)
- `db.go` — resource lifecycle (`Open` / `Migrate` / connection setup)
- **Never co-locate an interface with its implementation** in the same file
Rationale: keeping the contract in its own file makes implementations swappable
and testable in isolation — an in-memory fake satisfies the interface file with
zero coupling to the real (e.g. sqlite) implementation.
```go
// store/types.go — DTO only
type Profile struct { Name string; ... }
// store/store.go — interface only
type ProfileStore interface { GetProfile(ctx, name) (*Profile, error) }
// store/sqlite.go — implementation only
type sqliteProfileStore struct{ db *sql.DB }
```
## Error Handling (CRITICAL)
**ALWAYS handle errors explicitly:**
- Functions return `(result, error)` pairs
- Never ignore error returns
- Check errors immediately after calls
- Use "comma ok" idiom for type assertions
```go
// CORRECT
file, err := os.Open("config.txt")
if err != nil {
log.Fatalf("failed to open config: %v", err)
}
defer file.Close()
// WRONG - ignoring error
file, _ := os.Open("config.txt")
```
**Error return pattern:**
- Return early on errors
- Success path runs down the page
- No unnecessary `else` after error return
```go
// CORRECT
func processFile(name string) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
d, err := f.Stat()
if err != nil {
return err
}
process(f, d)
return nil
}
```
## Control Structures
**No parentheses in control structures:**
```go
// CORRECT
if x > 0 {
return y
}
for i := 0; i < 10; i++ {
sum += i
}
// WRONG
if (x > 0) {
return y
}
```
**Range loops for collections:**
```go
// Over slice/array/map
for key, value := range myMap {
fmt.Printf("%s: %v\n", key, value)
}
// Only keys
for key := range myMap {
if key.expired() {
delete(myMap, key)
}
}
// Only values (use blank identifier)
for _, value := range mySlice {
sum += value
}
```
**Type switch:**
```go
switch v := value.(type) {
case int:
fmt.Printf("integer %d\n", v)
case string:
fmt.Printf("string %s\n", v)
default:
fmt.Printf("unknown type %T\n", v)
}
```
## Functions
**Multiple return values:**
```go
func nextInt(b []byte, pos int) (value, nextPos int) {
// ... implementation
return value, nextPos
}
```
**Named result parameters:**
```go
func ReadFull(r Reader, buf []byte) (n int, err error) {
for len(buf) > 0 && err == nil {
var nr int
nr, err = r.Read(buf)
n += nr
buf = buf[nr:]
}
return // uses current values of n and err
}
```
**Defer for cleanup:**
```go
func processFile(filename string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close() // runs when function returns
// ... process file
return result, nil
}
```
## Data Structures
**Use `make` for slices, maps, channels:**
```go
// CORRECT
slice := make([]int, 10)
m := make(map[string]int)
ch := make(chan int, 100)
// WRONG - new returns pointer to zero value
var p *[]int = new([]int) // *p == nil; rarely useful
```
**Slices over arrays:**
- Prefer slices in most cases
- Arrays are values (copied on assignment)
- Slices are references to underlying arrays
```go
// Array (value type)
arr := [3]int{1, 2, 3}
// Slice (reference type)
slice := []int{1, 2, 3}
slice = append(slice, 4)
```
**Map with comma ok idiom:**
```go
value, ok := myMap[key]
if !ok {
// key not present
}
```
## Concurrency
**Goroutines for concurrent work:**
```go
go func() {
// runs concurrently
process(data)
}()
```
**Channels for communication:**
```go
ch := make(chan int)
go func() {
ch <- calculate() // send result
}()
result := <-ch // wait for result
```
**Share memory by communicating:**
- Pass data through channels
- Avoid explicit mutexes when possible
- One goroutine owns the data at a time
## Methods
**Pointers vs Values:**
- Use pointer receivers when method needs to mutate
- Use value receivers for immutable operations
- Value methods can be called on pointers automatically
```go
type Counter struct {
count int
}
// Pointer receiver - mutates
func (c *Counter) Increment() {
c.count++
}
// Value receiver - doesn't mutate
func (c Counter) Count() int {
return c.count
}
```
## Code Quality Checklist
Before marking work complete:
- [ ] Code is formatted with `gofmt`
- [ ] Package name is lowercase, single word
- [ ] Exported names use `MixedCaps`
- [ ] All errors are handled (never ignored)
- [ ] Functions are small (<50 lines)
- [ ] Files are focused (<800 lines)
- [ ] Interface, DTO (`types.go`), and implementation live in separate files
- [ ] No deep nesting (>4 levels)
- [ ] Defer used for cleanup
- [ ] Named return parameters clarify intent
- [ ] Interfaces use `-er` suffix for single-method interfaces
- [ ] Comments are complete for exported declarations
- [ ] No unnecessary comments (code is self-documenting)
## Documentation
**Exported declarations need doc comments:**
```go
// ReadAll reads from r until an error or EOF and returns the data it read.
// A successful call returns err == nil, not err == EOF.
// Because ReadAll is defined to read from src until EOF,
// it does not treat an EOF from Read as an error to be reported.
func ReadAll(r io.Reader) ([]byte, error) {
// ...
}
```
**Doc comment conventions:**
- Comment starts with name of exported item
- Complete sentences
- No blank line between comment and declaration
- Focus on what, not how (for exported APIs)
## Interfaces
**Implicit implementation:**
- Types implement interfaces without explicit declaration
- Small interfaces (1-2 methods) preferred
- Define interfaces where they're used
```go
// Define interface where it's consumed
func processData(r io.Reader) error {
// ... any type implementing io.Reader works
}
```
## Blank Identifier
**Use `_` for ignored values:**
```go
// Ignore index, use value
for _, value := range slice {
fmt.Println(value)
}
// Ignore error when it's safe (document why!)
data, _ := os.ReadFile("config.json")
```
## Custom Project Rules
### Database/Store Package Organization
**Package structure for data access layers:**
- `types.go` — Domain models/DTOs only (structs, no logic)
- `interfaces.go` — Interface definitions only (no implementations)
- `db.go` — Database lifecycle (Open, Migrate, connection setup)
- Implementation subdirectory (e.g., `sqlite/`) — All database-specific code
**Implementation subdirectory organization:**
- One file per table/domain entity (e.g., `profile.go`, `secret.go`, `kv.go`)
- Each file contains the store implementation for one entity
- Shared helper functions in `db.go` or separate `util.go`
- Maximum 100-150 lines per file
**Test organization:**
- Test files MUST match implementation file names
- `profile.go` → `profile_test.go`
- `secret.go` → `secret_test.go`
- `kv.go` → `kv_test.go`
- `db.go` → `db_test.go`
- Shared test utilities in `testutil.go`
- Tests reside in the same subdirectory as implementations
```go
// internal/store/
├── types.go // Domain models
├── interfaces.go // Interface definitions
├── sqlite/ // SQLite implementation
│ ├── db.go // DB lifecycle, migrations, helpers
│ ├── profile.go // ProfileStore implementation
│ ├── secret.go // SecretStore implementation
│ ├── kv.go // KVStore implementation
│ ├── testutil.go // Shared test helpers
│ ├── db_test.go
│ ├── profile_test.go
│ ├── secret_test.go
│ └── kv_test.go
```
### Error Handling Conventions
**Error wrapping:**
- Use `fmt.Errorf` with `%w` verb for error wrapping
- Preserve error chain for `errors.Is` and `errors.As`
- Add context to errors before returning
```go
// CORRECT
if err := db.Exec(query); err != nil {
return fmt.Errorf("failed to create profile: %w", err)
}
// WRONG - loses error context
if err := db.Exec(query); err != nil {
return err
}
```
**Return early on errors:**
- Success path runs down the page
- No unnecessary `else` after error return
- Always check errors immediately
### Context Propagation
**Context usage:**
- Always pass `context.Context` as first parameter
- Use `context.Background()` for tests or CLI entry points
- Use `ctx.Value()` for request-scoped data when needed
- Respect context cancellation in long-running operations
- If a parameter is required by convention but unused in the body (e.g. `context.Context` kept first), name it `_` — never leave an unused named parameter
```go
// CORRECT - ctx slot kept by convention, but unused in the body
func Setup(_ context.Context, cfg Config) error {
return nil
}
// WRONG - unused named parameter trips linters and signals nothing
func Setup(ctx context.Context, cfg Config) error {
return nil
}
```
```go
// CORRECT
func (s *Store) AddProfile(ctx context.Context, p *Profile) error {
// Use ctx in all database calls
_, err := s.db.ExecContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("add profile: %w", err)
}
return nil
}
// WRONG - no context
func (s *Store) AddProfile(p *Profile) error {
_, err := s.db.Exec(query, args...)
return err
}
```
### Database Operations
**Query patterns:**
- Use `ExecContext` for INSERT, UPDATE, DELETE
- Use `QueryRowContext` for single-row SELECT
- Use `QueryContext` for multi-row SELECT
- Always defer `rows.Close()` for `QueryContext`
- Check `rows.Err()` after iteration
```go
// CORRECT
rows, err := s.db.QueryContext(ctx, "SELECT name FROM profiles")
if err != nil {
return err
}
defer rows.Close()
var profiles []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return err
}
profiles = append(profiles, name)
}
return rows.Err() // Check iteration errors
```
**Validation:**
- Validate inputs before database operations
- Return descriptive errors for validation failures
- Use meaningful error messages
### Testing Conventions
**Test setup:**
- Use `setupTestDB(t *testing.T)` helper for consistent test database creation
- Always cleanup temporary resources in `defer`
- Use `t.Fatal` for setup failures, `t.Error` for test failures
**Test naming:**
- `TestFunctionName` for unit tests
- `TestFunctionName_Condition` for specific scenarios
- Use descriptive test names that explain what is being tested
```go
// CORRECT
func TestProfileStore_AddDuplicateProfile_ReturnsError(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// ... test implementation
}
```
### Dependency Non-Nil Contract
**All dependencies injected through constructors are assumed non-nil.**
- Constructors receive every dependency as a required argument — there are no optional/nullable fields.
- Never write `if dep != nil` guards inside method bodies. A nil dependency is a **wiring bug**; fail fast at startup, not silently at runtime.
- If a dependency is truly optional, model it explicitly with a no-op implementation (Null Object pattern) and inject that instead.
```go
// CORRECT — no nil guard; the constructor is the only gate
type GetTaskUsecase struct {
store repositories.TaskRepository
cache repositories.TaskCache
}
func NewGetTaskUsecase(store repositories.TaskRepository, cache repositories.TaskCache) driver.TaskGetter {
return &GetTaskUsecase{store: store, cache: cache}
}
func (u *GetTaskUsecase) GetTask(ctx context.Context, id domain.ID) (domain.Task, error) {
if t, ok := u.cache.Get(ctx, id); ok {
return t, nil
}
t, err := u.store.GetByID(ctx, id)
if err != nil {
return domain.Task{}, err
}
u.cache.Set(ctx, t)
return t, nil
}
// WRONG — hides a wiring error; cache should never be nil
func (u *GetTaskUsecase) GetTask(ctx context.Context, id domain.ID) (domain.Task, error) {
if u.cache != nil {
if t, ok := u.cache.Get(ctx, id); ok {
return t, nil
}
}
// ...
}
```
**Null Object example** — when you genuinely need a no-op variant:
```go
// noopCache satisfies TaskCache but does nothing.
type noopCache struct{}
func (noopCache) Get(_ context.Context, _ domain.ID) (domain.Task, bool) { return domain.Task{}, false }
func (noopCache) Set(_ context.Context, _ domain.Task) {}
func (noopCache) Delete(_ context.Context, _ domain.ID) {}
```
### Code Organization
**Import grouping:**
- Standard library imports first
- Third-party imports second
- Internal imports last
- Separate groups with blank lines
```go
// CORRECT
import (
"context"
"database/sql"
"fmt"
"github.com/lib/pq"
"github.com/oniharnantyo/onclaw/internal/config"
)
```
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

