The Constitution: Technical Preference Universal Principles
⚖️ CRITICAL GOVERNANCE NOTICE
CRITICAL: BEFORE doing ANYTHING else, Read and Comprehend this document COMPLETELY.
MANDATORY COMPLIANCE CHECK:
Before executing your task, you must perform a "Constitution Lookup":
- IDENTIFY the domain of your task (e.g., API, DB, Auth, logging, etc.).
- SEARCH the relevant sections (e.g., grep "API Design").
- REVIEW Critical Constraints table for domain
- VERIFY your plan against the discipline and constraints before proceeding.
1. The Supremacy Clause & Conflict Resolution
When directives conflict or seem impossible to satisfy simultaneously, follow this precedence:
Security Principles [Non-Negotiable]
- OWASP Top 10 compliance
- Input validation and sanitization
- Authentication and authorization
- Secrets management
- No information leakage
- Action: Security ALWAYS wins. Refactor other requirements to satisfy security.
Testability & Modularity [Structural Law]
- I/O isolation (dependencies mockable in tests)
- Pure business logic (no side effects in core logic)
- Clear module boundaries with contracts
- Action: If code cannot be unit tested without external dependencies, refactor to add abstraction layer.
Error Handling Standards [Reliability Law]
- No silent failures
- Correlation IDs required
- JSON envelope format
- Resource cleanup in all paths
- Action: All error paths must be explicit. No exceptions.
Language Idioms [Implementation Preference]
- Use native patterns (defer, RAII, context managers)
- Follow community conventions
- Leverage standard library
- Action: Implement above laws idiomatically, don't blindly copy other languages.
Performance Optimizations [Measure First]
- Appropriate data structures
- Profile before optimizing
- Caching strategies
- Action: Only optimize with measured bottlenecks. Correctness > speed
Escalation Protocol
If following a directive is impossible:
- STOP coding immediately
- Document the conflict:
- Which directives conflict?
- Why is compliance impossible?
- What are the tradeoffs?
- Propose alternatives:
- Option A: [approach + which rules satisfied/violated]
- Option B: [approach + which rules satisfied/violated]
- ...
- ASK human for decision
- Present the precedence hierarchy
- Recommend least-harmful deviation option with justification based on hierarchy
- Wait for explicit approval
CRITICAL: NEVER silently violate, If following directive is impossible, STOP and ask human
Example:
Scenario 1: Framework Requires Inheritance (Architecture vs Language Idiom)
- Conflict: Django ORM requires model inheritance, but domain must be pure
- Hierarchy: Architecture (Level 2) > Framework idiom (Level 4)
- Resolution: Create Database Model (inherits ORM) + Pure Domain Entity + Mapper pattern
- PROCEED: Architecture wins
Scenario 2: Performance vs Security
- Conflict: Caching would speed up response but contains PII
- Hierarchy: Security (Level 1) > Performance (Level 5)
- Resolution: Sanitize PII before caching OR skip caching for PII endpoints
- PROCEED: Security wins
Scenario 3: Testing Pure Functions with Time Dependencies
- Conflict: Domain needs current timestamp but should be pure
- Hierarchy: Architecture purity (Level 2) maintained via Time Port (Level 4 idiom)
- Resolution: Inject Clock/Time interface as driven port, mock in tests
- PROCEED: Both satisfied through proper port design
2. Critical Constraints Manifest (Context Triggers)
Agent Note: If the user query touches on these specific topics, prioritize the following internal rules over general knowledge. These are the High-Priority Constraints. Violating these is an automatic failure.
| Topic |
Critical Constraint (Summary) |
| Architecture |
Testability-First Design. Domain is pure, All code must be independently testable. Feature-based packaging. |
| Essential Software Design |
SOLID Principles, Essential Design Practices(DRY, YAGNI, KISS), Code Organization Principles. |
| Error Handling |
JSON format only (code, message, correlationId). No silent failures. No try/catch swallowing. |
| Testing |
70/20/10 Pyramid. Mock Ports, not Internals. Integration tests use real infrastructure (Testcontainers). |
| Concurrency |
Avoid shared memory. Use message passing/channels. Timeout ALL I/O operations. |
| Config |
Hybrid approach: YAML for structure, .env for secrets. Fail fast on missing config. |
| API Design |
Resource-based URLs. Standard HTTP status codes. Envelope response format (data, meta). |
| Security (Auth) |
Deny by default. Server-side checks EVERY request. RBAC/ABAC. MFA for sensitive ops. Rate limit (5/15min). Bcrypt/Argon2 only. |
| Security (Data) |
TLS 1.2+. Encrypt at rest. No secrets in code. PII redacted in logs. |
| Security (Input) |
Validation: Validated Zod/Pydantic Schemas at ALL boundaries. Sanitization: Parameterized queries ONLY. Sanitize output. |
3. Table of Contents
Agent Note: Refer to the sections below for detailed implementation rules on all 16 topics.
Architectural Patterns - Testability-First Design
Core Principle
All code must be independently testable without running the full application or external infrastructure.
Universal Architecture Rules
Rule 1: I/O Isolation
Problem: Tightly coupled I/O makes tests slow, flaky, and environment-dependent.
Solution: Abstract all I/O behind interfaces/contracts:
- Database queries
- HTTP calls (to external APIs)
- File system operations
- Time/randomness (for determinism)
- Message queues
Implementation Discovery:
- Search for existing abstraction patterns:
find_symbol("Interface"), find_symbol("Mock"), find_symbol("Repository")
- Match the style (interface in Go, Protocol in Python, interface in TypeScript)
- Implement production adapter AND test adapter
Example (Go):
// Contract (port)
type UserStore interface {
Create(ctx context.Context, user User) error
GetByEmail(ctx context.Context, email string) (*User, error)
}
// Production adapter
type PostgresUserStore struct { /* ... */ }
// Test adapter
type MockUserStore struct { /* ... */ }
Example (TypeScript/Vue):
// Contract (service layer)
export interface TaskAPI {
createTask(title: string): Promise<Task>;
getTasks(): Promise<Task[]>;
}
// Production adapter
export class EncoreTaskAPI implements TaskAPI { /* ... */ }
// Test adapter (vi.mock or manual)
export class MockTaskAPI implements TaskAPI { /* ... */ }
Rule 2: Pure Business Logic
Problem: Business rules mixed with I/O are impossible to test without infrastructure.
Solution: Extract calculations, validations, transformations into pure functions:
- Input → Output, no side effects
- Deterministic: same input = same output
- No I/O inside business rules
Examples:
// ✅ Pure function - easy to test
func calculateDiscount(items []Item, coupon Coupon) (float64, error) {
// Pure calculation, returns value
}
// ❌ Impure - database call inside
func calculateDiscount(ctx context.Context, items []Item, coupon Coupon) (float64, error) {
validCoupon, err := db.GetCoupon(ctx, coupon.ID) // NO!
}
Correct approach:
// 1. Fetch dependencies first (in handler/service)
validCoupon, err := store.GetCoupon(ctx, coupon.ID)
// 2. Pass to pure logic
discount, err := calculateDiscount(items, validCoupon)
// 3. Persist result
err = store.SaveOrder(ctx, order)
Rule 3: Module Boundaries
Problem: Cross-module coupling makes changes ripple across codebase.
Solution: Feature-based organization with clear public interfaces:
- One feature = one directory
- Each module exposes a public API (exported functions/classes)
- Internal implementation details are private
- Cross-module calls only through public API
Directory Structure (Language-Agnostic):
/task
- public_api.{ext} # Exported interface
- business.{ext} # Pure logic
- store.{ext} # I/O abstraction (interface)
- postgres.{ext} # I/O implementation
- mock.{ext} # Test implementation
- test.{ext} # Unit tests (mocked I/O)
- integration.test.{ext} # Integration tests (real I/O)
Go Example:
/apps/backend/task
- task.go # Encore API endpoints (public)
- business.go # Pure domain logic
- store.go # interface UserStore
- postgres.go # implements UserStore
- task_test.go # Unit tests with MockStore
- task_integration_test.go # Integration with real DB
Vue Example:
/apps/frontend/src/features/task
- index.ts # Public exports
- task.service.ts # Business logic
- task.api.ts # interface TaskAPI
- task.api.encore.ts # implements TaskAPI
- task.store.ts # Pinia store (uses TaskAPI)
- task.service.spec.ts # Unit tests (mock API)
Rule 4: Dependency Direction
Principle: Dependencies point inward toward business logic.
┌─────────────────────────────────────┐
│ Infrastructure Layer │
│ (DB, HTTP, Files, External APIs) │
│ │
│ Depends on ↓ │
└─────────────────────────────────────┘
↓
┌─────────────────────────────────────┐
│ Contracts/Interfaces Layer │
│ (Abstract ports - no implementation)│
│ │
│ Depends on ↓ │
└─────────────────────────────────────┘
↓
┌─────────────────────────────────────┐
│ Business Logic Layer │
│ (Pure functions, domain rules) │
│ NO dependencies on infrastructure │
└─────────────────────────────────────┘
Never:
- Business logic imports database driver
- Domain entities import HTTP framework
- Core calculations import config files
Always:
- Infrastructure implements interfaces defined by business layer
- Business logic receives dependencies via injection
Package Structure Philosophy:
- Organize by FEATURE, not by technical layer
- Each feature is a vertical slice
- Enables modular growth, clear boundaries, and independent deployability
Universal Rule: Context → Feature → Layer
1. Level 1: Repository Scope (Conditional)
- Scenario A (Monorepo/Full-Stack): Root contains
apps/ grouping distinct applications (e.g., apps/backend, apps/web).
- Scenario B (Single Service): Root IS the application. Do not create
apps/backend wrapper. Start directly at Level 2.
2. Level 2: Feature Organization
- Rule: Divide application into vertical business slices (e.g.,
user/, order/, payment/).
- Anti-Pattern: Do NOT organize by technical layer (e.g.,
controllers/, models/, services/) at the top level.
Layout Examples
A. Standard Single Service (Backend, Microservice or MVC)
apps/
task/ # Feature: Task management
task.go # API handlers (public interface)
task_test.go # Unit tests (mocked dependencies)
business.go # Pure business logic
business_test.go # Unit tests (pure functions)
store.go # interface TaskStore
postgres.go # implements TaskStore
postgres_integration_test.go # Integration tests (real DB)
mock_store.go # Test implementation
migrations/
001_create_tasks.up.sql
order/ # Feature: Order management
...
B. Monorepo Layout (Multi-Stack):
*Use this structure when managing monolithic full-stack applications with backend, frontend, mobile in a single repository.
Clear Boundaries: Backend business logic is isolated from Frontend UI logic, even if they share the same repo
apps/
backend/ # Backend application source code
task/ # Feature: Task management
task.go # API handlers (public interface)
...
order/ # Feature: Order management
...
frontend/ # Frontend application source code
assets/ # Fonts, Images
components/ # Shared Component (Buttons, Inputs) - Dumb UI, No Domain Logic
BaseButton.vue
BaseInput.vue
layouts/ # App shells (Sidebar, Navbar wrappers)
utils/ # Date formatting, validation helpers
features/ # Business Features (Vertical Slices)
task/ # Feature: Task management
TaskForm.vue # Feature-specific components
TaskListItem.vue
TaskFilters.vue
index.ts # Public exports
task.service.ts # Business logic
task.api.ts # interface TaskAPI
task.api.encore.ts # Production implementation
task.store.ts # Pinia store
order/
...
This Feature/Domain/UI/API structure is framework-agnostic. It applies equally to React, Vue, Svelte, and Mobile (React Native/Flutter). 'UI' always refers to the framework's native component format (.tsx, .vue, .svelte, .dart).
Pattern Discovery Protocol
Before implementing ANY feature:
- Search existing patterns (MANDATORY):
find_symbol("Interface") OR find_symbol("Repository") OR find_symbol("Service")
- Examine 3 existing modules for consistency:
- How do they handle database access?
- Where are pure functions vs I/O operations?
- What testing patterns exist?
- Document pattern (80%+ consistency required):
- "Following pattern from [task, user, auth] modules"
- "X/Y modules use interface-based stores"
- "All tests use [MockStore, vi.mock, TestingPinia] pattern"
- If consistency <80%: STOP and report fragmentation to human.
Testing Requirements
Unit Tests (must run without infrastructure):
- Mock all I/O dependencies
- Test business logic in isolation
- Fast (<100ms per test)
- 85%+ coverage of business paths
Integration Tests (must test real infrastructure):
- Use real database (Testcontainers, Firebase emulator)
- Test adapter implementations
- Verify contracts work end-to-end
- Cover all I/O adapters
Test Organization:
- Unit/Integration tests: Co-located with implementation
- E2E tests: Separate
/e2e directory
Language-Specific Idioms
How to achieve testability in each ecosystem:
| Language/Framework |
Abstraction Pattern |
Test Strategy |
| Go |
Interface types, dependency injection |
Table-driven tests, mock implementations |
| TypeScript/Vue |
Interface types, service layer, Pinia stores |
Vitest with vi.mock, createTestingPinia |
| TypeScript/React |
Interface types, service layer, Context/hooks |
Jest with mock factories, React Testing Library |
| Python |
typing.Protocol or abstract base classes |
pytest with fixtures, monkeypatch |
| Rust |
Traits, dependency injection |
Unit tests with mock implementations, #[cfg(test)] |
| Flutter/Dart |
Abstract classes, dependency injection |
mockito package, widget tests |
Enforcement Checklist
Before marking code complete, verify:
Related Principles
Core Design Principles
SOLID Principles
Single Responsibility Principle (SRP):
- Each class, module, or function should have ONE and ONLY ONE reason to change
- Generate focused, cohesive units of functionality
- If explaining what something does requires "and", it likely violates SRP
Open/Closed Principle (OCP):
- Software entities should be open for extension but closed for modification
- Design abstractions (interfaces, ports) that allow behavior changes without modifying existing code
- Use composition and dependency injection to enable extensibility
Liskov Substitution Principle (LSP):
- Subtypes must be substitutable for their base types without altering program correctness
- Inheritance hierarchies must maintain behavioral consistency
- If substituting a subclass breaks functionality, LSP is violated
Interface Segregation Principle (ISP):
- Clients should not be forced to depend on interfaces they don't use
- Create focused, role-specific interfaces rather than monolithic ones
- Many small, cohesive interfaces > one large, general-purpose interface
Dependency Inversion Principle (DIP):
- Depend on abstractions (interfaces/ports), not concretions (implementations/adapters)
- High-level modules should not depend on low-level modules; both should depend on abstractions
- Core principle enabling Testability-First architecture
Essential Design Practices
DRY (Don't Repeat Yourself):
- Eliminate code duplication through proper abstraction, shared utilities, composable functions
- Each piece of knowledge should have single, authoritative representation
- Don't duplicate logic, algorithms, or business rules
YAGNI (You Aren't Gonna Need It):
CRITICAL: Code maintainability always prevail
- Avoid implementing functionality before it's actually required
- Don't add features based on speculation about future needs
- Build for today's requirements, refactor when needs change
KISS (Keep It Simple, Stupid):
CRITICAL: Code maintainability always prevail
- Prefer simple(simple to maintain), straightforward solutions over complex, clever ones
- Complexity should be justified by actual requirements, not theoretical flexibility
- Simple code is easier to test, maintain, and debug
Separation of Concerns:
- Divide program functionality into distinct sections with minimal overlap
- Each concern should be isolated in its own module or layer
Composition Over Inheritance:
- Favor object composition and delegation over class inheritance for code reuse
- Composition is more flexible and easier to test
- Use interfaces/traits for polymorphism instead of deep inheritance hierarchies
Principle of Least Astonishment:
- Code should behave in ways that users and maintainers naturally expect
- Avoid surprising or counterintuitive behavior
- Follow established conventions and patterns
Code Organization Principles
- Generate small, focused functions with clear single purposes (typically 10-50 lines)
- Keep cognitive complexity low (cyclomatic complexity < 10 for most functions)
- Maintain clear boundaries between different layers (presentation, business logic, data access)
- Design for testability from the start, avoiding tight coupling that prevents testing
- Apply consistent naming conventions that reveal intent without requiring comments
Error Handling Principles
Error Categories
1. Validation Errors (4xx):
- User input doesn't meet requirements (wrong format, missing fields, out of range)
- Examples: Invalid email, password too short, required field missing
- Response: 400 Bad Request with detailed field-level errors
- User can fix: Yes, by correcting input
2. Business Errors (4xx):
- Domain rule violations (insufficient balance, duplicate email, order already shipped)
- Examples: Can't delete user with active orders, can't process refund after 30 days
- Response: 400/409/422 with business rule explanation
- User can fix: Maybe, depends on business context
3. Authentication Errors (401):
- Identity verification failed (invalid credentials, expired token, missing token)
- Response: 401 Unauthorized
- User can fix: Yes, by providing valid credentials
4. Authorization Errors (403):
- Permission denied (user identified but lacks permission)
- Response: 403 Forbidden
- User can fix: No, requires admin intervention
5. Not Found Errors (404):
- Resource doesn't exist or user lacks permission to know it exists
- Response: 404 Not Found
- User can fix: No
6. Infrastructure Errors (5xx):
- Database down, network timeout, external service failure, out of memory
- Response: 500/502/503 with generic message
- User can fix: No, system issue
Recoverable vs Non-Recoverable Errors
Recoverable (4xx - User can fix):
- Invalid input, missing fields, wrong format
- Action: Allow retry with corrected input
- Response: Detailed error message with guidance
Non-Recoverable (5xx - System issue):
- Database down, disk full, out of memory
- Action: Log details, alert ops team, return safe generic error
- Response: Generic message, correlation ID for support
Universal Error Handling Principles
1. Never Fail Silently:
- All errors must be handled explicitly (no empty catch blocks)
- If you catch an error, do something with it (log, return, transform, retry)
2. Fail Fast:
- Detect and report errors as early as possible
- Validate at system boundaries before processing
- Don't process invalid data hoping it'll work out
3. Provide Context:
- Include error codes, correlation IDs, actionable messages
- Enough information for debugging without exposing sensitive details
- Example: "Database query failed (correlation-id: abc-123)" not "SELECT * FROM users WHERE..."
4. Separate Concerns:
- Different handlers for different error types
- Business errors ≠ technical errors ≠ security errors
5. Resource Cleanup:
- Always clean up in error scenarios (close files, release connections, unlock resources)
- Use language-appropriate patterns (defer, finally, RAII, context managers)
6. No Information Leakage:
- Sanitize error messages for external consumption
- Don't expose stack traces, SQL queries, file paths, internal structure to users
- Log full details internally, show generic message externally
Application Error Object (Internal/Log Format)
{
"status": "error",
"code": "VALIDATION_ERROR",
"message": "User-friendly error message",
"correlationId": "uuid-for-tracking",
"details": {
"field": "email",
"issue": "Invalid email format",
"provided": "invalid-email",
"expected": "valid email format (user@example.com)"
}
}
Error Handling Checklist
Related Principles
Concurrency and Threading Principles
When to Use Concurrency
I/O-Bound Operations (async/await, event loops):
- Network requests, file I/O, database queries
- Waiting for external responses dominates execution time
- Use: Asynchronous I/O, event-driven concurrency, coroutines
CPU-Bound Operations (threads, parallel processing):
- Heavy computation, data processing, video encoding
- CPU cycles dominate execution time
- Use: OS threads, thread pools, parallel workers
Don't Over-Use Concurrency:
- Adds significant complexity (race conditions, deadlocks, debugging difficulty)
- Use only when there's measurable performance benefit
- Profile first, optimize second
Universal Concurrency Principles
1. Avoid Race Conditions
What is a race condition:
- Multiple threads access shared data concurrently
- At least one thread writes/modifies the data
- No synchronization mechanism in place
- Result depends on unpredictable thread execution timing
Prevention strategies:
- Synchronization: Locks, mutexes, semaphores
- Immutability: Immutable data is thread-safe by default
- Message passing: Send data between threads instead of sharing
- Thread-local storage: Each thread has its own copy
Detection:
- Go: Run with
-race flag (race detector)
- Rust: Miri tool for undefined behavior detection
- C/C++: ThreadSanitizer (TSan)
- Java: JCStress, FindBugs
2. Prevent Deadlocks
What is a deadlock:
- Two or more threads waiting for each other indefinitely
- Example: Thread A holds Lock 1, waits for Lock 2; Thread B holds Lock 2, waits for Lock 1
Four conditions (ALL must be true for deadlock):
- Mutual exclusion: Resources held exclusively (locks)
- Hold and wait: Holding one resource while waiting for another
- No preemption: Can't force unlock
- Circular wait: A waits for B, B waits for A
Prevention (break any one condition):
- Lock ordering: Always acquire locks in same order
- Timeout: Use try_lock with timeout, back off and retry
- Avoid nested locks: Don't hold multiple locks simultaneously
- Use lock-free data structures when possible
3. Prefer Immutability
- Immutable data = thread-safe by default (no synchronization needed)
- Share immutable data freely between threads
- Use immutable data structures where possible (Rust default, functional languages)
- If data must change, use message passing instead of shared mutable state
4. Message Passing Over Shared Memory
- "Don't communicate by sharing memory; share memory by communicating" (Go proverb)
- Send data through channels/queues instead of accessing shared memory
- Reduces need for locks and synchronization
- Easier to reason about and test
5. Graceful Degradation
- Handle concurrency errors gracefully (timeouts, retries, circuit breakers)
- Don't crash entire application on one thread failure
- Use supervisors/monitors for fault tolerance (Erlang/Elixir actor model)
- Implement backpressure for producer-consumer scenarios
Concurrency Models by Use Case
- I/O-bound: async/await, event loops, coroutines, green threads
- CPU-bound: OS threads, thread pools, parallel processing
- Actor model: Erlang/Elixir actors, Akka (message passing, isolated state)
- CSP (Communicating Sequential Processes): Go channels, Rust channels
Testing Concurrent Code
- Write unit tests with controlled concurrency (deterministic execution)
- Test timeout scenarios and resource exhaustion
- Test thread pool full, queue full scenarios
Related Principles
Resource and Memory Management Principles
Universal Resource Management Rules
1. Always Clean Up Resources
Resources requiring cleanup:
- Files, network connections, database connections
- Locks, semaphores, mutexes
- Memory allocations (in manual-memory languages)
- OS handles, GPU resources
Clean up in ALL paths:
- Success path: Normal completion
- Error path: Exception thrown, error returned
- Early return path: Guard clauses, validation failures
Use language-appropriate patterns:
- Go: defer statements
- Rust: Drop trait (RAII)
- Python: context managers (with statement)
- TypeScript: try/finally
- Java: try-with-resources
2. Timeout All I/O Operations
Why timeout:
- Network requests can hang indefinitely
- Prevents resource exhaustion (connections, threads)
- Provides predictable failure behavior
Timeout recommendations:
- Network requests: 30s default, shorter (5-10s) for interactive
- Database queries: 10s default, configure per query complexity
- File operations: Usually fast, but timeout on network filesystems
- Message queue operations: Configurable, avoid indefinite blocking
3. Pool Expensive Resources
Resources to pool:
- Database connections: Pool size 5-20 per app instance
- HTTP connections: Reuse with keep-alive
- Thread pools: Size based on CPU count (CPU-bound) or I/O wait (I/O-bound)
Benefits:
- Reduces latency (no connection setup overhead)
- Limits resource consumption (cap on max connections)
- Improves throughput (reuse vs create new)
Connection Pool Best Practices:
- Minimum connections: 5 (ensures pool is warm)
- Maximum connections: 20-50 (prevents overwhelming database)
- Idle timeout: Close connections idle >5-10 minutes
- Validation: Test connections before use (avoid broken connections)
- Monitoring: Track utilization, wait times, timeout rates
4. Avoid Resource Leaks
What is a leak:
- Acquire resource (open file, allocate memory, get connection)
- Never release it (forget to close, exception prevents cleanup)
- Eventually exhaust system resources (OOM, max connections, file descriptors)
Detection:
- Monitor open file descriptors, connection counts, memory usage over time
- Run long-duration tests, verify resource counts stay stable
- Use leak detection tools (valgrind, ASan, heap profilers)
Prevention:
- Use language patterns that guarantee cleanup (RAII, defer, context managers)
- Never rely on manual cleanup alone (use language features)
5. Handle Backpressure
Problem: Producer faster than consumer
- Queue grows unbounded → memory exhaustion
- System becomes unresponsive under load
Solutions:
- Bounded queues: Fixed size, block or reject when full
- Rate limiting: Limit incoming request rate
- Flow control: Consumer signals producer to slow down
- Circuit breakers: Stop accepting requests when overwhelmed
- Drop/reject: Fail fast when overloaded (better than crashing)
Memory Management by Language Type
Garbage Collected (Go, Java, Python, JavaScript, C#):
- Memory automatically freed by GC
- Still must release non-memory resources (files, connections, locks)
- Be aware of GC pauses in latency-sensitive applications
- Profile memory usage to find leaks (retained references preventing GC)
Manual Memory Management (C, C++):
- Explicit malloc/free or new/delete
- Use RAII pattern in C++ (Resource Acquisition Is Initialization)
- Avoid manual management in modern C++ (use smart pointers: unique_ptr, shared_ptr)
Ownership-Based (Rust):
- Compiler enforces memory safety at compile time
- No GC pauses, no manual management
- Ownership rules prevent leaks and use-after-free automatically
- Use reference counting (Arc, Rc) for shared ownership
Related Principles
API Design Principles
RESTful API Standards
Resource-Based URLs:
- Use plural nouns for resources:
/api/{version}/users, /api/{version}/orders
- Hierarchical relationships:
/api/{version}/users/:userId/orders
- Avoid verbs in URLs:
/api/{version}/getUser ❌ → /api/{version}/users/:id ✅
HTTP Methods:
- GET: Read/retrieve resource (safe, idempotent, cacheable)
- POST: Create new resource (not idempotent)
- PUT: Replace entire resource (idempotent)
- PATCH: Partial update (idempotent)
- DELETE: Remove resource (idempotent)
HTTP Status Codes:
- 200 OK: Success (GET, PUT, PATCH)
- 201 Created: Resource created successfully (POST)
- 204 No Content: Success with no response body (DELETE)
- 400 Bad Request: Invalid input, validation failure
- 401 Unauthorized: Authentication required or failed
…(truncated)
1---2name: technical-constitution3description: Generates technical implementation plans and architectural strategies that enforce the Project Constitution. Use when designing new features, starting implementation tasks, refactoring code, or ensuring compliance with critical standards like Testability-First Architecture, security mandates, testing strategies, and error handling.4---56# The Constitution: Technical Preference Universal Principles78**⚖️ CRITICAL GOVERNANCE NOTICE**910**CRITICAL:** BEFORE doing ANYTHING else, Read and Comprehend this document COMPLETELY.1112MANDATORY COMPLIANCE CHECK:1314Before executing your task, you must perform a "Constitution Lookup":15161. **IDENTIFY** the domain of your task (e.g., API, DB, Auth, logging, etc.). 172. **SEARCH** the relevant sections (e.g., grep "API Design"). 183. **REVIEW** Critical Constraints table for domain194. **VERIFY** your plan against the discipline and constraints before proceeding.2021## 1. The Supremacy Clause & Conflict Resolution2223When directives conflict or seem impossible to satisfy simultaneously, follow this precedence:24251. **Security Principles** [Non-Negotiable]26 - OWASP Top 10 compliance27 - Input validation and sanitization28 - Authentication and authorization29 - Secrets management30 - No information leakage31 - **Action:** Security ALWAYS wins. Refactor other requirements to satisfy security.32332. **Testability & Modularity** [Structural Law]34 - I/O isolation (dependencies mockable in tests)35 - Pure business logic (no side effects in core logic)36 - Clear module boundaries with contracts37 - **Action:** If code cannot be unit tested without external dependencies, refactor to add abstraction layer.38393. **Error Handling Standards** [Reliability Law]40 - No silent failures41 - Correlation IDs required42 - JSON envelope format43 - Resource cleanup in all paths44 - **Action:** All error paths must be explicit. No exceptions.45464. **Language Idioms** [Implementation Preference]47 - Use native patterns (defer, RAII, context managers)48 - Follow community conventions49 - Leverage standard library50 - **Action:** Implement above laws idiomatically, don't blindly copy other languages.51525. **Performance Optimizations** [Measure First]53 - Appropriate data structures54 - Profile before optimizing55 - Caching strategies56 - **Action:** Only optimize with measured bottlenecks. Correctness > speed5758### Escalation Protocol5960**If following a directive is impossible:**61621. **STOP coding immediately**632. **Document the conflict:**64 - Which directives conflict?65 - Why is compliance impossible?66 - What are the tradeoffs?673. **Propose alternatives:**68 - Option A: [approach + which rules satisfied/violated]69 - Option B: [approach + which rules satisfied/violated]70 - ...714. **ASK human for decision**72 - Present the precedence hierarchy73 - Recommend least-harmful deviation option with justification based on hierarchy74 - Wait for explicit approval7576**CRITICAL: NEVER silently violate**, If following directive is impossible, **STOP** and ask human7778#### Example:7980**Scenario 1: Framework Requires Inheritance (Architecture vs Language Idiom)**81- Conflict: Django ORM requires model inheritance, but domain must be pure82- Hierarchy: Architecture (Level 2) > Framework idiom (Level 4)83- Resolution: Create Database Model (inherits ORM) + Pure Domain Entity + Mapper pattern84- PROCEED: Architecture wins8586**Scenario 2: Performance vs Security**87- Conflict: Caching would speed up response but contains PII88- Hierarchy: Security (Level 1) > Performance (Level 5)89- Resolution: Sanitize PII before caching OR skip caching for PII endpoints90- PROCEED: Security wins9192**Scenario 3: Testing Pure Functions with Time Dependencies**93- Conflict: Domain needs current timestamp but should be pure94- Hierarchy: Architecture purity (Level 2) maintained via Time Port (Level 4 idiom)95- Resolution: Inject Clock/Time interface as driven port, mock in tests96- PROCEED: Both satisfied through proper port design9798## 2. Critical Constraints Manifest (Context Triggers)99100*Agent Note: If the user query touches on these specific topics, prioritize the following internal rules over general knowledge. These are the High-Priority Constraints. Violating these is an automatic failure.*101102| Topic | Critical Constraint (Summary) |103| :---- | :---- |104| **Architecture** | Testability-First Design. Domain is pure, All code must be independently testable. Feature-based packaging. |105| **Essential Software Design** | SOLID Principles, Essential Design Practices(DRY, YAGNI, KISS), Code Organization Principles. |106| **Error Handling** | JSON format only (`code`, `message`, `correlationId`). No silent failures. No `try/catch` swallowing. |107| **Testing** | 70/20/10 Pyramid. Mock Ports, not Internals. Integration tests use real infrastructure (Testcontainers). |108| **Concurrency** | Avoid shared memory. Use message passing/channels. Timeout ALL I/O operations. |109| **Config** | Hybrid approach: YAML for structure, `.env` for secrets. Fail fast on missing config. |110| **API Design** | Resource-based URLs. Standard HTTP status codes. Envelope response format (`data`, `meta`). |111| **Security (Auth)** | Deny by default. Server-side checks EVERY request. RBAC/ABAC. MFA for sensitive ops. Rate limit (5/15min). Bcrypt/Argon2 only. |112| **Security (Data)** | TLS 1.2+. Encrypt at rest. No secrets in code. PII redacted in logs. |113| **Security (Input)** | **Validation:** Validated Zod/Pydantic Schemas at ALL boundaries. **Sanitization:** Parameterized queries ONLY. Sanitize output. |114115## 3. Table of Contents116117*Agent Note: Refer to the sections below for detailed implementation rules on all 16 topics.*118119- [The Constitution: Technical Preference Universal Principles](#the-constitution-technical-preference-universal-principles)120 - [1. The Supremacy Clause \& Conflict Resolution](#1-the-supremacy-clause--conflict-resolution)121 - [Escalation Protocol](#escalation-protocol)122 - [Example:](#example)123 - [2. Critical Constraints Manifest (Context Triggers)](#2-critical-constraints-manifest-context-triggers)124 - [3. Table of Contents](#3-table-of-contents)125 - [Architectural Patterns - Testability-First Design](#architectural-patterns---testability-first-design)126 - [Core Principle](#core-principle)127 - [Universal Architecture Rules](#universal-architecture-rules)128 - [Rule 1: I/O Isolation](#rule-1-io-isolation)129 - [Rule 2: Pure Business Logic](#rule-2-pure-business-logic)130 - [Rule 3: Module Boundaries](#rule-3-module-boundaries)131 - [Rule 4: Dependency Direction](#rule-4-dependency-direction)132 - [Layout Examples](#layout-examples)133 - [Pattern Discovery Protocol](#pattern-discovery-protocol)134 - [Testing Requirements](#testing-requirements)135 - [Language-Specific Idioms](#language-specific-idioms)136 - [Enforcement Checklist](#enforcement-checklist)137 - [Related Principles](#related-principles)138 - [Core Design Principles](#core-design-principles)139 - [SOLID Principles](#solid-principles)140 - [Essential Design Practices](#essential-design-practices)141 - [Code Organization Principles](#code-organization-principles)142 - [Error Handling Principles](#error-handling-principles)143 - [Error Categories](#error-categories)144 - [Recoverable vs Non-Recoverable Errors](#recoverable-vs-non-recoverable-errors)145 - [Universal Error Handling Principles](#universal-error-handling-principles)146 - [Application Error Object (Internal/Log Format)](#application-error-object-internallog-format)147 - [Error Handling Checklist](#error-handling-checklist)148 - [Related Principles](#related-principles-1)149 - [Concurrency and Threading Principles](#concurrency-and-threading-principles)150 - [When to Use Concurrency](#when-to-use-concurrency)151 - [Universal Concurrency Principles](#universal-concurrency-principles)152 - [Concurrency Models by Use Case](#concurrency-models-by-use-case)153 - [Testing Concurrent Code](#testing-concurrent-code)154 - [Related Principles](#related-principles-2)155 - [Resource and Memory Management Principles](#resource-and-memory-management-principles)156 - [Universal Resource Management Rules](#universal-resource-management-rules)157 - [Memory Management by Language Type](#memory-management-by-language-type)158 - [Related Principles](#related-principles-3)159 - [API Design Principles](#api-design-principles)160 - [RESTful API Standards](#restful-api-standards)161 - [Related Principles](#related-principles-4)162 - [Testing Strategy](#testing-strategy)163 - [Test Pyramid](#test-pyramid)164 - [Test-Driven Development (TDD)](#test-driven-development-tdd)165 - [Test Doubles Strategy](#test-doubles-strategy)166 - [Test Organization](#test-organization)167 - [A. Backend (Go - Feature-Based)](#a-backend-go---feature-based)168 - [B. Frontend (Vue - Feature-Sliced)](#b-frontend-vue---feature-sliced)169 - [C. Monorepo (Multi-Stack)](#c-monorepo-multi-stack)170 - [Test Quality Standards](#test-quality-standards)171 - [Related Principles](#related-principles-5)172 - [Configuration Management Principles](#configuration-management-principles)173 - [Separation of Configuration and Code](#separation-of-configuration-and-code)174 - [Configuration Validation](#configuration-validation)175 - [Configuration Hierarchy](#configuration-hierarchy)176 - [Configuration Organization](#configuration-organization)177 - [Related Principles](#related-principles-6)178 - [Performance Optimization Principles](#performance-optimization-principles)179 - [Measure Before Optimizing](#measure-before-optimizing)180 - [Choose Appropriate Data Structures](#choose-appropriate-data-structures)181 - [Avoid Premature Abstraction](#avoid-premature-abstraction)182 - [Optimization Techniques](#optimization-techniques)183 - [Data Serialization and Interchange Principles](#data-serialization-and-interchange-principles)184 - [Validate at System Boundaries](#validate-at-system-boundaries)185 - [Handle Encoding Explicitly](#handle-encoding-explicitly)186 - [Serialization Format Selection](#serialization-format-selection)187 - [Security Considerations](#security-considerations)188 - [Related Principles](#related-principles-7)189 - [Logging and Observability Principles](#logging-and-observability-principles)190 - [Logging Standards](#logging-standards)191 - [Log Levels (Standard Priority)](#log-levels-standard-priority)192 - [Logging Rules](#logging-rules)193 - [Language-Specific Implementations](#language-specific-implementations)194 - [Go (using slog standard library)](#go-using-slog-standard-library)195 - [TypeScript/Node.js (using pino)](#typescriptnodejs-using-pino)196 - [Python (using structlog)](#python-using-structlog)197 - [Log Patterns by Operation Type](#log-patterns-by-operation-type)198 - [API Request/Response](#api-requestresponse)199 - [Database Operations](#database-operations)200 - [External API Calls](#external-api-calls)201 - [Background Jobs](#background-jobs)202 - [Error Scenarios](#error-scenarios)203 - [Environment-Specific Configuration](#environment-specific-configuration)204 - [Testing Logs](#testing-logs)205 - [Monitoring Integration](#monitoring-integration)206 - [Checklist for Every Feature](#checklist-for-every-feature)207 - [Observability Strategy](#observability-strategy)208 - [Related Principles](#related-principles-8)209 - [Code Idioms and Conventions](#code-idioms-and-conventions)210 - [Universal Principle](#universal-principle)211 - [Idiomatic Code Characteristics](#idiomatic-code-characteristics)212 - [Avoid Cross-Language Anti-Patterns](#avoid-cross-language-anti-patterns)213 - [Dependency Management Principles](#dependency-management-principles)214 - [Version Pinning](#version-pinning)215 - [Minimize Dependencies](#minimize-dependencies)216 - [Organize Imports](#organize-imports)217 - [Avoid Circular Dependencies](#avoid-circular-dependencies)218 - [Command Execution Principles](#command-execution-principles)219 - [Security](#security)220 - [Portability](#portability)221 - [Error Handling](#error-handling)222 - [Related Principles](#related-principles-9)223 - [Documentation Principles](#documentation-principles)224 - [Self-Documenting Code](#self-documenting-code)225 - [Documentation Levels](#documentation-levels)226 - [Security Principles](#security-principles)227 - [OWASP Top 10 Enforcement](#owasp-top-10-enforcement)228 - [Authentication \& Authorization](#authentication--authorization)229 - [Input Validation \& Sanitization](#input-validation--sanitization)230 - [Logging \& Monitoring (Security Focus)](#logging--monitoring-security-focus)231 - [Secrets Management](#secrets-management)232 - [Related Principles](#related-principles-10)233234## Architectural Patterns - Testability-First Design235236### Core Principle237All code must be independently testable without running the full application or external infrastructure.238239### Universal Architecture Rules240241#### Rule 1: I/O Isolation242**Problem:** Tightly coupled I/O makes tests slow, flaky, and environment-dependent.243244**Solution:** Abstract all I/O behind interfaces/contracts:245- Database queries246- HTTP calls (to external APIs)247- File system operations248- Time/randomness (for determinism)249- Message queues250251**Implementation Discovery:**2521. Search for existing abstraction patterns: `find_symbol("Interface")`, `find_symbol("Mock")`, `find_symbol("Repository")`2532. Match the style (interface in Go, Protocol in Python, interface in TypeScript)2543. Implement production adapter AND test adapter255256**Example (Go):**257258```Go259260// Contract (port)261type UserStore interface {262 Create(ctx context.Context, user User) error263 GetByEmail(ctx context.Context, email string) (*User, error)264}265266// Production adapter267type PostgresUserStore struct { /* ... */ }268269// Test adapter270type MockUserStore struct { /* ... */ }271```272273**Example (TypeScript/Vue):**274```typescript275276// Contract (service layer)277export interface TaskAPI {278 createTask(title: string): Promise<Task>;279 getTasks(): Promise<Task[]>;280}281282// Production adapter283export class EncoreTaskAPI implements TaskAPI { /* ... */ }284285// Test adapter (vi.mock or manual)286export class MockTaskAPI implements TaskAPI { /* ... */ }287288```289290#### Rule 2: Pure Business Logic291**Problem:** Business rules mixed with I/O are impossible to test without infrastructure.292293**Solution:** Extract calculations, validations, transformations into pure functions:294- Input → Output, no side effects295- Deterministic: same input = same output296- No I/O inside business rules297298**Examples:**299```300301// ✅ Pure function - easy to test302func calculateDiscount(items []Item, coupon Coupon) (float64, error) {303// Pure calculation, returns value304}305306// ❌ Impure - database call inside307func calculateDiscount(ctx context.Context, items []Item, coupon Coupon) (float64, error) {308validCoupon, err := db.GetCoupon(ctx, coupon.ID) // NO!309}310311```312313**Correct approach:**314```315316// 1. Fetch dependencies first (in handler/service)317validCoupon, err := store.GetCoupon(ctx, coupon.ID)318319// 2. Pass to pure logic320discount, err := calculateDiscount(items, validCoupon)321322// 3. Persist result323err = store.SaveOrder(ctx, order)324325```326327#### Rule 3: Module Boundaries328**Problem:** Cross-module coupling makes changes ripple across codebase.329330**Solution:** Feature-based organization with clear public interfaces:331- One feature = one directory332- Each module exposes a public API (exported functions/classes)333- Internal implementation details are private334- Cross-module calls only through public API335336**Directory Structure (Language-Agnostic):**337```338339/task340341- public_api.{ext} # Exported interface342- business.{ext} # Pure logic343- store.{ext} # I/O abstraction (interface)344- postgres.{ext} # I/O implementation345- mock.{ext} # Test implementation346- test.{ext} # Unit tests (mocked I/O)347- integration.test.{ext} # Integration tests (real I/O)348349```350351**Go Example:**352```353354/apps/backend/task355356- task.go # Encore API endpoints (public)357- business.go # Pure domain logic358- store.go # interface UserStore359- postgres.go # implements UserStore360- task_test.go # Unit tests with MockStore361- task_integration_test.go # Integration with real DB362363```364365**Vue Example:**366```367368/apps/frontend/src/features/task369370- index.ts # Public exports371- task.service.ts # Business logic372- task.api.ts # interface TaskAPI373- task.api.encore.ts # implements TaskAPI374- task.store.ts # Pinia store (uses TaskAPI)375- task.service.spec.ts # Unit tests (mock API)376377```378379#### Rule 4: Dependency Direction380**Principle:** Dependencies point inward toward business logic.381382```383384┌─────────────────────────────────────┐385│ Infrastructure Layer │386│ (DB, HTTP, Files, External APIs) │387│ │388│ Depends on ↓ │389└─────────────────────────────────────┘390↓391┌─────────────────────────────────────┐392│ Contracts/Interfaces Layer │393│ (Abstract ports - no implementation)│394│ │395│ Depends on ↓ │396└─────────────────────────────────────┘397↓398┌─────────────────────────────────────┐399│ Business Logic Layer │400│ (Pure functions, domain rules) │401│ NO dependencies on infrastructure │402└─────────────────────────────────────┘403404```405406**Never:**407- Business logic imports database driver408- Domain entities import HTTP framework409- Core calculations import config files410411**Always:**412- Infrastructure implements interfaces defined by business layer413- Business logic receives dependencies via injection414415**Package Structure Philosophy:**416417- **Organize by FEATURE, not by technical layer** 418- Each feature is a vertical slice419- Enables modular growth, clear boundaries, and independent deployability 420421**Universal Rule: Context → Feature → Layer**422423**1. Level 1: Repository Scope (Conditional)**424 - **Scenario A (Monorepo/Full-Stack):** Root contains `apps/` grouping distinct applications (e.g., `apps/backend`, `apps/web`).425 - **Scenario B (Single Service):** Root **IS** the application. Do not create `apps/backend` wrapper. Start directly at Level 2.426427**2. Level 2: Feature Organization**428 - **Rule:** Divide application into vertical business slices (e.g., `user/`, `order/`, `payment/`).429 - **Anti-Pattern:** Do NOT organize by technical layer (e.g., `controllers/`, `models/`, `services/`) at the top level.430431#### Layout Examples432433**A. Standard Single Service (Backend, Microservice or MVC)**434```435 apps/ 436 task/ # Feature: Task management 437 task.go # API handlers (public interface)438 task_test.go # Unit tests (mocked dependencies)439 business.go # Pure business logic440 business_test.go # Unit tests (pure functions)441 store.go # interface TaskStore442 postgres.go # implements TaskStore443 postgres_integration_test.go # Integration tests (real DB)444 mock_store.go # Test implementation445 migrations/446 001_create_tasks.up.sql447 order/ # Feature: Order management 448 ...449```450451**B. Monorepo Layout (Multi-Stack):**452**Use this structure when managing monolithic full-stack applications with backend, frontend, mobile in a single repository.*453*Clear Boundaries: Backend business logic is isolated from Frontend UI logic, even if they share the same repo*454``` 455 apps/456 backend/ # Backend application source code 457 task/ # Feature: Task management 458 task.go # API handlers (public interface)459 ... 460 order/ # Feature: Order management 461 ...462 frontend/ # Frontend application source code463 assets/ # Fonts, Images464 components/ # Shared Component (Buttons, Inputs) - Dumb UI, No Domain Logic465 BaseButton.vue466 BaseInput.vue467 layouts/ # App shells (Sidebar, Navbar wrappers)468 utils/ # Date formatting, validation helpers469 features/ # Business Features (Vertical Slices)470 task/ # Feature: Task management471 TaskForm.vue # Feature-specific components472 TaskListItem.vue 473 TaskFilters.vue 474 index.ts # Public exports475 task.service.ts # Business logic476 task.api.ts # interface TaskAPI477 task.api.encore.ts # Production implementation478 task.store.ts # Pinia store479 order/480 ...481```482> This Feature/Domain/UI/API structure is framework-agnostic. It applies equally to React, Vue, Svelte, and Mobile (React Native/Flutter). 'UI' always refers to the framework's native component format (.tsx, .vue, .svelte, .dart).483484### Pattern Discovery Protocol485486**Before implementing ANY feature:**4874881. **Search existing patterns** (MANDATORY):489```490491find_symbol("Interface") OR find_symbol("Repository") OR find_symbol("Service")492493```4944952. **Examine 3 existing modules** for consistency:496- How do they handle database access?497- Where are pure functions vs I/O operations?498- What testing patterns exist?4995003. **Document pattern** (80%+ consistency required):501- "Following pattern from [task, user, auth] modules"502- "X/Y modules use interface-based stores"503- "All tests use [MockStore, vi.mock, TestingPinia] pattern"5045054. **If consistency <80%**: STOP and report fragmentation to human.506507### Testing Requirements508509**Unit Tests (must run without infrastructure):**510- Mock all I/O dependencies511- Test business logic in isolation512- Fast (<100ms per test)513- 85%+ coverage of business paths514515**Integration Tests (must test real infrastructure):**516- Use real database (Testcontainers, Firebase emulator)517- Test adapter implementations518- Verify contracts work end-to-end519- Cover all I/O adapters520521**Test Organization:**522- Unit/Integration tests: Co-located with implementation523- E2E tests: Separate `/e2e` directory524525### Language-Specific Idioms526527**How to achieve testability in each ecosystem:**528529| Language/Framework | Abstraction Pattern | Test Strategy |530|-------------------|---------------------|---------------|531| **Go** | Interface types, dependency injection | Table-driven tests, mock implementations |532| **TypeScript/Vue** | Interface types, service layer, Pinia stores | Vitest with `vi.mock`, `createTestingPinia` |533| **TypeScript/React** | Interface types, service layer, Context/hooks | Jest with mock factories, React Testing Library |534| **Python** | `typing.Protocol` or abstract base classes | pytest with fixtures, monkeypatch |535| **Rust** | Traits, dependency injection | Unit tests with mock implementations, `#[cfg(test)]` |536| **Flutter/Dart** | Abstract classes, dependency injection | `mockito` package, widget tests |537538### Enforcement Checklist539540Before marking code complete, verify:541- [ ] Can I run unit tests without starting database/external services?542- [ ] Are all I/O operations behind an abstraction?543- [ ] Is business logic pure (no side effects)?544- [ ] Do integration tests exist for all adapters?545- [ ] Does pattern match existing codebase (80%+ consistency)?546547### Related Principles548- [SOLID: Dependency Inversion](#dependency-inversion-principle-dip) - Ports as abstractions549- [Testing: Mock Ports Strategy](#test-doubles-strategy) - Unit test isolation550- [Code Organization: Feature Packaging](#code-organization-principles) - Vertical slices551- [Dependency Management: Avoid Circular](#avoid-circular-dependencies) - Layer separation552553554## Core Design Principles555556### SOLID Principles557558**Single Responsibility Principle (SRP):**559560- Each class, module, or function should have ONE and ONLY ONE reason to change 561- Generate focused, cohesive units of functionality 562- If explaining what something does requires "and", it likely violates SRP563564**Open/Closed Principle (OCP):**565566- Software entities should be open for extension but closed for modification 567- Design abstractions (interfaces, ports) that allow behavior changes without modifying existing code 568- Use composition and dependency injection to enable extensibility569570**Liskov Substitution Principle (LSP):**571572- Subtypes must be substitutable for their base types without altering program correctness 573- Inheritance hierarchies must maintain behavioral consistency 574- If substituting a subclass breaks functionality, LSP is violated575576**Interface Segregation Principle (ISP):**577578- Clients should not be forced to depend on interfaces they don't use 579- Create focused, role-specific interfaces rather than monolithic ones 580- Many small, cohesive interfaces > one large, general-purpose interface581582**Dependency Inversion Principle (DIP):**583584- Depend on abstractions (interfaces/ports), not concretions (implementations/adapters) 585- High-level modules should not depend on low-level modules; both should depend on abstractions 586- Core principle enabling Testability-First architecture587588### Essential Design Practices589590**DRY (Don't Repeat Yourself):**591592- Eliminate code duplication through proper abstraction, shared utilities, composable functions 593- Each piece of knowledge should have single, authoritative representation 594- Don't duplicate logic, algorithms, or business rules595596**YAGNI (You Aren't Gonna Need It):**597598**CRITICAL:** Code maintainability always prevail599600- Avoid implementing functionality before it's actually required 601- Don't add features based on speculation about future needs 602- Build for today's requirements, refactor when needs change603604**KISS (Keep It Simple, Stupid):**605606**CRITICAL:** Code maintainability always prevail607608- Prefer simple(simple to maintain), straightforward solutions over complex, clever ones 609- Complexity should be justified by actual requirements, not theoretical flexibility 610- Simple code is easier to test, maintain, and debug611612**Separation of Concerns:**613614- Divide program functionality into distinct sections with minimal overlap 615- Each concern should be isolated in its own module or layer 616617**Composition Over Inheritance:**618619- Favor object composition and delegation over class inheritance for code reuse 620- Composition is more flexible and easier to test 621- Use interfaces/traits for polymorphism instead of deep inheritance hierarchies622623**Principle of Least Astonishment:**624625- Code should behave in ways that users and maintainers naturally expect 626- Avoid surprising or counterintuitive behavior 627- Follow established conventions and patterns628629### Code Organization Principles630631- Generate small, focused functions with clear single purposes (typically 10-50 lines) 632- Keep cognitive complexity low (cyclomatic complexity < 10 for most functions) 633- Maintain clear boundaries between different layers (presentation, business logic, data access) 634- Design for testability from the start, avoiding tight coupling that prevents testing 635- Apply consistent naming conventions that reveal intent without requiring comments636637## Error Handling Principles638639### Error Categories640641**1. Validation Errors (4xx):**642643- User input doesn't meet requirements (wrong format, missing fields, out of range) 644- Examples: Invalid email, password too short, required field missing 645- Response: 400 Bad Request with detailed field-level errors 646- User can fix: Yes, by correcting input647648**2. Business Errors (4xx):**649650- Domain rule violations (insufficient balance, duplicate email, order already shipped) 651- Examples: Can't delete user with active orders, can't process refund after 30 days 652- Response: 400/409/422 with business rule explanation 653- User can fix: Maybe, depends on business context654655**3. Authentication Errors (401):**656657- Identity verification failed (invalid credentials, expired token, missing token) 658- Response: 401 Unauthorized 659- User can fix: Yes, by providing valid credentials660661**4. Authorization Errors (403):**662663- Permission denied (user identified but lacks permission) 664- Response: 403 Forbidden 665- User can fix: No, requires admin intervention666667**5. Not Found Errors (404):**668669- Resource doesn't exist or user lacks permission to know it exists 670- Response: 404 Not Found 671- User can fix: No672673**6. Infrastructure Errors (5xx):**674675- Database down, network timeout, external service failure, out of memory 676- Response: 500/502/503 with generic message 677- User can fix: No, system issue678679### Recoverable vs Non-Recoverable Errors680681**Recoverable (4xx - User can fix):**682683- Invalid input, missing fields, wrong format 684- Action: Allow retry with corrected input 685- Response: Detailed error message with guidance686687**Non-Recoverable (5xx - System issue):**688689- Database down, disk full, out of memory 690- Action: Log details, alert ops team, return safe generic error 691- Response: Generic message, correlation ID for support692693### Universal Error Handling Principles694695**1. Never Fail Silently:**696697- All errors must be handled explicitly (no empty catch blocks) 698- If you catch an error, do something with it (log, return, transform, retry)699700**2. Fail Fast:**701702- Detect and report errors as early as possible 703- Validate at system boundaries before processing 704- Don't process invalid data hoping it'll work out705706**3. Provide Context:**707708- Include error codes, correlation IDs, actionable messages 709- Enough information for debugging without exposing sensitive details 710- Example: "Database query failed (correlation-id: abc-123)" not "SELECT * FROM users WHERE..."711712**4. Separate Concerns:**713714- Different handlers for different error types 715- Business errors ≠ technical errors ≠ security errors716717**5. Resource Cleanup:**718719- Always clean up in error scenarios (close files, release connections, unlock resources) 720- Use language-appropriate patterns (defer, finally, RAII, context managers)721722**6. No Information Leakage:**723724- Sanitize error messages for external consumption 725- Don't expose stack traces, SQL queries, file paths, internal structure to users 726- Log full details internally, show generic message externally727728### Application Error Object (Internal/Log Format)729```730{731 "status": "error",732 "code": "VALIDATION_ERROR",733 "message": "User-friendly error message",734 "correlationId": "uuid-for-tracking",735 "details": {736 "field": "email",737 "issue": "Invalid email format",738 "provided": "invalid-email",739 "expected": "valid email format (user@example.com)"740 }741}742```743744### Error Handling Checklist745746- [ ] Are all error paths explicitly handled (no empty catch blocks)? 747- [ ] Do errors include correlation IDs for debugging? 748- [ ] Are sensitive details sanitized before returning to client? 749- [ ] Are resources cleaned up in all error scenarios? 750- [ ] Are errors logged at appropriate levels (warn for 4xx, error for 5xx)? 751- [ ] Are error tests written (negative test cases)? 752- [ ] Is error handling consistent across application?753754### Related Principles755- [API Design: Error Response Format](#api-design-principles) - JSON envelope structure756- [Logging: Correlation IDs](#logging-and-observability-principles) - Traceability757- [Security: No Information Leakage](#security-principles) - Sanitization758- [Testing: Negative Test Cases](#testing-strategy) - Error path coverage759- [Concurrency: Error in Thread Context](#concurrency-and-threading-principles) - Thread failures760761## Concurrency and Threading Principles762763### When to Use Concurrency764765**I/O-Bound Operations (async/await, event loops):**766767- Network requests, file I/O, database queries 768- Waiting for external responses dominates execution time 769- Use: Asynchronous I/O, event-driven concurrency, coroutines770771**CPU-Bound Operations (threads, parallel processing):**772773- Heavy computation, data processing, video encoding 774- CPU cycles dominate execution time 775- Use: OS threads, thread pools, parallel workers776777**Don't Over-Use Concurrency:**778779- Adds significant complexity (race conditions, deadlocks, debugging difficulty) 780- Use only when there's measurable performance benefit 781- Profile first, optimize second782783### Universal Concurrency Principles784785**1. Avoid Race Conditions**786787**What is a race condition:**788789- Multiple threads access shared data concurrently 790- At least one thread writes/modifies the data 791- No synchronization mechanism in place 792- Result depends on unpredictable thread execution timing793794**Prevention strategies:**795796- Synchronization: Locks, mutexes, semaphores 797- Immutability: Immutable data is thread-safe by default 798- Message passing: Send data between threads instead of sharing 799- Thread-local storage: Each thread has its own copy800801**Detection:**802803- Go: Run with `-race` flag (race detector) 804- Rust: Miri tool for undefined behavior detection 805- C/C++: ThreadSanitizer (TSan) 806- Java: JCStress, FindBugs807808**2. Prevent Deadlocks**809810**What is a deadlock:**811812- Two or more threads waiting for each other indefinitely 813- Example: Thread A holds Lock 1, waits for Lock 2; Thread B holds Lock 2, waits for Lock 1814815**Four conditions (ALL must be true for deadlock):**8168171. Mutual exclusion: Resources held exclusively (locks) 8182. Hold and wait: Holding one resource while waiting for another 8193. No preemption: Can't force unlock 8204. Circular wait: A waits for B, B waits for A821822**Prevention (break any one condition):**823824- Lock ordering: Always acquire locks in same order 825- Timeout: Use try_lock with timeout, back off and retry 826- Avoid nested locks: Don't hold multiple locks simultaneously 827- Use lock-free data structures when possible828829**3. Prefer Immutability**830831- Immutable data = thread-safe by default (no synchronization needed) 832- Share immutable data freely between threads 833- Use immutable data structures where possible (Rust default, functional languages) 834- If data must change, use message passing instead of shared mutable state835836**4. Message Passing Over Shared Memory**837838- "Don't communicate by sharing memory; share memory by communicating" (Go proverb) 839- Send data through channels/queues instead of accessing shared memory 840- Reduces need for locks and synchronization 841- Easier to reason about and test842843**5. Graceful Degradation**844845- Handle concurrency errors gracefully (timeouts, retries, circuit breakers) 846- Don't crash entire application on one thread failure 847- Use supervisors/monitors for fault tolerance (Erlang/Elixir actor model) 848- Implement backpressure for producer-consumer scenarios849850### Concurrency Models by Use Case851852- **I/O-bound:** async/await, event loops, coroutines, green threads 853- **CPU-bound:** OS threads, thread pools, parallel processing 854- **Actor model:** Erlang/Elixir actors, Akka (message passing, isolated state) 855- **CSP (Communicating Sequential Processes):** Go channels, Rust channels856857### Testing Concurrent Code858859- Write unit tests with controlled concurrency (deterministic execution) 860- Test timeout scenarios and resource exhaustion 861- Test thread pool full, queue full scenarios862863### Related Principles864- [Resource and Memory Management Principles](#resource-and-memory-management-principles)865- [Error Handling Principles](#error-handling-principles) 866- [Testing Strategy](#testing-strategy) 867868## Resource and Memory Management Principles869870### Universal Resource Management Rules871872**1. Always Clean Up Resources**873874**Resources requiring cleanup:**875876- Files, network connections, database connections 877- Locks, semaphores, mutexes 878- Memory allocations (in manual-memory languages) 879- OS handles, GPU resources880881**Clean up in ALL paths:**882883- Success path: Normal completion 884- Error path: Exception thrown, error returned 885- Early return path: Guard clauses, validation failures886887**Use language-appropriate patterns:**888889- Go: defer statements 890- Rust: Drop trait (RAII) 891- Python: context managers (with statement) 892- TypeScript: try/finally 893- Java: try-with-resources894895**2. Timeout All I/O Operations**896897**Why timeout:**898899- Network requests can hang indefinitely 900- Prevents resource exhaustion (connections, threads) 901- Provides predictable failure behavior902903**Timeout recommendations:**904905- Network requests: 30s default, shorter (5-10s) for interactive 906- Database queries: 10s default, configure per query complexity 907- File operations: Usually fast, but timeout on network filesystems 908- Message queue operations: Configurable, avoid indefinite blocking909910**3. Pool Expensive Resources**911912**Resources to pool:**913914- Database connections: Pool size 5-20 per app instance 915- HTTP connections: Reuse with keep-alive 916- Thread pools: Size based on CPU count (CPU-bound) or I/O wait (I/O-bound)917918**Benefits:**919920- Reduces latency (no connection setup overhead) 921- Limits resource consumption (cap on max connections) 922- Improves throughput (reuse vs create new)923924**Connection Pool Best Practices:**925926- Minimum connections: 5 (ensures pool is warm) 927- Maximum connections: 20-50 (prevents overwhelming database) 928- Idle timeout: Close connections idle >5-10 minutes 929- Validation: Test connections before use (avoid broken connections) 930- Monitoring: Track utilization, wait times, timeout rates931932**4. Avoid Resource Leaks**933934**What is a leak:**935936- Acquire resource (open file, allocate memory, get connection) 937- Never release it (forget to close, exception prevents cleanup) 938- Eventually exhaust system resources (OOM, max connections, file descriptors)939940**Detection:**941942- Monitor open file descriptors, connection counts, memory usage over time 943- Run long-duration tests, verify resource counts stay stable 944- Use leak detection tools (valgrind, ASan, heap profilers)945946**Prevention:**947948- Use language patterns that guarantee cleanup (RAII, defer, context managers) 949- Never rely on manual cleanup alone (use language features)950951**5. Handle Backpressure**952953**Problem:** Producer faster than consumer954955- Queue grows unbounded → memory exhaustion 956- System becomes unresponsive under load957958**Solutions:**959960- Bounded queues: Fixed size, block or reject when full 961- Rate limiting: Limit incoming request rate 962- Flow control: Consumer signals producer to slow down 963- Circuit breakers: Stop accepting requests when overwhelmed 964- Drop/reject: Fail fast when overloaded (better than crashing)965966### Memory Management by Language Type967968**Garbage Collected (Go, Java, Python, JavaScript, C#):**969970- Memory automatically freed by GC 971- Still must release non-memory resources (files, connections, locks) 972- Be aware of GC pauses in latency-sensitive applications 973- Profile memory usage to find leaks (retained references preventing GC)974975**Manual Memory Management (C, C++):**976977- Explicit malloc/free or new/delete 978- Use RAII pattern in C++ (Resource Acquisition Is Initialization) 979- Avoid manual management in modern C++ (use smart pointers: unique_ptr, shared_ptr)980981**Ownership-Based (Rust):**982983- Compiler enforces memory safety at compile time 984- No GC pauses, no manual management 985- Ownership rules prevent leaks and use-after-free automatically 986- Use reference counting (Arc, Rc) for shared ownership987988### Related Principles989- [Concurrency and Threading Principles](#concurrency-and-threading-principles) - Thread safety, timeouts990- [Error Handling Principles](#error-handling-principles) - Resource cleanup in error paths991992## API Design Principles993994### RESTful API Standards995996**Resource-Based URLs:**997998- Use plural nouns for resources: `/api/{version}/users`, `/api/{version}/orders` 999- Hierarchical relationships: `/api/{version}/users/:userId/orders` 1000- Avoid verbs in URLs: `/api/{version}/getUser` ❌ → `/api/{version}/users/:id` ✅10011002**HTTP Methods:**10031004- GET: Read/retrieve resource (safe, idempotent, cacheable) 1005- POST: Create new resource (not idempotent) 1006- PUT: Replace entire resource (idempotent) 1007- PATCH: Partial update (idempotent) 1008- DELETE: Remove resource (idempotent)10091010**HTTP Status Codes:**10111012- 200 OK: Success (GET, PUT, PATCH) 1013- 201 Created: Resource created successfully (POST) 1014- 204 No Content: Success with no response body (DELETE) 1015- 400 Bad Request: Invalid input, validation failure 1016- 401 Unauthorized: Authentication required or failed 10171018…(truncated)