@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.
Files changed (42) hide show
  1. package/AGENTS.md +13 -0
  2. package/CHANGELOG.md +35 -0
  3. package/README.md +25 -39
  4. package/app/.claude-plugin/plugin.json +1 -1
  5. package/app/skills/cpp-rules/SKILL.md +275 -0
  6. package/app/skills/csharp-rules/SKILL.md +282 -0
  7. package/app/skills/dart-rules/SKILL.md +299 -0
  8. package/app/skills/golang-rules/SKILL.md +262 -0
  9. package/app/skills/java-rules/SKILL.md +273 -0
  10. package/app/skills/kotlin-rules/SKILL.md +271 -0
  11. package/app/skills/medplum-rules/SKILL.md +271 -0
  12. package/app/skills/php-rules/SKILL.md +292 -0
  13. package/app/skills/python-rules/SKILL.md +257 -0
  14. package/app/skills/ruby-rules/SKILL.md +286 -0
  15. package/app/skills/rust-rules/SKILL.md +276 -0
  16. package/app/skills/swift-rules/SKILL.md +293 -0
  17. package/app/skills/typescript-rules/SKILL.md +249 -0
  18. package/benchmarks/ecosystem-doctor-snapshot.json +14 -14
  19. package/kb/history/completed/deep-coverage-v3-20260423.md +3 -3
  20. package/kb/history/completed/ecosystem-deep-sweep-20260423.md +1 -1
  21. package/kb/procedures/release-preparation-sop.md +4 -4
  22. package/kb/procedures/release-verification-sop.md +11 -12
  23. package/kb/reference/architecture-overview.md +1 -1
  24. package/kb/reference/global-install-model.md +29 -6
  25. package/kb/reference/language-rules.md +54 -18
  26. package/kb/reference/mcp-editor-compatibility.md +4 -3
  27. package/kb/reference/mcp-templates.md +3 -2
  28. package/kb/reference/supported-tools-registry.md +10 -8
  29. package/llms-full.txt +133 -58
  30. package/manifest.json +3 -3
  31. package/package.json +10 -3
  32. package/scripts/codex_skill_adapter.py +19 -3
  33. package/scripts/ecosystem_tools.json +7 -7
  34. package/scripts/generate_cline_rules.py +17 -8
  35. package/scripts/generate_codex_skills.py +33 -96
  36. package/scripts/generate_language_rules_skills.py +232 -0
  37. package/scripts/generate_roo_rules.py +11 -3
  38. package/scripts/install.py +6 -1
  39. package/scripts/install_steps/ai_tools.py +154 -51
  40. package/scripts/install_steps/install_state.py +14 -2
  41. package/scripts/install_steps/project_registry.py +38 -5
  42. package/scripts/mcp_editors.py +7 -0
@@ -0,0 +1,286 @@
1
+ ---
2
+ name: ruby-rules
3
+ description: "Ruby coding rules from ai-toolkit: coding-style, frameworks, patterns, security, testing. Triggers: .rb, Gemfile, .gemspec, Rails, ActiveRecord, Sidekiq, RSpec, Sorbet, rubocop. Load when writing, reviewing, or editing Ruby code."
4
+ effort: medium
5
+ user-invocable: false
6
+ allowed-tools: Read
7
+ ---
8
+
9
+ # Ruby Rules
10
+
11
+ These rules come from `app/rules/ruby/` in ai-toolkit. They cover
12
+ the project's standards for coding style, frameworks, patterns,
13
+ security, and testing in Ruby. Apply them when writing or
14
+ reviewing Ruby code.
15
+
16
+ # Ruby Coding Style
17
+
18
+ ## Naming
19
+ - PascalCase: classes, modules.
20
+ - snake_case: methods, variables, file names, directories.
21
+ - UPPER_SNAKE: constants (`MAX_RETRIES = 3`).
22
+ - Prefix boolean methods with predicate: `empty?`, `valid?`, `admin?`.
23
+ - Suffix dangerous methods with `!`: `save!`, `sort!`, `strip!`.
24
+ - Use `_` prefix for intentionally unused variables: `_unused`.
25
+
26
+ ## Methods
27
+ - Keep methods short: 5-10 lines ideal. Extract helper methods.
28
+ - Use keyword arguments for methods with >2 parameters.
29
+ - Use default parameter values instead of checking for nil.
30
+ - Use `def method_name = expression` (Ruby 3.0+) for one-liners.
31
+ - Prefer `each` over `for` loops. Use block-style iteration.
32
+ - Return values implicitly (last expression). Use explicit `return` only for early exit.
33
+
34
+ ## Blocks, Procs, Lambdas
35
+ - Use `{ }` for single-line blocks. Use `do...end` for multi-line blocks.
36
+ - Use `&:method` shorthand: `names.map(&:upcase)`.
37
+ - Use lambdas for strict argument checking. Use procs for flexible arity.
38
+ - Use `yield` for single-block methods. Use explicit `&block` for storing/forwarding.
39
+
40
+ ## Classes
41
+ - Use `attr_reader`, `attr_writer`, `attr_accessor` for simple getters/setters.
42
+ - Use `Struct` for simple data containers. Use `Data.define` (Ruby 3.2+) for immutable.
43
+ - Use modules for mixins: `include` for instance methods, `extend` for class methods.
44
+ - Use `frozen_string_literal: true` magic comment at the top of every file.
45
+ - Use `private` / `protected` keywords to control method visibility.
46
+
47
+ ## Collections
48
+ - Use `map`, `select`, `reject`, `reduce`, `flat_map` for transformations.
49
+ - Use `each_with_object` over `inject` when accumulating into a mutable object.
50
+ - Use `dig` for safe nested hash/array access: `data.dig(:user, :address, :city)`.
51
+ - Use `Hash#fetch` with default for explicit missing-key handling.
52
+ - Use `Enumerable#lazy` for large collection processing.
53
+
54
+ ## Pattern Matching (Ruby 3+)
55
+ - Use `case/in` for structural pattern matching on hashes and arrays.
56
+ - Use `=>` pin operator to match against existing variables.
57
+ - Use `in` pattern for conditional deconstruction in `if` statements.
58
+ - Use pattern matching for API response parsing and validation.
59
+
60
+ ## Formatting
61
+ - Use RuboCop for automated style enforcement.
62
+ - Use `.rubocop.yml` committed to the repository for project conventions.
63
+ - Max line length: 120 characters.
64
+ - Two-space indentation. No tabs.
65
+ - Use trailing commas in multi-line arrays and hashes.
66
+
67
+ # Ruby Frameworks
68
+
69
+ ## Rails (General)
70
+ - Follow Rails conventions: convention over configuration.
71
+ - Use `rails generate` for scaffolding models, controllers, migrations.
72
+ - Use strong parameters: `params.require(:user).permit(:name, :email)`.
73
+ - Use concerns for shared controller/model behavior.
74
+ - Use `config/routes.rb` with resourceful routing: `resources :users`.
75
+ - Use environment-specific configuration in `config/environments/`.
76
+
77
+ ## ActiveRecord
78
+ - Use migrations for all schema changes. Never modify the database directly.
79
+ - Use `has_many`, `belongs_to`, `has_many :through` for associations.
80
+ - Use scopes for reusable query chains: `scope :active, -> { where(active: true) }`.
81
+ - Use `includes()` for eager loading to prevent N+1 queries.
82
+ - Use `find_each` for batch processing large record sets.
83
+ - Use `transaction` blocks for atomic multi-record operations.
84
+
85
+ ## ActionController
86
+ - Keep controllers thin: max 7 RESTful actions per controller.
87
+ - Use `before_action` for authentication and authorization checks.
88
+ - Use `respond_to` for content negotiation (JSON, HTML).
89
+ - Use `rescue_from` for centralized error handling in controllers.
90
+ - Use `render json:` with serializers (e.g., `ActiveModelSerializers`, `Blueprinter`).
91
+
92
+ ## Background Jobs
93
+ - Use Sidekiq for Redis-backed background job processing.
94
+ - Use ActiveJob as the abstraction layer over queue backends.
95
+ - Use `perform_later` for async execution. Use `perform_now` only in tests.
96
+ - Set `retry` count and `discard_on` / `retry_on` for error handling.
97
+ - Use `Sidekiq::Cron` or `clockwork` for scheduled recurring jobs.
98
+
99
+ ## Sinatra / Hanami
100
+ - Use Sinatra for lightweight APIs and microservices.
101
+ - Use Hanami for structured, modular Ruby web applications.
102
+ - Use Hanami actions (single-purpose) instead of fat controllers.
103
+ - Use Hanami repositories for data access abstraction.
104
+
105
+ ## API Mode
106
+ - Use `rails new --api` for API-only applications (no views, sessions).
107
+ - Use `Jbuilder` or `Blueprinter` for JSON serialization.
108
+ - Use `Rack::Attack` for rate limiting and throttling.
109
+ - Use versioned API namespaces: `namespace :v1 do ... end`.
110
+ - Use pagination with `kaminari` or `pagy` for collection endpoints.
111
+
112
+ ## Hotwire / Turbo
113
+ - Use Turbo Frames for partial page updates without JavaScript.
114
+ - Use Turbo Streams for real-time server-pushed DOM updates.
115
+ - Use Stimulus for lightweight JavaScript behavior on HTML elements.
116
+ - Keep JavaScript minimal: let the server render HTML.
117
+
118
+ # Ruby Patterns
119
+
120
+ ## Error Handling
121
+ - Rescue specific exceptions. Never bare `rescue` (catches `StandardError`).
122
+ - Create domain exception hierarchies: `class AppError < StandardError; end`.
123
+ - Use `raise` with message and optional cause: `raise AppError, "msg"`.
124
+ - Use `retry` with a counter for transient failures.
125
+ - Use `ensure` for cleanup. Use `else` for code that runs only on success.
126
+
127
+ ## Service Objects
128
+ - Use single-purpose service classes with a `call` method.
129
+ - Use `Dry::Monads` Result type for operation outcomes.
130
+ - Return `Success(value)` or `Failure(error)` from service calls.
131
+ - Chain services with `bind` / `fmap` for pipeline composition.
132
+ - Keep services stateless. Pass all data through method parameters.
133
+
134
+ ## Value Objects
135
+ - Use `Data.define` (Ruby 3.2+) for immutable value objects.
136
+ - Use `Struct` with `keyword_init: true` for lightweight data containers.
137
+ - Use `freeze` on objects that should not be mutated after creation.
138
+ - Override `==` and `hash` for value-based equality when needed.
139
+
140
+ ## Metaprogramming (Use Sparingly)
141
+ - Use `define_method` over `method_missing` when possible.
142
+ - Always define `respond_to_missing?` alongside `method_missing`.
143
+ - Use `class_attribute` (Rails) for inheritable class-level configuration.
144
+ - Prefer explicit code over DSL magic for maintainability.
145
+ - Document metaprogrammed methods with YARD `@!method` directives.
146
+
147
+ ## Concurrency
148
+ - Use `Concurrent::Future` (concurrent-ruby) for parallel operations.
149
+ - Use `Concurrent::Promise` for composable async chains.
150
+ - Use thread pools (`Concurrent::FixedThreadPool`) for bounded concurrency.
151
+ - Use `Ractor` (Ruby 3+) for true parallel execution without GVL.
152
+ - Use `Mutex` and `Queue` for thread-safe shared state access.
153
+
154
+ ## Module Patterns
155
+ - Use `include` for shared behavior (instance methods).
156
+ - Use `prepend` for wrapping/overriding existing methods (decorating).
157
+ - Use `extend` for adding class-level methods from a module.
158
+ - Use `Concern` (ActiveSupport) for Rails modules with class methods.
159
+ - Keep modules focused: one responsibility per module.
160
+
161
+ ## Decorator Pattern
162
+ - Use `SimpleDelegator` for transparent object wrapping.
163
+ - Use `Draper` gem for view-layer decorators in Rails.
164
+ - Prefer composition (wrapping) over inheritance for adding behavior.
165
+ - Use `Module#prepend` for method-level decoration without wrapper classes.
166
+
167
+ ## Anti-Patterns
168
+ - Monkey-patching core classes: use refinements or wrapper methods.
169
+ - Callbacks for business logic (Rails): use service objects.
170
+ - God objects: split into focused classes with single responsibility.
171
+ - N+1 queries: use `includes()`, `preload()`, `eager_load()`.
172
+ - Using `eval` or `send` with user input: remote code execution risk.
173
+
174
+ # Ruby Security
175
+
176
+ ## Mass Assignment
177
+ - Use strong parameters in controllers: `params.require(:user).permit(:name, :email)`.
178
+ - Never use `params.permit!` or pass unsanitized params to `create`/`update`.
179
+ - Use `attr_readonly` for fields that should never be updated after creation.
180
+ - Audit `update_columns` and `update_attribute` usage (bypass validations).
181
+
182
+ ## SQL Injection
183
+ - Use ActiveRecord query interface with parameterized conditions.
184
+ - Use `where(name: value)` hash syntax or `where("name = ?", value)` placeholders.
185
+ - Never interpolate user input into `where()` strings: `where("name = '#{input}'")`.
186
+ - Use `sanitize_sql_array` if building raw SQL fragments is unavoidable.
187
+ - Audit all `find_by_sql`, `execute`, and `Arel.sql` calls.
188
+
189
+ ## XSS Prevention
190
+ - Rails auto-escapes ERB output with `<%= %>`. Never use `raw()` with user data.
191
+ - Use `sanitize()` helper for allowing limited HTML tags.
192
+ - Set `Content-Security-Policy` header in `config/initializers/content_security_policy.rb`.
193
+ - Use `content_tag` helper for safe HTML generation.
194
+ - Mark strings as `html_safe` only when content is guaranteed safe.
195
+
196
+ ## CSRF Protection
197
+ - Use `protect_from_forgery with: :exception` in `ApplicationController`.
198
+ - Use `authenticity_token` in all forms (Rails includes it by default).
199
+ - Use `X-CSRF-Token` header for AJAX requests from JavaScript.
200
+ - Exempt only webhook endpoints from CSRF (with payload signature verification).
201
+
202
+ ## Authentication
203
+ - Use Devise or `has_secure_password` for authentication.
204
+ - Use `bcrypt` for password hashing (included with `has_secure_password`).
205
+ - Implement account lockout after N failed login attempts.
206
+ - Use `SecureRandom.urlsafe_base64` for generating tokens.
207
+ - Store sessions server-side (Redis/database) instead of cookie store in production.
208
+
209
+ ## Authorization
210
+ - Use Pundit or CanCanCan for authorization logic.
211
+ - Define policies per model: `class UserPolicy < ApplicationPolicy`.
212
+ - Check ownership in policies, not just role membership.
213
+ - Use `authorize @resource` in every controller action.
214
+ - Default deny: require explicit authorization for all actions.
215
+
216
+ ## Secrets Management
217
+ - Use `Rails.application.credentials` for encrypted secrets.
218
+ - Use `EDITOR="vim" bin/rails credentials:edit` to manage secrets.
219
+ - Use per-environment credentials: `credentials/production.yml.enc`.
220
+ - Never commit `master.key` or `production.key` to version control.
221
+ - Use environment variables for CI/CD and containerized deployments.
222
+
223
+ ## Dependency Security
224
+ - Run `bundle audit check --update` for known vulnerability scanning.
225
+ - Use `Dependabot` for automated dependency update PRs.
226
+ - Pin gem versions in `Gemfile`. Review `Gemfile.lock` changes carefully.
227
+ - Use `bundler-audit` in CI pipeline as a required check.
228
+ - Update Rails promptly when security patches are released.
229
+
230
+ # Ruby Testing
231
+
232
+ ## Framework
233
+ - Use RSpec as the primary test framework.
234
+ - Use Minitest for lightweight, stdlib-based testing.
235
+ - Use FactoryBot for test data generation.
236
+ - Use WebMock or VCR for HTTP request stubbing.
237
+
238
+ ## File Naming
239
+ - RSpec: `spec/models/user_spec.rb` mirroring `app/models/user.rb`.
240
+ - Minitest: `test/models/user_test.rb` mirroring source structure.
241
+ - Support files: `spec/support/` for shared helpers and configurations.
242
+ - Use `spec/rails_helper.rb` for Rails-specific RSpec configuration.
243
+
244
+ ## Structure (RSpec)
245
+ - Use `describe` for the class/method under test. Use `context` for scenarios.
246
+ - Use `it` for individual test cases with clear descriptions.
247
+ - Use `let` for lazy-evaluated test data. Use `let!` for eager evaluation.
248
+ - Use `before` / `after` blocks for setup and teardown.
249
+ - Use `subject` for the primary object under test.
250
+
251
+ ## Matchers (RSpec)
252
+ - Use `expect(result).to eq(expected)` for equality.
253
+ - Use `expect(result).to be_truthy`, `be_falsy`, `be_nil`.
254
+ - Use `expect { action }.to raise_error(FooError)` for exception testing.
255
+ - Use `expect { action }.to change { User.count }.by(1)` for side effects.
256
+ - Use `expect(list).to include(item)`, `contain_exactly(a, b, c)`.
257
+ - Use `expect(result).to match(hash_including(key: value))` for partial matching.
258
+
259
+ ## Mocking (RSpec)
260
+ - Use `instance_double(UserService)` for verified doubles.
261
+ - Stub: `allow(mock).to receive(:find).with(1).and_return(user)`.
262
+ - Verify: `expect(mock).to have_received(:save).once`.
263
+ - Use `receive_messages(method1: val1, method2: val2)` for multi-stubbing.
264
+ - Use `class_double` for stubbing class methods.
265
+ - Avoid stubbing the object under test. Stub only collaborators.
266
+
267
+ ## FactoryBot
268
+ - Define factories in `spec/factories/`: `FactoryBot.define { factory :user { ... } }`.
269
+ - Use `create` for persisted records. Use `build` for in-memory only.
270
+ - Use traits for variations: `create(:user, :admin)`.
271
+ - Use `build_stubbed` for fast tests that do not need database.
272
+ - Use sequences for unique attributes: `sequence(:email) { |n| "user#{n}@test.com" }`.
273
+
274
+ ## Rails Testing
275
+ - Use `request specs` for API endpoint testing (RSpec).
276
+ - Use `system specs` with Capybara for browser integration tests.
277
+ - Use `DatabaseCleaner` or `use_transactional_fixtures` for test isolation.
278
+ - Use `travel_to` for time-dependent test scenarios.
279
+ - Use `ActiveJob::TestHelper` for testing background jobs inline.
280
+
281
+ ## Best Practices
282
+ - Test behavior, not implementation. Do not test private methods directly.
283
+ - Use `shared_examples` for testing common behavior across classes.
284
+ - Use `aggregate_failures` to collect multiple assertion failures.
285
+ - Keep tests fast: stub external services, use `build_stubbed`.
286
+ - Run `bundle exec rspec --format documentation` for readable output.
@@ -0,0 +1,276 @@
1
+ ---
2
+ name: rust-rules
3
+ description: "Rust coding rules from ai-toolkit: coding-style, frameworks, patterns, security, testing. Triggers: .rs, Cargo.toml, Cargo.lock, Tokio, Axum, Serde, clippy, cargo test. Load when writing, reviewing, or editing Rust code."
4
+ effort: medium
5
+ user-invocable: false
6
+ allowed-tools: Read
7
+ ---
8
+
9
+ # Rust Rules
10
+
11
+ These rules come from `app/rules/rust/` in ai-toolkit. They cover
12
+ the project's standards for coding style, frameworks, patterns,
13
+ security, and testing in Rust. Apply them when writing or
14
+ reviewing Rust code.
15
+
16
+ # Rust Coding Style
17
+
18
+ ## Naming
19
+ - snake_case: functions, methods, variables, modules, crates.
20
+ - PascalCase: types, traits, enums, structs, type parameters.
21
+ - SCREAMING_SNAKE: constants and statics.
22
+ - Short lifetimes: `'a`, `'b`. Descriptive only when multiple coexist: `'input`, `'output`.
23
+ - Crate names: kebab-case in Cargo.toml, snake_case in code.
24
+
25
+ ## Ownership
26
+ - Borrow (`&T`) when you only need to read. Own (`T`) when storing or consuming.
27
+ - Use `&str` over `String` in function parameters when possible.
28
+ - Use `Cow<'_, str>` when you sometimes need to allocate.
29
+ - Avoid `.clone()` as a first resort -- restructure ownership instead.
30
+ - Use `Arc<T>` only when shared ownership across threads is required.
31
+
32
+ ## Types
33
+ - Use newtypes for domain primitives: `struct UserId(Uuid)`.
34
+ - Use `#[derive(Debug, Clone, PartialEq)]` on data types.
35
+ - Implement `Display` for user-facing output, `Debug` for developer output.
36
+ - Use `#[non_exhaustive]` on public enums and structs for future compatibility.
37
+ - Prefer enums over boolean flags for state representation.
38
+
39
+ ## Functions
40
+ - Return `Result<T, E>` for operations that can fail. Avoid panicking.
41
+ - Use `impl Trait` in argument position for flexibility, return position for simplicity.
42
+ - Use `where` clauses for complex bounds instead of inline.
43
+ - Prefer iterators over index-based loops.
44
+ - Use `let-else` (1.65+) for early-exit pattern matching.
45
+
46
+ ## Modules
47
+ - Use `mod.rs` or filename-based modules. Be consistent within the project.
48
+ - Re-export public API from `lib.rs` for a clean surface.
49
+ - Keep modules focused. One major type or concept per module.
50
+ - Use `pub(crate)` for internal-only visibility.
51
+
52
+ ## Formatting
53
+ - Use `rustfmt` with default settings. Do not fight the formatter.
54
+ - Use `clippy` with `-D warnings` in CI. Fix all warnings.
55
+ - Set MSRV (Minimum Supported Rust Version) in `Cargo.toml`.
56
+
57
+ ## Cargo
58
+ - Use workspace dependencies to unify versions across crates.
59
+ - Use feature flags for optional functionality.
60
+ - Set `edition = "2021"` (or latest stable edition).
61
+ - Use `[profile.release]` with `lto = true` and `codegen-units = 1` for production.
62
+
63
+ # Rust Frameworks
64
+
65
+ ## Axum
66
+ - Use extractors for typed request parsing: `Path`, `Query`, `Json`, `State`.
67
+ - Use `Router::new().route("/path", get(handler))` for route definitions.
68
+ - Share state via `State(Arc<AppState>)` extractor.
69
+ - Implement `IntoResponse` on error types for clean error handling.
70
+ - Use Tower middleware layers for auth, logging, tracing, rate limiting.
71
+
72
+ ## Actix-web
73
+ - Use extractors: `web::Path`, `web::Json`, `web::Data`.
74
+ - Use `App::new().service()` for route configuration.
75
+ - Share state with `web::Data<Arc<State>>`.
76
+ - Use `actix-web::middleware` for logging and error handling.
77
+
78
+ ## Tokio
79
+ - Use `#[tokio::main]` for the entry point. Use `tokio::spawn` for tasks.
80
+ - Use `tokio::select!` for waiting on multiple futures.
81
+ - Use `tokio::time::timeout()` for operation deadlines.
82
+ - Use `tokio::sync::broadcast` for pub/sub, `mpsc` for work queues.
83
+ - Use `tokio::task::spawn_blocking()` for CPU-intensive work in async context.
84
+
85
+ ## SQLx
86
+ - Use compile-time checked queries: `sqlx::query_as!(User, "SELECT ...")`.
87
+ - Use `PgPool` for connection pooling. Pass as shared state.
88
+ - Use migrations: `sqlx migrate add` and `sqlx migrate run`.
89
+ - Use `sqlx::FromRow` derive for automatic struct mapping.
90
+ - Set `DATABASE_URL` for compile-time query verification.
91
+
92
+ ## Serde
93
+ - Use `#[derive(Serialize, Deserialize)]` on all DTOs.
94
+ - Use `#[serde(rename_all = "camelCase")]` for JSON API compatibility.
95
+ - Use `#[serde(deny_unknown_fields)]` for strict deserialization.
96
+ - Use `#[serde(default)]` for optional fields with defaults.
97
+ - Use `#[serde(skip_serializing_if = "Option::is_none")]` for clean output.
98
+
99
+ ## Clap
100
+ - Use `#[derive(Parser)]` for CLI argument parsing.
101
+ - Use subcommands with enum variants: `#[derive(Subcommand)]`.
102
+ - Use `#[arg(env = "VAR_NAME")]` for env var fallback.
103
+ - Use `value_parser` for custom validation of arguments.
104
+
105
+ ## Tracing
106
+ - Use `tracing` crate over `log` for structured, async-aware logging.
107
+ - Use `#[instrument]` attribute on functions for automatic span creation.
108
+ - Use `tracing_subscriber` with `EnvFilter` for runtime log level control.
109
+ - Add `trace_id` to all log entries for distributed tracing correlation.
110
+
111
+ ## Testing Crates
112
+ - `mockall`: auto-generate mocks from traits.
113
+ - `wiremock`: HTTP mock server for integration tests.
114
+ - `testcontainers`: Docker containers for database tests.
115
+ - `proptest` / `quickcheck`: property-based testing.
116
+
117
+ # Rust Patterns
118
+
119
+ ## Error Handling
120
+ - Use `thiserror` for library error types (structured, typed enums).
121
+ - Use `anyhow` for application/binary code (flexible, context-rich).
122
+ - Wrap errors with context: `.with_context(|| format!("loading {path}"))?`.
123
+ - Use `#[from]` attribute for automatic error conversion in thiserror enums.
124
+ - Map domain errors to HTTP/gRPC errors at API boundaries only.
125
+
126
+ ## Builder Pattern
127
+ - Use builder for structs with many optional fields.
128
+ - Return `Result` from `build()` when validation is needed.
129
+ - Use `#[derive(Default)]` + `TypedBuilder` derive macro for compile-time safety.
130
+ - Chain setter methods returning `Self` for ergonomic API.
131
+
132
+ ## Newtype Pattern
133
+ - Wrap primitive types for type safety: `struct Email(String)`.
134
+ - Validate in constructor: `Email::new(raw) -> Result<Self, ValidationError>`.
135
+ - Implement `Deref` only when the inner type's full API is appropriate.
136
+ - Use `#[repr(transparent)]` for zero-cost newtypes in FFI.
137
+
138
+ ## Trait Design
139
+ - Keep traits small and focused. Compose with supertraits.
140
+ - Use associated types for output types: `type Output;`.
141
+ - Use default method implementations for common behavior.
142
+ - Use extension traits to add methods to foreign types.
143
+
144
+ ## Async Patterns
145
+ - Use `tokio` as the async runtime for most applications.
146
+ - Use `tokio::spawn` for concurrent tasks, `tokio::select!` for racing.
147
+ - Use `tokio::sync::mpsc` for channels, `tokio::sync::Mutex` for async locks.
148
+ - Prefer `async fn` in traits (Rust 1.75+) over manual `Pin<Box<dyn Future>>`.
149
+ - Use `tower` middleware pattern for layered request processing.
150
+
151
+ ## Iterator Patterns
152
+ - Use `.iter()` / `.into_iter()` / `.iter_mut()` appropriately.
153
+ - Chain: `filter().map().collect()` instead of manual loops.
154
+ - Use `collect::<Result<Vec<_>, _>>()` to short-circuit on first error.
155
+ - Implement `IntoIterator` for custom collections.
156
+
157
+ ## State Machine
158
+ - Use enums with data variants for state machines.
159
+ - Use `match` exhaustively -- compiler prevents missing states.
160
+ - Encode valid transitions in the type system when possible.
161
+ - Use typestate pattern for compile-time state transition enforcement.
162
+
163
+ ## Anti-Patterns
164
+ - `.unwrap()` in library code -- return `Result` or `Option`.
165
+ - `.clone()` to fix borrow checker -- restructure ownership.
166
+ - `Arc<Mutex<T>>` as first approach -- consider channels or actors.
167
+ - `Box<dyn Error>` in libraries -- use typed error enums.
168
+ - Ignoring `#[must_use]` warnings -- handle or explicitly discard with `let _ =`.
169
+
170
+ # Rust Security
171
+
172
+ ## Memory Safety
173
+ - Rust's ownership system prevents most memory bugs. Do not circumvent it.
174
+ - Minimize `unsafe` blocks. Document every safety invariant with `// SAFETY:`.
175
+ - Use `#![forbid(unsafe_code)]` in library crates when possible.
176
+ - Audit all `unsafe` code during review. Treat it as a security boundary.
177
+ - Use `miri` in CI for detecting undefined behavior in unsafe code.
178
+
179
+ ## Input Validation
180
+ - Validate all external input before processing. Use newtypes with validation.
181
+ - Use `serde` with `#[serde(deny_unknown_fields)]` for strict deserialization.
182
+ - Set size limits on deserialized data: `#[serde(deserialize_with = "...")]`.
183
+ - Validate string lengths, numeric ranges, and formats at API boundaries.
184
+
185
+ ## SQL Injection
186
+ - Use `sqlx` parameterized queries: `sqlx::query!("SELECT * WHERE id = $1", id)`.
187
+ - Never build SQL strings with `format!()` using user input.
188
+ - Use `sqlx::query_builder::QueryBuilder` for dynamic query construction.
189
+ - Type-check queries at compile time with `sqlx::query!` macro.
190
+
191
+ ## Cryptography
192
+ - Use `ring` or `rustcrypto` crates for cryptographic operations.
193
+ - Use `argon2` crate for password hashing.
194
+ - Use `subtle::ConstantTimeEq` for timing-safe comparisons.
195
+ - Use `rand` crate with `OsRng` for cryptographically secure random values.
196
+ - Never implement custom cryptographic algorithms.
197
+
198
+ ## Dependencies
199
+ - Run `cargo audit` in CI to check for known vulnerabilities.
200
+ - Run `cargo deny check` for license compliance and advisory checking.
201
+ - Use `cargo tree -d` to find duplicate dependencies.
202
+ - Review `build.rs` scripts in dependencies -- they execute at compile time.
203
+ - Minimize dependency count. Each crate is a potential attack surface.
204
+
205
+ ## Secrets
206
+ - Load secrets from environment: `std::env::var("SECRET")`.
207
+ - Use `secrecy` crate for values that should not be logged or displayed.
208
+ - Zeroize sensitive data after use with `zeroize` crate.
209
+ - Never hardcode secrets, tokens, or keys in source code.
210
+
211
+ ## Panic Safety
212
+ - Use `Result` and `Option` instead of panicking in library code.
213
+ - Use `catch_unwind` at FFI boundaries to prevent unwinding across languages.
214
+ - Set `panic = "abort"` in release profile to prevent panic exploitation.
215
+ - Avoid `unwrap()` and `expect()` on user-controlled data.
216
+
217
+ ## Network Security
218
+ - Use `rustls` over OpenSSL for TLS (pure Rust, memory-safe).
219
+ - Set timeouts on all network operations.
220
+ - Implement rate limiting on public endpoints.
221
+ - Validate and sanitize URLs before making outbound requests.
222
+
223
+ ## Supply Chain
224
+ - Use `cargo-vet` to track third-party audit status.
225
+ - Use `cargo-crev` for community code reviews.
226
+ - Enable `Cargo.lock` in version control for applications (not libraries).
227
+ - Prefer well-maintained crates with recent activity and security audits.
228
+
229
+ # Rust Testing
230
+
231
+ ## Unit Tests
232
+ - Place unit tests in `#[cfg(test)] mod tests` at the bottom of each file.
233
+ - Use `#[test]` attribute. Use `#[tokio::test]` for async tests.
234
+ - Name tests descriptively: `fn rejects_invalid_email()`.
235
+ - Access private items directly -- unit test modules are inside the parent module.
236
+
237
+ ## Integration Tests
238
+ - Place in `tests/` directory. Each file compiles as a separate crate.
239
+ - Test only the public API from integration tests.
240
+ - Use `tests/common/mod.rs` for shared test utilities.
241
+ - Name files by feature area: `tests/api_test.rs`, `tests/auth_test.rs`.
242
+
243
+ ## Assertions
244
+ - Use `assert_eq!(actual, expected)` with the actual value first.
245
+ - Use `assert!(matches!(result, Ok(_)))` for pattern matching in assertions.
246
+ - Use custom error messages: `assert_eq!(x, 5, "expected x to be 5, got {x}")`.
247
+ - Use `#[should_panic(expected = "message")]` for testing panics.
248
+
249
+ ## Result Testing
250
+ - Use `-> Result<(), Box<dyn Error>>` return type in tests for `?` support.
251
+ - Test error variants: `assert!(matches!(result, Err(AppError::NotFound(_))))`.
252
+ - Use `.unwrap()` in tests when failure means a bug in the test.
253
+
254
+ ## Mocking
255
+ - Use `mockall` crate with `#[automock]` on trait definitions.
256
+ - Use `expect_*` methods to set expectations on mock behavior.
257
+ - Prefer trait-based DI for testability. Accept `impl Trait` in constructors.
258
+ - Use `fake` crate for generating realistic test data.
259
+
260
+ ## Property Testing
261
+ - Use `proptest` for property-based testing on parsing and validation.
262
+ - Define strategies: `prop::string::string_regex("[a-z]+@[a-z]+\\.[a-z]{2,4}")`.
263
+ - Use `proptest!` macro for concise property test definitions.
264
+ - Test invariants: serialization roundtrips, ordering consistency.
265
+
266
+ ## Benchmarks
267
+ - Use `criterion` crate for statistical benchmarks (not built-in `#[bench]`).
268
+ - Use `black_box()` to prevent compiler optimization of benchmark code.
269
+ - Run benchmarks before and after optimization to measure impact.
270
+ - Use `cargo bench` with `-- --save-baseline` for regression tracking.
271
+
272
+ ## CI Pipeline
273
+ - Minimum: `cargo fmt --check && cargo clippy -- -D warnings && cargo test`.
274
+ - Add `cargo audit` for vulnerability scanning.
275
+ - Use `cargo nextest` for parallel test execution and better output.
276
+ - Enable `-Z randomize-layout` in nightly CI to catch layout-dependent code.