System Design
Create or update system design documents based on requirement documents, supporting both initial design and incremental design modes.
Language Rules
- Supports questions in both Chinese and English
- Provide unified English responses
- Generate documents in English
Trigger Conditions
Initial Design Mode
- User has completed requirement documents, and there is no system design for the project
- User requests system/technical design
- User needs architecture or API design
Incremental Design Mode
- Design changes are required after new features are added (from )
- Design adjustments are required after optimization suggestions are confirmed (from )
- Architecture adjustments are required for technical improvements
- User requests to update/modify existing design
Preconditions
- Requirement document:
docs/devdocs/01-requirements.md
- If it does not exist, it is recommended to run first
Design Mode Detection
Automatic detection on startup
│
▼
Check if 02-system-design.md exists
│
├── Does not exist → Initial Design Mode
│
└── Exists → Incremental Design Mode
│
▼
Check if there are unimplemented new requirements (F-XXX)
│
├── Yes → Prompt for incremental design
│
└── No → Ask user's intention
Workflow
Initial Design Workflow
1. Read Requirements → Load 01-requirements.md
│
▼
2. Ask Preferences → Tech stack, platform, integration requirements
│
▼
3. Explore Code → Understand existing architecture
│
▼
4. Create Design → Generate system design document
│
▼
5. Verify Coverage → Check that all F-XXX have corresponding modules/interfaces
│
▼
6. User Confirmation → Finalize after approval
Incremental Design Workflow
1. Read Existing Design → Load 02-system-design*.md
│
▼
2. Identify Change Sources
├── New feature requirements (F-XXX)
├── Optimization suggestions (INS-XXX)
└── Technical improvements
│
▼
3. Impact Analysis
├── Identify affected modules
├── Identify affected interfaces
└── Identify affected data models
│
▼
4. Compatibility Assessment
├── Are interface changes backward compatible?
├── Do data model changes require migration?
└── Are there breaking changes?
│
▼
5. Design Changes
├── Add new modules/interfaces/data models
├── Modify existing design
└── Mark change version
│
▼
6. Generate Change Record → Append to design document
│
▼
7. User Confirmation → Update document after approval
Mandatory Questions Before Design
Must use AskUserQuestion to ask the user:
-
Tech Stack Preference
- Do you have a preferred tech stack?
- Options: Specify tech stack / No preference (will recommend based on requirements)
-
Target Platform
- What is the target platform?
- Options: Web / Mobile (iOS/Android) / Desktop / Server / Cross-platform
-
Deployment Environment
- Where will it be deployed?
- Options: Cloud service (AWS/GCP/Azure) / On-premises / Hybrid
-
Existing System Integration
- Is integration with existing systems required?
- Options: No / Yes (specify system, API, database)
If the user has no preference, design the optimal solution based on requirements.
Incremental Design
Impact Analysis
Impact analysis must be performed before incremental design:
markdown
## Impact Analysis: <Change Name>
**Change Source**: F-XXX / INS-XXX / Technical Improvement
**Change Date**: YYYY-MM-DD
### Affected Modules
|------|----------|------|
| UserService | Modify | Add new method `resetPassword()` |
| AuthModule | Add | Add password reset module |
| EmailService | No Change | Reuse existing email service |
### Affected Interfaces
|------|----------|----------|------|
| POST /api/auth/reset-password | Add | ✅ | New interface |
| GET /api/user/:id | Modify | ✅ | Add new field to return value |
| POST /api/auth/login | Modify | ❌ | Parameter structure changed |
### Affected Data Models
|------|----------|----------|------|
| User | Modify | ✅ | Add `resetToken` field |
| PasswordResetLog | Add | ✅ | New table |
Compatibility Assessment
| Change Type | Backward Compatibility Judgment | Handling Method |
|---|
| New interface | ✅ Compatible | Add directly |
| Add optional field | ✅ Compatible | Add directly |
| Add required field | ❌ Incompatible | Need migration plan |
| Modify field type | ❌ Incompatible | Need migration plan |
| Delete field/interface | ❌ Incompatible | Need deprecation period |
| Modify interface parameters | ⚠️ Depends | Evaluate impact scope |
Breaking Change Handling:
- Mark as Deprecated
- Set deprecation period (e.g., 2 versions)
- Provide migration guide
- Explain in change records
Design Change Records
After completing incremental design, append change records at the end of the design document:
markdown
---
## Design Change Records
### v1.2.0 (2024-01-20)
**Change Source**: F-005 Password Reset Feature, INS-003 Login Security Optimization
**Added Modules**:
- `PasswordResetModule` - Password reset module (associated with F-005)
**Modified Modules**:
- `AuthModule` - Added password reset entry
**Added Interfaces**:
- `IPasswordResetService.sendResetEmail()` - Send reset email
- `IPasswordResetService.resetPassword()` - Execute password reset
**Added APIs**:
- `POST /api/auth/forgot-password` - Request password reset
- `POST /api/auth/reset-password` - Execute password reset
**Data Model Changes**:
- `User` added fields: `resetToken`, `resetTokenExpiry`
- Added entity: `PasswordResetLog`
**Breaking Changes**: None
**Migration Instructions**:
- Execute database migration script `migrations/001-add-reset-token.sql`
---
### v1.1.0 (2024-01-10)
...
Incremental Design Checklist
Output Files
Main File:
docs/devdocs/02-system-design.md
Document Splitting Rules
Split the document when any of the following conditions are met:
- Document exceeds 300 lines
- Number of modules exceeds 5
- Number of API interfaces exceeds 10
Splitting Method:
docs/devdocs/
├── 02-system-design.md # Main document: Architecture overview, tech selection, module division
├── 02-system-design-api.md # API Design: Interface definitions, request/response examples
└── 02-system-design-data.md # Data Model: Entity definitions, ER diagrams, indexing strategies
Splitting Content Allocation:
| File | Included Chapters |
|---|
| 02-system-design.md | 1-7: Platform, architecture, tech selection, modules, interface signatures, patterns, code structure |
| 02-system-design-api.md | 9-10: Complete API design, state transitions |
| 02-system-design-data.md | 8, 11-13: Data models, exception handling, extensibility, requirement traceability |
Refer to templates/design-template.md for detailed templates.
Design Principles
MTE Principles
System design must follow the MTE Principles:
| Principle | Description | Checkpoint |
|---|
| Maintainability | Maintainability | Single responsibility for modules, clear dependencies, easy to understand and modify |
| Testability | Testability | Core logic can be unit tested, dependencies can be Mocked, clear boundaries (refer to ) |
| Extensibility | Extensibility | Reserved extension points, interface abstraction, open/closed principle |
Design Pattern Selection
Select appropriate design patterns based on scenarios, only use when necessary:
| Scenario | Recommended Pattern | Applicable Situation |
|---|
| Object Creation | Factory / Builder | Complex object construction, multiple type creation |
| Behavior Extension | Strategy / Template | Replaceable algorithms, fixed process with variable steps |
| Structure Organization | Facade / Adapter | Simplify complex interfaces, adapt third-party libraries |
| State Management | State / Observer | State-driven behavior, event notification |
| Data Access | Repository / DAO | Data layer abstraction, query encapsulation |
Design Layers
┌─────────────────────────────────────┐
│ Interface Layer │ ← API/Controller (thin layer, no business logic)
├─────────────────────────────────────┤
│ Service Layer │ ← Business logic (core, testable)
├─────────────────────────────────────┤
│ Domain Layer │ ← Domain models (entities, value objects)
├─────────────────────────────────────┤
│ Infrastructure Layer │ ← Data access, external services (replaceable)
└─────────────────────────────────────┘
Document Structure
- Target Platform - Platform, version requirements, deployment environment
- Architecture Overview - High-level architecture diagram (Mermaid)
- Tech Selection - Tech choices and reasons
- Module Design - Module responsibilities and dependencies, mark associated feature points (F-XXX)
- Core Interfaces - Interface-oriented (only signatures): Key interfaces and method signatures (strictly no implementation logic), mark associated F-XXX
- Design Patterns - Applied patterns and reasons
- Code Structure - Directory structure design
- Data Model - Entity definitions and relationships
- API Design - Interface endpoints and request/response examples, mark associated F-XXX, AC-XXX
- State Transitions - State machines for key business processes
- Exception Handling - Error codes and handling strategies
- Log Design - Log levels, key log points, trace ID
- Extensibility - Extension points and future considerations
- Requirement Traceability - Mapping between feature points and modules/interfaces, coverage checklist
Core Interface Design
Core interface definitions should be reflected in the design document (only define signatures, no implementation), and mark associated feature points:
markdown
### Core Interfaces
#### IUserService (Associated: F-001 User Registration, F-002 User Login)
|------|------|--------|------|------|
| `createUser` | `CreateUserDTO` | `User` | F-001, AC-001 | Create user |
| `validateEmail` | `string` | `boolean` | F-001, AC-002 | Validate email |
| `login` | `LoginDTO` | `AuthToken` | F-002, AC-006 | User login |
#### IUserRepository
|------|------|--------|------|
| `save` | `User` | `User` | Save user |
| `findById` | `string` | `User \| null` | Query by ID |
| `findByEmail` | `string` | `User \| null` | Query by email |
Code Structure Design
markdown
### Directory Structure
src/
├── api/ # Interface layer
│ ├── controllers/ # Controllers (route handling)
│ ├── middlewares/ # Middlewares (authentication, logging, etc.)
│ └── validators/ # Request validation
├── services/ # Service layer
│ ├── interfaces/ # Service interface definitions
│ └── impl/ # Service implementations
├── domain/ # Domain layer
│ ├── entities/ # Entities
│ ├── value-objects/ # Value objects
│ └── events/ # Domain events
├── infrastructure/ # Infrastructure layer
│ ├── repositories/ # Data repository implementations
│ ├── external/ # External service adapters
│ └── config/ # Configuration
└── shared/ # Shared
├── types/ # Type definitions
├── utils/ # Utility functions
└── constants/ # Constants
Log Design
Logs are critical tools for debugging and troubleshooting, especially for manual testing and E2E testing scenarios.
Log Levels
| Level | Purpose | Example Scenario |
|---|
| ERROR | Errors requiring immediate handling | Database connection failure, payment failure, critical service unavailability |
| WARN | Potential issues that do not affect core functions | Retry success, degradation handling, resource approaching threshold |
| INFO | Key business operations | User login, order creation, state change |
| DEBUG | Debug information | Function input parameters, intermediate states, performance metrics |
Key Log Points
Key operation log points should be listed in the design document:
markdown
|------|----------|----------|----------|
| User login success | INFO | `[F-002] User login: userId={}, ip={}` | F-002, AC-006 |
| User login failure | WARN | `[F-002] Login failed: userId={}, reason={}` | F-002, AC-007 |
| Password verification failure | WARN | `[F-002] Password mismatch: userId={}` | AC-007 |
| Database exception | ERROR | `[INFRA] DB error: {}, query={}` | - |
| Order creation | INFO | `[F-003] Order created: orderId={}, userId={}` | F-003 |
Log Format
[Timestamp] [Level] [Trace ID] [Module] Message {Structured Data}
Example:
2024-01-26 10:30:15 INFO [req-abc123] [UserService] User created {"userId": "u001", "email": "user@example.com"}
2024-01-26 10:30:16 ERROR [req-abc123] [EmailService] Failed to send verification email {"userId": "u001", "error": "SMTP timeout"}
Trace ID (Correlation ID)
| Attribute | Description |
|---|
| Generation Timing | Generate a unique ID at each request entry |
| Transmission Method | Pass through the entire call chain via Context/Header |
| Naming Convention | or |
| Format | UUID or |
Purposes:
- Query the complete log chain via when E2E tests fail
- Cross-service tracing in distributed systems
- Correlate all relevant logs during troubleshooting
E2E Test Log Strategy
| Scenario | Log Strategy | Description |
|---|
| Test passed | Only retain ERROR/WARN logs | Reduce log volume |
| Test failed | Retain complete logs (including DEBUG) | Facilitate troubleshooting |
| Manual reproduction | Enable DEBUG level | Maximize information |
Failure Analysis Process:
1. Obtain the traceId of the failed test
│
▼
2. Query the complete log chain for this traceId
│
▼
3. Locate the first ERROR/exception point
│
▼
4. Analyze contextual logs
Log Design Constraints
Constraints
Basic Constraints
MTE Principle Constraints
Design Pattern Constraints
Avoid Over-Design
Security Constraints
Incremental Design Constraints
Skill Collaboration
| Scenario | Collaboration Skill | Description |
|---|
| New feature design change | | New features trigger incremental design |
| Optimization suggestion design change | | Incremental design is triggered after insights are confirmed |
| Testability design | | Ensure core logic is unit testable |
| Code quality | | Guide design with MTE principles |
| UI architecture | | Route to professional external UI/UX Skill |
| Automatic interface extraction | | Reverse extract interface definitions from existing code and sync to design documents |
Next Steps
After Initial Design
After the user confirms the system design, it is recommended to run
to enter the test case design phase.
After Incremental Design
- If there are new feature points → Run to supplement test cases
- If there are data model changes → Prepare database migration scripts
- If there are breaking changes → Notify relevant dependent parties