mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-06-15 12:41:26 +08:00
feat: expand Kiro adapter to full language coverage (#2101)
* feat: expand Kiro adapter to full language coverage - Add 17 new agents (typescript, rust, kotlin, java, cpp, django, swift, fsharp, pytorch, mle, performance-optimizer) in both .md and .json formats - Add 25 new skills (rust, kotlin, java/spring, django, fastapi, nestjs, react, nextjs, cpp, swift, mle/pytorch, deep-research, strategic-compact, autonomous-loops, content-hash-cache-pattern) - Add 6 new language-specific steering files (rust, kotlin, java, cpp, php, ruby) - Add 3 new hooks (rust-check-on-edit, python-lint-on-edit, security-check-on-create) - Update README with expanded component inventory and documentation - Fix install.sh line endings for macOS compatibility Total Kiro components: 33 agents, 43 skills, 22 steering files, 13 hooks * fix: resolve P1/P2 violations in Kiro agents, skills, and steering - java-patterns.md: remove reference to non-existent quarkus-patterns skill - kotlin-patterns.md: fix insecure BuildConfig recommendation for secrets - swift-actor-persistence: fix Swift version claim (5.9+) and Dictionary crash - java-reviewer.md: add recursive framework detection + robust diff chain - kotlin-reviewer.md: replace unreliable diff detection with fallback chain - rust-reviewer.md: add diff fallback + make CI gating mandatory - jpa-patterns: add DISTINCT to fetch-join query to prevent duplicates - django-reviewer.md: add migration safety check, narrow save() rule, fix pytest-django behavior description * fix: resolve remaining violations in Kiro agents, skills, and docs Agents: - java-build-resolver.md: remove quarkus-patterns ref, fix 'Initialise' spelling - java-reviewer.json: remove quarkus-patterns ref from prompt - mle-reviewer.md, cpp-build-resolver.md, java-build-resolver.md, performance-optimizer.md: fix allowedTools 'read' -> 'fs_read' Hooks: - rust-check-on-edit: fix description to match askAgent behavior Skills: - content-hash-cache-pattern: hyphenate 'Content-Hash-Based' - cpp-testing: hyphenate 'real-time' - django-security: use placeholder secrets, fix CSRF_COOKIE_HTTPONLY=False - nestjs-patterns: add Logger to HttpExceptionFilter for non-Http errors - react-patterns: add React 19 compatibility note for useActionState - rust-patterns: remove edition-specific 'Rust 2024+' reference - springboot-patterns: cap exponential backoff, recommend Resilience4j - springboot-security: fix invalid @Query SQL injection example - swift-protocol-di-testing: add thread-safety doc comment to mock Docs: - README.md: fix Project Structure counts (33/43/22/13) * fix: sync README tree with counts, restore local diff in kotlin-reviewer, correct django FK index guidance - README.md: Project Structure tree now lists all 33 agents, 43 skills, 22 steering files, and 13 hooks (was showing old subset) - kotlin-reviewer.md: restore git diff --staged / git diff for local pre-commit review before falling back to HEAD~1 - django-reviewer.md: clarify that ForeignKey fields are indexed by default; only flag missing db_index on non-FK filter columns
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
---
|
||||
inclusion: fileMatch
|
||||
fileMatchPattern: "*.cpp,*.hpp,*.h,*.cc,*.cxx"
|
||||
description: C++ coding standards, RAII, smart pointers, and modern C++ patterns.
|
||||
---
|
||||
|
||||
# C++ Patterns
|
||||
|
||||
> This file extends the common patterns with C++ specific content.
|
||||
|
||||
## Modern C++ (C++17/20/23)
|
||||
|
||||
- Prefer modern C++ features over C-style constructs
|
||||
- Use `auto` when the type is obvious from context
|
||||
- Use `constexpr` for compile-time constants
|
||||
- Use structured bindings: `auto [key, value] = map_entry;`
|
||||
|
||||
## RAII (Resource Acquisition Is Initialization)
|
||||
|
||||
Tie resource lifetime to object lifetime — no manual `new`/`delete`:
|
||||
|
||||
```cpp
|
||||
class FileHandle {
|
||||
public:
|
||||
explicit FileHandle(const std::string& path) : file_(std::fopen(path.c_str(), "r")) {}
|
||||
~FileHandle() { if (file_) std::fclose(file_); }
|
||||
FileHandle(const FileHandle&) = delete;
|
||||
FileHandle& operator=(const FileHandle&) = delete;
|
||||
private:
|
||||
std::FILE* file_;
|
||||
};
|
||||
```
|
||||
|
||||
## Smart Pointers
|
||||
|
||||
- Use `std::unique_ptr` for exclusive ownership
|
||||
- Use `std::shared_ptr` only when shared ownership is truly needed
|
||||
- Use `std::make_unique` / `std::make_shared` over raw `new`
|
||||
|
||||
## Rule of Five/Zero
|
||||
|
||||
- **Rule of Zero**: Prefer classes that need no custom destructor, copy/move constructors, or assignments
|
||||
- **Rule of Five**: If you define any of destructor/copy-ctor/copy-assign/move-ctor/move-assign, define all five
|
||||
|
||||
## Value Semantics & Error Handling
|
||||
|
||||
- Pass small/trivial types by value, large types by `const&`
|
||||
- Return by value (rely on RVO/NRVO)
|
||||
- Use `std::optional` for values that may not exist
|
||||
- Use `std::expected` (C++23) or result types for expected failures
|
||||
|
||||
## Memory Safety
|
||||
|
||||
- Never use raw `new`/`delete` — use smart pointers
|
||||
- Never use C-style arrays — use `std::array` or `std::vector`
|
||||
- Use `std::string` over `char*`
|
||||
- Use `.at()` for bounds-checked access when safety matters
|
||||
- Never use `strcpy`, `strcat`, `sprintf`
|
||||
|
||||
## Formatting & Static Analysis
|
||||
|
||||
```bash
|
||||
clang-format -i <file>
|
||||
clang-tidy --checks='*' src/*.cpp
|
||||
cppcheck --enable=all src/
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Use GoogleTest (gtest/gmock) with CMake/CTest:
|
||||
|
||||
```bash
|
||||
cmake --build build && ctest --test-dir build --output-on-failure
|
||||
```
|
||||
|
||||
Always run tests with sanitizers in CI:
|
||||
|
||||
```bash
|
||||
cmake -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined" ..
|
||||
```
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
- Types/Classes: `PascalCase`
|
||||
- Functions/Methods: `snake_case` or `camelCase` (follow project convention)
|
||||
- Constants: `kPascalCase` or `UPPER_SNAKE_CASE`
|
||||
- Namespaces: `lowercase`
|
||||
|
||||
## Reference
|
||||
|
||||
See agents: `cpp-reviewer`, `cpp-build-resolver` for C++ review and build error resolution.
|
||||
See skill: `cpp-coding-standards` for comprehensive C++ guidelines.
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
inclusion: fileMatch
|
||||
fileMatchPattern: "*.java"
|
||||
description: Java-specific patterns, Spring Boot, and enterprise best practices.
|
||||
---
|
||||
|
||||
# Java Patterns
|
||||
|
||||
> This file extends the common patterns with Java specific content.
|
||||
|
||||
## Immutability
|
||||
|
||||
- Prefer `record` for value types (Java 16+)
|
||||
- Mark fields `final` by default — use mutable state only when required
|
||||
- Return defensive copies: `List.copyOf()`, `Map.copyOf()`
|
||||
|
||||
```java
|
||||
public record OrderSummary(Long id, String customerName, BigDecimal total) {}
|
||||
```
|
||||
|
||||
## Modern Java Features
|
||||
|
||||
- **Records** for DTOs and value types (Java 16+)
|
||||
- **Sealed classes** for closed type hierarchies (Java 17+)
|
||||
- **Pattern matching** with `instanceof` (Java 16+)
|
||||
- **Switch expressions** with arrow syntax (Java 14+)
|
||||
|
||||
```java
|
||||
public sealed interface PaymentResult permits PaymentSuccess, PaymentFailure {}
|
||||
record PaymentSuccess(String transactionId, BigDecimal amount) implements PaymentResult {}
|
||||
record PaymentFailure(String errorCode, String message) implements PaymentResult {}
|
||||
```
|
||||
|
||||
## Constructor Injection
|
||||
|
||||
Always use constructor injection — never field injection:
|
||||
|
||||
```java
|
||||
// GOOD
|
||||
public class NotificationService {
|
||||
private final EmailSender emailSender;
|
||||
public NotificationService(EmailSender emailSender) {
|
||||
this.emailSender = emailSender;
|
||||
}
|
||||
}
|
||||
|
||||
// BAD — field injection
|
||||
@Inject private EmailSender emailSender;
|
||||
```
|
||||
|
||||
## Repository Pattern
|
||||
|
||||
```java
|
||||
public interface OrderRepository {
|
||||
Optional<Order> findById(Long id);
|
||||
List<Order> findAll();
|
||||
Order save(Order order);
|
||||
void deleteById(Long id);
|
||||
}
|
||||
```
|
||||
|
||||
## Optional Usage
|
||||
|
||||
- Return `Optional<T>` from finder methods that may have no result
|
||||
- Use `map()`, `flatMap()`, `orElseThrow()` — never call `get()` without `isPresent()`
|
||||
- Never use `Optional` as a field type or method parameter
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Prefer unchecked exceptions for domain errors
|
||||
- Create domain-specific exceptions extending `RuntimeException`
|
||||
- Never expose stack traces in API responses
|
||||
|
||||
```java
|
||||
public class OrderNotFoundException extends RuntimeException {
|
||||
public OrderNotFoundException(Long id) {
|
||||
super("Order not found: id=" + id);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- Never hardcode secrets — use `System.getenv("API_KEY")`
|
||||
- Always use parameterized queries (`PreparedStatement`, JPA, JDBC template)
|
||||
- Use Bean Validation (`@NotNull`, `@NotBlank`, `@Size`) on DTOs
|
||||
- Store passwords with bcrypt or Argon2
|
||||
|
||||
## Testing
|
||||
|
||||
- JUnit 5 with AssertJ for fluent assertions
|
||||
- Mockito for mocking dependencies
|
||||
- Testcontainers for integration tests
|
||||
- Target 80%+ coverage with JaCoCo
|
||||
|
||||
```java
|
||||
@Test
|
||||
@DisplayName("findById returns order when exists")
|
||||
void findById_existingOrder_returnsOrder() {
|
||||
var order = new Order(1L, "Alice", BigDecimal.TEN);
|
||||
when(orderRepository.findById(1L)).thenReturn(Optional.of(order));
|
||||
var result = orderService.findById(1L);
|
||||
assertThat(result.customerName()).isEqualTo("Alice");
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
See agents: `java-reviewer`, `java-build-resolver` for Java-specific review and build error resolution.
|
||||
See skills: `springboot-patterns`, `jpa-patterns` for framework-specific guidance.
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
inclusion: fileMatch
|
||||
fileMatchPattern: "*.kt"
|
||||
description: Kotlin-specific patterns, coroutines, Compose, and Android/KMP best practices.
|
||||
---
|
||||
|
||||
# Kotlin Patterns
|
||||
|
||||
> This file extends the common patterns with Kotlin and Android/KMP specific content.
|
||||
|
||||
## Immutability & Null Safety
|
||||
|
||||
- Prefer `val` over `var` — default to `val` and only use `var` when mutation is required
|
||||
- Use `data class` for value types; use immutable collections in public APIs
|
||||
- Never use `!!` — prefer `?.`, `?:`, `requireNotNull()`, or `checkNotNull()`
|
||||
|
||||
```kotlin
|
||||
// BAD
|
||||
val name = user!!.name
|
||||
|
||||
// GOOD
|
||||
val name = user?.name ?: "Unknown"
|
||||
```
|
||||
|
||||
## Sealed Types
|
||||
|
||||
Use sealed classes/interfaces to model closed state hierarchies:
|
||||
|
||||
```kotlin
|
||||
sealed interface UiState<out T> {
|
||||
data object Loading : UiState<Nothing>
|
||||
data class Success<T>(val data: T) : UiState<T>
|
||||
data class Error(val message: String) : UiState<Nothing>
|
||||
}
|
||||
```
|
||||
|
||||
Always use exhaustive `when` with sealed types — no `else` branch.
|
||||
|
||||
## ViewModel Pattern
|
||||
|
||||
Single state object, event sink, one-way data flow:
|
||||
|
||||
```kotlin
|
||||
data class ScreenState(
|
||||
val items: List<Item> = emptyList(),
|
||||
val isLoading: Boolean = false
|
||||
)
|
||||
|
||||
class ScreenViewModel(private val useCase: GetItemsUseCase) : ViewModel() {
|
||||
private val _state = MutableStateFlow(ScreenState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
fun onEvent(event: ScreenEvent) {
|
||||
when (event) {
|
||||
is ScreenEvent.Load -> load()
|
||||
is ScreenEvent.Delete -> delete(event.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## UseCase Pattern
|
||||
|
||||
Single responsibility, `operator fun invoke`:
|
||||
|
||||
```kotlin
|
||||
class GetItemUseCase(private val repository: ItemRepository) {
|
||||
suspend operator fun invoke(id: String): Result<Item> {
|
||||
return repository.getById(id)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
Prefer constructor injection. Use Koin (KMP) or Hilt (Android-only):
|
||||
|
||||
```kotlin
|
||||
// Koin
|
||||
val dataModule = module {
|
||||
single<ItemRepository> { ItemRepositoryImpl(get(), get()) }
|
||||
factory { GetItemsUseCase(get()) }
|
||||
viewModelOf(::ItemListViewModel)
|
||||
}
|
||||
```
|
||||
|
||||
## Coroutine Patterns
|
||||
|
||||
- Use `viewModelScope` in ViewModels, `coroutineScope` for structured child work
|
||||
- Use `supervisorScope` when child failures should be independent
|
||||
- Never catch `CancellationException` — always rethrow it
|
||||
|
||||
## expect/actual (KMP)
|
||||
|
||||
Use for platform-specific implementations:
|
||||
|
||||
```kotlin
|
||||
// commonMain
|
||||
expect fun platformName(): String
|
||||
|
||||
// androidMain
|
||||
actual fun platformName(): String = "Android"
|
||||
|
||||
// iosMain
|
||||
actual fun platformName(): String = "iOS"
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- Never embed secrets in `BuildConfig` or resources — values are extractable from the APK
|
||||
- Use `EncryptedSharedPreferences` or Android Keystore (Android), Keychain (iOS), or a server-side proxy for runtime secrets
|
||||
- Use parameterized queries for Room/SQLDelight
|
||||
- Configure `network_security_config.xml` to block cleartext traffic
|
||||
|
||||
## Testing
|
||||
|
||||
- Use `kotlin.test` for multiplatform, JUnit for Android-specific tests
|
||||
- Use Turbine for testing Flows and StateFlow
|
||||
- Use `runTest` with `kotlinx-coroutines-test` for coroutine testing
|
||||
- Prefer hand-written fakes over mocking frameworks
|
||||
|
||||
```kotlin
|
||||
@Test
|
||||
fun `loading state emitted then data`() = runTest {
|
||||
val repo = FakeItemRepository()
|
||||
val viewModel = ItemListViewModel(GetItemsUseCase(repo))
|
||||
|
||||
viewModel.state.test {
|
||||
assertEquals(ItemListState(), awaitItem())
|
||||
viewModel.onEvent(ItemListEvent.Load)
|
||||
assertTrue(awaitItem().isLoading)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
See agents: `kotlin-reviewer`, `kotlin-build-resolver` for Kotlin-specific review and build error resolution.
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
inclusion: fileMatch
|
||||
fileMatchPattern: "*.php"
|
||||
description: PHP-specific patterns, Laravel, and modern PHP best practices.
|
||||
---
|
||||
|
||||
# PHP Patterns
|
||||
|
||||
> This file extends the common patterns with PHP specific content.
|
||||
|
||||
## Standards
|
||||
|
||||
- Follow **PSR-12** formatting and naming conventions
|
||||
- Prefer `declare(strict_types=1);` in application code
|
||||
- Use scalar type hints, return types, and typed properties everywhere
|
||||
|
||||
## Immutability
|
||||
|
||||
- Prefer immutable DTOs and value objects for data crossing service boundaries
|
||||
- Use `readonly` properties or immutable constructors for request/response payloads
|
||||
|
||||
## Thin Controllers, Explicit Services
|
||||
|
||||
- Keep controllers focused on transport: auth, validation, serialization, status codes
|
||||
- Move business rules into application/domain services testable without HTTP bootstrapping
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
- Depend on interfaces or narrow service contracts, not framework globals
|
||||
- Pass collaborators through constructors so services are testable without service-locator lookups
|
||||
|
||||
## DTOs and Value Objects
|
||||
|
||||
- Replace shape-heavy associative arrays with DTOs for requests, commands, and API payloads
|
||||
- Use value objects for money, identifiers, date ranges, and constrained concepts
|
||||
|
||||
## Security
|
||||
|
||||
- Validate request input at the framework boundary (`FormRequest`, Symfony Validator)
|
||||
- Use prepared statements (PDO, Eloquent query builder) for all dynamic queries
|
||||
- Load secrets from environment variables, never from committed config files
|
||||
- Use `password_hash()` / `password_verify()` for password storage
|
||||
- Enforce CSRF protection on state-changing web requests
|
||||
- Run `composer audit` in CI
|
||||
|
||||
## Formatting & Analysis
|
||||
|
||||
```bash
|
||||
# PHP-CS-Fixer or Laravel Pint for formatting
|
||||
# PHPStan or Psalm for static analysis
|
||||
vendor/bin/phpstan analyse
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
- Use **PHPUnit** as default; prefer **Pest** if configured in the project
|
||||
- Separate fast unit tests from framework/database integration tests
|
||||
- Use factory/builders for fixtures instead of large hand-written arrays
|
||||
|
||||
```bash
|
||||
vendor/bin/phpunit --coverage-text
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
See skills: `laravel-patterns`, `laravel-security`, `laravel-tdd` for Laravel-specific guidance.
|
||||
See skill: `api-design` for endpoint conventions and response-shape guidance.
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
inclusion: fileMatch
|
||||
fileMatchPattern: "*.rb"
|
||||
description: Ruby-specific patterns and Rails best practices.
|
||||
---
|
||||
|
||||
# Ruby Patterns
|
||||
|
||||
> This file extends the common patterns with Ruby and Rails specific content.
|
||||
|
||||
## Standards
|
||||
|
||||
- Target **Ruby 3.3+** for new Rails work
|
||||
- Add `# frozen_string_literal: true` to new files when the project uses that convention
|
||||
- Prefer clear Ruby over clever metaprogramming
|
||||
|
||||
## Formatting & Linting
|
||||
|
||||
```bash
|
||||
bundle exec rubocop
|
||||
bundle exec rubocop -A
|
||||
```
|
||||
|
||||
## Rails Way First
|
||||
|
||||
- Start with plain Rails MVC and Active Record conventions
|
||||
- Introduce service objects, query objects, form objects when model/controller carries multiple responsibilities
|
||||
- Keep controllers transport-focused: auth, params, response shape
|
||||
|
||||
## Persistence
|
||||
|
||||
- Prefer PostgreSQL for multi-host production Rails apps
|
||||
- Keep raw SQL behind query objects or model scopes; parameterize every dynamic value
|
||||
|
||||
## Background Jobs
|
||||
|
||||
- Use **Solid Queue** for greenfield Rails 8 apps with modest throughput
|
||||
- Use **Sidekiq** for mature observability, high throughput, or existing Redis infrastructure
|
||||
|
||||
## Frontend
|
||||
|
||||
- Prefer **Hotwire** (Turbo, Stimulus, Importmap, Propshaft) for server-rendered Rails apps
|
||||
- Use React/Vue/Inertia when interaction complexity justifies the extra client surface
|
||||
|
||||
## Authentication
|
||||
|
||||
- Use Rails 8 authentication generator for straightforward session auth
|
||||
- Use Devise when requirements include OAuth, MFA, confirmable/lockable flows
|
||||
|
||||
## Security
|
||||
|
||||
- Keep CSRF protection enabled for state-changing browser requests
|
||||
- Use strong parameters or typed boundary objects before mass assignment
|
||||
- Store secrets in Rails credentials or environment variables — never commit plaintext keys
|
||||
- Prefer Active Record query APIs and parameterized SQL — never interpolate user input into SQL
|
||||
|
||||
```bash
|
||||
bundle exec bundle-audit check --update
|
||||
bundle exec brakeman --no-progress
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
- Use **Minitest** when the app follows default Rails test stack
|
||||
- Use **RSpec** when already established in the project
|
||||
- Put fast domain behavior in model/service/query tests
|
||||
- Use system tests with Capybara for browser-critical flows only
|
||||
|
||||
```bash
|
||||
bin/rails test
|
||||
bundle exec rspec
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
See skill: `backend-patterns` for service boundaries and adapter patterns.
|
||||
See skill: `security-review` for secure-by-default review patterns.
|
||||
@@ -0,0 +1,123 @@
|
||||
---
|
||||
inclusion: fileMatch
|
||||
fileMatchPattern: "*.rs"
|
||||
description: Rust-specific patterns, ownership, lifetimes, error handling, and best practices.
|
||||
---
|
||||
|
||||
# Rust Patterns
|
||||
|
||||
> This file extends the common patterns with Rust specific content.
|
||||
|
||||
## Formatting & Linting
|
||||
|
||||
- Run `cargo fmt` before committing
|
||||
- Run `cargo clippy -- -D warnings` (treat warnings as errors)
|
||||
|
||||
## Immutability & Ownership
|
||||
|
||||
- Use `let` by default; only `let mut` when mutation is required
|
||||
- Borrow (`&T`) by default; take ownership only when storing or consuming
|
||||
- Accept `&str` over `String`, `&[T]` over `Vec<T>` in function parameters
|
||||
- Never clone to satisfy the borrow checker without understanding the root cause
|
||||
|
||||
```rust
|
||||
// GOOD — borrows when ownership isn't needed
|
||||
fn word_count(text: &str) -> usize {
|
||||
text.split_whitespace().count()
|
||||
}
|
||||
|
||||
// GOOD — takes ownership in constructor via Into
|
||||
fn new(name: impl Into<String>) -> Self {
|
||||
Self { name: name.into() }
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Use `Result<T, E>` and `?` for propagation — never `unwrap()` in production code
|
||||
- Libraries: define typed errors with `thiserror`
|
||||
- Applications: use `anyhow` for flexible error context
|
||||
- Reserve `unwrap()` / `expect()` for tests and truly unreachable states
|
||||
|
||||
```rust
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("failed to read config: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("invalid config format: {0}")]
|
||||
Parse(String),
|
||||
}
|
||||
```
|
||||
|
||||
## Newtype Pattern
|
||||
|
||||
Prevent argument mix-ups with distinct wrapper types:
|
||||
|
||||
```rust
|
||||
struct UserId(u64);
|
||||
struct OrderId(u64);
|
||||
|
||||
fn get_order(user: UserId, order: OrderId) -> anyhow::Result<Order> {
|
||||
todo!()
|
||||
}
|
||||
```
|
||||
|
||||
## Enum State Machines
|
||||
|
||||
Model states as enums — make illegal states unrepresentable:
|
||||
|
||||
```rust
|
||||
enum ConnectionState {
|
||||
Disconnected,
|
||||
Connecting { attempt: u32 },
|
||||
Connected { session_id: String },
|
||||
Failed { reason: String, retries: u32 },
|
||||
}
|
||||
```
|
||||
|
||||
Always match exhaustively — no wildcard `_` for business-critical enums.
|
||||
|
||||
## Repository Pattern with Traits
|
||||
|
||||
```rust
|
||||
pub trait OrderRepository: Send + Sync {
|
||||
fn find_by_id(&self, id: u64) -> Result<Option<Order>, StorageError>;
|
||||
fn save(&self, order: &Order) -> Result<Order, StorageError>;
|
||||
fn delete(&self, id: u64) -> Result<(), StorageError>;
|
||||
}
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- Never hardcode secrets — use `std::env::var("API_KEY")`
|
||||
- Always use parameterized queries (sqlx, diesel, sea-orm)
|
||||
- Minimize `unsafe` blocks; every `unsafe` must have a `// SAFETY:` comment
|
||||
- Run `cargo audit` and `cargo deny check` in CI
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests in `#[cfg(test)]` modules in the same file
|
||||
- Integration tests in `tests/` directory
|
||||
- Use `rstest` for parameterized tests, `mockall` for trait mocking
|
||||
- Target 80%+ coverage with `cargo llvm-cov`
|
||||
|
||||
```rust
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn creates_user_with_valid_email() {
|
||||
let user = User::new("Alice", "alice@example.com").unwrap();
|
||||
assert_eq!(user.name, "Alice");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Module Organization
|
||||
|
||||
Organize by domain, not by type. Default to private; use `pub(crate)` for internal sharing.
|
||||
|
||||
## Reference
|
||||
|
||||
See agents: `rust-reviewer`, `rust-build-resolver` for Rust-specific review and build error resolution.
|
||||
Reference in New Issue
Block a user