--- allowed-tools: [Read, Write, Glob, TodoWrite] description: Designs detailed system components with specifications, interfaces, and implementation guidelines based on architecture framework. --- # Design Components ## Context - **User Request:** $ARGUMENTS - **Architecture Session:** Identified by `--name` argument (architecture session name or index). - **Source Architecture:** Architecture framework document from the specified architecture session directory. - **Component Selection:** Optional `--components` argument to focus on specific components. - **Design Directory:** `.taskmaster/docs/design/architecture/` ## Goal To transform the high-level architecture framework into detailed component specifications that define interfaces, responsibilities, implementation patterns, and integration contracts necessary for development teams to build robust, maintainable software components. ## Process 1. **Identify Source Architecture Session:** - Use the `--name` argument to locate the correct architecture session directory (e.g., `.taskmaster/docs/design/architecture/001-enterprise-expansion/`). - Find the architecture framework document (`architecture-framework_*.md`) within the session directory. 2. **Extract Component Requirements from Architecture:** - **Component Identification:** Components identified in the architecture framework - **Layer Assignments:** Which architectural layer each component belongs to - **Domain Boundaries:** Domain context and bounded context for each component - **Quality Attributes:** Performance, security, scalability requirements per component - **Integration Points:** How components interact with each other 3. **Process Component Selection (if specified):** - If `--components` argument is provided, focus on specific components only - Parse comma-separated component names or indices - Validate that specified components exist in the architecture framework 4. **Perform Component Analysis:** - **Responsibility Definition:** Clear definition of what each component does - **Interface Design:** Public APIs, contracts, and communication protocols - **Dependency Analysis:** Dependencies on other components and external systems - **Data Flow Analysis:** How data flows through and between components - **Error Handling:** Error handling strategies and fault tolerance patterns 5. **Design Component Specifications:** - **Component Architecture:** Internal structure and sub-components - **Interface Contracts:** Detailed API specifications and data models - **Implementation Patterns:** Recommended design patterns and practices - **Technology Guidelines:** Technology stack and framework recommendations - **Testing Strategy:** Unit, integration, and contract testing approaches 6. **Generate Component Design Document:** - Create the component design document named `component-design_[architecture_session_name].md`. - Structure content according to the component design template. - Include: - **Component Overview:** High-level component landscape and relationships - **Component Specifications:** Detailed specifications for each component - **Interface Definitions:** API contracts and communication protocols - **Implementation Guidelines:** Development patterns and best practices - **Integration Patterns:** Component interaction and communication patterns - **Quality Assurance:** Testing and validation approaches 7. **Create Component Interface Specifications:** - Generate individual interface specification files for complex components - Create API documentation and contract definitions - Define data models and schema specifications - Document error handling and exception patterns 8. **Update Architecture Session State:** - Update the existing `_session-state.json` file in the architecture session directory. - Add component design completion status and results. - Update `completedSteps` and `nextAction` fields. 9. **Notify User with Component Insights:** - Inform the user that the component design has been successfully generated. - Provide file paths and key component highlights. - **Suggest logical next steps based on component design:** - "Your component design is complete. Consider defining integration architecture using `/design/system-architecture/3-integration-architecture --name=[session_name]`" - "Review the component interfaces with your development teams to ensure implementation feasibility." - "Use the component specifications to create detailed development tasks and sprint planning." ## Templates & Structures ### Component Design Template ```markdown # Component Design: [Architecture Session Name] **Created:** [Date] **Source:** Architecture Framework: [Architecture Session Name] **Component Scope:** [All Components / Specific Components] **Target Components:** [List of components if specific scope] **Last Updated:** [Date] --- ## Component Overview ### System Component Landscape - **Total Components:** [Number of components in the system] - **Layer Distribution:** [Number of components per architectural layer] - **Domain Distribution:** [Number of components per domain] - **Integration Complexity:** [Assessment of component integration complexity] ### Component Relationships - **Core Components:** [Components that are central to system functionality] - **Supporting Components:** [Components that support core functionality] - **Infrastructure Components:** [Components that provide technical infrastructure] - **Integration Components:** [Components that handle external integrations] ### Component Dependencies - **High-Level Dependencies:** [Major dependency relationships between components] - **Circular Dependencies:** [Any circular dependencies and resolution strategies] - **External Dependencies:** [Dependencies on external systems and services] --- ## Component Specifications ### Presentation Layer Components #### Component 1: [Component Name] **Layer:** Presentation **Domain:** [Domain Context] **Responsibility:** [Primary responsibility and purpose] ##### Architecture - **Component Type:** [Controller/Gateway/UI Component/API Handler] - **Deployment Unit:** [How this component is deployed] - **Scalability:** [Horizontal/Vertical scaling characteristics] - **State Management:** [Stateless/Stateful and state handling approach] ##### Responsibilities - **Primary Responsibility:** [Main function of this component] - **Secondary Responsibilities:** [Additional functions and capabilities] - **Business Rules:** [Business logic handled by this component] - **Data Transformation:** [Data processing and transformation responsibilities] ##### Interface Definition ```typescript // Public Interface interface ComponentName { // Core Methods methodName(request: RequestType): Promise; // Event Handlers onEvent(event: EventType): void; // Lifecycle Methods initialize(): Promise; shutdown(): Promise; } // Request/Response Types interface RequestType { // Request structure } interface ResponseType { // Response structure } ``` ##### Dependencies - **Required Dependencies:** [Components this depends on] - **Optional Dependencies:** [Components this can optionally use] - **External Dependencies:** [External services and systems] - **Infrastructure Dependencies:** [Databases, message queues, etc.] ##### Data Flow - **Input Data:** [Data received from other components or external sources] - **Output Data:** [Data produced and sent to other components] - **Data Transformation:** [How data is processed and transformed] - **Data Validation:** [Input validation and sanitization] ##### Error Handling - **Error Types:** [Types of errors this component can encounter] - **Error Handling Strategy:** [How errors are handled and propagated] - **Retry Logic:** [Retry mechanisms and policies] - **Fallback Mechanisms:** [Fallback strategies for failures] ##### Quality Attributes - **Performance:** [Performance requirements and optimization strategies] - **Security:** [Security requirements and implementation approach] - **Reliability:** [Reliability requirements and fault tolerance] - **Maintainability:** [Code organization and maintenance considerations] ##### Testing Strategy - **Unit Testing:** [Unit testing approach and coverage] - **Integration Testing:** [Integration testing strategy] - **Contract Testing:** [API contract testing approach] - **Performance Testing:** [Performance testing requirements] ##### Implementation Guidelines - **Design Patterns:** [Recommended design patterns] - **Technology Stack:** [Recommended technologies and frameworks] - **Code Organization:** [Code structure and organization guidelines] - **Configuration:** [Configuration management approach] ### Application Layer Components #### Component 2: [Component Name] **Layer:** Application **Domain:** [Domain Context] **Responsibility:** [Primary responsibility and purpose] ##### Architecture - **Component Type:** [Application Service/Command Handler/Query Handler/Orchestrator] - **Deployment Unit:** [How this component is deployed] - **Scalability:** [Horizontal/Vertical scaling characteristics] - **State Management:** [Stateless/Stateful and state handling approach] ##### Responsibilities - **Primary Responsibility:** [Main function of this component] - **Secondary Responsibilities:** [Additional functions and capabilities] - **Business Rules:** [Business logic handled by this component] - **Workflow Coordination:** [Business process coordination responsibilities] ##### Interface Definition ```typescript // Application Service Interface interface ApplicationService { // Use Case Methods executeUseCase(command: CommandType): Promise; // Query Methods handleQuery(query: QueryType): Promise; // Workflow Methods coordinateWorkflow(workflow: WorkflowType): Promise; } // Command/Query Types interface CommandType { // Command structure } interface QueryType { // Query structure } ``` ##### Dependencies - **Domain Dependencies:** [Domain services and repositories] - **Infrastructure Dependencies:** [Data access and external services] - **Cross-Cutting Dependencies:** [Logging, monitoring, configuration] ##### Data Flow - **Command Processing:** [How commands are processed] - **Query Processing:** [How queries are handled] - **Event Publishing:** [Events published by this component] - **Data Persistence:** [Data storage and retrieval patterns] ##### Error Handling - **Business Rule Violations:** [How business rule violations are handled] - **Infrastructure Failures:** [How infrastructure failures are managed] - **Transaction Management:** [Transaction handling and rollback strategies] - **Compensation Patterns:** [Compensation actions for failures] ##### Quality Attributes - **Performance:** [Performance requirements and optimization strategies] - **Security:** [Security requirements and implementation approach] - **Reliability:** [Reliability requirements and fault tolerance] - **Maintainability:** [Code organization and maintenance considerations] ##### Testing Strategy - **Unit Testing:** [Unit testing approach and coverage] - **Integration Testing:** [Integration testing strategy] - **Business Logic Testing:** [Business rule testing approach] - **End-to-End Testing:** [End-to-end testing requirements] ##### Implementation Guidelines - **Design Patterns:** [CQRS, Mediator, Unit of Work, etc.] - **Technology Stack:** [Recommended technologies and frameworks] - **Code Organization:** [Code structure and organization guidelines] - **Transaction Management:** [Transaction handling guidelines] ### Domain Layer Components #### Component 3: [Component Name] **Layer:** Domain **Domain:** [Domain Context] **Responsibility:** [Primary responsibility and purpose] ##### Architecture - **Component Type:** [Domain Service/Entity/Value Object/Aggregate] - **Deployment Unit:** [How this component is deployed] - **Scalability:** [Horizontal/Vertical scaling characteristics] - **State Management:** [State handling and persistence approach] ##### Responsibilities - **Primary Responsibility:** [Main function of this component] - **Business Rules:** [Core business rules and invariants] - **Domain Logic:** [Domain-specific business logic] - **Data Integrity:** [Data consistency and validation responsibilities] ##### Interface Definition ```typescript // Domain Service Interface interface DomainService { // Business Logic Methods performBusinessOperation(params: BusinessParams): BusinessResult; // Validation Methods validateBusinessRules(entity: EntityType): ValidationResult; // Calculation Methods calculateBusinessValue(input: InputType): CalculationResult; } // Domain Types interface BusinessParams { // Business parameter structure } interface BusinessResult { // Business result structure } ``` ##### Dependencies - **Domain Dependencies:** [Other domain services and entities] - **Infrastructure Dependencies:** [Repository interfaces] - **External Dependencies:** [External domain services if any] ##### Data Flow - **Entity Lifecycle:** [How entities are created, modified, and destroyed] - **Business Events:** [Domain events generated by this component] - **Validation Flow:** [How business rules are validated] - **State Transitions:** [Valid state transitions and constraints] ##### Error Handling - **Business Rule Violations:** [How business invariants are enforced] - **Domain Exceptions:** [Domain-specific exceptions and handling] - **Validation Failures:** [How validation failures are communicated] - **Consistency Enforcement:** [How data consistency is maintained] ##### Quality Attributes - **Performance:** [Performance requirements and optimization strategies] - **Security:** [Security requirements and implementation approach] - **Reliability:** [Reliability requirements and fault tolerance] - **Maintainability:** [Code organization and maintenance considerations] ##### Testing Strategy - **Unit Testing:** [Unit testing approach and coverage] - **Domain Testing:** [Domain logic testing strategy] - **Business Rule Testing:** [Business rule validation testing] - **Integration Testing:** [Integration testing with repositories] ##### Implementation Guidelines - **Design Patterns:** [Domain-Driven Design patterns] - **Technology Stack:** [Recommended technologies and frameworks] - **Code Organization:** [Code structure and organization guidelines] - **Business Rule Implementation:** [How to implement business rules] ### Infrastructure Layer Components #### Component 4: [Component Name] **Layer:** Infrastructure **Domain:** [Domain Context] **Responsibility:** [Primary responsibility and purpose] ##### Architecture - **Component Type:** [Repository/External Service Client/Message Handler/Data Access] - **Deployment Unit:** [How this component is deployed] - **Scalability:** [Horizontal/Vertical scaling characteristics] - **State Management:** [Connection and resource management approach] ##### Responsibilities - **Primary Responsibility:** [Main function of this component] - **Data Access:** [Data persistence and retrieval responsibilities] - **External Integration:** [External service integration responsibilities] - **Technical Concerns:** [Cross-cutting technical concerns] ##### Interface Definition ```typescript // Repository Interface interface Repository { // CRUD Operations create(entity: T): Promise; findById(id: string): Promise; update(entity: T): Promise; delete(id: string): Promise; // Query Operations findBy(criteria: QueryCriteria): Promise; exists(criteria: QueryCriteria): Promise; } // External Service Interface interface ExternalServiceClient { // Service Operations callService(request: ServiceRequest): Promise; // Health Check healthCheck(): Promise; } ``` ##### Dependencies - **Database Dependencies:** [Database systems and drivers] - **External Service Dependencies:** [Third-party services and APIs] - **Infrastructure Dependencies:** [Message queues, caches, etc.] - **Configuration Dependencies:** [Configuration and secrets management] ##### Data Flow - **Data Access Patterns:** [How data is accessed and manipulated] - **Connection Management:** [Database connection and pooling] - **Error Handling:** [Database and service error handling] - **Performance Optimization:** [Caching and optimization strategies] ##### Error Handling - **Database Errors:** [Database connection and query error handling] - **External Service Errors:** [External service failure handling] - **Network Errors:** [Network connectivity and timeout handling] - **Resource Errors:** [Resource exhaustion and cleanup] ##### Quality Attributes - **Performance:** [Performance requirements and optimization strategies] - **Security:** [Security requirements and implementation approach] - **Reliability:** [Reliability requirements and fault tolerance] - **Maintainability:** [Code organization and maintenance considerations] ##### Testing Strategy - **Unit Testing:** [Unit testing approach and coverage] - **Integration Testing:** [Integration testing strategy] - **Database Testing:** [Database testing approach] - **External Service Testing:** [Service integration testing] ##### Implementation Guidelines - **Design Patterns:** [Repository, Adapter, Circuit Breaker, etc.] - **Technology Stack:** [Recommended technologies and frameworks] - **Code Organization:** [Code structure and organization guidelines] - **Resource Management:** [Connection and resource management] --- ## Interface Definitions ### API Contracts #### REST API Specification ```yaml # OpenAPI 3.0 Specification openapi: 3.0.0 info: title: Component API version: 1.0.0 description: API specification for component interfaces paths: /api/resource: get: summary: Get resource parameters: - name: id in: query required: true schema: type: string responses: '200': description: Resource found content: application/json: schema: $ref: '#/components/schemas/Resource' '404': description: Resource not found post: summary: Create resource requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateResourceRequest' responses: '201': description: Resource created content: application/json: schema: $ref: '#/components/schemas/Resource' components: schemas: Resource: type: object properties: id: type: string name: type: string status: type: string enum: [active, inactive] CreateResourceRequest: type: object required: - name properties: name: type: string description: type: string ``` #### Message Contracts ```typescript // Event Message Contracts interface DomainEvent { eventId: string; eventType: string; aggregateId: string; aggregateType: string; eventData: any; timestamp: Date; version: number; } // Command Message Contracts interface Command { commandId: string; commandType: string; payload: any; timestamp: Date; userId: string; } // Query Message Contracts interface Query { queryId: string; queryType: string; parameters: any; timestamp: Date; userId: string; } ``` ### Integration Protocols #### Synchronous Communication - **HTTP/REST:** [RESTful API patterns and conventions] - **gRPC:** [gRPC service definitions and protocols] - **GraphQL:** [GraphQL schema and query patterns] #### Asynchronous Communication - **Message Queues:** [Message queue patterns and protocols] - **Event Streams:** [Event streaming patterns and schemas] - **Publish-Subscribe:** [Pub/sub patterns and topic structures] #### Data Formats - **JSON:** [JSON schema definitions and conventions] - **Protocol Buffers:** [Protobuf definitions and usage] - **Avro:** [Avro schema definitions and evolution] --- ## Implementation Guidelines ### Development Patterns #### Design Patterns by Layer ##### Presentation Layer - **MVC Pattern:** [Model-View-Controller implementation] - **API Gateway Pattern:** [Centralized API management] - **Backend for Frontend (BFF):** [Client-specific backends] ##### Application Layer - **Command Query Responsibility Segregation (CQRS):** [Separate read/write operations] - **Mediator Pattern:** [Request/response handling] - **Unit of Work Pattern:** [Transaction management] ##### Domain Layer - **Domain-Driven Design (DDD):** [Domain modeling patterns] - **Repository Pattern:** [Data access abstraction] - **Factory Pattern:** [Complex object creation] - **Strategy Pattern:** [Business rule variations] ##### Infrastructure Layer - **Repository Pattern:** [Data access implementation] - **Adapter Pattern:** [External service integration] - **Circuit Breaker Pattern:** [Fault tolerance] - **Decorator Pattern:** [Cross-cutting concerns] ### Technology Guidelines #### Programming Languages - **Primary Language:** [Main programming language and rationale] - **Secondary Languages:** [Additional languages for specific components] - **Language Standards:** [Coding standards and conventions] #### Frameworks and Libraries - **Web Framework:** [Web framework selection and configuration] - **ORM Framework:** [Object-relational mapping framework] - **Testing Framework:** [Testing framework and tools] - **Logging Framework:** [Logging and monitoring framework] #### Development Tools - **IDE Configuration:** [Development environment setup] - **Build Tools:** [Build automation and dependency management] - **Code Quality Tools:** [Static analysis and quality tools] - **Version Control:** [Version control practices and branching] ### Quality Assurance #### Testing Strategy - **Unit Testing:** [Component-level testing approach] - **Integration Testing:** [Component integration testing] - **Contract Testing:** [API contract testing] - **End-to-End Testing:** [System-level testing] #### Code Quality - **Code Reviews:** [Code review process and standards] - **Static Analysis:** [Static code analysis tools and rules] - **Documentation:** [Code documentation standards] - **Refactoring:** [Refactoring guidelines and practices] #### Performance - **Performance Testing:** [Performance testing approach] - **Profiling:** [Performance profiling and optimization] - **Monitoring:** [Runtime monitoring and alerting] - **Optimization:** [Performance optimization strategies] --- ## Integration Patterns ### Component Communication #### Synchronous Patterns - **Direct Method Calls:** [In-process component communication] - **HTTP APIs:** [RESTful API communication] - **RPC Calls:** [Remote procedure call patterns] #### Asynchronous Patterns - **Message Queues:** [Queue-based communication] - **Event Streams:** [Event-driven communication] - **Publish-Subscribe:** [Pub/sub communication patterns] #### Hybrid Patterns - **Request-Response with Events:** [Combined synchronous/asynchronous] - **Saga Pattern:** [Distributed transaction coordination] - **Event Sourcing:** [Event-based state management] ### Data Consistency #### Consistency Patterns - **Strong Consistency:** [ACID transaction patterns] - **Eventual Consistency:** [BASE transaction patterns] - **Causal Consistency:** [Causal ordering patterns] #### Conflict Resolution - **Last Write Wins:** [Conflict resolution strategy] - **Merge Strategies:** [Data merge and conflict resolution] - **Compensating Actions:** [Compensation patterns for failures] --- ## Next Steps ### Component Implementation 1. **Development Planning:** [Plan component development order and dependencies] 2. **Team Assignment:** [Assign development teams to components] 3. **Interface Implementation:** [Implement component interfaces first] 4. **Component Development:** [Develop component implementations] ### Integration Planning 1. **Integration Architecture:** [Design component integration approach] 2. **Communication Protocols:** [Implement communication mechanisms] 3. **Data Flow Testing:** [Test data flow between components] 4. **End-to-End Testing:** [Test complete system integration] ### Quality Assurance 1. **Testing Implementation:** [Implement testing strategy] 2. **Code Quality Setup:** [Set up code quality tools] 3. **Performance Testing:** [Implement performance testing] 4. **Security Testing:** [Implement security testing] --- ## Appendices ### A. Component Mapping Matrix [Matrix showing component relationships and dependencies] ### B. Interface Specifications [Detailed interface specifications for each component] ### C. Implementation Examples [Code examples and implementation patterns] ### D. Testing Examples [Testing examples and test case specifications] ### E. Performance Considerations [Performance analysis and optimization guidelines] ``` ### Updated Session State Structure ```json { "index": 1, "name": "architecture-session-name", "type": "architecture", "status": "component_design_complete", "created": "ISO datetime", "lastUpdated": "ISO datetime", "currentStep": "component_design", "completedSteps": ["architecture_framework_creation", "domain_analysis", "layer_design", "component_design"], "nextAction": "Ready for integration architecture or summary generation", "sourceType": "prd", "sourceName": "prd-session-name", "architectureScope": "system-wide", "architectureStyle": "layered", "architectureResults": { "domains": 3, "layers": 4, "components": 12, "componentSpecs": 12, "interfaces": 24, "patterns": 8, "qualityAttributes": 5, "decisions": 6, "createdDate": "ISO datetime", "componentDesignDate": "ISO datetime" } } ``` ## Best Practices ### ✅ DO: Interface-First Design - **Define clear interfaces** before implementing component internals - **Use contract-first approach** for API and message design - **Maintain interface stability** and versioning strategies - **Document interface contracts** comprehensively **Why:** Interface-first design enables parallel development, reduces integration issues, and improves system maintainability. ### ✅ DO: Responsibility-Driven Design - **Assign single responsibility** to each component - **Define clear boundaries** between component responsibilities - **Minimize coupling** between components - **Maximize cohesion** within components **Why:** Responsibility-driven design creates maintainable, testable, and evolvable components. ### ✅ DO: Quality-Driven Implementation - **Define quality requirements** for each component - **Implement appropriate patterns** for quality attributes - **Plan for testing** and quality assurance - **Consider operational requirements** from the start **Why:** Quality-driven implementation ensures that components meet production requirements and performance expectations. ### ❌ DON'T: Premature Implementation Details - **Don't specify implementation details** too early in the design process - **Don't couple components** to specific technologies unnecessarily - **Don't ignore testing** and quality requirements - **Don't forget operational concerns** like monitoring and deployment **Why:** Premature implementation details can constrain development flexibility and complicate system evolution. ### ❌ DON'T: Monolithic Component Design - **Don't create components** that are too large or complex - **Don't mix concerns** within a single component - **Don't ignore separation** of business and technical concerns - **Don't create tight coupling** between unrelated components **Why:** Monolithic component design reduces maintainability, testability, and team productivity. ## Output - **Format:** Detailed component specifications with interfaces and guidelines - **Location:** `.taskmaster/docs/design/architecture/[index]-[architecture_session_name]/` - **Primary Files:** - `component-design_[architecture_session_name].md` - Main component design document - `_session-state.json` - Updated session state ## Example Usage - **Design all components from architecture:** `/design/system-architecture/2-design-components --name="enterprise-expansion"` - **Design specific components:** `/design/system-architecture/2-design-components --name="enterprise-expansion" --components="UserService,PaymentService"` - **Design by architecture index:** `/design/system-architecture/2-design-components --name="1"`