Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:37:27 +08:00
commit 37774aa937
131 changed files with 31137 additions and 0 deletions

View File

@@ -0,0 +1,373 @@
# API Specification: {{PROJECT_NAME}}
**Document Version:** 1.0
**Date:** {{DATE}}
**Status:** {{STATUS}}
**OpenAPI Version:** 3.0.3
<!-- SCOPE: API endpoints (methods, paths, parameters, responses), authentication mechanisms (JWT, OAuth2, API keys), error codes (HTTP status + custom codes), rate limiting, API versioning ONLY. -->
<!-- DO NOT add here: Database schema → database_schema.md, Tech stack versions → tech_stack.md, Architecture patterns → architecture.md, Requirements → requirements.md, Deployment → runbook.md, Design system → design_guidelines.md -->
---
## 1. API Overview
### 1.1 Base URL
{{BASE_URL}}
<!-- Example: Development: http://localhost:3000/api/v1, Production: https://api.example.com/v1 -->
### 1.2 API Design Principles
{{API_DESIGN_PRINCIPLES}}
<!-- Example: RESTful design, Stateless communication, JSON request/response format, HATEOAS links for discoverability, Consistent error handling -->
### 1.3 API Versioning
{{API_VERSIONING}}
<!-- Example: URI versioning (/api/v1/, /api/v2/), Deprecation policy (6 months notice), Backward compatibility for minor updates -->
---
## 2. Authentication & Authorization
### 2.1 Authentication Methods
**Supported Methods:**
{{AUTH_METHODS}}
<!-- Example: JWT Bearer tokens (primary), OAuth2 (Google, GitHub), API Keys (for service-to-service) -->
**JWT Token Format:**
```json
{
"header": {
"alg": "HS256",
"typ": "JWT"
},
"payload": {
"sub": "user_id",
"role": "admin",
"exp": 1234567890
}
}
```
**Token Expiration:**
{{TOKEN_EXPIRATION}}
<!-- Example: Access token: 1 hour, Refresh token: 30 days -->
### 2.2 Authorization (RBAC)
**Roles:**
{{RBAC_ROLES}}
<!-- Example:
| Role | Permissions | Description |
|------|-------------|-------------|
| Admin | Full access | System administration |
| Editor | Read, Create, Update | Content management |
| Viewer | Read only | View-only access |
-->
---
## 3. API Endpoints
### 3.1 Authentication Endpoints
| Method | Endpoint | Description | Auth Required |
|--------|----------|-------------|---------------|
| POST | `/auth/register` | Register new user | No |
| POST | `/auth/login` | Login (email/password) | No |
| POST | `/auth/refresh` | Refresh access token | Yes (Refresh token) |
| POST | `/auth/logout` | Logout (invalidate tokens) | Yes |
| GET | `/auth/me` | Get current user info | Yes |
**Example: POST /auth/login**
Request:
```json
{
"email": "user@example.com",
"password": "secure_password"
}
```
Response (200 OK):
```json
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": 3600,
"user": {
"id": "uuid",
"email": "user@example.com",
"role": "editor"
}
}
```
---
### 3.2 User Management Endpoints
| Method | Endpoint | Description | Auth Required | Roles |
|--------|----------|-------------|---------------|-------|
| GET | `/users` | List all users (paginated) | Yes | Admin |
| GET | `/users/:id` | Get user by ID | Yes | Admin, self |
| PUT | `/users/:id` | Update user | Yes | Admin, self |
| DELETE | `/users/:id` | Delete user | Yes | Admin |
| PATCH | `/users/:id/password` | Change password | Yes | Admin, self |
**Example: GET /users?page=1&limit=20**
Response (200 OK):
```json
{
"data": [
{
"id": "uuid",
"email": "user@example.com",
"role": "editor",
"createdAt": "2024-01-01T00:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 20,
"total": 150,
"totalPages": 8
}
}
```
---
### 3.3 {{RESOURCE_1}} Endpoints
| Method | Endpoint | Description | Auth Required |
|--------|----------|-------------|---------------|
| GET | `/{{resource}}` | List {{resource}} | Yes |
| GET | `/{{resource}}/:id` | Get {{resource}} by ID | Yes |
| POST | `/{{resource}}` | Create {{resource}} | Yes |
| PUT | `/{{resource}}/:id` | Update {{resource}} | Yes |
| DELETE | `/{{resource}}/:id` | Delete {{resource}} | Yes |
<!-- Example: Products
| GET | `/products` | List products | Yes |
| GET | `/products/:id` | Get product by ID | Yes |
| POST | `/products` | Create product | Yes (Editor+) |
| PUT | `/products/:id` | Update product | Yes (Editor+) |
| DELETE | `/products/:id` | Delete product | Yes (Admin) |
-->
---
### 3.4 {{RESOURCE_2}} Endpoints
{{RESOURCE_2_ENDPOINTS}}
<!-- Repeat structure from 3.3 for additional resources: Orders, Categories, etc. -->
---
## 4. Request & Response Formats
### 4.1 Common Query Parameters
| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `page` | integer | Page number (1-based) | `?page=2` |
| `limit` | integer | Items per page (max 100) | `?limit=50` |
| `sort` | string | Sort field (+asc, -desc) | `?sort=-createdAt` |
| `filter` | string | Filter expression | `?filter=status:active` |
| `search` | string | Search query | `?search=keyword` |
### 4.2 Standard Response Structure
**Success Response:**
```json
{
"data": { /* resource data */ },
"meta": { /* metadata, pagination */ }
}
```
**Error Response:**
```json
{
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": [ /* validation errors, if applicable */ ]
}
}
```
---
## 5. Error Codes
### 5.1 HTTP Status Codes
| Status | Meaning | When Used |
|--------|---------|-----------|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | Created | Successful POST |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Invalid request format, validation errors |
| 401 | Unauthorized | Missing or invalid authentication token |
| 403 | Forbidden | Authenticated but insufficient permissions |
| 404 | Not Found | Resource not found |
| 409 | Conflict | Duplicate resource (email already exists) |
| 422 | Unprocessable Entity | Validation errors |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server error |
### 5.2 Custom Error Codes
| Code | HTTP Status | Description | Example |
|------|-------------|-------------|---------|
| `AUTH_INVALID_CREDENTIALS` | 401 | Invalid email/password | Login failed |
| `AUTH_TOKEN_EXPIRED` | 401 | JWT token expired | Token needs refresh |
| `AUTH_INSUFFICIENT_PERMISSIONS` | 403 | User lacks required role | Admin-only action |
| `VALIDATION_FAILED` | 422 | Input validation failed | Missing required field |
| `RESOURCE_NOT_FOUND` | 404 | Requested resource not found | User ID not found |
| `RESOURCE_CONFLICT` | 409 | Resource already exists | Email already registered |
| `RATE_LIMIT_EXCEEDED` | 429 | Too many requests | 100 req/min limit hit |
**Example Error Response:**
```json
{
"error": {
"code": "VALIDATION_FAILED",
"message": "Validation failed for request body",
"details": [
{
"field": "email",
"message": "Invalid email format"
},
{
"field": "password",
"message": "Password must be at least 8 characters"
}
]
}
}
```
---
## 6. Rate Limiting
**Limits:**
{{RATE_LIMITS}}
<!-- Example:
| Endpoint Type | Limit | Window |
|--------------|-------|--------|
| Authentication | 5 requests | 15 minutes |
| Read (GET) | 100 requests | 1 minute |
| Write (POST/PUT/DELETE) | 30 requests | 1 minute |
-->
**Rate Limit Headers:**
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
X-RateLimit-Reset: 1640000000
```
---
## 7. Pagination
**Request:**
```
GET /users?page=2&limit=20
```
**Response:**
```json
{
"data": [ /* 20 users */ ],
"pagination": {
"page": 2,
"limit": 20,
"total": 150,
"totalPages": 8,
"hasNext": true,
"hasPrev": true
},
"links": {
"self": "/users?page=2&limit=20",
"first": "/users?page=1&limit=20",
"prev": "/users?page=1&limit=20",
"next": "/users?page=3&limit=20",
"last": "/users?page=8&limit=20"
}
}
```
---
## 8. OpenAPI Specification
**OpenAPI Documentation:**
{{OPENAPI_LINK}}
<!-- Example: Swagger UI available at `/api-docs`, OpenAPI JSON at `/api-docs.json` -->
**Example OpenAPI Snippet (users endpoint):**
```yaml
paths:
/users:
get:
summary: List all users
tags: [Users]
security:
- bearerAuth: []
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: limit
in: query
schema:
type: integer
default: 20
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/User'
pagination:
$ref: '#/components/schemas/Pagination'
```
---
## 9. Maintenance
**Last Updated:** {{DATE}}
**Update Triggers:**
- New API endpoints added
- Authentication/authorization changes
- Error code modifications
- Rate limiting adjustments
- API versioning (major/minor releases)
**Verification:**
- [ ] All endpoints documented with methods/paths/params/responses
- [ ] Authentication requirements specified for each endpoint
- [ ] Error codes match implementation
- [ ] OpenAPI specification up to date
- [ ] Rate limits tested and validated
---
**Version:** 1.0.0
**Template Last Updated:** 2025-11-16

View File

@@ -0,0 +1,271 @@
# Software Architecture Document: {{PROJECT_NAME}}
**Document Version:** 1.0
**Date:** {{DATE}}
**Status:** {{STATUS}}
**Architecture Framework:** arc42 (simplified)
**Standard Compliance:** ISO/IEC/IEEE 42010:2022
<!-- SCOPE: System architecture (arc42 structure), C4 diagrams (Context, Container, Component), runtime scenarios (sequence diagrams), crosscutting concepts (security, error handling, configuration), ADR references ONLY. -->
<!-- DO NOT add here: Deployment procedures → runbook.md, Testing strategy → tests/README.md, Monitoring/Logging operations → runbook.md, Tech stack versions → tech_stack.md, API specs → api_spec.md, Database schema → database_schema.md, Design system → design_guidelines.md, Requirements → requirements.md -->
---
## 1. Introduction and Goals
### 1.1 Requirements Overview
{{REQUIREMENTS_OVERVIEW}}
<!-- Example: Brief summary of key functional requirements from Requirements Document and quality goals from Section 1.2 -->
### 1.2 Quality Goals
{{QUALITY_GOALS}}
<!-- Example: 1. Performance: <200ms (p95), 2. Security: GDPR compliance + AES-256, 3. Scalability: 1K→500K users, 4. Reliability: 99.9% uptime, 5. Maintainability: <5% technical debt -->
### 1.3 Stakeholders
{{STAKEHOLDERS_SUMMARY}}
<!-- Example: Product Owner (business direction), Development Team (implementation), DevOps (infrastructure), End Users (consumers), QA (quality assurance) -->
---
## 2. Constraints
### 2.1 Technical Constraints
{{TECHNICAL_CONSTRAINTS}}
<!-- Example: Languages: TypeScript/Node.js (team expertise), Database: PostgreSQL 12 (locked until Q2 2025), Cloud: AWS (company standard), Browser: Chrome/Firefox/Safari last 2 versions -->
### 2.2 Organizational Constraints
{{ORGANIZATIONAL_CONSTRAINTS}}
<!-- Example: Team Size: 11 people (no new hires this quarter), Compliance: GDPR mandatory (EU market), Process: Agile/Scrum 2-week sprints -->
### 2.3 Conventions
{{CONVENTIONS}}
<!-- Example: Code: ESLint+Prettier (CI enforced), Git: GitHub Flow, API: RESTful+JSON+semantic versioning, Testing: Risk-Based (2-5 E2E, 3-8 Integration, 5-15 Unit, Priority ≥15) -->
---
## 3. Context and Scope
### 3.1 Business Context
{{BUSINESS_CONTEXT}}
<!-- Example: System provides e-commerce platform connecting Customers (browsing/purchasing) and Admins (managing content) with external services: Payment Gateway (Stripe), Email (SendGrid), Auth (Okta) -->
**Business Context Diagram:**
```mermaid
{{BUSINESS_CONTEXT_DIAGRAM}}
```
**External Interfaces:**
{{EXTERNAL_INTERFACES}}
<!-- Example table: Stripe API | External | HTTPS REST | Payment processing | SendGrid API | External | HTTPS REST | Email notifications -->
### 3.2 Technical Context
{{TECHNICAL_CONTEXT}}
<!-- Example: Web Browser (HTTPS) → API Gateway → Application Server (Node.js) → PostgreSQL Database + Redis Cache + RabbitMQ Queue -->
**Technical Context Diagram:**
```mermaid
{{TECHNICAL_CONTEXT_DIAGRAM}}
```
---
## 4. Solution Strategy
### 4.1 Technology Decisions
{{TECHNOLOGY_DECISIONS}}
<!-- Example table: Frontend | React 18+Next.js 14 | SSR for SEO, team expertise | ADR-001 | Backend | Node.js+Express | JavaScript fullstack, async I/O | ADR-002 | Database | PostgreSQL 15 | ACID, JSON support, mature | ADR-003 -->
### 4.2 Top-Level Decomposition
{{TOP_LEVEL_DECOMPOSITION}}
<!-- Example: Layered Architecture (4 layers): Presentation (Next.js+React) → API (Express REST) → Business Logic (Service classes) → Data (Repositories+PostgreSQL+Redis). Rationale: Separation of concerns, testability, team familiarity -->
### 4.3 Approach to Quality Goals
{{QUALITY_APPROACH}}
<!-- Example table: Performance <200ms | Redis caching, DB indexing, CDN, async I/O | Security GDPR | Encryption at rest/transit, OAuth2, RBAC, audit logging | Scalability 500K | Horizontal scaling (K8s), stateless API, DB read replicas -->
---
## 5. Building Block View
### 5.1 Level 1: System Context (C4 Model)
{{SYSTEM_CONTEXT}}
<!-- Example: Highest level view - System as black box with external actors (Customers, Admins) and external systems (Stripe, SendGrid, Okta) -->
**System Context Diagram:**
```mermaid
{{SYSTEM_CONTEXT_DIAGRAM}}
```
### 5.2 Level 2: Container Diagram (C4 Model)
{{CONTAINER_DIAGRAM}}
<!-- Example: Deployable units - Web App (Next.js), API (Node.js+Express), Background Workers (Node.js), Database (PostgreSQL), Cache (Redis), Queue (RabbitMQ) -->
**Container Diagram:**
```mermaid
{{CONTAINER_DIAGRAM_MERMAID}}
```
### 5.3 Level 3: Component Diagram (C4 Model)
{{COMPONENT_DIAGRAM}}
<!-- Example: API breakdown - Controllers (HTTP endpoints) → Services (business logic) → Repositories (data access) + Middleware (auth, logging, errors) -->
**Components within API Container:**
```mermaid
{{COMPONENT_DIAGRAM_MERMAID}}
```
**Key Components:**
{{KEY_COMPONENTS}}
<!-- Example table: AuthController | Handle login/register endpoints | AuthService, JWTService | ProductService | Product catalog business logic | ProductRepository, CacheService | OrderService | Order processing workflow | OrderRepository, PaymentClient, EmailClient -->
**Infrastructure Layer Components:**
{{INFRASTRUCTURE_COMPONENTS}}
<!-- Example table:
Component | Responsibility | Dependencies
DataAccess/ | EF Core DbContext, Repositories, Migrations | PostgreSQL, Entity Framework
ExternalServices/ | Third-party integrations (Excel, PDF, Email) | ClosedXML, QuestPDF, MailKit
Localization/ | Resource files, culture management | Microsoft.Extensions.Localization
-->
---
## 6. Runtime View
### 6.1 Scenario 1: User Registration
{{SCENARIO_USER_REGISTRATION}}
<!-- Example: User fills form → Web App POST /api/v1/auth/register → API validates + hashes password → DB creates user → Email Service sends verification → User receives success message -->
**Sequence Diagram:**
```mermaid
{{SCENARIO_1_SEQUENCE_DIAGRAM}}
```
### 6.2 Scenario 2: Product Purchase Flow
{{SCENARIO_PURCHASE_FLOW}}
<!-- Example: User clicks Purchase → API creates order → Payment Client calls Stripe → Queue publishes order_created → Background Worker sends confirmation email + updates DB status -->
**Sequence Diagram:**
```mermaid
{{SCENARIO_2_SEQUENCE_DIAGRAM}}
```
### 6.3 [Additional Key Scenarios]
{{ADDITIONAL_SCENARIOS}}
<!-- Example: Add 2-3 more critical scenarios with sequence diagrams (e.g., Password Reset, Search Products, Admin Content Update) -->
---
## 7. Crosscutting Concepts
### 7.1 Security Concept
{{SECURITY_CONCEPT}}
<!-- Example: Auth: JWT (1h expiration) + refresh tokens (30d), Authorization: RBAC (5 roles), Encryption: TLS 1.3 (transit) + AES-256 (at rest for PII), API: Rate limiting (100 req/min), Secrets: AWS Secrets Manager (prod), Audit: All write operations logged -->
### 7.2 Error Handling Concept
{{ERROR_HANDLING_CONCEPT}}
<!-- Example: Custom domain exceptions (PaymentFailedError, UserNotFoundError), Global Express middleware catches all, JSON format {error: {code, message, details}}, Logging with trace_id + stack (Datadog), Sanitized user-facing messages, Retry: Exponential backoff for transient failures -->
### 7.3 Configuration Management Concept
{{CONFIG_MANAGEMENT_CONCEPT}}
<!-- Example: Env vars: .env (dev) + AWS Secrets Manager (prod), Library: dotenv + Joi validation, Environments: Dev (local) + Staging (AWS) + Production (AWS), Secrets: Never in Git, rotated quarterly, Feature Flags: LaunchDarkly or custom Redis-based -->
### 7.4 Data Access Pattern
{{DATA_ACCESS_PATTERN}}
<!-- Example: Repository Pattern (Generic + Specific repositories), Unit of Work via DbContext.SaveChanges(), EF Core code-first migrations, Connection pooling (default 100), Lazy loading disabled (explicit Include()), Query optimization (AsNoTracking() for reads), Transaction management (explicit for multi-repo operations) -->
---
## 8. Architecture Decisions (ADRs)
{{ADR_LIST}}
<!-- Example: List all ADRs with links - [ADR-001](../adrs/adr-001-frontend-framework.md) Use React+Next.js | Accepted | 2024-10-15 -->
**Critical ADRs Summary:**
{{CRITICAL_ADRS_SUMMARY}}
<!-- Example: Brief summary of top 3-5 most impactful decisions (e.g., ADR-001 React+Next.js for SEO requirements, ADR-003 PostgreSQL for ACID compliance, ADR-007 Kubernetes for horizontal scalability) -->
---
## 9. Quality Requirements
### 9.1 Quality Tree
{{QUALITY_TREE}}
<!-- Example: ISO 25010 hierarchy - Performance (Response time <200ms p95, Throughput >10K req/sec), Security (Authentication: OAuth2+JWT, Authorization: RBAC, Encryption: TLS 1.3+AES-256), Scalability (Horizontal: 1K→500K users), Reliability (Uptime: 99.9%, Failover: <60s), Maintainability (Code coverage >80%, Tech debt <5%) -->
### 9.2 Quality Scenarios
{{QUALITY_SCENARIOS}}
<!-- Example table: QS-1 | Performance | User searches "laptop", system returns results | <200ms (p95) | MUST | QS-2 | Scalability | Black Friday spike 1K→50K concurrent users | No degradation | MUST | QS-3 | Security | Attacker SQL injection on login | Attack blocked + logged | MUST -->
---
## 10. Risks and Technical Debt
### 10.1 Known Technical Risks
{{TECHNICAL_RISKS}}
<!-- Example: 1. PostgreSQL 12 EOL approaching (security risk), 2. No database sharding (scalability limit at 5TB), 3. Single region deployment (DR risk), 4. Third-party API dependency (Stripe downtime impact) -->
### 10.2 Technical Debt
{{TECHNICAL_DEBT}}
<!-- Example table: PostgreSQL 12 EOL | Security risk | Upgrade to PG 15 | Q2 2025 | No database sharding | Scalability limit 5TB | Implement sharding | Year 2 | Monolithic deployment | Slow rollouts | Migrate to microservices | Q3 2025 -->
### 10.3 Mitigation Strategies
{{MITIGATION_STRATEGIES}}
<!-- Example: 1. PostgreSQL upgrade: Plan migration window Q2 2025, test on staging first, 2. Sharding: Design partition strategy (by user_id hash), 3. Microservices: Incremental extraction (start with payment service), 4. Stripe dependency: Implement circuit breaker + fallback queue -->
---
## 11. Glossary
| Term | Definition |
|------|------------|
| {{TERM_1}} | {{DEFINITION_1}} |
| Container | Deployable/runnable unit (C4 Model), NOT Docker container |
| Component | Grouping of related functionality within a container |
| SSR | Server-Side Rendering |
| RBAC | Role-Based Access Control |
| JWT | JSON Web Token |
---
## 12. References
1. arc42 Architecture Template v8.2 - https://arc42.org/
2. C4 Model for Visualizing Software Architecture - https://c4model.com/
3. ISO/IEC/IEEE 42010:2022 - Architecture description
4. Michael Nygard's ADR Format - https://cognitect.com/blog/2011/11/15/documenting-architecture-decisions
5. {{PROJECT_NAME}} Requirements Document
6. {{PROJECT_NAME}} ADRs Directory
---
## Maintenance
**Last Updated:** {{DATE}}
**Update Triggers:**
- New architectural decisions (create new ADR, update Section 8)
- New microservices or containers added (update C4 Container diagram)
- New components in existing services (update C4 Component diagram)
- New external systems or integrations (update Context diagram)
- Major refactoring affecting system structure
- Changes to quality requirements or scenarios
**Verification:**
- [ ] All C4 diagrams (Context, Container, Component) are consistent
- [ ] All ADRs referenced in Section 8 exist in adrs/ directory
- [ ] Runtime view scenarios cover main use cases
- [ ] All external systems documented in Technical Context
- [ ] All placeholders replaced with actual content
---
## Revision History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | {{DATE}} | {{AUTHOR}} | Initial version |
---
**Version:** 4.0.0 (Added Infrastructure Layer guidance: Section 5.3 Infrastructure Components + Section 7.4 Data Access Pattern)
**Template Last Updated:** 2025-11-18

View File

@@ -0,0 +1,293 @@
# Database Schema: {{PROJECT_NAME}}
**Document Version:** 1.0
**Date:** {{DATE}}
**Status:** {{STATUS}}
<!-- SCOPE: Database schema (ER diagrams, table definitions, data dictionary, indexes, constraints, migrations, normalization) ONLY. -->
<!-- DO NOT add here: API endpoints → api_spec.md, Tech stack versions → tech_stack.md, Architecture patterns → architecture.md, Requirements → requirements.md, Deployment → runbook.md -->
---
## 1. Introduction
### 1.1 Purpose
This document specifies the database schema, entity relationships, and data dictionary for {{PROJECT_NAME}}.
### 1.2 Database System
{{DATABASE_SYSTEM}}
<!-- Example: PostgreSQL 16.x, MySQL 8.x, MongoDB 7.x -->
### 1.3 Normalization Level
{{NORMALIZATION_LEVEL}}
<!-- Example: Third Normal Form (3NF) with selective denormalization for performance -->
---
## 2. Entity Relationship Diagram
### 2.1 High-Level ER Diagram
```mermaid
erDiagram
{{ER_DIAGRAM_ENTITIES_RELATIONSHIPS}}
```
<!-- Example:
```mermaid
erDiagram
USERS ||--o{ ORDERS : places
USERS ||--o{ REVIEWS : writes
ORDERS ||--|{ ORDER_ITEMS : contains
PRODUCTS ||--o{ ORDER_ITEMS : "ordered in"
PRODUCTS ||--o{ REVIEWS : "reviewed in"
CATEGORIES ||--o{ PRODUCTS : contains
USERS {
uuid id PK
string email UK
string password_hash
string role
timestamp created_at
}
PRODUCTS {
uuid id PK
uuid category_id FK
string name
text description
decimal price
int stock_quantity
}
ORDERS {
uuid id PK
uuid user_id FK
decimal total_amount
string status
timestamp created_at
}
```
-->
---
## 3. Data Dictionary
### 3.1 {{TABLE_1}} Table
**Table Name:** `{{table_1}}`
**Description:** {{TABLE_1_DESCRIPTION}}
<!-- Example: users - Stores user account information including authentication credentials and profile data -->
| Column | Type | Null | Default | Constraints | Description |
|--------|------|------|---------|-------------|-------------|
| `id` | UUID | NO | gen_random_uuid() | PRIMARY KEY | Unique user identifier |
| `email` | VARCHAR(255) | NO | - | UNIQUE, CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$') | User email address |
| `password_hash` | VARCHAR(255) | NO | - | - | bcrypt hashed password |
| `first_name` | VARCHAR(100) | YES | NULL | - | User first name |
| `last_name` | VARCHAR(100) | YES | NULL | - | User last name |
| `role` | VARCHAR(20) | NO | 'viewer' | CHECK (role IN ('admin', 'editor', 'viewer')) | User role for RBAC |
| `is_active` | BOOLEAN | NO | TRUE | - | Account status |
| `created_at` | TIMESTAMP | NO | CURRENT_TIMESTAMP | - | Account creation timestamp |
| `updated_at` | TIMESTAMP | NO | CURRENT_TIMESTAMP | ON UPDATE CURRENT_TIMESTAMP | Last update timestamp |
**Indexes:**
```sql
CREATE UNIQUE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_role ON users(role);
CREATE INDEX idx_users_created_at ON users(created_at);
```
**Relationships:**
- `users.id``orders.user_id` (One-to-Many)
- `users.id``reviews.user_id` (One-to-Many)
---
### 3.2 {{TABLE_2}} Table
**Table Name:** `{{table_2}}`
**Description:** {{TABLE_2_DESCRIPTION}}
<!-- Example: products - Product catalog with pricing, inventory, and categorization -->
| Column | Type | Null | Default | Constraints | Description |
|--------|------|------|---------|-------------|-------------|
| `id` | UUID | NO | gen_random_uuid() | PRIMARY KEY | Product identifier |
| `category_id` | UUID | NO | - | FOREIGN KEY REFERENCES categories(id) ON DELETE RESTRICT | Product category |
| `name` | VARCHAR(200) | NO | - | - | Product name |
| `slug` | VARCHAR(220) | NO | - | UNIQUE | URL-friendly name |
| `description` | TEXT | YES | NULL | - | Product description |
| `price` | DECIMAL(10,2) | NO | - | CHECK (price >= 0) | Product price (USD) |
| `stock_quantity` | INTEGER | NO | 0 | CHECK (stock_quantity >= 0) | Available inventory |
| `is_published` | BOOLEAN | NO | FALSE | - | Publish status |
| `created_at` | TIMESTAMP | NO | CURRENT_TIMESTAMP | - | Creation timestamp |
| `updated_at` | TIMESTAMP | NO | CURRENT_TIMESTAMP | ON UPDATE CURRENT_TIMESTAMP | Last update timestamp |
**Indexes:**
```sql
CREATE UNIQUE INDEX idx_products_slug ON products(slug);
CREATE INDEX idx_products_category_id ON products(category_id);
CREATE INDEX idx_products_is_published ON products(is_published);
CREATE INDEX idx_products_price ON products(price);
```
**Relationships:**
- `categories.id``products.category_id` (One-to-Many)
- `products.id``order_items.product_id` (One-to-Many)
- `products.id``reviews.product_id` (One-to-Many)
---
### 3.3 {{TABLE_3}} Table
{{TABLE_3_DEFINITION}}
<!-- Repeat structure from 3.1/3.2 for additional tables: orders, order_items, categories, reviews, etc. -->
---
## 4. Database Constraints
### 4.1 Foreign Key Constraints
| FK Name | Child Table | Child Column | Parent Table | Parent Column | On Delete | On Update |
|---------|-------------|--------------|--------------|---------------|-----------|-----------|
| `fk_orders_user` | orders | user_id | users | id | CASCADE | CASCADE |
| `fk_products_category` | products | category_id | categories | id | RESTRICT | CASCADE |
| `fk_order_items_order` | order_items | order_id | orders | id | CASCADE | CASCADE |
| `fk_order_items_product` | order_items | product_id | products | id | RESTRICT | CASCADE |
<!-- Example explanations:
- CASCADE: If parent deleted, delete child rows
- RESTRICT: Prevent parent deletion if children exist
- SET NULL: Set child FK to NULL if parent deleted
-->
### 4.2 Check Constraints
| Constraint Name | Table | Expression | Description |
|-----------------|-------|------------|-------------|
| `chk_users_role` | users | `role IN ('admin', 'editor', 'viewer')` | Valid role values |
| `chk_products_price` | products | `price >= 0` | Non-negative price |
| `chk_products_stock` | products | `stock_quantity >= 0` | Non-negative stock |
| `chk_orders_status` | orders | `status IN ('pending', 'paid', 'shipped', 'delivered', 'canceled')` | Valid order statuses |
---
## 5. Indexes Strategy
### 5.1 Primary Indexes
{{PRIMARY_INDEXES}}
<!-- Example: All tables use UUID primary keys for distributed scalability and security (no sequential IDs) -->
### 5.2 Secondary Indexes
{{SECONDARY_INDEXES}}
<!-- Example:
- Email lookup: idx_users_email (UNIQUE) - fast authentication
- Category filtering: idx_products_category_id - product catalog queries
- Order history: idx_orders_user_id - user dashboard
- Price range queries: idx_products_price - product search/filter
-->
### 5.3 Composite Indexes
{{COMPOSITE_INDEXES}}
<!-- Example:
```sql
CREATE INDEX idx_products_category_published ON products(category_id, is_published);
CREATE INDEX idx_orders_user_created ON orders(user_id, created_at DESC);
```
Purpose: Optimize common query patterns (published products by category, recent orders by user)
-->
---
## 6. Database Migrations
### 6.1 Migration Tool
{{MIGRATION_TOOL}}
<!-- Example: Prisma Migrate, Flyway, Liquibase, Alembic (Python), TypeORM migrations -->
### 6.2 Migration Strategy
{{MIGRATION_STRATEGY}}
<!-- Example:
- Versioned migrations (001_initial_schema.sql, 002_add_reviews.sql)
- Up/Down scripts for rollback capability
- Automated migration on deployment (CI/CD)
- Manual review for production migrations (peer review required)
-->
### 6.3 Migration Examples
**Migration 001: Initial Schema**
```sql
-- Up Migration
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT 'viewer',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Down Migration
DROP TABLE IF EXISTS users;
```
**Migration 002: Add Soft Delete**
```sql
-- Up Migration
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL;
CREATE INDEX idx_users_deleted_at ON users(deleted_at);
-- Down Migration
ALTER TABLE users DROP COLUMN deleted_at;
```
---
## 7. Data Types & Standards
### 7.1 Common Data Types
| Logical Type | PostgreSQL Type | MySQL Type | Description |
|--------------|----------------|------------|-------------|
| UUID | UUID | CHAR(36) | Unique identifiers |
| Money | DECIMAL(10,2) | DECIMAL(10,2) | Currency values (2 decimal places) |
| Timestamp | TIMESTAMP | DATETIME | Date and time (UTC) |
| Boolean | BOOLEAN | TINYINT(1) | True/false values |
| JSON | JSONB | JSON | Semi-structured data |
### 7.2 Naming Conventions
{{NAMING_CONVENTIONS}}
<!-- Example:
- Tables: snake_case plural (users, order_items)
- Columns: snake_case (first_name, created_at)
- Indexes: idx_table_column (idx_users_email)
- Foreign Keys: fk_child_parent (fk_orders_user)
- Primary Keys: Always named 'id'
-->
---
## 8. Maintenance
**Last Updated:** {{DATE}}
**Update Triggers:**
- New tables added
- Schema changes (columns, indexes, constraints)
- Migration scripts created
- Denormalization for performance
- Relationship changes
**Verification:**
- [ ] All tables documented with columns/types/constraints
- [ ] ER diagram matches actual schema
- [ ] Indexes match query patterns
- [ ] Foreign keys enforce referential integrity
- [ ] Migrations tested (up + down)
---
**Version:** 1.0.0
**Template Last Updated:** 2025-11-16

View File

@@ -0,0 +1,351 @@
# Design Guidelines: {{PROJECT_NAME}}
**Document Version:** 1.0
**Date:** {{DATE}}
**Status:** {{STATUS}}
<!-- SCOPE: UI/UX design system (typography, colors, spacing, grid), component library (buttons, forms, cards, navigation, modals), layout patterns (page templates), accessibility guidelines (WCAG AA, keyboard, ARIA), responsive behavior (breakpoints, adaptations), branding (logo, imagery, icons) ONLY. -->
<!-- DO NOT add here: Technical implementation → tech_stack.md, React/Vue code examples → Task descriptions, API contracts → api_spec.md, State management → architecture.md, Performance optimization → runbook.md -->
---
## 1. Design Approach
### 1.1 Design Philosophy
{{DESIGN_PHILOSOPHY}}
<!-- Example: Reference-Based Approach inspired by Airbnb Design System - professional, user-friendly, consistency across platform. Focuses on clarity, simplicity, and accessibility. -->
### 1.2 Design Inspiration
{{DESIGN_INSPIRATION}}
<!-- Example: Primary reference: example.com design system. Secondary influences: Material Design (components), Tailwind CSS (utility-first approach), Carbon Design System (enterprise patterns) -->
---
## 2. Core Design Elements
### 2.1 Typography
**Font Families:**
{{FONT_FAMILIES}}
<!-- Example:
- Primary (Body): Inter (400, 500, 600) - high legibility for long-form text
- Headings: Poppins (600, 700) - distinct hierarchy, professional
- Monospace: JetBrains Mono (400) - code snippets, technical content
-->
**Type Scale:**
{{TYPE_SCALE}}
<!-- Example (Tailwind CSS classes):
| Element | Class | Size | Line Height | Usage |
|---------|-------|------|-------------|-------|
| Hero | text-5xl | 48px | 1.2 | Landing page hero headlines |
| H1 | text-4xl | 36px | 1.25 | Page titles |
| H2 | text-2xl | 24px | 1.33 | Section headers |
| H3 | text-xl | 20px | 1.4 | Sub-section headers |
| Body | text-base | 16px | 1.5 | Paragraphs, content |
| Small | text-sm | 14px | 1.43 | Captions, labels |
| Tiny | text-xs | 12px | 1.33 | Metadata, timestamps |
-->
**Line Height:**
{{LINE_HEIGHT}}
<!-- Example: Headings: 1.2-1.33 (tight), Body: 1.5 (comfortable reading), UI elements: 1.25 (compact) -->
---
### 2.2 Color System
**Primary Colors:**
{{PRIMARY_COLORS}}
<!-- Example:
- Primary: #FF6B35 (Vibrant orange - CTAs, interactive elements)
- Secondary: #004E89 (Deep blue - headings, trust/authority)
- Accent: #1A936F (Teal green - highlights, success states)
-->
**Semantic Colors:**
{{SEMANTIC_COLORS}}
<!-- Example:
| Purpose | Color | Hex | Usage |
|---------|-------|-----|-------|
| Success | Green | #10B981 | Form success, confirmations |
| Warning | Amber | #F59E0B | Cautions, important notices |
| Error | Red | #EF4444 | Form errors, destructive actions |
| Info | Blue | #3B82F6 | Informational messages, tips |
-->
**Neutral Colors:**
{{NEUTRAL_COLORS}}
<!-- Example:
| Shade | Hex | Usage |
|-------|-----|-------|
| Dark Text | #1F2937 | Primary text, headings |
| Medium Gray | #6B7280 | Secondary text, labels |
| Light Gray | #F3F4F6 | Backgrounds, cards |
| Border | #E5E7EB | Dividers, input borders |
| White | #FFFFFF | Backgrounds, contrast |
-->
**Color Accessibility:**
{{COLOR_ACCESSIBILITY}}
<!-- Example: All color combinations meet WCAG 2.1 AA contrast ratio (4.5:1 for text, 3:1 for UI components). Primary on White: 4.8:1, Dark Text on Light Gray: 12.6:1 -->
---
### 2.3 Layout System
**Spacing Primitives:**
{{SPACING_SYSTEM}}
<!-- Example: Tailwind spacing units: 2 (0.5rem/8px), 4 (1rem/16px), 6 (1.5rem/24px), 8 (2rem/32px), 12 (3rem/48px), 16 (4rem/64px), 20 (5rem/80px), 24 (6rem/96px) -->
**Container Strategy:**
{{CONTAINER_STRATEGY}}
<!-- Example:
| Container Type | Max Width | Padding | Usage |
|----------------|-----------|---------|-------|
| Page | max-w-7xl (1280px) | px-6 | Main page wrapper |
| Content | max-w-6xl (1152px) | px-4 | Article content |
| Narrow | max-w-4xl (896px) | px-4 | Forms, focused content |
| Wide | max-w-full | px-8 | Dashboards, data tables |
-->
**Grid System:**
{{GRID_SYSTEM}}
<!-- Example: 12-column grid, gap-6 (24px), responsive breakpoints (sm/md/lg/xl/2xl). Example: `grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6` -->
---
### 2.4 Component Library
#### 2.4.1 Navigation
{{NAVIGATION_COMPONENTS}}
<!-- Example:
- **Header**: Fixed top, h-16 (64px), bg-white shadow-sm, z-50
- **Logo**: Left-aligned, h-8 (32px)
- **Main Menu**: Center (desktop), hamburger (mobile), active state: border-b-2 border-primary
- **User Menu**: Right-aligned, dropdown on click, avatar icon
-->
#### 2.4.2 Buttons
{{BUTTON_COMPONENTS}}
<!-- Example:
| Variant | Classes | Usage |
|---------|---------|-------|
| Primary | bg-primary text-white hover:bg-primary-dark px-6 py-3 rounded-lg | Primary CTAs, submit actions |
| Secondary | border-2 border-primary text-primary hover:bg-primary-light px-6 py-3 rounded-lg | Secondary actions |
| Text | text-primary hover:underline | Tertiary actions, links |
| Icon | p-2 rounded-full hover:bg-gray-100 | Icon-only buttons, close buttons |
Size variants: Small (px-4 py-2 text-sm), Medium (px-6 py-3 text-base), Large (px-8 py-4 text-lg)
-->
#### 2.4.3 Forms
{{FORM_COMPONENTS}}
<!-- Example:
- **Input Fields**: border border-gray-300 rounded-lg px-4 py-3 focus:ring-2 focus:ring-primary focus:border-primary
- **Labels**: text-sm font-medium text-gray-700 mb-2
- **Error Messages**: text-red-500 text-sm mt-1
- **Help Text**: text-gray-500 text-sm mt-1
- **Checkboxes/Radio**: Accent color matches primary, 44px min tap target
-->
#### 2.4.4 Cards
{{CARD_COMPONENTS}}
<!-- Example:
- **Default**: bg-white shadow-md rounded-lg border border-gray-200 p-6
- **Hover State**: hover:shadow-lg transition-shadow duration-200
- **Interactive**: cursor-pointer hover:border-primary
- **Image Card**: Image top (aspect-16/9), content below, rounded-t-lg for image
-->
#### 2.4.5 Modals & Dialogs
{{MODAL_COMPONENTS}}
<!-- Example:
- **Backdrop**: fixed inset-0 bg-black/50 z-40 backdrop-blur-sm
- **Modal**: fixed inset-0 flex items-center justify-center z-50
- **Content**: bg-white rounded-lg shadow-xl max-w-lg w-full p-6 m-4
- **Close Button**: Absolute top-right, p-2, X icon
- **Actions**: Right-aligned button group, primary + secondary
-->
#### 2.4.6 Tables
{{TABLE_COMPONENTS}}
<!-- Example:
- **Header**: bg-gray-50 text-left font-semibold text-gray-700 px-4 py-3
- **Rows**: border-b border-gray-200 hover:bg-gray-50
- **Cells**: px-4 py-3 text-gray-900
- **Responsive**: Horizontal scroll on mobile, sticky header optional
-->
---
### 2.5 Responsive Behavior
**Breakpoints:**
{{BREAKPOINTS}}
<!-- Example (Tailwind defaults):
| Breakpoint | Min Width | Device | Layout |
|------------|-----------|--------|--------|
| sm | 640px | Large phones | Single column, stacked nav |
| md | 768px | Tablets | 2-column grids, horizontal nav |
| lg | 1024px | Laptops | 3-column grids, full navigation |
| xl | 1280px | Desktops | 4-column grids, max-width containers |
| 2xl | 1536px | Large displays | Wide layouts, extra whitespace |
-->
**Layout Adaptations:**
{{RESPONSIVE_LAYOUTS}}
<!-- Example:
- **Desktop (>1024px)**: 3-column grid for products, sidebar navigation, header with full menu
- **Tablet (768-1024px)**: 2-column grid, hamburger menu, condensed header
- **Mobile (<768px)**: 1-column stack, bottom navigation, collapsible sections
- **Touch Targets**: Min 44x44px for all interactive elements on mobile
-->
---
## 3. Accessibility Guidelines
### 3.1 WCAG Compliance
{{WCAG_LEVEL}}
<!-- Example: WCAG 2.1 Level AA compliance (minimum). Contrast ratios: 4.5:1 for text, 3:1 for UI components. -->
### 3.2 Keyboard Navigation
{{KEYBOARD_NAVIGATION}}
<!-- Example:
- All interactive elements focusable via Tab key
- Visible focus ring: ring-2 ring-primary ring-offset-2
- Logical tab order (top-to-bottom, left-to-right)
- Skip to main content link (hidden, appears on Tab)
- Modal focus trap (Tab cycles within modal)
-->
### 3.3 Screen Reader Support
{{SCREEN_READER}}
<!-- Example:
- ARIA labels for icon buttons: aria-label="Close dialog"
- Semantic HTML: <nav>, <main>, <article>, <aside>
- Table headers with scope attribute
- Form labels associated with inputs (for/id)
- Alt text for all images (descriptive, not decorative)
-->
### 3.4 Focus Management
{{FOCUS_MANAGEMENT}}
<!-- Example:
- Focus visible on all interactive elements (ring-2 ring-primary)
- Focus returns to trigger after modal close
- Error messages announced to screen readers (aria-live="polite")
- Skip navigation links for keyboard users
-->
---
## 4. Branding & Visual Identity
### 4.1 Logo Usage
{{LOGO_USAGE}}
<!-- Example:
- Primary logo (full color) on light backgrounds
- Secondary logo (monochrome white) on dark backgrounds
- Minimum size: 32px height (digital), 0.5in (print)
- Clear space: Logo height on all sides
- Never stretch, skew, or rotate logo
-->
### 4.2 Imagery Guidelines
{{IMAGERY_GUIDELINES}}
<!-- Example:
- Hero images: 16:9 aspect ratio, min 1920x1080px
- Product photos: 1:1 aspect ratio, min 800x800px
- Illustrations: Flat design style, minimalist, 2-3 color palette
- Image optimization: WebP format, lazy loading, responsive srcset
- Stock photos: Professional, diverse, authentic (avoid clichés)
-->
### 4.3 Iconography
{{ICONOGRAPHY}}
<!-- Example:
- Icon library: Heroicons (outline for UI, solid for emphasis)
- Sizes: 16px (inline), 24px (buttons), 32px (features), 48px (headers)
- Style: Outline (2px stroke), consistent visual weight
- Color: Inherit text color or use semantic colors
-->
---
## 5. Page Layout Patterns
### 5.1 {{PAGE_TYPE_1}}
{{PAGE_LAYOUT_1}}
<!-- Example: Homepage
- Hero section: Full-width, py-20, bg-gradient, centered CTA
- Features grid: 3-column (desktop), 1-column (mobile), gap-8
- CTA section: bg-primary, text-white, py-16, centered
- Footer: 4-column links (desktop), stacked (mobile)
-->
### 5.2 {{PAGE_TYPE_2}}
{{PAGE_LAYOUT_2}}
<!-- Example: Dashboard
- Fixed header: h-16, shadow-sm
- Sidebar: w-64 (desktop), hidden (mobile, toggle button)
- Main content: Filters bar → KPI cards (4-column) → Charts grid (2-column) → Data table
- Mobile: Bottom navigation, stacked KPI cards
-->
### 5.3 {{PAGE_TYPE_3}}
{{PAGE_LAYOUT_3}}
<!-- Example: Form page
- Centered narrow container (max-w-2xl)
- Progress indicator (multi-step forms)
- Section dividers with headings
- Action buttons: Right-aligned, primary + secondary
-->
---
## 6. Internationalization (if applicable)
{{I18N_GUIDELINES}}
<!-- Example:
- Language toggle: Top-right header, flag icons + text
- RTL support: Arabic/Hebrew layouts (flex-row-reverse)
- Date/time formatting: Intl.DateTimeFormat API
- Number formatting: Intl.NumberFormat (1,234.56 vs 1.234,56)
- Text expansion: Allow 30% growth for translations (German, Finnish)
- Font fallbacks: Sans-serif for Arabic (Noto Sans Arabic), Cyrillic (Roboto)
-->
---
## 7. Maintenance
**Last Updated:** {{DATE}}
**Update Triggers:**
- New component added to design system
- Brand refresh or logo change
- Accessibility audit findings
- Design system library update (Material UI, Ant Design, etc.)
- Responsive breakpoint changes
- Color palette modifications
**Verification:**
- [ ] All components documented with examples
- [ ] Color contrast ratios WCAG AA compliant (4.5:1 text, 3:1 UI)
- [ ] Typography scale consistent across platform
- [ ] Accessibility guidelines up to date
- [ ] Responsive behaviors tested on all breakpoints
- [ ] Logo usage rules followed
---
**Version:** 1.0.0
**Template Last Updated:** 2025-11-16

View File

@@ -0,0 +1,168 @@
# Requirements Specification: {{PROJECT_NAME}}
**Document Version:** 1.0
**Date:** {{DATE}}
**Status:** {{STATUS}}
**Standard Compliance:** ISO/IEC/IEEE 29148:2018
<!-- SCOPE: Functional requirements (FR-XXX-NNN) with MoSCoW prioritization, acceptance criteria, constraints, assumptions, traceability ONLY. -->
<!-- DO NOT add here: NFR (removed completely per project policy), Tech stack → tech_stack.md, Database → database_schema.md, API → api_spec.md, Design system → design_guidelines.md, Operations → runbook.md, Architecture → architecture.md, Implementation → technical_specification.md -->
---
## 1. Introduction
### 1.1 Purpose
This document specifies the functional requirements for {{PROJECT_NAME}}.
### 1.2 Scope
{{PROJECT_SCOPE}}
<!-- Example: E-commerce platform for retail sales. IN SCOPE: Product catalog, shopping cart, checkout, user accounts, order management. OUT OF SCOPE: Warehouse management, shipping logistics, third-party marketplace integration -->
### 1.3 Intended Audience
- Development Team
- QA Team
- DevOps Team
- Technical Writers
- System Architects
### 1.4 References
- Project Charter: {{PROJECT_CHARTER_LINK}}
- Architecture Document: {{ARCHITECTURE_DOC_LINK}}
- Definition of Done: {{DOD_LINK}}
---
## 2. Overall Description
### 2.1 Product Perspective
{{PRODUCT_PERSPECTIVE}}
<!-- Example: Web-based SaaS application replacing legacy desktop system. Interfaces with existing CRM (Salesforce), Payment Gateway (Stripe), Email Service (SendGrid). Deployed on AWS cloud infrastructure -->
### 2.2 User Classes and Characteristics
{{USER_CLASSES}}
<!-- Example: 1. End Customers (tech-savvy, mobile-first, 18-45 age), 2. Admin Users (tech-proficient, desktop, content management), 3. Support Team (moderate tech skills, tickets + reports), 4. API Consumers (developers, programmatic access) -->
### 2.3 Operating Environment
{{OPERATING_ENVIRONMENT}}
<!-- Example: Client: Modern web browsers (Chrome/Firefox/Safari/Edge last 2 versions), Mobile (iOS 14+, Android 10+). Server: AWS (Node.js 18+, PostgreSQL 15, Redis 7), Docker containers, Kubernetes orchestration -->
---
## 3. Functional Requirements
### 3.1 User Management
{{FR_USER_MANAGEMENT}}
<!-- Example: FR-UM-001 (MUST): Users shall register with email+password. FR-UM-002 (MUST): Users shall login with OAuth2 (Google/GitHub). FR-UM-003 (SHOULD): Users shall reset password via email link. FR-UM-004 (MUST): Admins shall manage user roles (Admin/Editor/Viewer) -->
### 3.2 [Feature Group 2]
{{FR_FEATURE_GROUP_2}}
<!-- Example: FR-PC-001 (MUST): System shall display product catalog with search/filter. FR-PC-002 (MUST): Users shall add products to cart. FR-PC-003 (SHOULD): System shall recommend related products -->
### 3.3 [Feature Group 3]
{{FR_FEATURE_GROUP_3}}
<!-- Example: FR-CHK-001 (MUST): Users shall checkout with Stripe payment. FR-CHK-002 (MUST): System shall send order confirmation email. FR-CHK-003 (COULD): Users shall save payment methods for reuse -->
---
## 4. Acceptance Criteria (High-Level)
{{HIGH_LEVEL_ACCEPTANCE_CRITERIA}}
<!-- Example:
1. All MUST functional requirements implemented and passing tests
2. All SHOULD functional requirements reviewed and prioritized
3. All critical user journeys end-to-end tested
4. Acceptance criteria verified for each requirement
5. Traceability matrix complete (FR → Epic → Story → Test Case)
-->
---
## 5. Constraints
### 5.1 Technical Constraints
{{TECHNICAL_CONSTRAINTS}}
<!-- Example: Languages: TypeScript/Node.js (team expertise), Database: PostgreSQL 12 (upgrade planned Q2 2025), Cloud: AWS only (company standard), API: RESTful (no GraphQL this release), Legacy integration: SAP SOAP API (max 10 req/sec) -->
### 5.2 Regulatory Constraints
{{REGULATORY_CONSTRAINTS}}
<!-- Example: GDPR (EU users): Right to erasure, data portability. PCI DSS (payment): Cannot store CVV, encrypted card data. SOC 2: Annual audit required. Data residency: EU data must stay in eu-central-1 region -->
---
## 6. Assumptions and Dependencies
### 6.1 Assumptions
{{ASSUMPTIONS}}
<!-- Example: 1. Users have stable internet (>1 Mbps), 2. Third-party APIs (Stripe, SendGrid) maintain 99.9% uptime, 3. Team size remains 11 people through Year 1, 4. AWS infrastructure scales as needed, 5. Users accept cookies (session management) -->
### 6.2 Dependencies
{{DEPENDENCIES}}
<!-- Example: 1. Stripe API (payment processing), 2. SendGrid API (email delivery), 3. AWS services (ECS, RDS, S3, CloudFront), 4. Salesforce integration (customer sync), 5. DNS provider (Route 53), 6. SSL certificates (ACM) -->
---
## 7. Requirements Traceability
| Requirement ID | Epic | User Story | Test Case | Status |
|---------------|------|------------|-----------|--------|
| FR-UM-001 | Epic-001 | US-001 | TC-001 | {{STATUS}} |
<!-- Example: FR-UM-001 (User Registration) | EP-1 User Management | US-1 Email signup | TC-1 Register with valid email | Implemented -->
---
## 8. Glossary
| Term | Definition |
|------|------------|
| {{TERM_1}} | {{DEFINITION_1}} |
<!-- Example: SLA | Service Level Agreement - contractual uptime commitment (99.9%) | MTTR | Mean Time To Recovery - average time to restore service after failure | p95 | 95th percentile - 95% of requests faster than this value -->
---
## 9. Appendices
### Appendix A: MoSCoW Prioritization Summary
- **MUST have**: {{MUST_COUNT}} requirements
- **SHOULD have**: {{SHOULD_COUNT}} requirements
- **COULD have**: {{COULD_COUNT}} requirements
- **WON'T have (this release)**: {{WONT_COUNT}} requirements
<!-- Example: MUST: 45 (75%), SHOULD: 12 (20%), COULD: 3 (5%), WON'T: 8 (deferred to v2.0) -->
### Appendix B: References
1. ISO/IEC/IEEE 29148:2018 - Systems and software engineering
2. OWASP ASVS (Application Security Verification Standard)
3. WCAG 2.1 (Web Content Accessibility Guidelines)
---
## Maintenance
**Last Updated:** {{DATE}}
**Update Triggers:**
- New functional requirements identified during development
- New constraints or dependencies discovered
- Stakeholder feedback on requirements clarity
- Post-release feedback requiring requirement modifications
- MoSCoW prioritization changes
**Verification:**
- [ ] All FR-XXX-NNN requirements have acceptance criteria
- [ ] All FR-XXX-NNN requirements have MoSCoW priority (MUST/SHOULD/COULD/WON'T)
- [ ] Traceability matrix links requirements to epics/stories
- [ ] No orphaned requirements (all linked to business value)
- [ ] All placeholders replaced with actual content
---
## Revision History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | {{DATE}} | {{AUTHOR}} | Initial version |
---
**Version:** 3.0.0 (BREAKING: NFR sections removed completely per project policy)
**Template Last Updated:** 2025-11-16

View File

@@ -0,0 +1,632 @@
# Operations Runbook: {{PROJECT_NAME}}
**Document Version:** 1.0
**Date:** {{DATE}}
**Status:** {{STATUS}}
<!-- SCOPE: ALL operational procedures (local development setup, Docker commands, environment variables, testing commands, build/deployment, production operations, troubleshooting, SSH access, logs, restart procedures) ONLY. -->
<!-- DO NOT add here: Architecture patterns → architecture.md, Tech stack versions → tech_stack.md, Database schema → database_schema.md, API endpoints → api_spec.md, Testing strategy → tests/README.md, Design system → design_guidelines.md, Requirements → requirements.md -->
---
## 1. Overview
### 1.1 Purpose
This runbook provides step-by-step operational procedures for {{PROJECT_NAME}} across all environments: local development, testing, and production.
### 1.2 Quick Links
- Architecture: {{ARCHITECTURE_LINK}}
- Tech Stack: {{TECH_STACK_LINK}}
- API Spec: {{API_SPEC_LINK}}
- Database Schema: {{DATABASE_SCHEMA_LINK}}
### 1.3 Key Contacts
{{KEY_CONTACTS}}
<!-- Example:
| Role | Name | Contact | Availability |
|------|------|---------|--------------|
| DevOps Lead | John Doe | john@example.com | 24/7 on-call |
| Tech Lead | Jane Smith | jane@example.com | Mon-Fri 9-6 |
| DBA | Bob Johnson | bob@example.com | Mon-Fri 9-5 |
-->
---
## 2. Prerequisites
### 2.1 Required Tools
{{REQUIRED_TOOLS}}
<!-- Example:
| Tool | Version | Installation |
|------|---------|--------------|
| Docker | 24.0+ | https://docs.docker.com/get-docker/ |
| Docker Compose | 2.20+ | Included with Docker Desktop |
| Node.js | 20.x LTS | https://nodejs.org/ (for local npm scripts) |
| Git | 2.40+ | https://git-scm.com/ |
-->
### 2.2 Access Requirements
{{ACCESS_REQUIREMENTS}}
<!-- Example:
- GitHub repository access (read for development, write for deployment)
- Production SSH keys (request from DevOps lead)
- Database credentials (stored in 1Password vault "ProjectName")
- AWS Console access (IAM role: Developer)
- VPN access for production (if required)
-->
### 2.3 Environment Variables
See [Appendix A: Environment Variables](#appendix-a-environment-variables-reference) for complete reference.
---
## 3. Local Development
### 3.1 Initial Setup
```bash
# Clone repository
git clone https://github.com/org/{{PROJECT_NAME}}.git
cd {{PROJECT_NAME}}
# Copy environment template
cp .env.example .env
# Edit .env with your credentials
# See Appendix A for required variables
# Build and start services
docker compose up -d
# Wait for services to be ready (check logs)
docker compose logs -f app
```
**Expected output:**
```
app-1 | Server started on port 3000
db-1 | database system is ready to accept connections
```
### 3.2 Docker Commands
**Start all services:**
```bash
docker compose up -d
```
**Stop all services:**
```bash
docker compose down
```
**Rebuild after code changes:**
```bash
docker compose down
docker compose build --no-cache app
docker compose up -d
```
**View logs:**
```bash
# All services
docker compose logs -f
# Specific service
docker compose logs -f app
# Last 100 lines
docker compose logs --tail 100 app
```
**Exec into running container:**
```bash
docker compose exec app sh
# or
docker compose exec app bash
```
**Restart specific service:**
```bash
docker compose restart app
```
### 3.3 Database Operations (Local)
**Run migrations:**
```bash
docker compose exec app npm run migrate
# Or using Prisma
docker compose exec app npx prisma migrate dev
```
**Seed database:**
```bash
docker compose exec app npm run seed
```
**Reset database (⚠️ DESTRUCTIVE):**
```bash
docker compose down
docker volume rm {{PROJECT_NAME}}_postgres_data
docker compose up -d
docker compose exec app npm run migrate
docker compose exec app npm run seed
```
**Database shell:**
```bash
# PostgreSQL
docker compose exec db psql -U {{DB_USER}} -d {{DB_NAME}}
# MySQL
docker compose exec db mysql -u {{DB_USER}} -p{{DB_PASSWORD}} {{DB_NAME}}
```
### 3.4 Common Development Tasks
**Install dependencies (after package.json changes):**
```bash
docker compose down
docker compose build app
docker compose up -d
```
**Run linter:**
```bash
docker compose exec app npm run lint
# Fix automatically
docker compose exec app npm run lint:fix
```
**Format code:**
```bash
docker compose exec app npm run format
```
**Check syntax (TypeScript):**
```bash
docker compose exec app npm run type-check
```
---
## 4. Testing
### 4.1 Run All Tests
```bash
# Using docker-compose.test.yml
docker compose -f docker-compose.test.yml up --abort-on-container-exit
```
### 4.2 Run Specific Test Types
**Unit tests:**
```bash
docker compose exec app npm run test:unit
# Watch mode
docker compose exec app npm run test:unit:watch
```
**Integration tests:**
```bash
docker compose exec app npm run test:integration
```
**E2E tests:**
```bash
# Start app first
docker compose up -d
# Run E2E
docker compose exec app npm run test:e2e
```
### 4.3 Test Coverage
```bash
docker compose exec app npm run test:coverage
# Open coverage report
open coverage/index.html
```
### 4.4 Debug Tests
```bash
# Run single test file
docker compose exec app npm test -- path/to/test.spec.ts
# Run with debugging
docker compose exec app node --inspect-brk=0.0.0.0:9229 node_modules/.bin/jest
```
---
## 5. Build & Deployment
### 5.1 Build for Production
```bash
# Build production image
docker build -t {{PROJECT_NAME}}:{{VERSION}} .
# Test production build locally
docker run -p 3000:3000 --env-file .env.production {{PROJECT_NAME}}:{{VERSION}}
```
### 5.2 Deployment to Production
{{DEPLOYMENT_PROCEDURE}}
<!-- Example:
**Prerequisites:**
- [ ] All tests passing (CI/CD green)
- [ ] Code reviewed and approved
- [ ] Database migrations tested in staging
- [ ] Backup created
**Deployment steps:**
```bash
# 1. SSH to production server
ssh production-server
# 2. Navigate to project directory
cd /opt/{{PROJECT_NAME}}
# 3. Pull latest code
git pull origin main
# 4. Backup database
./scripts/backup-db.sh
# 5. Stop services
docker compose down
# 6. Rebuild images
docker compose build --no-cache
# 7. Run migrations
docker compose run --rm app npm run migrate
# 8. Start services
docker compose up -d
# 9. Verify deployment
docker compose logs -f app
curl http://localhost:3000/health
```
**Rollback procedure (if deployment fails):**
```bash
# 1. Rollback code
git reset --hard HEAD~1
# 2. Restore database (if migrations ran)
./scripts/restore-db.sh {{BACKUP_FILE}}
# 3. Restart services
docker compose down && docker compose up -d
```
-->
---
## 6. Production Operations
### 6.1 SSH Access
**SSH to production server:**
```bash
ssh {{PRODUCTION_USER}}@{{PRODUCTION_HOST}}
# Or with SSH key
ssh -i ~/.ssh/{{PROJECT_NAME}}_prod.pem {{PRODUCTION_USER}}@{{PRODUCTION_HOST}}
```
**SSH via jump host (if behind VPN):**
```bash
ssh -J {{JUMP_HOST}} {{PRODUCTION_USER}}@{{PRODUCTION_HOST}}
```
### 6.2 Health Checks
**Check application status:**
```bash
# Health endpoint
curl http://localhost:3000/health
# Expected response:
# {"status": "ok", "uptime": 123456, "timestamp": "2024-01-01T00:00:00Z"}
```
**Check service status:**
```bash
docker compose ps
# Expected output:
# NAME STATUS PORTS
# app-1 Up 5 minutes 0.0.0.0:3000->3000/tcp
# db-1 Up 5 minutes 5432/tcp
# cache-1 Up 5 minutes 6379/tcp
```
**Check resource usage:**
```bash
docker stats
# Or specific container
docker stats app-1
```
### 6.3 Monitoring & Logs
**View logs:**
```bash
# Real-time logs (all services)
docker compose logs -f
# Last 500 lines from app
docker compose logs --tail 500 app
# Logs from specific time
docker compose logs --since 2024-01-01T00:00:00 app
# Save logs to file
docker compose logs --no-color app > app-logs-$(date +%Y%m%d).log
```
**Search logs:**
```bash
# Find errors
docker compose logs app | grep ERROR
# Find specific request
docker compose logs app | grep "request_id=123"
```
**Log rotation:**
{{LOG_ROTATION}}
<!-- Example: Docker logs automatically rotate at 100MB, keep last 3 files. Manual rotation: `docker compose down && docker compose up -d` -->
### 6.4 Common Maintenance Tasks
**Restart application (zero downtime):**
```bash
docker compose up -d --no-deps --force-recreate app
```
**Clear cache:**
```bash
docker compose exec cache redis-cli FLUSHALL
```
**Database backup:**
```bash
# PostgreSQL
docker compose exec db pg_dump -U {{DB_USER}} {{DB_NAME}} > backup-$(date +%Y%m%d-%H%M%S).sql
# MySQL
docker compose exec db mysqldump -u {{DB_USER}} -p{{DB_PASSWORD}} {{DB_NAME}} > backup-$(date +%Y%m%d-%H%M%S).sql
```
**Database restore:**
```bash
# PostgreSQL
cat backup-20240101-120000.sql | docker compose exec -T db psql -U {{DB_USER}} {{DB_NAME}}
# MySQL
cat backup-20240101-120000.sql | docker compose exec -T db mysql -u {{DB_USER}} -p{{DB_PASSWORD}} {{DB_NAME}}
```
**Update dependencies:**
```bash
# Update package.json
docker compose exec app npm update
# Rebuild image
docker compose down
docker compose build --no-cache app
docker compose up -d
```
---
## 7. Troubleshooting
### 7.1 Common Issues
#### Issue 1: Application won't start
**Symptoms:**
```
app-1 | Error: Cannot connect to database
app-1 | Error: ECONNREFUSED
```
**Diagnosis:**
```bash
# Check if database is running
docker compose ps db
# Check database logs
docker compose logs db
# Test database connection
docker compose exec app nc -zv db 5432
```
**Resolution:**
```bash
# Restart database
docker compose restart db
# Wait for database to be ready
docker compose logs -f db
# Look for: "database system is ready to accept connections"
# Restart app
docker compose restart app
```
---
#### Issue 2: Out of disk space
**Symptoms:**
```
Error: no space left on device
```
**Diagnosis:**
```bash
df -h
docker system df
```
**Resolution:**
```bash
# Remove unused Docker resources
docker system prune -a
# Remove specific volumes (⚠️ DESTRUCTIVE)
docker volume rm {{PROJECT_NAME}}_postgres_data
# Remove old log files
find /var/log -name "*.log" -mtime +30 -delete
```
---
#### Issue 3: {{ISSUE_3_NAME}}
{{ISSUE_3_TROUBLESHOOTING}}
<!-- Add project-specific common issues -->
---
### 7.2 Emergency Procedures
**Production outage:**
```bash
# 1. Check health status
curl http://localhost:3000/health
# 2. Check logs for errors
docker compose logs --tail 200 app | grep ERROR
# 3. Restart services
docker compose restart
# 4. If restart fails, rollback
git reset --hard HEAD~1
docker compose down && docker compose up -d
# 5. Notify team (Slack/PagerDuty)
```
**Database corruption:**
```bash
# 1. Stop application
docker compose stop app
# 2. Restore from latest backup
./scripts/restore-db.sh {{LATEST_BACKUP}}
# 3. Verify data integrity
docker compose exec db psql -U {{DB_USER}} -d {{DB_NAME}} -c "SELECT COUNT(*) FROM users;"
# 4. Restart application
docker compose start app
```
---
## 8. Appendices
### Appendix A: Environment Variables Reference
**Required variables:**
| Variable | Example | Description |
|----------|---------|-------------|
| `DATABASE_URL` | `postgresql://user:pass@db:5432/myapp` | Database connection string |
| `REDIS_URL` | `redis://cache:6379` | Cache connection string |
| `API_KEY` | `sk_live_abc123...` | External API key (e.g., Stripe) |
| `JWT_SECRET` | `random_secret_key` | JWT signing secret |
| `NODE_ENV` | `development` or `production` | Environment mode |
**Optional variables:**
| Variable | Default | Description |
|----------|---------|-------------|
| `PORT` | `3000` | Application port |
| `LOG_LEVEL` | `info` | Logging verbosity (debug/info/warn/error) |
| `RATE_LIMIT` | `100` | API rate limit (requests/minute) |
---
### Appendix B: Service Dependencies
{{SERVICE_DEPENDENCIES}}
<!-- Example:
**Internal dependencies:**
- app → db (PostgreSQL 16)
- app → cache (Redis 7)
- app → queue (RabbitMQ 3.12)
**External dependencies:**
- Stripe API (https://api.stripe.com)
- SendGrid API (https://api.sendgrid.com)
- AWS S3 (file storage)
**Health check URLs:**
- App: http://localhost:3000/health
- Database: `docker compose exec db pg_isready`
- Cache: `docker compose exec cache redis-cli ping`
-->
---
### Appendix C: Port Mapping
{{PORT_MAPPING}}
<!-- Example:
| Service | Container Port | Host Port | Description |
|---------|----------------|-----------|-------------|
| app | 3000 | 3000 | Application HTTP |
| db | 5432 | 5432 | PostgreSQL |
| cache | 6379 | 6379 | Redis |
| adminer | 8080 | 8080 | Database admin UI |
-->
---
## 9. Maintenance
**Last Updated:** {{DATE}}
**Update Triggers:**
- New deployment procedures
- Infrastructure changes (new services, ports)
- New operational commands
- Troubleshooting scenarios discovered
- Environment variable changes
- SSH access changes
**Verification:**
- [ ] All commands tested in staging
- [ ] SSH access verified
- [ ] Health check procedures validated
- [ ] Backup/restore procedures tested
- [ ] Emergency procedures reviewed
- [ ] Contact information current
---
**Version:** 1.0.0
**Template Last Updated:** 2025-11-16

View File

@@ -0,0 +1,249 @@
# Technology Stack: {{PROJECT_NAME}}
**Document Version:** 1.0
**Date:** {{DATE}}
**Status:** {{STATUS}}
<!-- SCOPE: Technology stack (specific versions, libraries, frameworks), Docker configuration (Dockerfile, docker-compose.yml), development tools, naming conventions ONLY. -->
<!-- DO NOT add here: API endpoints → api_spec.md, Database schema → database_schema.md, Architecture patterns → architecture.md, Requirements → requirements.md, Deployment procedures → runbook.md, Design system → design_guidelines.md -->
---
## 1. Introduction
### 1.1 Purpose
This document specifies the technology stack, frameworks, libraries, and tools used in {{PROJECT_NAME}}.
### 1.2 Scope
{{SCOPE}}
<!-- Example: Full-stack web application. IN SCOPE: Frontend (React), Backend (Node.js/Express), Database (PostgreSQL), Cache (Redis), Docker setup. OUT OF SCOPE: Infrastructure provisioning (see runbook.md), API contracts (see api_spec.md) -->
---
## 2. Technology Stack
### 2.1 Stack Overview
| Layer | Technology | Version | Rationale | ADR |
|-------|------------|---------|-----------|-----|
| **Frontend** | {{FRONTEND_FRAMEWORK}} | {{FRONTEND_VERSION}} | {{FRONTEND_RATIONALE}} | {{FRONTEND_ADR_LINK}} |
| **Backend** | {{BACKEND_FRAMEWORK}} | {{BACKEND_VERSION}} | {{BACKEND_RATIONALE}} | {{BACKEND_ADR_LINK}} |
| **Database** | {{DATABASE}} | {{DATABASE_VERSION}} | {{DATABASE_RATIONALE}} | {{DATABASE_ADR_LINK}} |
| **Cache** | {{CACHE}} | {{CACHE_VERSION}} | {{CACHE_RATIONALE}} | {{CACHE_ADR_LINK}} |
| **Message Queue** | {{QUEUE}} | {{QUEUE_VERSION}} | {{QUEUE_RATIONALE}} | {{QUEUE_ADR_LINK}} |
| **Testing** | {{TEST_FRAMEWORK}} | {{TEST_VERSION}} | {{TEST_RATIONALE}} | {{TEST_ADR_LINK}} |
| **DevOps** | {{DEVOPS_TOOLS}} | {{DEVOPS_VERSION}} | {{DEVOPS_RATIONALE}} | {{DEVOPS_ADR_LINK}} |
<!-- Example:
| Frontend | React | 18.2.0 | Component-based UI, large ecosystem, TypeScript support | [ADR-003](../reference/adrs/adr-003-react.md) |
| Backend | Node.js + Express | 20.x + 4.18.x | JavaScript full-stack, async/await, vast npm ecosystem | [ADR-001](../reference/adrs/adr-001-nodejs.md) |
| Database | PostgreSQL | 16.x | ACID compliance, JSON support, mature ecosystem | [ADR-002](../reference/adrs/adr-002-postgresql.md) |
| Cache | Redis | 7.x | In-memory performance, pub/sub, session storage | [ADR-004](../reference/adrs/adr-004-redis.md) |
| Queue | RabbitMQ | 3.12.x | Reliable message delivery, dead letter queues | [ADR-005](../reference/adrs/adr-005-rabbitmq.md) |
| Testing | Jest + Playwright | 29.x + 1.40.x | Unit testing (Jest), E2E testing (Playwright) | [ADR-006](../reference/adrs/adr-006-testing.md) |
| DevOps | Docker + GitHub Actions | 24.x + latest | Containerization, CI/CD automation | [ADR-007](../reference/adrs/adr-007-devops.md) |
-->
### 2.2 Key Libraries & Dependencies
**Frontend:**
{{FRONTEND_LIBRARIES}}
<!-- Example: React Router (6.x) - routing, Tailwind CSS (3.x) - styling, Axios (1.x) - HTTP client, React Query (5.x) - data fetching -->
**Backend:**
{{BACKEND_LIBRARIES}}
<!-- Example: Prisma (5.x) - ORM, bcrypt (5.x) - password hashing, jsonwebtoken (9.x) - JWT auth, winston (3.x) - logging -->
**Common:**
{{COMMON_LIBRARIES}}
<!-- Example: TypeScript (5.x) - type safety, ESLint (8.x) - linting, Prettier (3.x) - code formatting -->
---
## 3. Docker Development Environment
### 3.1 Dockerfile
```dockerfile
{{DOCKERFILE_CONTENT}}
```
<!-- Example:
```dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
```
-->
### 3.2 docker-compose.yml (Development)
```yaml
{{DOCKER_COMPOSE_DEV}}
```
<!-- Example:
```yaml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
DATABASE_URL: postgresql://user:password@db:5432/myapp
REDIS_URL: redis://cache:6379
depends_on:
- db
- cache
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp
volumes:
- postgres_data:/var/lib/postgresql/data
cache:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
postgres_data:
```
-->
### 3.3 docker-compose.test.yml (Testing)
```yaml
{{DOCKER_COMPOSE_TEST}}
```
<!-- Example:
```yaml
version: '3.8'
services:
test:
build: .
command: npm run test
environment:
DATABASE_URL: postgresql://user:password@db-test:5432/myapp_test
depends_on:
- db-test
tmpfs:
- /app/coverage
db-test:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp_test
```
-->
---
## 4. Development Tools
### 4.1 Required Tools
| Tool | Version | Purpose | Installation |
|------|---------|---------|--------------|
| Node.js | {{NODE_VERSION}} | Runtime environment | https://nodejs.org/ |
| Docker | 24.0+ | Container runtime | https://docs.docker.com/get-docker/ |
| Git | 2.40+ | Version control | https://git-scm.com/ |
| {{IDE}} | Latest | Code editor | {{IDE_LINK}} |
<!-- Example:
| Node.js | 20.x LTS | Runtime environment | https://nodejs.org/ |
| Docker | 24.0+ | Container runtime | https://docs.docker.com/get-docker/ |
| Git | 2.40+ | Version control | https://git-scm.com/ |
| VS Code | Latest | Code editor | https://code.visualstudio.com/ |
-->
### 4.2 VS Code Extensions (Recommended)
{{VSCODE_EXTENSIONS}}
<!-- Example: ESLint, Prettier, Docker, Prisma, Tailwind CSS IntelliSense -->
### 4.3 Linters & Code Quality Tools
| Tool | Version | Purpose | Command | Config File |
|------|---------|---------|---------|-------------|
| {{LINTER_1}} | {{VERSION_1}} | {{PURPOSE_1}} | {{COMMAND_1}} | {{CONFIG_1}} |
<!-- Example:
| ESLint | 9.x | JavaScript/TypeScript linting | `npm run lint` | .eslintrc.js |
| Prettier | 3.x | Code formatting | `npm run format:check` | .prettierrc |
| TypeScript | 5.x | Type checking | `tsc --noEmit` | tsconfig.json |
| Ruff | 0.4.x | Python linting | `ruff check .` | pyproject.toml |
| Stylelint | 16.x | CSS/SCSS linting | `npm run lint:css` | .stylelintrc |
-->
**CI/CD Integration:**
{{CI_LINT_INTEGRATION}}
<!-- Example:
- Pre-commit hook: `npm run lint && npm run format:check`
- GitHub Actions: `npm run lint` in CI workflow
- Required for merge: All linters must pass (0 errors)
-->
**Run All Quality Checks:**
```bash
{{LINT_ALL_COMMAND}}
```
<!-- Example: npm run lint && npm run format:check && tsc --noEmit -->
---
## 5. Naming Conventions
### 5.1 File Naming
{{FILE_NAMING}}
<!-- Example: Components: PascalCase (UserProfile.tsx), Utilities: camelCase (formatDate.ts), Constants: UPPER_SNAKE_CASE (API_ENDPOINTS.ts) -->
### 5.2 Variable Naming
{{VARIABLE_NAMING}}
<!-- Example: camelCase for variables/functions, PascalCase for classes/components, UPPER_SNAKE_CASE for constants -->
### 5.3 Database Naming
{{DATABASE_NAMING}}
<!-- Example: Tables: snake_case plural (user_profiles), Columns: snake_case (first_name), Indexes: idx_table_column -->
---
## 6. Maintenance
**Last Updated:** {{DATE}}
**Update Triggers:**
- Technology version upgrade (major/minor releases)
- New library added to dependencies
- Docker configuration changes
- Development tool updates
**Verification:**
- [ ] All versions match package.json/Dockerfile
- [ ] ADR links valid and point to correct decisions
- [ ] Docker compose files tested and working
- [ ] All listed tools accessible with installation links
---
**Version:** 1.0.0
**Template Last Updated:** 2025-11-16