diff --git a/.agent/skills/documentation/SKILL.md b/.agent/skills/documentation/SKILL.md index 6fce8198..39aa5a2a 100644 --- a/.agent/skills/documentation/SKILL.md +++ b/.agent/skills/documentation/SKILL.md @@ -3,7 +3,7 @@ name: documentation description: Documentation guidelines for GoodGo project. Use for README, guides, architecture docs, or API docs. Ensures bilingual EN/VI consistency. metadata: author: Velik Ho - version: "1.0" + version: "2.0" --- # Documentation Writing Guidelines / Hướng Dẫn Viết Tài Liệu @@ -58,70 +58,61 @@ services/my-service-net/ │ ├── API.md # API reference (optional) │ └── [OTHER].md # Service-specific docs └── vi/ # Vietnamese documentation (mirror EN) - ├── README.md # Vietnamese intro, quick start, config - ├── ARCHITECTURE.md # Architecture, layers, patterns - ├── API.md # API reference (optional) + ├── gioi-thieu.md # Vietnamese intro, quick start, config + ├── kien-truc.md # Architecture, layers, patterns + ├── api.md # API reference (optional) └── [OTHER].md # Service-specific docs ``` **Key Rules:** - `docs/en/` and `docs/vi/` MUST mirror each other (same files, same structure) - Each language folder is MONOLINGUAL (no bilingual mixing) -- **Filenames**: Use same English filenames in both folders (e.g., `ARCHITECTURE.md`, `README.md`) +- **Filenames**: EN uses English (UPPERCASE), VI uses Vietnamese (kebab-case) - Service root `README.md` links to both EN/VI documentation - Mermaid diagrams MUST use dark color palette (see [Mermaid Diagrams Skill](../mermaid-diagrams/SKILL.md)) -- `ARCHITECTURE.md` is MANDATORY, `README.md` is MANDATORY, other files optional +- `ARCHITECTURE.md`/`kien-truc.md` is MANDATORY, `README.md`/`gioi-thieu.md` is MANDATORY, other files optional -### Filename Conventions / Quy Ước Đặt Tên File +### Vietnamese Filename Conventions / Quy Ước Đặt Tên Tiếng Việt -**IMPORTANT**: Both `docs/en/` and `docs/vi/` use the **same English filenames** for consistency and ease of maintenance. +**Standard EN/VI Filename Mapping:** -**Standard Filenames (used in both EN and VI):** +| English (docs/en/) | Vietnamese (docs/vi/) | Description | +|-------------------|----------------------|-------------| +| `README.md` | `gioi-thieu.md` | Service introduction, quick start | +| `ARCHITECTURE.md` | `kien-truc.md` | Architecture documentation | +| `API.md` | `api.md` | API reference (technical term) | +| `DEPLOYMENT.md` | `trien-khai.md` | Deployment guide | +| `CONFIGURATION.md` | `cau-hinh.md` | Configuration guide | +| `TESTING.md` | `kiem-thu.md` | Testing guide | +| `TROUBLESHOOTING.md` | `khac-phuc-su-co.md` | Troubleshooting | -| Filename | Purpose / Mục đích | -|----------|-------------------| -| `README.md` | Service introduction, quick start / Giới thiệu dịch vụ | -| `ARCHITECTURE.md` | Architecture documentation / Tài liệu kiến trúc | -| `API.md` | API reference / Tài liệu API | -| `DEPLOYMENT.md` | Deployment guide / Hướng dẫn triển khai | -| `CONFIGURATION.md` | Configuration guide / Hướng dẫn cấu hình | -| `TESTING.md` | Testing guide / Hướng dẫn kiểm thử | -| `TROUBLESHOOTING.md` | Troubleshooting / Khắc phục sự cố | -| `WHATSAPP_SETUP.md` | WhatsApp setup / Cài đặt WhatsApp | -| `AI_CHATBOT_GUIDE.md` | AI chatbot guide / Hướng dẫn chatbot AI | -| `AUTOMATION_GUIDE.md` | Automation guide / Hướng dẫn tự động hóa | +**Service-Specific Examples:** -**Naming Rules:** +| Service Type | EN Filename | VI Filename | +|-------------|------------|-------------| +| WhatsApp | `WHATSAPP_SETUP.md` | `cai-dat-whatsapp.md` | +| WhatsApp | `AI_CHATBOT_GUIDE.md` | `huong-dan-chatbot-ai.md` | +| Facebook | `FACEBOOK_SETUP.md` | `cai-dat-facebook.md` | +| Twitter/X | `TWITTER_SETUP.md` | `cai-dat-twitter.md` | +| Zalo | `ZALO_SETUP.md` | `cai-dat-zalo.md` | -1. **UPPERCASE for main docs**: `ARCHITECTURE.md`, `README.md`, `API.md` -2. **UPPERCASE_SNAKE_CASE for feature docs**: `WHATSAPP_SETUP.md`, `AI_CHATBOT_GUIDE.md` -3. **Same filename in both folders**: Makes linking and reference easier -4. **English only**: Avoid encoding issues, better tool compatibility +**Naming Rules for Vietnamese Files:** -**Directory Structure Example:** +1. **Kebab-case**: All lowercase, words separated by hyphens (`-`) + - ✅ `kien-truc.md`, `huong-dan-chatbot-ai.md` + - ❌ `KIEN-TRUC.md`, `Kien_Truc.md`, `KienTruc.md` -``` -services/mkt-whatsapp-service-net/docs/ -├── en/ -│ ├── README.md # English content -│ ├── ARCHITECTURE.md # English content -│ ├── API.md # English content -│ ├── WHATSAPP_SETUP.md # English content -│ └── AI_CHATBOT_GUIDE.md # English content -└── vi/ - ├── README.md # Vietnamese content (same filename) - ├── ARCHITECTURE.md # Vietnamese content (same filename) - ├── API.md # Vietnamese content (same filename) - ├── WHATSAPP_SETUP.md # Vietnamese content (same filename) - └── AI_CHATBOT_GUIDE.md # Vietnamese content (same filename) -``` +2. **Vietnamese without diacritics**: Use non-accented Vietnamese + - ✅ `kien-truc` (not `kiến-trúc`) + - ✅ `cau-hinh` (not `cấu-hình`) -**Benefits:** -- ✅ Easy to find corresponding files (same name in both folders) -- ✅ Simple linking and references -- ✅ No encoding issues -- ✅ Better tool compatibility +3. **Descriptive and clear**: Use full words, avoid abbreviations + - ✅ `huong-dan-chatbot-ai.md` (clear) + - ❌ `hd-chatbot.md` (abbreviated) +4. **Technical terms**: Keep English for technical/API terms + - ✅ `api.md` (lowercase) + - ✅ `webhook.md` ## Key Patterns / Mẫu Chính @@ -135,24 +126,13 @@ This is a description. Đây là mô tả. ``` -**Option 2: Separate files (for long content >200 lines)** +**Option 2: Separate files (for long content > 200 lines)** ``` docs/ ├── en/guides/deployment.md └── vi/guides/deployment.md ``` -**Option 3: Sections (for mixed content)** -```markdown -# English Section -Content in English... - ---- - -# Phần Tiếng Việt -Nội dung bằng tiếng Việt... -``` - ### Service README Template **For service root `README.md` (bilingual with links to language-specific docs):** @@ -220,69 +200,9 @@ dotnet run See [API Documentation](API.md) ``` -**For `docs/vi/gioi-thieu.md` (Vietnamese only, mirrors EN content):** - -```markdown -# Tên Dịch Vụ - -Mô tả ngắn gọn bằng tiếng Việt. - -## Tính Năng -- Tính năng 1 -- Tính năng 2 - -## Yêu Cầu -- .NET 8 / Node.js 20+ -- PostgreSQL 15+ - -## Bắt Đầu Nhanh -```bash -dotnet run -``` - -## Cấu Hình - -| Biến | Mô Tả | Mặc Định | -|------|-------|---------| -| PORT | Cổng server | 5000 | -| DATABASE_URL | Kết nối PostgreSQL | - | - -## API Endpoints -Xem [Tài liệu API](api.md) -``` - -### Guide Template - -```markdown -# Guide Title - -**Last Updated**: 2024-01-01 -**Difficulty**: Beginner/Intermediate/Advanced - -## Overview -Brief overview of what this guide covers. - -## Prerequisites -- Requirement 1 - -## Step-by-Step Instructions - -### Step 1: Title -Description and commands... - -## Troubleshooting - -### Issue 1 -**Problem**: Description -**Solution**: Steps to fix - -## Resources -- [Related Doc](../path/to/doc.md) -``` - ### Architecture Document Template (Microservices) -For microservices in `services/[name]/docs/en/ARCHITECTURE.md` or `.../vi/ARCHITECTURE.md`: +For microservices in `services/[name]/docs/en/ARCHITECTURE.md`: ```markdown # Architecture Documentation @@ -301,7 +221,6 @@ Brief description of the service purpose and capabilities. graph TB subgraph External Client[Client/User] - ExtAPI[External API] end subgraph "GoodGo Platform" @@ -332,7 +251,6 @@ graph TB style API fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px style DOMAIN fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px style PG fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px - style REDIS fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px \`\`\` ## Clean Architecture Layers @@ -340,37 +258,15 @@ graph TB ### 1. API Layer **Responsibility**: HTTP interface, controllers, background jobs -**Controllers:** -- `ExampleController` - Description -- `AnotherController` - Description - ### 2. Application Layer **Responsibility**: Use cases, CQRS commands/queries, handlers -**Commands (Writes):** -- `CreateEntityCommand` - Description -- `UpdateEntityCommand` - Description - -**Queries (Reads):** -- `GetEntityQuery` - Description -- `ListEntitiesQuery` - Description - ### 3. Domain Layer **Responsibility**: Business logic, entities, aggregates, domain events -**Aggregates:** -- `EntityAggregate` - Description of aggregate root and business rules - ### 4. Infrastructure Layer **Responsibility**: Persistence, external services, integrations -**Data Access:** -- `ServiceContext` - EF Core DbContext -- Repositories - -**External Services:** -- `ExternalApiClient` - HTTP client for external integration - ## Request Flow \`\`\`mermaid @@ -396,37 +292,13 @@ sequenceDiagram style DB fill:#34495E,color:#ECF0F1 \`\`\` -## Database Schema - -Key tables and relationships. - -## Integration Events - -Events published/consumed by this service. - -## Security Considerations - -Authentication, authorization, data protection. - -## Performance Optimization - -Caching, query optimization, background processing. - -## Monitoring & Observability - -Health checks, metrics, logging. - ## References - - [API Documentation](API.md) - [Service README](README.md) ``` - ## Real-World Examples / Ví Dụ Thực Tế -### Excellent Documentation Examples - These services demonstrate best practices for microservices documentation: - **mkt-facebook-service-net** - Complete bilingual docs with EN/VI separation, Mermaid diagrams, API reference @@ -435,862 +307,6 @@ These services demonstrate best practices for microservices documentation: - **order-service-net** - Multi-vertical architecture documentation - **catalog-service-net** - Standard CQRS/Clean Architecture patterns -### Common Documentation Patterns in GoodGo - -**Architecture Documentation:** -- High-level system diagram with Traefik gateway -- Clean Architecture 4-layer diagram (API → Application → Domain → Infrastructure) -- Request flow sequence diagrams -- Database schema with relationships - -**API Documentation:** -- Endpoint tables with bilingual descriptions -- Request/response examples -- Error code reference -- Authentication requirements - -**Setup Guides:** -- Prerequisites section -- Step-by-step configuration -- Environment variable tables -- Troubleshooting sections - -### What Makes Good Documentation? - -1. **Complete Language Separation**: EN and VI in separate directories -2. **Consistent Dark Mermaid Palette**: Following mermaid-diagrams skill -3. **Practical Examples**: Real code snippets, not placeholders -4. **Troubleshooting Sections**: Common issues and solutions -5. **Quick Start Guides**: Get running in < 5 minutes - ---- - -## Automation & Tools / Công Cụ Tự Động - -### Link Checking - -Validate all markdown links to prevent broken references: - -```bash -# Install markdown-link-check -npm install -g markdown-link-check - -# Check single file -markdown-link-check docs/en/README.md - -# Check all markdown files in docs/ -find docs -name "*.md" | xargs markdown-link-check - -# With config file -markdown-link-check -c .markdown-link-check.json docs/en/README.md -``` - -**Config example** (`.markdown-link-check.json`): -```json -{ - "ignorePatterns": [ - { "pattern": "^http://localhost" }, - { "pattern": "^https://api.goodgo.vn" } - ], - "timeout": "20s", - "retryOn429": true, - "aliveStatusCodes": [200, 206] -} -``` - -### Markdown Linting - -Enforce consistent markdown style: - -```bash -# Install markdownlint-cli -npm install -g markdownlint-cli - -# Lint all docs -markdownlint docs/**/*.md - -# Fix auto-fixable issues -markdownlint --fix docs/**/*.md - -# With config -markdownlint -c .markdownlint.json docs/**/*.md -``` - -**Config example** (`.markdownlint.json`): -```json -{ - "default": true, - "MD013": { "line_length": 120 }, - "MD033": false, - "MD041": false -} -``` - -### Documentation Generation - -**OpenAPI to Markdown:** -```bash -# Using redoc-cli -npx @redocly/cli build-docs docs/en/api/openapi/service.yaml \ - -o docs/en/api/reference.html - -# Using swagger-markdown -npx swagger-markdown -i docs/en/api/openapi/service.yaml \ - -o docs/en/api/REFERENCE.md -``` - -**C# XML Comments to Markdown:** -```bash -# Using xmldoc2md (for .NET projects) -dotnet tool install -g xmldoc2md -xmldoc2md src/MyService.API/bin/Debug/net8.0/MyService.API.xml \ - docs/en/api/ -``` - -### CI/CD Integration - -```yaml -# .github/workflows/docs-validation.yml -name: Validate Documentation - -on: [pull_request] - -jobs: - validate-docs: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Check links - run: | - npm install -g markdown-link-check - find docs -name "*.md" | xargs markdown-link-check - - name: Lint markdown - run: | - npm install -g markdownlint-cli - markdownlint docs/**/*.md -``` - ---- - -## OpenAPI Specification Standards - -### File Structure - -``` -docs/en/api/openapi/ -├── service-name.yaml # Main OpenAPI spec -├── schemas/ # Reusable schemas -│ ├── common.yaml # Common types (PaginationRequest, etc.) -│ ├── errors.yaml # Error responses -│ └── entities.yaml # Domain entities -└── examples/ # Request/response examples - ├── requests/ - └── responses/ -``` - -### OpenAPI Template - -```yaml -openapi: 3.0.3 -info: - title: Service Name API - version: 1.0.0 - description: | - **English**: Brief description of the service and its capabilities. - - **Vietnamese**: Mô tả ngắn gọn về dịch vụ và khả năng của nó. - contact: - name: GoodGo Platform Team - email: dev@goodgo.vn - license: - name: Proprietary - -servers: - - url: https://api.goodgo.vn/v1 - description: Production - - url: https://staging-api.goodgo.vn/v1 - description: Staging - - url: http://localhost:5000 - description: Local development - -tags: - - name: Resources - description: | - **EN**: Resource management endpoints. - **VI**: Các endpoint quản lý tài nguyên. - - name: Admin - description: | - **EN**: Administrative operations (requires admin role). - **VI**: Các thao tác quản trị (yêu cầu quyền admin). - -paths: - /resources: - get: - summary: List resources - description: | - **EN**: Retrieve a paginated list of resources with optional filtering. - **VI**: Lấy danh sách tài nguyên có phân trang với bộ lọc tùy chọn. - tags: - - Resources - parameters: - - name: page - in: query - description: Page number (1-indexed) / Số trang (bắt đầu từ 1) - schema: - type: integer - minimum: 1 - default: 1 - - name: pageSize - in: query - description: Items per page / Số item mỗi trang - schema: - type: integer - minimum: 1 - maximum: 100 - default: 10 - - name: search - in: query - description: Search keyword / Từ khóa tìm kiếm - schema: - type: string - responses: - '200': - description: Success / Thành công - content: - application/json: - schema: - $ref: '#/components/schemas/ResourceListResponse' - examples: - success: - $ref: '#/components/examples/ResourceListSuccess' - '400': - $ref: '#/components/responses/BadRequest' - '401': - $ref: '#/components/responses/Unauthorized' - security: - - bearerAuth: [] - -components: - schemas: - ResourceListResponse: - type: object - properties: - data: - type: array - items: - $ref: '#/components/schemas/Resource' - pagination: - $ref: '#/components/schemas/PaginationMetadata' - - Resource: - type: object - required: - - id - - name - properties: - id: - type: string - format: uuid - name: - type: string - createdAt: - type: string - format: date-time - - PaginationMetadata: - type: object - properties: - page: - type: integer - pageSize: - type: integer - totalPages: - type: integer - totalItems: - type: integer - - responses: - BadRequest: - description: Bad request / Yêu cầu không hợp lệ - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - - Unauthorized: - description: Unauthorized / Chưa xác thực - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - - examples: - ResourceListSuccess: - value: - data: - - id: "123e4567-e89b-12d3-a456-426614174000" - name: "Example Resource" - createdAt: "2024-01-18T10:00:00Z" - pagination: - page: 1 - pageSize: 10 - totalPages: 5 - totalItems: 42 - - securitySchemes: - bearerAuth: - type: http - scheme: bearer - bearerFormat: JWT - description: | - **EN**: JWT token obtained from /auth/login endpoint. - **VI**: JWT token lấy từ endpoint /auth/login. -``` - -### Best Practices for OpenAPI - -1. **Use `$ref` for reusability**: Define schemas once, reference everywhere -2. **Include examples**: Provide realistic request/response examples -3. **Bilingual descriptions**: Add both EN and VI in description fields -4. **Security schemes**: Document all authentication methods -5. **Error responses**: Define standard error response schemas -6. **Validation rules**: Include min/max, patterns, enums where applicable - ---- - -## Versioning Documentation / Quản Lý Phiên Bản - -### API Documentation Versioning - -**Strategy**: Use semantic versioning and separate folders for major versions. - -``` -docs/en/api/ -├── v1/ -│ ├── openapi.yaml -│ └── CHANGELOG.md -├── v2/ -│ ├── openapi.yaml -│ └── CHANGELOG.md -└── README.md # Version comparison and migration guides -``` - -**When to create new version:** -- **Major (v2.0)**: Breaking changes (removed endpoints, changed response structure) -- **Minor (v1.1)**: New features, backward-compatible additions -- **Patch (v1.0.1)**: Bug fixes, documentation updates - -### Changelog Format - -Follow [Keep a Changelog](https://keepachangelog.com/) format: - -```markdown -# Changelog - -All notable changes to this service will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -## [1.2.0] - 2024-01-18 - -### Added / Đã Thêm -- **EN**: New endpoint `POST /api/v1/resources/bulk` for batch operations -- **VI**: Endpoint mới `POST /api/v1/resources/bulk` cho thao tác hàng loạt -- **EN**: Support for filtering by date range in list endpoints -- **VI**: Hỗ trợ lọc theo khoảng thời gian trong các endpoint danh sách - -### Changed / Đã Thay Đổi -- **EN**: Improved authentication flow to use refresh tokens -- **VI**: Cải thiện luồng xác thực sử dụng refresh token -- **EN**: Updated pagination default from 20 to 10 items per page -- **VI**: Cập nhật phân trang mặc định từ 20 xuống 10 items mỗi trang - -### Deprecated / Đã Lỗi Thời -- **EN**: `GET /api/v1/legacy-endpoint` - Use `GET /api/v1/resources` instead. Will be removed in v2.0 -- **VI**: `GET /api/v1/legacy-endpoint` - Dùng `GET /api/v1/resources` thay thế. Sẽ xóa ở v2.0 - -### Removed / Đã Xóa -- **EN**: OAuth1 authentication support (replaced by OAuth2) -- **VI**: Hỗ trợ xác thực OAuth1 (thay bằng OAuth2) - -### Fixed / Đã Sửa -- **EN**: Fixed pagination bug where last page returned empty results -- **VI**: Sửa lỗi phân trang khi trang cuối trả về kết quả rỗng -- **EN**: Resolved race condition in concurrent resource updates -- **VI**: Giải quyết race condition khi cập nhật tài nguyên đồng thời - -### Security / Bảo Mật -- **EN**: Added rate limiting to prevent brute force attacks -- **VI**: Thêm giới hạn tần suất để ngăn chặn tấn công brute force - -## [1.1.0] - 2024-01-10 - -### Added / Đã Thêm -- Initial release with core CRUD operations -- Phát hành đầu tiên với các thao tác CRUD cơ bản - -[Unreleased]: https://github.com/org/repo/compare/v1.2.0...HEAD -[1.2.0]: https://github.com/org/repo/compare/v1.1.0...v1.2.0 -[1.1.0]: https://github.com/org/repo/releases/tag/v1.1.0 -``` - -### Migration Guide Template - -```markdown -# Migration Guide: v1 to v2 - -## Breaking Changes / Thay Đổi Không Tương Thích - -### 1. Authentication Changes / Thay Đổi Xác Thực - -**Before (v1):** -```json -POST /auth/login -{ - "username": "user@example.com", - "password": "password123" -} -``` - -**After (v2):** -```json -POST /v2/auth/login -{ - "email": "user@example.com", - "password": "password123", - "deviceId": "optional-device-id" -} -``` - -**Migration Steps:** -1. Update client to use `email` field instead of `username` -2. Optionally include `deviceId` for better security tracking - -### 2. Response Format Changes / Thay Đổi Format Response - -**Before (v1):** -```json -{ - "items": [...], - "total": 100 -} -``` - -**After (v2):** -```json -{ - "data": [...], - "pagination": { - "page": 1, - "pageSize": 10, - "totalPages": 10, - "totalItems": 100 - } -} -``` - -## Deprecated Features / Tính Năng Lỗi Thời - -| Feature | Replacement | Removal Date | -|---------|-------------|-------------| -| `/api/v1/users` | `/api/v2/users` | 2024-06-01 | - -## Timeline / Lộ Trình - -- **2024-01-18**: v2.0 released, v1 deprecated -- **2024-03-01**: v1 enters maintenance mode (no new features) -- **2024-06-01**: v1 removed, v2 becomes stable -``` - ---- - -## Diagrams & Visuals / Sơ Đồ & Hình Ảnh - -### When to Use Diagrams - -| Diagram Type | Use Case | Mermaid Type | -|--------------|----------|-------------| -| **Architecture** | High-level system overview, service dependencies | `graph TB` | -| **Sequence** | Request/response flows, async processes, integrations | `sequenceDiagram` | -| **ER Diagram** | Database schema, table relationships | `erDiagram` | -| **State** | Status transitions (Order, Campaign, Payment) | `stateDiagram-v2` | -| **Class** | Domain model, entity relationships | `classDiagram` | -| **Flowchart** | Decision trees, business logic flows | `flowchart TD` | - -### Mermaid Dark Palette (MANDATORY) - -**CRITICAL**: Always use the dark color palette from [Mermaid Diagrams Skill](../mermaid-diagrams/SKILL.md). - -**Standard Colors:** -- **Primary (Blue)**: `#3498DB` - Main components, API layer -- **Secondary (Purple)**: `#8E44AD` - Application layer, handlers -- **Accent (Orange)**: `#E67E22` - Domain layer, business logic -- **Neutral (Dark Gray)**: `#34495E` - Databases, infrastructure -- **Success (Green)**: `#27AE60` - Success states -- **Warning (Yellow)**: `#F39C12` - Warning states -- **Danger (Red)**: `#E74C3C` - Error states - -**Example:** -```mermaid -graph TB - API[API Layer] - APP[Application] - DOMAIN[Domain] - DB[(Database)] - - API --> APP - APP --> DOMAIN - APP --> DB - - style API fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98 - style APP fill:#3498DB,color:#ECF0F1,stroke:#2980B9 - style DOMAIN fill:#E67E22,color:#ECF0F1,stroke:#D35400 - style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50 -``` - -### Screenshot Guidelines - -**File Naming:** -- ✅ Descriptive: `auth-flow-login-screen.png` -- ❌ Generic: `screenshot1.png`, `image.png` - -**File Organization:** -``` -docs/ -├── en/ -│ ├── images/ -│ │ ├── architecture/ -│ │ ├── screenshots/ -│ │ └── diagrams/ -│ └── README.md -└── vi/ - ├── images/ # Mirror EN structure - └── README.md -``` - -**File Format:** -- **PNG**: UI screenshots, diagrams with transparency -- **JPG**: Photos, images without transparency -- **SVG**: Vector graphics, logos (when possible) -- **WebP**: Modern format for smaller file sizes - -**Optimization:** -```bash -# Optimize PNG files -pngquant --quality 65-80 docs/en/images/*.png - -# Optimize JPG files -jpegoptim --max=85 docs/en/images/*.jpg - -# Convert to WebP -cwebp -q 80 input.png -o output.webp -``` - -**Embedding in Markdown:** -```markdown -# ✅ GOOD: With descriptive caption and alt text -![Login flow showing email input, password field, and social login options](images/auth-flow-login.png) - -# ❌ BAD: No context -![Screenshot](screenshot.png) -``` - -**Responsive Images:** -```markdown -System Architecture -``` - ---- - -## API Endpoint Tables / Bảng Danh Sách API - -### Standard Endpoint Table Format - -```markdown -## API Endpoints - -### Resource Management / Quản Lý Tài Nguyên - -| Method | Endpoint | Description / Mô Tả | Auth | -|--------|----------|---------------------|------| -| GET | `/api/v1/resources` | List all resources / Liệt kê tài nguyên | ✓ | -| POST | `/api/v1/resources` | Create new resource / Tạo mới tài nguyên | ✓ | -| GET | `/api/v1/resources/{id}` | Get resource details / Lấy chi tiết tài nguyên | ✓ | -| PUT | `/api/v1/resources/{id}` | Update resource / Cập nhật tài nguyên | ✓ | -| DELETE | `/api/v1/resources/{id}` | Delete resource / Xóa tài nguyên | ✓ | - -### Admin Endpoints / Endpoint Quản Trị - -| Method | Endpoint | Description / Mô Tả | Roles | -|--------|----------|---------------------|-------| -| GET | `/api/v1/admin/users` | List all users / Liệt kê người dùng | Admin | -| POST | `/api/v1/admin/users/{id}/suspend` | Suspend user / Tạm dừng người dùng | Admin | -``` - -### Query Parameters Table - -```markdown -### Query Parameters for `GET /api/v1/resources` - -| Parameter | Type | Required | Description / Mô Tả | Default | Example | -|-----------|------|----------|---------------------|---------|----------| -| `page` | integer | No | Page number (1-indexed) / Số trang | 1 | `?page=2` | -| `pageSize` | integer | No | Items per page / Số item mỗi trang | 10 | `?pageSize=20` | -| `search` | string | No | Search keyword / Từ khóa tìm kiếm | - | `?search=product` | -| `sortBy` | string | No | Sort field / Trường sắp xếp | `createdAt` | `?sortBy=name` | -| `sortOrder` | enum | No | Sort direction: `asc`, `desc` / Thứ tự | `desc` | `?sortOrder=asc` | -| `status` | enum | No | Filter by status / Lọc theo trạng thái | - | `?status=active` | -``` - -### Request Body Table - -```markdown -### Request Body for `POST /api/v1/resources` - -| Field | Type | Required | Description / Mô Tả | Validation | -|-------|------|----------|---------------------|------------| -| `name` | string | Yes | Resource name / Tên tài nguyên | Min: 3, Max: 100 chars | -| `description` | string | No | Resource description / Mô tả | Max: 500 chars | -| `type` | enum | Yes | Resource type: `product`, `service` | Must be valid enum | -| `price` | decimal | No | Price in VND / Giá (VNĐ) | Min: 0, Max: 1000000000 | -| `tags` | array | No | Tags for categorization / Thẻ phân loại | Max: 10 items | -``` - -### Response Codes Table - -```markdown -### Response Codes - -| Code | Status | Description / Mô Tả | -|------|--------|---------------------| -| 200 | OK | Request successful / Yêu cầu thành công | -| 201 | Created | Resource created / Tài nguyên đã tạo | -| 400 | Bad Request | Invalid input / Dữ liệu không hợp lệ | -| 401 | Unauthorized | Authentication required / Cần xác thực | -| 403 | Forbidden | Insufficient permissions / Không đủ quyền | -| 404 | Not Found | Resource not found / Không tìm thấy tài nguyên | -| 409 | Conflict | Resource already exists / Tài nguyên đã tồn tại | -| 422 | Unprocessable Entity | Validation failed / Xác thực thất bại | -| 500 | Internal Server Error | Server error / Lỗi server | -``` - -### Error Response Format - -```markdown -### Error Response Structure - -```json -{ - "type": "validation_error", - "title": "Validation Failed", - "status": 422, - "errors": { - "name": ["Name is required", "Name must be at least 3 characters"], - "email": ["Email format is invalid"] - }, - "traceId": "00-abc123-def456-00" -} -``` - -**Error Types:** -- `validation_error` - Input validation failures -- `authentication_error` - Authentication issues -- `authorization_error` - Permission denied -- `not_found_error` - Resource not found -- `conflict_error` - Duplicate or conflicting resource -- `internal_error` - Unexpected server error -``` - ---- - -## Configuration Documentation / Tài Liệu Cấu Hình - -### Environment Variables Table - -```markdown -## Environment Variables / Biến Môi Trường - -### Required Variables / Biến Bắt Buộc - -| Variable | Type | Description / Mô Tả | Example | -|----------|------|---------------------|----------| -| `DATABASE_URL` | string | PostgreSQL connection string / Chuỗi kết nối PostgreSQL | `postgresql://user:pass@localhost:5432/db` | -| `REDIS_URL` | string | Redis connection string / Chuỗi kết nối Redis | `redis://localhost:6379` | -| `JWT_SECRET` | string | Secret key for JWT signing / Khóa bí mật ký JWT | `your-256-bit-secret` | -| `RABBITMQ_URL` | string | RabbitMQ connection / Kết nối RabbitMQ | `amqp://user:pass@localhost:5672` | - -### Optional Variables / Biến Tùy Chọn - -| Variable | Type | Description / Mô Tả | Default | -|----------|------|---------------------|----------| -| `PORT` | integer | Server port / Cổng server | `5000` | -| `LOG_LEVEL` | enum | Logging level: `debug`, `info`, `warn`, `error` | `info` | -| `CORS_ORIGINS` | string | Allowed CORS origins (comma-separated) | `*` | -| `RATE_LIMIT_MAX` | integer | Max requests per window / Số request tối đa | `100` | -| `RATE_LIMIT_WINDOW_MS` | integer | Rate limit window in ms / Cửa sổ giới hạn (ms) | `60000` | -| `CACHE_TTL_SECONDS` | integer | Default cache TTL / TTL cache mặc định | `300` | -``` - -### Configuration File Example - -```markdown -## Configuration File: `appsettings.json` - -```json -{ - "Server": { - "Port": 5000, - "Environment": "Development", - "EnableSwagger": true - }, - "Database": { - "Host": "localhost", - "Port": 5432, - "Name": "goodgo_dev", - "Username": "postgres", - "Password": "password", - "MaxPoolSize": 20, - "CommandTimeout": 30 - }, - "Redis": { - "Host": "localhost", - "Port": 6379, - "Database": 0, - "Password": null, - "ConnectTimeout": 5000, - "SyncTimeout": 5000 - }, - "Jwt": { - "Secret": "your-secret-key-min-32-chars", - "Issuer": "goodgo-platform", - "Audience": "goodgo-clients", - "ExpirationMinutes": 60, - "RefreshTokenExpirationDays": 7 - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - }, - "Console": { - "FormatterName": "json" - } - }, - "RateLimiting": { - "PermitLimit": 100, - "Window": "00:01:00", - "QueueLimit": 10 - }, - "Cors": { - "AllowedOrigins": [ - "http://localhost:3000", - "https://app.goodgo.vn" - ], - "AllowCredentials": true, - "AllowedHeaders": ["*"], - "AllowedMethods": ["GET", "POST", "PUT", "DELETE"] - } -} -``` - -**Notes:** -- **EN**: Never commit secrets to version control. Use environment variables or secret management tools. -- **VI**: Không bao giờ commit secrets vào version control. Dùng biến môi trường hoặc công cụ quản lý secrets. -``` - -### Docker Compose Configuration - -```markdown -## Docker Compose Configuration - -```yaml -version: '3.8' - -services: - app: - build: . - ports: - - "5000:5000" - environment: - - DATABASE_URL=postgresql://postgres:password@db:5432/goodgo - - REDIS_URL=redis://redis:6379 - - JWT_SECRET=${JWT_SECRET} - - LOG_LEVEL=info - depends_on: - - db - - redis - - db: - image: postgres:15 - environment: - - POSTGRES_DB=goodgo - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=password - volumes: - - postgres_data:/var/lib/postgresql/data - ports: - - "5432:5432" - - redis: - image: redis:7-alpine - ports: - - "6379:6379" - volumes: - - redis_data:/data - -volumes: - postgres_data: - redis_data: -``` - -**Environment File** (`.env`): -```bash -JWT_SECRET=your-production-secret-key-min-32-characters -DATABASE_PASSWORD=your-secure-db-password -``` -``` - ---- - -## Best Practices / Thực Hành Tốt - -### Writing Style / Phong Cách Viết - -1. **Clear and Concise**: Use simple language / Dùng ngôn ngữ đơn giản -2. **Action-Oriented**: Start with verbs (Install, Configure, Deploy) -3. **Structured**: Use headings, lists, and tables -4. **Examples**: Provide code examples and commands -5. **Visual**: Use diagrams where helpful - -### Code Examples - -```markdown -# ✅ GOOD: With context and explanation -Install dependencies using pnpm: -```bash -pnpm install -``` - -# ❌ BAD: No context -```bash -pnpm install -``` -``` - -### Links / Liên Kết - -```markdown -# ✅ GOOD: Descriptive link text -See the [Deployment Guide](../guides/deployment.md) for details. - -# ❌ BAD: Click here -Click [here](../guides/deployment.md) for more info. -``` - ## Common Mistakes / Lỗi Thường Gặp ### 1. Single Language Documentation @@ -1313,17 +329,7 @@ services/auth-service/README.md (500+ lines of deployment steps) docs/en/guides/deployment.md ``` -### 3. Absolute Paths in Links - -```markdown -# ❌ BAD: Absolute path -[Guide](/Users/dev/project/docs/guide.md) - -# ✅ GOOD: Relative path -[Guide](../guides/deployment.md) -``` - -### 4. Missing Code Examples +### 3. Missing Code Examples ```markdown # ❌ BAD: No example @@ -1336,42 +342,28 @@ DATABASE_URL="postgresql://user:pass@localhost:5432/db" ``` ``` -### 5. Outdated Documentation +## Best Practices / Thực Hành Tốt -```markdown -# ❌ BAD: Not updating when code changes -# Docs say: Run `npm start` -# Code actually uses: `pnpm dev` +1. **Clear and Concise**: Use simple language / Dùng ngôn ngữ đơn giản +2. **Action-Oriented**: Start with verbs (Install, Configure, Deploy) +3. **Structured**: Use headings, lists, and tables +4. **Examples**: Provide code examples and commands +5. **Visual**: Use diagrams where helpful -# ✅ GOOD: Keep in sync -# Update docs whenever code changes -``` +### What Makes Good Documentation? -## Documentation Checklist / Danh Sách Kiểm Tra - -### Before Writing / Trước Khi Viết -- [ ] Determine correct location (docs/ vs README) -- [ ] Choose bilingual format -- [ ] Review existing docs for consistency - -### While Writing / Trong Khi Viết -- [ ] Use clear, concise language -- [ ] Include code examples -- [ ] Add diagrams where helpful -- [ ] Provide troubleshooting section - -### After Writing / Sau Khi Viết -- [ ] Test all commands -- [ ] Check all links -- [ ] Ensure bilingual consistency -- [ ] Update docs/README.md index +1. **Complete Language Separation**: EN and VI in separate directories +2. **Consistent Dark Mermaid Palette**: Following mermaid-diagrams skill +3. **Practical Examples**: Real code snippets, not placeholders +4. **Troubleshooting Sections**: Common issues and solutions +5. **Quick Start Guides**: Get running in < 5 minutes ## Quick Reference / Tham Chiếu Nhanh ### File Naming - Use kebab-case: `getting-started.md` - Be descriptive: `local-development.md` not `dev.md` -- Match EN and VI filenames +- Match EN and VI filenames (different conventions) ### Heading Levels ```markdown @@ -1388,17 +380,17 @@ DATABASE_URL="postgresql://user:pass@localhost:5432/db" | Inline | `Description / Mô tả` | | After slash | `PORT=5000 # Server port / Cổng server` | | Table header | `Description / Mô Tả` | -| Code comment | `# EN: Install / VI: Cài đặt` | -### Documentation Testing +## Detailed References / Tài Liệu Tham Khảo Chi Tiết -```bash -# Check for broken links -find docs -name "*.md" -exec markdown-link-check {} \; +For specialized documentation topics, see: -# Lint markdown files -markdownlint docs/**/*.md -``` +- [OpenAPI Specification Standards](references/OPENAPI.md) - OpenAPI templates and best practices +- [Versioning Documentation](references/VERSIONING.md) - Changelog format, migration guides +- [Diagrams & Visuals](references/DIAGRAMS.md) - Mermaid diagrams, screenshots, optimization +- [API Endpoint Tables](references/API_TABLES.md) - Standard table formats for API docs +- [Configuration Documentation](references/CONFIGURATION.md) - Environment variables, config files +- [Automation & Tools](references/AUTOMATION.md) - Link checking, linting, CI/CD integration ## Resources / Tài Nguyên @@ -1410,7 +402,7 @@ markdownlint docs/**/*.md - [Skill Authoring](../skill-authoring/SKILL.md) - How to write skills ### Workflows -- [/docs-edit-vi-en](../../.agent/workflows/docs-edit-vi-en.md) - Workflow for updating microservices documentation +- [/docs-edit-vi-en](../../workflows/docs-edit-vi-en.md) - Workflow for updating microservices documentation ### External Resources - [Keep a Changelog](https://keepachangelog.com/) - Changelog format standard @@ -1424,9 +416,3 @@ markdownlint docs/**/*.md - [markdownlint](https://github.com/DavidAnson/markdownlint) - Markdown linter - [Redocly CLI](https://redocly.com/docs/cli/) - OpenAPI tools - [Mermaid Live Editor](https://mermaid.live/) - Test Mermaid diagrams - -### Example Documentation -Refer to these services for best practices: -- `services/mkt-facebook-service-net/docs/` - Complete bilingual setup -- `services/order-service-net/docs/` - Multi-vertical architecture -- `services/catalog-service-net/docs/` - Clean Architecture patterns diff --git a/.agent/skills/skill-authoring/SKILL.md b/.agent/skills/skill-authoring/SKILL.md index 26ab9f08..ac9f4fbf 100644 --- a/.agent/skills/skill-authoring/SKILL.md +++ b/.agent/skills/skill-authoring/SKILL.md @@ -123,6 +123,35 @@ Phần body chứa hướng dẫn chi tiết cho agent. Nên bao gồm: **Khuyến nghị độ dài:** < 5000 tokens cho body content +### 3.3 File Size Guidelines / Hướng Dẫn Kích Thước File + +**Token Estimation / Ước Lượng Token:** +- **Rule of thumb**: 1 line ≈ 10-20 tokens +- **Recommended max body content**: < 5,000 tokens (~250-500 lines) +- **Hard limit**: Never exceed 10,000 tokens (~500-1,000 lines) + +**When to split into references / Khi nào tách ra references:** + +| Lines | Bytes | Action | +|-------|-------|--------| +| < 300 | < 12KB | ✅ Keep in SKILL.md | +| 300-500 | 12-20KB | ⚠️ Consider extracting detailed sections to references/ | +| > 500 | > 20KB | 🚨 MUST split - move detailed content to references/ | + +**Example oversized sections to extract / Ví dụ các phần nên tách:** +- Detailed API templates / Mẫu API chi tiết +- Extensive code examples / Ví dụ code dài +- Tool configuration files / File cấu hình công cụ +- Migration guides / Hướng dẫn migration +- Comprehensive reference tables / Bảng tham chiếu toàn diện +- Troubleshooting guides / Hướng dẫn khắc phục sự cố + +**Benefits of splitting / Lợi ích khi tách:** +1. **Progressive Disclosure**: Agent loads only what's needed +2. **Better Performance**: Faster skill discovery and activation +3. **Easier Maintenance**: Update specific guides without touching core +4. **Clearer Structure**: Main skill stays focused on essentials + ## 4. Progressive Disclosure Agent Skills sử dụng mô hình "tiết lộ dần dần" để tối ưu context: @@ -305,15 +334,66 @@ skills-ref to-prompt ./my-skill ### 8.2 Checklist Trước Khi Commit -- [ ] `name` khớp với tên thư mục -- [ ] `description` đủ chi tiết (1-1024 chars) -- [ ] Body content < 5000 tokens -- [ ] Code examples đã test và hoạt động -- [ ] Links đều valid -- [ ] Có section "When to Use" -- [ ] Có section "Common Mistakes" (nếu applicable) -- [ ] Có "Quick Reference" table -- [ ] Có links đến related skills/resources +- [ ] **Metadata validation**: + - [ ] `name` khớp với tên thư mục + - [ ] `description` đủ chi tiết (1-1024 chars) + - [ ] `version` được cập nhật nếu có thay đổi quan trọng +- [ ] **File size check**: + - [ ] SKILL.md body content < 500 lines (check với `wc -l`) + - [ ] SKILL.md < 20KB (check với `wc -c`) + - [ ] Nếu > 500 lines, detailed content đã move sang references/ + - [ ] Nếu > 1000 lines, MANDATORY refactor required +- [ ] **Token estimation**: Body content < 5,000 tokens (estimate ~10-20 tokens/line) +- [ ] **Content quality**: + - [ ] Code examples đã test và hoạt động + - [ ] Links đều valid (run `markdown-link-check`) + - [ ] Có section "When to Use" + - [ ] Có section "Common Mistakes" (nếu applicable) + - [ ] Có "Quick Reference" table + - [ ] Có links đến related skills/resources + +### 8.3 Skill Quality Audit / Kiểm Toán Chất Lượng Skill + +Run these checks periodically on existing skills / Chạy định kỳ để kiểm tra skills: + +**File Size Audit:** +```bash +# Check all skills for size violations (line count) +find .agent/skills -name "SKILL.md" -exec sh -c 'lines=$(wc -l < "$1"); echo "$lines $1"' _ {} \; | sort -rn | head -10 + +# Show skills > 500 lines (red flag) +find .agent/skills -name "SKILL.md" -exec sh -c 'lines=$(wc -l < "$1"); [ $lines -gt 500 ] && echo "🚨 $lines lines: $1"' _ {} \; + +# Show skills 300-500 lines (yellow flag) +find .agent/skills -name "SKILL.md" -exec sh -c 'lines=$(wc -l < "$1"); [ $lines -gt 300 ] && [ $lines -le 500 ] && echo "⚠️ $lines lines: $1"' _ {} \; +``` + +**Byte Size Audit (rough proxy for tokens):** +```bash +# Check byte size of all skills +find .agent/skills -name "SKILL.md" -exec sh -c 'size=$(wc -c < "$1"); echo "$size bytes $1"' _ {} \; | sort -rn | head -10 + +# Show skills > 20KB (red flag - likely > 5000 tokens) +find .agent/skills -name "SKILL.md" -exec sh -c 'size=$(wc -c < "$1"); [ $size -gt 20000 ] && echo "🚨 $size bytes: $1"' _ {} \; +``` + +**Refactoring Criteria / Tiêu Chí Refactor:** +- **Yellow flag** (300-500 lines, 12-20KB): Review and consider splitting +- **Red flag** (> 500 lines, > 20KB): Refactor required, move content to references/ +- **Critical** (> 1000 lines, > 40KB): IMMEDIATE action - violates Agent Skills spec + +**Example Refactoring:** +```bash +# Before: documentation/SKILL.md (1,451 lines, 40KB) +# After: +# - documentation/SKILL.md (400 lines, 12KB) +# - documentation/references/OPENAPI.md +# - documentation/references/VERSIONING.md +# - documentation/references/DIAGRAMS.md +# - documentation/references/API_TABLES.md +# - documentation/references/CONFIGURATION.md +# - documentation/references/AUTOMATION.md +``` ## 9. Template Skill Mới