# Cleanroom Testing Framework - Core Team Best Practices
# Enforces production-grade Rust development standards

## Core Principles
- Zero-cost abstractions where possible
- Memory safety without compromise
- Performance-first design
- Production-ready error handling
- Comprehensive testing and documentation
- Latest stable Rust features and ecosystem crates

## Rust Language Standards

### Edition and Features
- Use Rust 2021 edition minimum
- Enable `#![forbid(unsafe_code)]` unless absolutely necessary
- Use `#![warn(missing_docs)]` for all public APIs
- Prefer `const` functions and `const` generics where applicable
- Use `async`/`await` for I/O operations
- Leverage `Pin<Box<dyn Future>>` for async trait objects

### Error Handling
- Use `thiserror` for structured error types with `#[source]` and `#[backtrace]`
- Implement `std::error::Error` trait for all error types
- Use `anyhow` for application-level error handling
- Never use `unwrap()` or `expect()` in production code
- Always handle `Result` and `Option` explicitly
- Use `?` operator for error propagation
- Provide context with `anyhow::Context` or `thiserror::Context`

### Memory Management
- Prefer `Arc<T>` over `Rc<T>` for thread safety
- Use `RwLock` for read-heavy workloads, `Mutex` for write-heavy
- Implement `Drop` trait for RAII resource cleanup
- Use `Pin<Box<T>>` for self-referential structures
- Prefer `Cow<'static, str>` for zero-copy string handling
- Use `Box<dyn Trait>` for trait objects with proper lifetime bounds

### Concurrency and Async
- Use `tokio` as the async runtime
- Prefer `JoinSet` for structured concurrency
- Use `broadcast` channels for cancellation signals
- Implement graceful shutdown patterns
- Use `tokio::time::timeout` for operation timeouts
- Prefer `async fn` over `fn` returning `Future`
- Use `Send + Sync` bounds appropriately

### Type Safety
- Use newtype wrappers for domain-specific types
- Implement `From`/`Into` traits for conversions
- Use `PhantomData` for type-level programming
- Prefer `NonZeroU64` over `u64` for IDs
- Use `Cow<str>` for flexible string handling
- Implement `Clone` for lightweight types

## Dependency Management

### Core Dependencies (Always Latest Stable)
- `tokio = { version = "1.0", features = ["full"] }`
- `serde = { version = "1.0", features = ["derive"] }`
- `serde_json = "1.0"`
- `thiserror = "2.0"`
- `anyhow = "1.0"`
- `uuid = { version = "1.0", features = ["v4", "serde"] }`
- `chrono = { version = "0.4", features = ["serde"] }`
- `tracing = "0.1"`
- `async-trait = "0.1"`

### Container Dependencies (Latest Versions)
- `testcontainers = { version = "0.25", features = ["blocking"] }`
- `testcontainers-modules = { version = "0.13", features = ["postgres", "redis"] }`

### Testing Dependencies
- `criterion = "0.5"` for benchmarks
- `proptest = "1.0"` for property testing
- `insta = "1.0"` for snapshot testing
- `assert_cmd = "2.0"` for CLI testing
- `predicates = "3.0"` for test assertions

## Code Quality Standards

### Documentation
- All public APIs must have comprehensive documentation
- Use `///` for module-level documentation
- Include usage examples in doc comments
- Document error conditions and panics
- Use `# Examples` sections for complex APIs
- Document performance characteristics
- Include `# Safety` sections for unsafe code

### Testing
- Unit tests for all public functions
- Integration tests for API boundaries
- Property tests for data structures
- Benchmark tests for performance-critical code
- Snapshot tests for serialization
- Doctests for all examples
- Test coverage minimum 80%

### Performance
- Use `criterion` for benchmarking
- Profile with `tokio-console` and `tracing`
- Implement zero-copy operations where possible
- Use `Cow<str>` for string handling
- Prefer `Vec::with_capacity` for known sizes
- Use `HashMap::with_capacity` for known key counts
- Implement `Clone` only for lightweight types

### Security
- Never log sensitive data (passwords, tokens, keys)
- Use `secrecy` crate for sensitive strings
- Implement proper input validation
- Use `regex` for data redaction
- Sanitize all user inputs
- Implement rate limiting where appropriate

## Architecture Patterns

### Builder Pattern
- Use typestate pattern for compile-time validation
- Implement `Default` trait for configuration
- Use `Into`/`From` for conversions
- Provide fluent API with method chaining

### RAII Pattern
- Implement `Drop` for all resource management
- Use guards for automatic cleanup
- Provide `into_inner()` for ownership transfer
- Use `Arc<Mutex<T>>` for shared mutable state

### Observer Pattern
- Use `tracing` for structured logging
- Implement metrics collection
- Use `broadcast` channels for events
- Provide callback mechanisms

### Strategy Pattern
- Use trait objects for pluggable behavior
- Implement capability queries
- Use feature flags for optional functionality
- Provide extension points

## File Organization

### Module Structure
- One module per file
- Use `mod.rs` for module organization
- Group related functionality
- Use `pub use` for re-exports
- Implement `Default` for configuration types

### Import Organization
- Group imports by source (std, external, internal)
- Use `use` statements for frequently used items
- Prefer absolute paths for clarity
- Use `crate::` prefix for internal imports

### Error Organization
- Centralized error types in `error.rs`
- Use `thiserror` for error definitions
- Implement `Display` and `Error` traits
- Provide error context and chaining

## Specific Requirements

### Container Management
- Use latest testcontainers API (0.25+)
- Implement proper lifecycle management
- Use RAII guards for cleanup
- Provide health checks
- Implement metrics collection
- Use structured logging

### Async Operations
- Use `tokio::spawn` for concurrent tasks
- Implement structured concurrency with `JoinSet`
- Use `tokio::time::timeout` for operations
- Provide cancellation mechanisms
- Use `broadcast` channels for coordination

### Serialization
- Use `serde` for all serialization
- Implement `Serialize` and `Deserialize`
- Use `serde_json` for JSON handling
- Provide custom serializers for complex types
- Use `serde_with` for advanced patterns

### Configuration
- Use `serde` for configuration parsing
- Implement validation for all config
- Provide sensible defaults
- Use environment variable overrides
- Implement configuration hot-reloading

## Enforcement Rules

### Compilation
- All code must compile without warnings
- Use `#![deny(warnings)]` in production
- Fix all clippy suggestions
- Use `rustfmt` for code formatting
- Use `cargo clippy` for linting

### Testing
- All tests must pass
- No ignored tests in production
- Use `cargo test --all-features`
- Implement CI/CD pipeline
- Use `cargo audit` for security

### Performance
- Benchmark all performance-critical code
- Use `criterion` for regression detection
- Profile with `tokio-console`
- Implement performance monitoring
- Use `cargo bench` for benchmarks

### Documentation
- All public APIs documented
- Examples in all doc comments
- README with usage examples
- Architecture documentation
- API reference documentation

## Prohibited Practices

### Never Use
- `unwrap()` or `expect()` in production code
- `unsafe` code without justification
- `panic!` for error handling
- `println!` for logging
- `Rc<T>` in async contexts
- `std::thread` in async code
- Blocking operations in async functions
- Raw pointers without `unsafe`
- `transmute` without extreme justification

### Avoid
- Deeply nested error handling
- Complex trait bounds
- Overly generic types
- Premature optimization
- Copy-paste code
- Magic numbers
- Global state
- Synchronous I/O in async code

## Code Review Checklist

### Functionality
- [ ] Implements required behavior
- [ ] Handles all error cases
- [ ] Provides proper documentation
- [ ] Includes comprehensive tests
- [ ] Follows naming conventions
- [ ] Uses appropriate data structures

### Performance
- [ ] No unnecessary allocations
- [ ] Uses zero-copy operations where possible
- [ ] Implements proper caching
- [ ] Avoids blocking operations
- [ ] Uses appropriate concurrency
- [ ] Provides benchmarks

### Security
- [ ] No sensitive data in logs
- [ ] Validates all inputs
- [ ] Implements proper error handling
- [ ] Uses secure defaults
- [ ] Follows principle of least privilege
- [ ] Implements proper resource limits

### Maintainability
- [ ] Clear and readable code
- [ ] Proper error messages
- [ ] Comprehensive documentation
- [ ] Follows established patterns
- [ ] Uses appropriate abstractions
- [ ] Implements proper logging

## Continuous Integration

### Required Checks
- `cargo check --all-features`
- `cargo clippy --all-features -- -D warnings`
- `cargo test --all-features`
- `cargo bench --all-features`
- `cargo audit`
- `cargo fmt --check`
- `cargo doc --all-features --no-deps`

### Performance Regression
- Benchmark all performance-critical code
- Use `criterion` for regression detection
- Implement performance monitoring
- Use `tokio-console` for profiling
- Monitor memory usage and allocations

### Security Scanning
- Use `cargo audit` for vulnerability scanning
- Implement dependency scanning
- Use `cargo deny` for license compliance
- Implement secret scanning
- Use `cargo-geiger` for unsafe code detection

## Version Management

### Dependency Updates
- Update dependencies monthly
- Use `cargo outdated` to check for updates
- Test all dependency updates
- Use `cargo audit` for security updates
- Pin versions for reproducible builds

### Rust Version
- Use latest stable Rust version
- Update Rust toolchain monthly
- Use `rustup` for toolchain management
- Test with latest beta for compatibility
- Use `cargo +nightly` for experimental features

## Monitoring and Observability

### Logging
- Use `tracing` for structured logging
- Implement log levels (ERROR, WARN, INFO, DEBUG, TRACE)
- Use structured fields for context
- Implement log rotation and retention
- Use `tracing-subscriber` for formatting

### Metrics
- Implement Prometheus metrics
- Use `tracing` for metrics collection
- Implement health checks
- Use `tokio-console` for debugging
- Implement distributed tracing

### Error Tracking
- Use structured error types
- Implement error context and chaining
- Use `anyhow` for application errors
- Implement error reporting
- Use `thiserror` for error definitions

## Final Notes

This framework represents production-grade Rust development standards. Every line of code should be written with the assumption that it will run in a high-performance, high-reliability production environment. There are no shortcuts, no compromises, and no "good enough" solutions. Only the highest quality, most maintainable, and most performant code is acceptable.

Remember: Code is read far more often than it is written. Write for the next developer who will maintain this code, not for yourself.
