@softspark/ai-toolkit 3.0.2 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +13 -0
- package/CHANGELOG.md +35 -0
- package/README.md +25 -39
- package/app/.claude-plugin/plugin.json +1 -1
- package/app/skills/cpp-rules/SKILL.md +275 -0
- package/app/skills/csharp-rules/SKILL.md +282 -0
- package/app/skills/dart-rules/SKILL.md +299 -0
- package/app/skills/golang-rules/SKILL.md +262 -0
- package/app/skills/java-rules/SKILL.md +273 -0
- package/app/skills/kotlin-rules/SKILL.md +271 -0
- package/app/skills/medplum-rules/SKILL.md +271 -0
- package/app/skills/php-rules/SKILL.md +292 -0
- package/app/skills/python-rules/SKILL.md +257 -0
- package/app/skills/ruby-rules/SKILL.md +286 -0
- package/app/skills/rust-rules/SKILL.md +276 -0
- package/app/skills/swift-rules/SKILL.md +293 -0
- package/app/skills/typescript-rules/SKILL.md +249 -0
- package/benchmarks/ecosystem-doctor-snapshot.json +14 -14
- package/kb/history/completed/deep-coverage-v3-20260423.md +3 -3
- package/kb/history/completed/ecosystem-deep-sweep-20260423.md +1 -1
- package/kb/procedures/release-preparation-sop.md +4 -4
- package/kb/procedures/release-verification-sop.md +11 -12
- package/kb/reference/architecture-overview.md +1 -1
- package/kb/reference/global-install-model.md +29 -6
- package/kb/reference/language-rules.md +54 -18
- package/kb/reference/mcp-editor-compatibility.md +4 -3
- package/kb/reference/mcp-templates.md +3 -2
- package/kb/reference/supported-tools-registry.md +10 -8
- package/llms-full.txt +133 -58
- package/manifest.json +3 -3
- package/package.json +10 -3
- package/scripts/codex_skill_adapter.py +19 -3
- package/scripts/ecosystem_tools.json +7 -7
- package/scripts/generate_cline_rules.py +17 -8
- package/scripts/generate_codex_skills.py +33 -96
- package/scripts/generate_language_rules_skills.py +232 -0
- package/scripts/generate_roo_rules.py +11 -3
- package/scripts/install.py +6 -1
- package/scripts/install_steps/ai_tools.py +154 -51
- package/scripts/install_steps/install_state.py +14 -2
- package/scripts/install_steps/project_registry.py +38 -5
- package/scripts/mcp_editors.py +7 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: golang-rules
|
|
3
|
+
description: "Go coding rules from ai-toolkit: coding-style, frameworks, patterns, security, testing. Triggers: .go, go.mod, go.sum, Gin, Echo, Gorilla, testing, gofmt. Load when writing, reviewing, or editing Go code."
|
|
4
|
+
effort: medium
|
|
5
|
+
user-invocable: false
|
|
6
|
+
allowed-tools: Read
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Go Rules
|
|
10
|
+
|
|
11
|
+
These rules come from `app/rules/golang/` in ai-toolkit. They cover
|
|
12
|
+
the project's standards for coding style, frameworks, patterns,
|
|
13
|
+
security, and testing in Go. Apply them when writing or
|
|
14
|
+
reviewing Go code.
|
|
15
|
+
|
|
16
|
+
# Go Coding Style
|
|
17
|
+
|
|
18
|
+
## Naming
|
|
19
|
+
- MixedCaps/mixedCaps only. No underscores in Go names (except test functions).
|
|
20
|
+
- Exported: `PascalCase`. Unexported: `camelCase`. Acronyms: `HTTPClient`, `userID`.
|
|
21
|
+
- Short variable names in small scopes: `i`, `r`, `w`, `ctx`, `err`.
|
|
22
|
+
- Descriptive names in larger scopes: `userRepository`, `requestTimeout`.
|
|
23
|
+
- Package names: short, lowercase, singular (`auth`, `user`, not `utils`, `helpers`).
|
|
24
|
+
|
|
25
|
+
## Packages
|
|
26
|
+
- One package per directory. Package name = directory name.
|
|
27
|
+
- Avoid `util`, `common`, `helpers` packages. Name by what it provides.
|
|
28
|
+
- Keep package APIs small. Export only what consumers need.
|
|
29
|
+
- Use `internal/` directory for packages not meant for external consumption.
|
|
30
|
+
|
|
31
|
+
## Functions
|
|
32
|
+
- Accept interfaces, return structs.
|
|
33
|
+
- First parameter `ctx context.Context` if the function does I/O or may be cancelled.
|
|
34
|
+
- Return `(result, error)` tuple. Error is always last return value.
|
|
35
|
+
- Use named return values only for documentation, not for naked returns.
|
|
36
|
+
- Keep functions short. If >40 lines, consider splitting.
|
|
37
|
+
|
|
38
|
+
## Error Handling
|
|
39
|
+
- Always check errors. Never use `_` to discard errors silently.
|
|
40
|
+
- Wrap errors with context: `fmt.Errorf("fetching user %s: %w", id, err)`.
|
|
41
|
+
- Use sentinel errors (`var ErrNotFound = errors.New(...)`) for expected conditions.
|
|
42
|
+
- Use `errors.Is()` and `errors.As()` for error checking, not type assertions.
|
|
43
|
+
|
|
44
|
+
## Formatting
|
|
45
|
+
- Use `gofmt` / `goimports`. No formatting debates in Go.
|
|
46
|
+
- Use `golangci-lint` with a `.golangci.yml` config in CI.
|
|
47
|
+
- Use `go vet` as minimum static analysis.
|
|
48
|
+
|
|
49
|
+
## Struct Design
|
|
50
|
+
- Use struct embedding for composition, not inheritance.
|
|
51
|
+
- Prefer value receivers for small structs, pointer receivers for large or mutable.
|
|
52
|
+
- Be consistent: all methods on a type use the same receiver type.
|
|
53
|
+
- Use struct literals with field names: `User{Name: "Ada", Age: 30}`.
|
|
54
|
+
|
|
55
|
+
## Concurrency
|
|
56
|
+
- Do not start goroutines without a plan to stop them.
|
|
57
|
+
- Use `sync.WaitGroup` or `errgroup.Group` to coordinate goroutines.
|
|
58
|
+
- Use channels for communication, mutexes for state protection.
|
|
59
|
+
- Prefer `context.Context` for cancellation and timeouts over manual signaling.
|
|
60
|
+
|
|
61
|
+
# Go Frameworks
|
|
62
|
+
|
|
63
|
+
## Standard Library HTTP
|
|
64
|
+
- Use `http.NewServeMux()` (Go 1.22+ with method patterns) for simple APIs.
|
|
65
|
+
- Use `http.HandlerFunc` for handlers. Compose with middleware pattern.
|
|
66
|
+
- Use `context.Context` from `r.Context()` in all handlers.
|
|
67
|
+
- Use `http.TimeoutHandler` to prevent slow handlers from hanging.
|
|
68
|
+
|
|
69
|
+
## Chi / Gorilla Mux
|
|
70
|
+
- Use Chi for routing with middleware chains and URL params.
|
|
71
|
+
- Use `chi.URLParam(r, "id")` to extract path parameters.
|
|
72
|
+
- Use middleware groups: `r.Group(func(r chi.Router) { r.Use(authMiddleware) })`.
|
|
73
|
+
- Prefer Chi over Gorilla Mux (Gorilla was archived, Chi actively maintained).
|
|
74
|
+
|
|
75
|
+
## Gin / Echo
|
|
76
|
+
- Use Gin for high-performance APIs with built-in validation.
|
|
77
|
+
- Use binding tags: `binding:"required,email"` on struct fields.
|
|
78
|
+
- Use middleware for cross-cutting: logging, recovery, CORS, auth.
|
|
79
|
+
- Use `c.ShouldBindJSON()` over `c.BindJSON()` to handle errors yourself.
|
|
80
|
+
|
|
81
|
+
## GORM / sqlx / pgx
|
|
82
|
+
- Use `sqlx` for SQL-first with struct scanning (lightweight).
|
|
83
|
+
- Use `pgx` directly for PostgreSQL-specific features and performance.
|
|
84
|
+
- Use GORM only when rapid prototyping outweighs SQL control.
|
|
85
|
+
- Always use prepared statements or parameterized queries.
|
|
86
|
+
- Use `sqlx.In()` for dynamic IN clauses safely.
|
|
87
|
+
|
|
88
|
+
## gRPC
|
|
89
|
+
- Define services in `.proto` files. Generate Go code with `protoc`.
|
|
90
|
+
- Use interceptors for auth, logging, and tracing (equivalent to middleware).
|
|
91
|
+
- Use deadlines (context timeout) on every RPC call.
|
|
92
|
+
- Use streaming RPCs for real-time data, unary for request-response.
|
|
93
|
+
|
|
94
|
+
## Configuration
|
|
95
|
+
- Use `envconfig` or `viper` for configuration from env/files.
|
|
96
|
+
- Use struct tags for env mapping: `envconfig:"DATABASE_URL"`.
|
|
97
|
+
- Validate config at startup. Fail fast on invalid configuration.
|
|
98
|
+
- Use `flag` package for CLI arguments in tools and utilities.
|
|
99
|
+
|
|
100
|
+
## Observability
|
|
101
|
+
- Use `slog` (Go 1.21+) for structured logging. Replace `log` package.
|
|
102
|
+
- Use OpenTelemetry for distributed tracing and metrics.
|
|
103
|
+
- Export metrics via Prometheus endpoint.
|
|
104
|
+
- Use `pprof` for CPU and memory profiling in development.
|
|
105
|
+
|
|
106
|
+
## Project Layout
|
|
107
|
+
- Follow Standard Go Project Layout: `cmd/`, `internal/`, `pkg/`.
|
|
108
|
+
- Entry points in `cmd/appname/main.go`.
|
|
109
|
+
- Business logic in `internal/`. Shared libraries in `pkg/`.
|
|
110
|
+
- Use `Makefile` for common tasks: build, test, lint, run.
|
|
111
|
+
|
|
112
|
+
# Go Patterns
|
|
113
|
+
|
|
114
|
+
## Error Handling
|
|
115
|
+
- Wrap errors with context at each call site: `fmt.Errorf("loading config: %w", err)`.
|
|
116
|
+
- Define domain error types with `errors.New()` or custom error structs.
|
|
117
|
+
- Use `errors.Is()` for sentinel errors, `errors.As()` for typed errors.
|
|
118
|
+
- Return errors, do not panic. Reserve `panic` for truly unrecoverable states.
|
|
119
|
+
- Handle errors immediately after the call. No deferred error checking.
|
|
120
|
+
|
|
121
|
+
## Concurrency
|
|
122
|
+
- Use `errgroup.Group` for concurrent operations that may fail.
|
|
123
|
+
- Use `sync.Once` for one-time initialization (singleton pattern).
|
|
124
|
+
- Use `sync.Map` only for append-mostly maps with concurrent access.
|
|
125
|
+
- Use buffered channels as semaphores: `sem := make(chan struct{}, maxConcurrency)`.
|
|
126
|
+
- Prefer `context.WithTimeout` over manual timers for deadline management.
|
|
127
|
+
|
|
128
|
+
## Interface Design
|
|
129
|
+
- Keep interfaces small: 1-3 methods. Compose larger interfaces from smaller ones.
|
|
130
|
+
- Define interfaces where they are consumed, not where they are implemented.
|
|
131
|
+
- Use `io.Reader`, `io.Writer`, `fmt.Stringer` and standard interfaces where applicable.
|
|
132
|
+
- Avoid returning interfaces from functions. Return concrete types.
|
|
133
|
+
|
|
134
|
+
## Options Pattern
|
|
135
|
+
- Use functional options for constructors with many optional parameters.
|
|
136
|
+
- Pattern: `func WithTimeout(d time.Duration) Option { return func(c *Client) { c.timeout = d } }`.
|
|
137
|
+
- Provide sensible defaults. Options override defaults.
|
|
138
|
+
- Use `Option` type alias: `type Option func(*Config)`.
|
|
139
|
+
|
|
140
|
+
## Dependency Injection
|
|
141
|
+
- Pass dependencies through constructor functions, not global variables.
|
|
142
|
+
- Accept interfaces in constructors: `func NewService(repo UserRepo) *Service`.
|
|
143
|
+
- Use `wire` or manual wiring in `main()` for dependency graph.
|
|
144
|
+
- Avoid init() functions for anything other than simple registration.
|
|
145
|
+
|
|
146
|
+
## Resource Management
|
|
147
|
+
- Use `defer` for cleanup immediately after acquiring a resource.
|
|
148
|
+
- Use `context.Context` for cancellation propagation across goroutines.
|
|
149
|
+
- Close channels from the sender side, never the receiver.
|
|
150
|
+
- Use `sync.Pool` for frequently allocated temporary objects (buffers).
|
|
151
|
+
|
|
152
|
+
## Anti-Patterns
|
|
153
|
+
- Global mutable state: use dependency injection instead.
|
|
154
|
+
- `interface{}` / `any` everywhere: use generics (Go 1.18+) or specific types.
|
|
155
|
+
- Goroutine leaks: always ensure goroutines can exit.
|
|
156
|
+
- Ignoring `context.Context`: propagate it through all I/O paths.
|
|
157
|
+
- Large interfaces: split into focused, composable pieces.
|
|
158
|
+
|
|
159
|
+
# Go Security
|
|
160
|
+
|
|
161
|
+
## Input Validation
|
|
162
|
+
- Validate all input at API boundaries. Use struct tags or manual validation.
|
|
163
|
+
- Use `validator` package for struct validation: `validate:"required,email"`.
|
|
164
|
+
- Parse and validate numeric IDs: `strconv.Atoi()` with error checking.
|
|
165
|
+
- Limit request body size: `http.MaxBytesReader(w, r.Body, maxBytes)`.
|
|
166
|
+
|
|
167
|
+
## SQL Injection
|
|
168
|
+
- Always use parameterized queries: `db.Query("SELECT * FROM users WHERE id = $1", id)`.
|
|
169
|
+
- Never concatenate user input into SQL strings.
|
|
170
|
+
- Use `sqlx.In()` for safe dynamic IN clauses.
|
|
171
|
+
- Use ORM query builders (GORM, Ent) for dynamic query construction.
|
|
172
|
+
|
|
173
|
+
## Command Injection
|
|
174
|
+
- Use `exec.Command("binary", args...)` with separate arguments, not shell strings.
|
|
175
|
+
- Never use `exec.Command("sh", "-c", userInput)`.
|
|
176
|
+
- Validate and sanitize file paths against traversal attacks.
|
|
177
|
+
- Use `filepath.Clean()` and verify paths are within allowed directories.
|
|
178
|
+
|
|
179
|
+
## Cryptography
|
|
180
|
+
- Use `crypto/rand` for random values, never `math/rand` for security.
|
|
181
|
+
- Use `bcrypt` or `argon2` for password hashing: `golang.org/x/crypto/bcrypt`.
|
|
182
|
+
- Use `crypto/subtle.ConstantTimeCompare()` for timing-safe comparisons.
|
|
183
|
+
- Use `crypto/tls` with `tls.Config{MinVersion: tls.VersionTLS12}`.
|
|
184
|
+
|
|
185
|
+
## Secrets
|
|
186
|
+
- Load secrets from environment variables: `os.Getenv("SECRET_KEY")`.
|
|
187
|
+
- Never hardcode secrets, tokens, or API keys in source code.
|
|
188
|
+
- Use `go-envconfig` or similar for validated env var loading.
|
|
189
|
+
- Use Go build tags or ldflags for build-time configuration.
|
|
190
|
+
|
|
191
|
+
## HTTP Security
|
|
192
|
+
- Set `ReadTimeout`, `WriteTimeout`, `IdleTimeout` on `http.Server`.
|
|
193
|
+
- Use `helmet`-equivalent headers: HSTS, X-Content-Type-Options, X-Frame-Options.
|
|
194
|
+
- Implement rate limiting with `golang.org/x/time/rate` or middleware.
|
|
195
|
+
- Use `net/http` with TLS. Never serve production HTTP without encryption.
|
|
196
|
+
|
|
197
|
+
## Concurrency Safety
|
|
198
|
+
- Use `sync.Mutex` or `sync.RWMutex` for shared mutable state.
|
|
199
|
+
- Run `go test -race` in CI to detect data races.
|
|
200
|
+
- Avoid shared state where possible. Prefer channels for communication.
|
|
201
|
+
- Use `atomic` package for simple counters and flags.
|
|
202
|
+
|
|
203
|
+
## Dependencies
|
|
204
|
+
- Run `govulncheck ./...` in CI to check for known vulnerabilities.
|
|
205
|
+
- Use `go mod tidy` to remove unused dependencies.
|
|
206
|
+
- Pin dependencies via `go.sum`. Review dependency changes in PRs.
|
|
207
|
+
- Audit transitive dependencies. Use `go mod graph` to inspect the tree.
|
|
208
|
+
|
|
209
|
+
## Error Information Disclosure
|
|
210
|
+
- Never expose internal error messages to clients.
|
|
211
|
+
- Log detailed errors server-side, return generic messages to clients.
|
|
212
|
+
- Use error codes for machine-readable error classification.
|
|
213
|
+
- Do not include stack traces in production API responses.
|
|
214
|
+
|
|
215
|
+
# Go Testing
|
|
216
|
+
|
|
217
|
+
## Framework
|
|
218
|
+
- Use the standard `testing` package. No external test frameworks required.
|
|
219
|
+
- Use `testify/assert` and `testify/require` for readable assertions.
|
|
220
|
+
- Use `testify/mock` or `mockgen` for generating mocks.
|
|
221
|
+
- Use `go test -race` in CI to detect data races.
|
|
222
|
+
|
|
223
|
+
## File Naming
|
|
224
|
+
- Test files: `*_test.go` in the same package.
|
|
225
|
+
- Black-box tests: use `package foo_test` to test only exported API.
|
|
226
|
+
- White-box tests: use `package foo` to test internals.
|
|
227
|
+
- Test helpers: `testutil_test.go` or `testdata/` directory.
|
|
228
|
+
|
|
229
|
+
## Table-Driven Tests
|
|
230
|
+
- Use table-driven tests for functions with multiple input/output cases.
|
|
231
|
+
- Name each case: `{name: "empty input returns error", input: "", wantErr: true}`.
|
|
232
|
+
- Use `t.Run(tc.name, func(t *testing.T) { ... })` for subtests.
|
|
233
|
+
- Use `t.Parallel()` in subtests when tests are independent.
|
|
234
|
+
|
|
235
|
+
## Test Helpers
|
|
236
|
+
- Use `t.Helper()` in helper functions for correct line reporting.
|
|
237
|
+
- Use `t.Cleanup()` for teardown instead of defer in test functions.
|
|
238
|
+
- Use `testing.TB` interface to share helpers between tests and benchmarks.
|
|
239
|
+
- Use `testdata/` directory for test fixtures (excluded from build).
|
|
240
|
+
|
|
241
|
+
## Mocking
|
|
242
|
+
- Define interfaces at the consumer, not the provider.
|
|
243
|
+
- Use `mockgen` to auto-generate mocks from interfaces.
|
|
244
|
+
- Use `httptest.NewServer()` for HTTP integration tests.
|
|
245
|
+
- Use `httptest.NewRecorder()` for handler unit tests.
|
|
246
|
+
|
|
247
|
+
## Integration Tests
|
|
248
|
+
- Use build tags: `//go:build integration` to separate from unit tests.
|
|
249
|
+
- Use `testcontainers-go` for database/service containers in tests.
|
|
250
|
+
- Use `t.Setenv()` (Go 1.17+) for environment variable testing.
|
|
251
|
+
|
|
252
|
+
## Benchmarks
|
|
253
|
+
- Use `func BenchmarkXxx(b *testing.B)` with `b.N` loop.
|
|
254
|
+
- Use `b.ResetTimer()` after expensive setup.
|
|
255
|
+
- Use `b.ReportAllocs()` to track allocations.
|
|
256
|
+
- Run: `go test -bench=. -benchmem`.
|
|
257
|
+
|
|
258
|
+
## Coverage
|
|
259
|
+
- Run: `go test -coverprofile=coverage.out ./...`.
|
|
260
|
+
- View: `go tool cover -html=coverage.out`.
|
|
261
|
+
- Set minimum coverage threshold in CI.
|
|
262
|
+
- Focus coverage on business logic, not generated code.
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: java-rules
|
|
3
|
+
description: "Java coding rules from ai-toolkit: coding-style, frameworks, patterns, security, testing. Triggers: .java, pom.xml, build.gradle, Spring, Spring Boot, JPA, Hibernate, JUnit, Maven, Gradle. Load when writing, reviewing, or editing Java code."
|
|
4
|
+
effort: medium
|
|
5
|
+
user-invocable: false
|
|
6
|
+
allowed-tools: Read
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Java Rules
|
|
10
|
+
|
|
11
|
+
These rules come from `app/rules/java/` in ai-toolkit. They cover
|
|
12
|
+
the project's standards for coding style, frameworks, patterns,
|
|
13
|
+
security, and testing in Java. Apply them when writing or
|
|
14
|
+
reviewing Java code.
|
|
15
|
+
|
|
16
|
+
# Java Coding Style
|
|
17
|
+
|
|
18
|
+
## Naming
|
|
19
|
+
- PascalCase: classes, interfaces, enums, records, annotations.
|
|
20
|
+
- camelCase: methods, variables, parameters.
|
|
21
|
+
- UPPER_SNAKE: constants (`static final`).
|
|
22
|
+
- Package names: lowercase, dot-separated, reverse domain (`com.company.project`).
|
|
23
|
+
- No Hungarian notation. No `I` prefix on interfaces.
|
|
24
|
+
|
|
25
|
+
## Modern Java (17+)
|
|
26
|
+
- Use `record` for immutable data carriers. No need for Lombok in most cases.
|
|
27
|
+
- Use `sealed` classes/interfaces for restricted hierarchies.
|
|
28
|
+
- Use pattern matching: `if (obj instanceof String s)` instead of cast.
|
|
29
|
+
- Use `switch` expressions with arrow syntax and exhaustiveness.
|
|
30
|
+
- Use text blocks (`"""`) for multiline strings (SQL, JSON, HTML).
|
|
31
|
+
|
|
32
|
+
## Types
|
|
33
|
+
- Use `var` for local variables when the type is obvious from the right-hand side.
|
|
34
|
+
- Use `Optional<T>` for return types that may be absent. Never for fields or params.
|
|
35
|
+
- Prefer `List.of()`, `Map.of()`, `Set.of()` for immutable collections.
|
|
36
|
+
- Use `Stream` for collection transformations. Avoid streams for simple iterations.
|
|
37
|
+
|
|
38
|
+
## Classes
|
|
39
|
+
- Prefer composition over inheritance. Use interfaces for abstraction.
|
|
40
|
+
- Keep classes focused: single responsibility.
|
|
41
|
+
- Use `final` on classes not designed for extension.
|
|
42
|
+
- Use `private` constructors + static factory methods for controlled instantiation.
|
|
43
|
+
- Records over POJOs for value types. Lombok only if records are insufficient.
|
|
44
|
+
|
|
45
|
+
## Methods
|
|
46
|
+
- Max 20-30 lines per method. Extract when longer.
|
|
47
|
+
- Use `@Override` on every overridden method.
|
|
48
|
+
- Return empty collections over `null`. Use `Collections.emptyList()` or `List.of()`.
|
|
49
|
+
- Avoid checked exceptions for programming errors. Use runtime exceptions.
|
|
50
|
+
|
|
51
|
+
## Formatting
|
|
52
|
+
- Use project formatter (Google Java Format or IDE-configured).
|
|
53
|
+
- Use `@SuppressWarnings` sparingly and with specific warning names.
|
|
54
|
+
- Use `final` for parameters and local variables where practical.
|
|
55
|
+
|
|
56
|
+
## Nullability
|
|
57
|
+
- Annotate with `@Nullable` / `@NonNull` from JSpecify or JetBrains.
|
|
58
|
+
- Use `Objects.requireNonNull()` at public API boundaries.
|
|
59
|
+
- Never return `null` from collections or arrays. Return empty.
|
|
60
|
+
- Use `Optional` for genuinely optional return values.
|
|
61
|
+
|
|
62
|
+
## Documentation
|
|
63
|
+
- Javadoc on all public classes and methods.
|
|
64
|
+
- Use `@param`, `@return`, `@throws` tags for public API methods.
|
|
65
|
+
- Skip Javadoc for obvious getters, `toString()`, and `equals()`.
|
|
66
|
+
|
|
67
|
+
# Java Frameworks
|
|
68
|
+
|
|
69
|
+
## Spring Boot
|
|
70
|
+
- Use Spring Boot 3+ with Java 17+ minimum.
|
|
71
|
+
- Use `@RestController` for REST APIs. Return `ResponseEntity` for status control.
|
|
72
|
+
- Use `@Valid` + Jakarta Bean Validation for request validation.
|
|
73
|
+
- Use profiles (`@Profile`) for environment-specific configuration.
|
|
74
|
+
- Use `application.yml` over `application.properties` for readability.
|
|
75
|
+
- Externalize config: env vars > config files > hardcoded defaults.
|
|
76
|
+
|
|
77
|
+
## Spring Data JPA
|
|
78
|
+
- Use repository interfaces extending `JpaRepository`.
|
|
79
|
+
- Use `@Query` with JPQL for custom queries. Use native queries only when needed.
|
|
80
|
+
- Use `@EntityGraph` to prevent N+1 queries in associations.
|
|
81
|
+
- Use `Specification` for dynamic query building.
|
|
82
|
+
- Always use `@Transactional` at the service layer, not repository.
|
|
83
|
+
|
|
84
|
+
## Spring Security
|
|
85
|
+
- Use `SecurityFilterChain` bean configuration (not `WebSecurityConfigurerAdapter`).
|
|
86
|
+
- Use `@PreAuthorize` / `@Secured` for method-level authorization.
|
|
87
|
+
- Use BCrypt for password encoding: `new BCryptPasswordEncoder()`.
|
|
88
|
+
- Configure CORS, CSRF, and session management explicitly.
|
|
89
|
+
- Use OAuth2 Resource Server for JWT validation in APIs.
|
|
90
|
+
|
|
91
|
+
## Hibernate / JPA
|
|
92
|
+
- Use `FetchType.LAZY` by default on all associations.
|
|
93
|
+
- Use `@BatchSize` or `@Fetch(FetchMode.SUBSELECT)` to avoid N+1.
|
|
94
|
+
- Use `@Version` for optimistic locking on entities.
|
|
95
|
+
- Use DTOs (records) for read queries. Do not expose entities in APIs.
|
|
96
|
+
- Use Flyway or Liquibase for schema migrations.
|
|
97
|
+
|
|
98
|
+
## Quarkus / Micronaut
|
|
99
|
+
- Use for microservices and serverless where startup time matters.
|
|
100
|
+
- Use compile-time DI (Micronaut) or build-time optimization (Quarkus).
|
|
101
|
+
- Use reactive patterns with Mutiny (Quarkus) or Reactor (Micronaut).
|
|
102
|
+
- Use native image builds with GraalVM for production deployments.
|
|
103
|
+
|
|
104
|
+
## Build Tools
|
|
105
|
+
- Use Gradle (Kotlin DSL) for new projects. Maven for enterprise legacy.
|
|
106
|
+
- Use dependency management to unify versions across modules.
|
|
107
|
+
- Use Bill of Materials (BOM) imports for consistent Spring versions.
|
|
108
|
+
- Use Spotless or Checkstyle for enforced code formatting.
|
|
109
|
+
|
|
110
|
+
## Logging
|
|
111
|
+
- Use SLF4J facade with Logback or Log4j2 backend.
|
|
112
|
+
- Use structured logging with MDC for correlation IDs.
|
|
113
|
+
- Use parameterized logging: `log.info("User {} created", userId)`.
|
|
114
|
+
- Never log sensitive data (passwords, tokens, PII).
|
|
115
|
+
|
|
116
|
+
# Java Patterns
|
|
117
|
+
|
|
118
|
+
## Error Handling
|
|
119
|
+
- Use unchecked exceptions for programming errors (`IllegalArgumentException`).
|
|
120
|
+
- Use checked exceptions only for recoverable conditions the caller must handle.
|
|
121
|
+
- Create domain exception hierarchy: `AppException` -> `NotFoundException`, etc.
|
|
122
|
+
- Never catch `Exception` or `Throwable` broadly. Catch specific types.
|
|
123
|
+
- Use `try-with-resources` for all `AutoCloseable` resources.
|
|
124
|
+
|
|
125
|
+
## Immutability
|
|
126
|
+
- Use `record` for immutable value objects (Java 16+).
|
|
127
|
+
- Use `List.copyOf()`, `Map.copyOf()` to create unmodifiable copies.
|
|
128
|
+
- Make fields `private final`. No setters unless mutation is required.
|
|
129
|
+
- Return defensive copies of mutable collections from getters.
|
|
130
|
+
- Use builder pattern for constructing immutable objects with many fields.
|
|
131
|
+
|
|
132
|
+
## Optional
|
|
133
|
+
- Use `Optional<T>` as return type for methods that may not return a value.
|
|
134
|
+
- Chain: `optional.map(...).orElseThrow(...)`. Avoid `isPresent()` + `get()`.
|
|
135
|
+
- Never use `Optional` for fields, method parameters, or collection elements.
|
|
136
|
+
- Use `Optional.empty()` over `null`. Use `Optional.ofNullable()` at boundaries.
|
|
137
|
+
|
|
138
|
+
## Streams
|
|
139
|
+
- Use streams for transformations: `filter`, `map`, `collect`.
|
|
140
|
+
- Avoid side effects in stream operations. Keep them pure.
|
|
141
|
+
- Use `Collectors.toUnmodifiableList()` for immutable results.
|
|
142
|
+
- Prefer `for` loop for simple iterations that do not transform data.
|
|
143
|
+
- Use `Stream.of()` or `IntStream.range()` for generating sequences.
|
|
144
|
+
|
|
145
|
+
## Dependency Injection
|
|
146
|
+
- Use constructor injection exclusively. No field or setter injection.
|
|
147
|
+
- Accept interfaces in constructors, not implementations.
|
|
148
|
+
- Use `@Component`, `@Service`, `@Repository` for Spring-managed beans.
|
|
149
|
+
- Keep the number of constructor dependencies under 5. Split if more.
|
|
150
|
+
|
|
151
|
+
## Concurrency
|
|
152
|
+
- Use `ExecutorService` and `CompletableFuture` for async operations.
|
|
153
|
+
- Use `virtual threads` (Java 21+) for I/O-bound concurrent work.
|
|
154
|
+
- Use `ConcurrentHashMap`, `AtomicInteger` for thread-safe operations.
|
|
155
|
+
- Avoid `synchronized` blocks when possible -- use higher-level concurrency.
|
|
156
|
+
- Use `ReentrantReadWriteLock` for read-heavy shared state.
|
|
157
|
+
|
|
158
|
+
## Design Patterns
|
|
159
|
+
- Use Strategy pattern (via interfaces) over switch/if-else chains.
|
|
160
|
+
- Use Factory methods for flexible object creation.
|
|
161
|
+
- Use Decorator pattern for composable behavior augmentation.
|
|
162
|
+
- Avoid Singleton pattern -- use DI container for lifecycle management.
|
|
163
|
+
|
|
164
|
+
## Anti-Patterns
|
|
165
|
+
- Returning `null` from methods -- use `Optional` or empty collections.
|
|
166
|
+
- Mutable DTOs with getters/setters -- use records.
|
|
167
|
+
- God classes with 20+ dependencies -- split by responsibility.
|
|
168
|
+
- String typing for domain values -- use types, enums, or value objects.
|
|
169
|
+
|
|
170
|
+
# Java Security
|
|
171
|
+
|
|
172
|
+
## Input Validation
|
|
173
|
+
- Validate all input with Jakarta Bean Validation (`@NotNull`, `@Size`, `@Email`).
|
|
174
|
+
- Use `@Valid` on controller parameters to trigger validation automatically.
|
|
175
|
+
- Create custom validators for domain-specific rules.
|
|
176
|
+
- Never trust client-provided IDs. Verify resource ownership server-side.
|
|
177
|
+
|
|
178
|
+
## SQL Injection
|
|
179
|
+
- Use JPA/Hibernate parameterized queries. Never concatenate input into JPQL/SQL.
|
|
180
|
+
- Use `CriteriaBuilder` or Specifications for dynamic queries.
|
|
181
|
+
- For native queries, use named parameters: `@Query(value = "... WHERE id = :id", nativeQuery = true)`.
|
|
182
|
+
- Use `PreparedStatement` if using JDBC directly. Never `Statement` with concatenation.
|
|
183
|
+
|
|
184
|
+
## Authentication
|
|
185
|
+
- Use Spring Security with BCrypt (`BCryptPasswordEncoder`) for password hashing.
|
|
186
|
+
- Use JWT with short expiration (15 min) + refresh tokens for APIs.
|
|
187
|
+
- Implement account lockout after N failed attempts.
|
|
188
|
+
- Use `@AuthenticationPrincipal` to access the current user in controllers.
|
|
189
|
+
|
|
190
|
+
## Authorization
|
|
191
|
+
- Use `@PreAuthorize("hasRole('ADMIN')")` for role-based access control.
|
|
192
|
+
- Use method security for fine-grained authorization.
|
|
193
|
+
- Check resource ownership in service layer, not just role membership.
|
|
194
|
+
- Default deny: require explicit authorization for every endpoint.
|
|
195
|
+
|
|
196
|
+
## XSS and CSRF
|
|
197
|
+
- Spring auto-escapes Thymeleaf output. Do not use `th:utext` with user data.
|
|
198
|
+
- Enable CSRF protection for session-based auth. Disable only for stateless JWT APIs.
|
|
199
|
+
- Set `Content-Type` headers explicitly on responses.
|
|
200
|
+
- Use CSP headers to restrict script sources.
|
|
201
|
+
|
|
202
|
+
## Serialization
|
|
203
|
+
- Do not deserialize untrusted data with `ObjectInputStream` (RCE risk).
|
|
204
|
+
- Use Jackson with `@JsonIgnoreProperties(ignoreUnknown = true)`.
|
|
205
|
+
- Disable default typing in Jackson: never use `enableDefaultTyping()`.
|
|
206
|
+
- Validate deserialized objects with Bean Validation after parsing.
|
|
207
|
+
|
|
208
|
+
## Dependencies
|
|
209
|
+
- Run OWASP Dependency-Check in CI: `mvn verify -P owasp-check`.
|
|
210
|
+
- Update Spring Boot regularly -- security patches are frequent.
|
|
211
|
+
- Use `dependencyManagement` to control transitive dependency versions.
|
|
212
|
+
- Audit `mvn dependency:tree` for unexpected transitive dependencies.
|
|
213
|
+
|
|
214
|
+
## Secrets
|
|
215
|
+
- Use Spring Cloud Config or Vault for secrets management.
|
|
216
|
+
- Use `@Value("${secret}")` with env var placeholders, not hardcoded values.
|
|
217
|
+
- Never log request headers containing `Authorization` or session tokens.
|
|
218
|
+
- Use separate config profiles for dev/staging/prod with different secrets.
|
|
219
|
+
|
|
220
|
+
## Logging Security
|
|
221
|
+
- Use parameterized logging to prevent log injection.
|
|
222
|
+
- Sanitize user input before logging: remove newlines and control characters.
|
|
223
|
+
- Never log stack traces to API responses. Return generic error messages.
|
|
224
|
+
|
|
225
|
+
# Java Testing
|
|
226
|
+
|
|
227
|
+
## Framework
|
|
228
|
+
- Use JUnit 5 (Jupiter) for all new tests. No JUnit 4.
|
|
229
|
+
- Use AssertJ for fluent, readable assertions.
|
|
230
|
+
- Use Mockito for mocking dependencies.
|
|
231
|
+
- Use Testcontainers for integration tests with databases/services.
|
|
232
|
+
|
|
233
|
+
## File Naming
|
|
234
|
+
- Test classes: `FooTest.java` in `src/test/java/` mirroring source package.
|
|
235
|
+
- Integration tests: `FooIT.java` or use `@Tag("integration")`.
|
|
236
|
+
- Test utilities: `src/test/java/.../support/` or `TestUtils.java`.
|
|
237
|
+
|
|
238
|
+
## Structure
|
|
239
|
+
- Use `@Nested` classes to group related tests within a test class.
|
|
240
|
+
- Use `@DisplayName` for human-readable test descriptions.
|
|
241
|
+
- Use `@BeforeEach` for setup, `@AfterEach` for cleanup.
|
|
242
|
+
- Use `@ParameterizedTest` with `@ValueSource`, `@CsvSource`, `@MethodSource`.
|
|
243
|
+
|
|
244
|
+
## Assertions (AssertJ)
|
|
245
|
+
- Use `assertThat(actual).isEqualTo(expected)` over JUnit assertions.
|
|
246
|
+
- Use `assertThatThrownBy(() -> ...).isInstanceOf(FooException.class)`.
|
|
247
|
+
- Use `assertThat(list).hasSize(3).extracting("name").contains("Ada")`.
|
|
248
|
+
- Chain assertions for readable, self-documenting tests.
|
|
249
|
+
|
|
250
|
+
## Mocking (Mockito)
|
|
251
|
+
- Use `@Mock` + `@ExtendWith(MockitoExtension.class)` for injection.
|
|
252
|
+
- Use `when().thenReturn()` for stubbing. `verify()` for interaction checking.
|
|
253
|
+
- Use `@InjectMocks` to auto-inject mocks into the class under test.
|
|
254
|
+
- Prefer constructor injection in production code for testability.
|
|
255
|
+
- Use `ArgumentCaptor` to inspect complex arguments.
|
|
256
|
+
|
|
257
|
+
## Integration Testing
|
|
258
|
+
- Use Testcontainers for PostgreSQL, Redis, Kafka, etc.
|
|
259
|
+
- Use `@SpringBootTest` sparingly -- it starts the full context. Prefer slices.
|
|
260
|
+
- Use `@WebMvcTest` for controller tests, `@DataJpaTest` for repository tests.
|
|
261
|
+
- Use `@TestConfiguration` for test-specific bean overrides.
|
|
262
|
+
|
|
263
|
+
## Test Data
|
|
264
|
+
- Use test builders or factory methods for creating test objects.
|
|
265
|
+
- Use `@Sql` annotation to load test data from SQL files.
|
|
266
|
+
- Keep test data minimal. Only set fields relevant to the behavior under test.
|
|
267
|
+
- Use random UUIDs for IDs in tests to avoid collision.
|
|
268
|
+
|
|
269
|
+
## Performance
|
|
270
|
+
- Run tests in parallel: configure `junit.jupiter.execution.parallel.enabled=true`.
|
|
271
|
+
- Use `@SpringBootTest` only when integration context is needed.
|
|
272
|
+
- Mock external dependencies in unit tests for speed.
|
|
273
|
+
- Keep the full test suite under 5 minutes.
|