# Technical Design Rules and Principles

## Core Design Principles

### 1. Type Safety is Non-Negotiable
- **TypeScript**: Never use `any`; define precise types, generics, and discriminated unions for all public interfaces
- **Statically typed languages** (Java, Go, Rust, C#): Declare explicit types for all parameters, return values, and public boundaries; avoid unsafe casts
- **Dynamically typed languages** (Python, Ruby): Apply type annotations at all public interfaces; validate inputs at system boundaries
- Document every public interface contract clearly so cross-component interactions are unambiguous

### 2. Design Captures WHAT, Not HOW
- Specify interfaces, contracts, and observable behavior — never algorithm implementations or code structure
- Define pre-conditions, post-conditions, and invariants rather than step-by-step procedures
- Record architectural decisions and their rationale, not the mechanics of execution

### 3. Visual Communication Standards
- **Simple changes**: A diagram is optional; include one only if it adds clarity
- **Medium-complexity features**: Provide an architecture diagram plus a data flow diagram
- **High-complexity features**: Include multiple diagrams — architecture, sequence, state machine, and ER as appropriate
- **Always use pure Mermaid**: No custom styling, plugins, or renderer-specific extensions — standard syntax only

### 4. Component Design Principles
- **Single Responsibility**: Each component owns exactly one well-defined concern
- **Explicit Boundaries**: Domain ownership and transaction scope are declared, not inferred
- **Layered Dependencies**: Dependencies flow in one direction following the established architectural layer order
- **Interface Segregation**: Interfaces expose only the methods their consumers actually need
- **Parallel-Safe Design**: Define boundaries that allow independent implementation by different contributors without merge conflicts
- **Traceable Decisions**: Record boundary choices and their rationale in `research.md`

### 5. Data Modeling Standards
- **Domain First**: Begin with business concepts and aggregates before considering persistence mechanics
- **Clear Consistency Boundaries**: Identify aggregate roots and transaction scope explicitly
- **Balanced Normalization**: Optimize for the right trade-off between data integrity and query performance for this feature's access patterns
- **Evolution Planning**: Design schemas with anticipated changes in mind; document migration strategy upfront

### 6. Error Handling Philosophy
- **Fail Fast**: Validate inputs and preconditions as early as possible
- **Graceful Degradation**: Prefer partial functionality over complete failure when safe to do so
- **User-Actionable Messages**: Error messages should tell users what went wrong and what they can do about it
- **Observable by Default**: All errors must be loggable and traceable through monitoring infrastructure

### 7. Integration Design Principles
- **Loose Coupling**: Minimize direct dependencies between components; prefer events or well-defined interfaces
- **Contract First**: Specify API and event schemas before writing implementation code
- **Version Planning**: Design APIs to support evolution without breaking existing consumers
- **Idempotency**: Design every mutating operation to be safe to retry without unintended side effects
- **Surfaced Contracts**: API and event contracts belong in `design.md`; detailed investigation notes belong in `research.md`

---

## Documentation Standards

### Tone and Language
- **Declarative**: "The service authenticates users using JWT tokens" — not "The service should authenticate"
- **Precise**: Use the specific technical term, not a vague description
- **Concise**: Every sentence should carry necessary information; eliminate filler
- **Formal**: Professional technical writing suitable for cross-team review

### Document Structure Requirements
- **Hierarchical**: Clear section hierarchy with meaningful headings
- **Traceable**: Every requirement must map to at least one design element
- **Complete for Reviewers**: `design.md` must stand alone — do not require reviewers to consult `research.md` to understand a decision
- **Consistent Terminology**: Use each term with exactly one meaning throughout the document
- **Focused**: Architectural decisions and contracts belong in `design.md`; investigation logs and verbose comparisons belong in `research.md`

---

## Section Authoring Guidance

### Global Section Order
Default flow: Overview → Goals/Non-Goals → Requirements Traceability → Architecture → Technology Stack → System Flows → Components & Interface Contracts → Data Models → Optional sections.

Sections may be reordered when reordering genuinely improves reviewer comprehension — for example, surfacing Traceability earlier for compliance-sensitive features, or placing Data Models adjacent to Architecture when data structure is central to the design. Keep all section headings intact regardless of order.

Within each section, maintain the internal flow: **Summary → Scope → Decisions → Impacts/Risks** so reviewers can scan predictably.

### Requirement ID Rules
- Reference requirements using only their numeric ID: `2.1, 2.3` — no prefixes, no labels
- Use `N.M`-style IDs where `N` is the top-level requirement number and `M` is the sub-item index
- Every component, task, and traceability table row must reference the same canonical numeric IDs from `requirements.md`
- If any requirement lacks a numeric ID, stop and correct `requirements.md` before continuing

### Technology Stack Section
- Include only the layers this feature actually touches
- For each entry: tool or library name + version + role it plays in this feature
- Push extended rationale, benchmark comparisons, and migration notes to `research.md`; include only a summary and pointer here
- When extending an existing system, explicitly call out new dependencies and any stack deviations

### System Flows Section
- Include diagrams only when they clarify behavior that prose cannot convey efficiently:
  - **Sequence**: Multi-party request/response interactions
  - **State / Process**: Business workflows with branching or lifecycle transitions
  - **Data / Event**: Asynchronous pipelines or event-driven flows
- Use pure Mermaid syntax; test diagrams before including them
- If no complex flow exists, omit the entire section

### Requirements Traceability Section
- Use the standard table (`Requirement | Summary | Components | Interfaces | Flows`) for features with cross-cutting or compliance-sensitive requirements
- Collapse to a bullet list only when a single requirement maps exactly to a single component with no cross-cutting concerns
- Rerun this mapping whenever requirements or components change to prevent drift

### Components and Interfaces Section
- Open with a quick-reference summary table or compact list before diving into per-component blocks
- Summary table fields: Component, Domain/Layer, Intent (one line), Requirement coverage, Key dependencies (P0/P1), Contract types
- **Full detail blocks** are required for components introducing new boundaries — new logic hooks, external integrations, shared services, data layers
- **Summary-only rows** are sufficient for presentational or pass-through components with no new boundary
- Group components by domain or architectural layer
- Dependencies table must classify each entry as Inbound / Outbound / External and assign criticality: P0 (blocking), P1 (high-risk), P2 (informational)
- Contracts: mark only the applicable types (Service / API / Event / Batch / State); unchecked types must not appear later
- Service interfaces must declare method signatures, input/output types, and error envelopes
- API, Event, and Batch contracts require schema tables or structured bullets covering trigger, payload, delivery guarantees, and idempotency strategy
- **Implementation Notes** must consolidate Integration, Validation, and Risks into a single bulleted subsection — no repetition across sub-sections

### Shared Interfaces and Props
- Define a base interface for recurring UI component contracts; extend it per component to capture only the deltas
- Hooks, utilities, and integration adapters that introduce new contracts require full type signatures
- When reusing a base contract, reference it explicitly rather than duplicating the block

### Data Models Section
- **Domain Model**: Aggregates, entities, value objects, domain events, and business invariants; include Mermaid ER diagrams only for non-trivial relationships
- **Logical Data Model**: Structure, indexing strategy, sharding considerations, and storage-specific constraints relevant to this change
- **Data Contracts and Integration**: API payloads, event schemas, and cross-service synchronization patterns when the feature crosses service boundaries
- Move lengthy type definitions or vendor-specific option objects to the Supporting References section and link from the relevant section

### Error, Testing, Security, and Performance Sections
- Record only decisions or deviations that are specific to this feature
- Reference organization-wide standards in steering documents for baseline practices rather than restating them

### Avoiding Redundancy
- Do not restate diagram content verbatim in prose; use prose to surface trade-offs and decisions not visible in the diagram
- Avoid repeating the same fact across Overview, Architecture, and Components — reference earlier sections when the context is identical
- If a relationship is captured in the summary table, do not restate it elsewhere unless adding meaningful nuance

---

## Mermaid Diagram Requirements

### When to Include a Diagram
- **Architecture diagram**: When 3 or more components or external systems interact
- **Sequence diagram**: When a flow spans multiple actors or services across several steps
- **State or Process diagram**: For complex state machines or decision-heavy business workflows
- **ER diagram**: For non-trivial data model relationships
- **Skip**: Single-component changes generally do not need diagrams

### Mermaid Syntax Rules

```mermaid
graph TB
    Client --> ApiGateway
    ApiGateway --> ServiceA
    ApiGateway --> ServiceB
    ServiceA --> Database
```

- **Plain Mermaid only**: No custom themes, style blocks, or renderer extensions
- **Node IDs**: Alphanumeric characters and underscores only — no `@`, `/`, or leading `-`
- **Labels**: Plain words and spaces only — no parentheses `()`, square brackets `[]`, quotation marks `"`, or slashes `/` in label text
  - Incorrect: `DnD[@dnd-kit/core]` — `@` is invalid in a node ID
  - Incorrect: `UI[KanbanBoard(React)]` — parentheses break the label parser
  - Correct: `DndKit[dnd-kit core]` — use plain descriptive text; put technology names in the prose description
- **Edge direction**: Arrows must show data or control flow direction
- **Subgraphs**: Permitted to cluster related components; use sparingly and only when grouping adds clarity

---

## Design Completeness Checklist
Before considering a design document final, verify:
- All requirements are addressed by at least one component or interface
- No implementation code or algorithmic detail leaked into the design
- Component boundaries are explicit and non-overlapping
- Error scenarios are defined for all failure modes
- A testing strategy exists for each component
- Security implications are considered for sensitive data or auth flows
- Performance targets are stated for latency-sensitive or high-volume paths
- A migration or rollout strategy exists when replacing existing functionality

## Anti-Patterns to Avoid
- Mixing design intent with implementation logic
- Vague interface definitions that leave room for interpretation
- Missing error path specifications
- Ignoring non-functional requirements (latency, throughput, availability)
- Architectural complexity disproportionate to the problem
- Tight component coupling that prevents independent testing or deployment
- No strategy for data consistency across service boundaries
- Incomplete or shallow dependency analysis
