---
description: Audit source code để tìm business logic, workflows → cập nhật documentation chính xác theo code thực tế
---

# Workflow: Documentation Audit & Update

## Mục Đích / Purpose

Workflow này đảm bảo documentation phản ánh chính xác code thực tế bằng cách:
1. **Audit toàn bộ source code** trước khi viết/cập nhật docs
2. **Phân tích business logic, workflows, patterns** từ code
3. **Cập nhật documentation** dựa trên audit findings

> **Nguyên tắc cốt lõi**: Documentation phải là "single source of truth" - phản ánh đúng những gì code thực sự làm, không phải những gì ta *nghĩ* code làm.

## Khi Nào Sử Dụng / When to Use

- ✅ Cập nhật documentation cho service đã có code
- ✅ Viết documentation cho code mới hoàn thành
- ✅ Kiểm tra docs có khớp với implementation không
- ✅ Phát hiện undocumented features hoặc outdated docs
- ❌ **KHÔNG dùng** khi viết docs cho code chưa implement (dùng planning docs thay thế)

---

## Bước 1: Preparation & Scope Definition

### 1.1 Xác Định Phạm Vi Audit

**Actions:**
```bash
# Xác định service/component cần audit
# Ví dụ: services/order-service-net

# List tất cả directories
ls -la services/[service-name]/src/
```

**Checklist:**
- [ ] Xác định rõ service/package cần audit
- [ ] Kiểm tra có docs hiện tại không (`docs/` folder)
- [ ] Xác định target output (new docs vs update existing)

### 1.2 Inventory Check

```bash
# Đếm số files cần review
find services/[service-name]/src -name "*.cs" | wc -l
find services/[service-name]/src -name "*.ts" | wc -l

# Check current docs
ls -la services/[service-name]/docs/
```

---

## Bước 2: Source Code Audit

### 2.1 Architecture Layer Analysis

**Cho .NET Services (Clean Architecture):**

```
📂 Ưu tiên đọc theo thứ tự:
1. Domain Layer      → Entities, Aggregates, Value Objects, Domain Events
2. Application Layer → Commands, Queries, Handlers, DTOs
3. Infrastructure   → Repositories, External Services, DbContext
4. API Layer        → Controllers, Endpoints, Request/Response models
```

**Actions:**

// turbo
```bash
# Domain Layer - Business Core
find services/[service-name]/src -path "*Domain*" -name "*.cs" | head -20
```

// turbo
```bash
# Application Layer - Use Cases
find services/[service-name]/src -path "*Application*" -name "*.cs" | head -30
```

// turbo
```bash
# API Layer - Endpoints
find services/[service-name]/src -path "*Api*" -name "*Controller*.cs"
```

### 2.2 Business Logic Discovery

**Tìm kiếm patterns quan trọng:**

// turbo
```bash
# Commands & Queries (CQRS)
grep -r "IRequest<" services/[service-name]/src --include="*.cs" -l
grep -r "IRequestHandler" services/[service-name]/src --include="*.cs" -l
```

// turbo
```bash
# Domain Events
grep -r "IDomainEvent\|DomainEvent" services/[service-name]/src --include="*.cs" -l
```

// turbo
```bash
# Business Rules / Validators
grep -r "AbstractValidator\|IRuleFor" services/[service-name]/src --include="*.cs" -l
```

// turbo
```bash
# Integration Events
grep -r "IntegrationEvent\|IIntegrationEventHandler" services/[service-name]/src --include="*.cs" -l
```

### 2.3 Key Files to Read

**PHẢI đọc các files sau:**

| File Type | Priority | What to Extract |
|-----------|----------|-----------------|
| `**/Entities/*.cs` | 🔴 High | Domain models, properties, relationships |
| `**/Commands/*.cs` | 🔴 High | Business operations, input params |
| `**/Queries/*.cs` | 🔴 High | Data retrieval patterns |
| `**/Handlers/*.cs` | 🔴 High | Business logic implementation |
| `**/Controllers/*.cs` | 🟡 Medium | API endpoints, routes |
| `**/Validators/*.cs` | 🟡 Medium | Validation rules |
| `**/Events/*.cs` | 🟡 Medium | Event flows, integrations |
| `**/Configurations/*.cs` | 🟢 Low | App settings, DI setup |

### 2.4 Workflow & Flow Analysis

**Tìm và trace các workflows:**

// turbo
```bash
# State machines, workflows
grep -r "workflow\|state\|status" services/[service-name]/src --include="*.cs" -i | head -20
```

// turbo
```bash
# Transaction patterns
grep -r "UnitOfWork\|transaction\|commit" services/[service-name]/src --include="*.cs" -i | head -20
```

---

## Bước 3: Audit Documentation Generation

### 3.1 Create Audit Notes

Sau khi đọc code, tạo file audit notes tạm thời:

```markdown
# Code Audit Notes: [service-name]

## Entities Found
- EntityA: [description, properties]
- EntityB: [description, relationships]

## Business Operations (Commands)
- CreateXCommand: [what it does, validation rules]
- UpdateYCommand: [what it does, side effects]

## Queries
- GetXQuery: [what data it returns]
- ListYQuery: [filtering, sorting options]

## API Endpoints
| Method | Route | Handler | Description |
|--------|-------|---------|-------------|
| POST | /api/x | CreateXHandler | Creates new X |
| GET | /api/x/{id} | GetXHandler | Get X by ID |

## Integration Points
- Publishes: EventA, EventB
- Subscribes: ExternalEventC
- External APIs: ServiceD

## Discovered Workflows
1. Workflow A: step1 → step2 → step3
2. State Machine B: draft → pending → approved → rejected

## Undocumented Features
- Feature X (code exists but no docs)
- Hidden endpoint Y

## Discrepancies vs Current Docs
- Docs say A, but code does B
- Missing docs for feature C
```

### 3.2 Gap Analysis

**So sánh audit findings với current docs:**

| Audit Finding | Current Docs | Status |
|--------------|--------------|--------|
| Entity X với 5 props | Mentions 3 props | ⚠️ Outdated |
| CreateY command | Not documented | ❌ Missing |
| Deprecated endpoint Z | Still in docs | 🗑️ Remove |
| Workflow A→B→C | Correct | ✅ OK |

---

## Bước 4: Documentation Update

### 4.1 Update Strategy

Dựa trên audit, quyết định:

1. **New docs cần tạo**: Cho features/endpoints chưa có docs
2. **Docs cần update**: Cho thông tin outdated
3. **Docs cần xóa**: Cho code đã deprecated/removed

### 4.2 Apply /docs-edit-vi-en Workflow

Sau khi có audit findings, áp dụng workflow `/docs-edit-vi-en` để:
- Tạo/cập nhật docs theo cấu trúc chuẩn `docs/en/` và `docs/vi/`
- Đảm bảo bilingual consistency
- Apply dark Mermaid color palette

**Reference:** Xem chi tiết tại [/docs-edit-vi-en](./docs-edit-vi-en.md)

### 4.3 Documentation Sections to Update

Dựa trên audit, cập nhật các sections tương ứng:

| Audit Category | Documentation Section |
|----------------|----------------------|
| Entities, Domain | ARCHITECTURE.md → Domain Model |
| Commands, Queries | API.md → Endpoints |
| Workflows | ARCHITECTURE.md → Request Flow |
| Integration Events | ARCHITECTURE.md → Integration |
| Configuration | README.md → Configuration |
| Validation Rules | API.md → Validation |

---

## Bước 5: Verification

### 5.1 Cross-Check Audit vs Docs

**Checklist cuối cùng:**

- [ ] Tất cả entities trong code → có trong docs
- [ ] Tất cả API endpoints → có trong docs
- [ ] Tất cả business workflows → có diagrams
- [ ] Tất cả integration events → documented
- [ ] Không có thông tin outdated trong docs
- [ ] Mermaid diagrams phản ánh đúng code flow

### 5.2 Validation Commands

// turbo
```bash
# Đếm endpoints trong code
grep -r "\[Http" services/[service-name]/src --include="*.cs" | wc -l

# So sánh với số endpoints documented
grep -c "| POST\|| GET\|| PUT\|| DELETE" services/[service-name]/docs/en/API.md
```

---

## Quick Reference: Audit Checklist

### Pre-Audit ⬜
- [ ] Identify target service/package
- [ ] Check existing docs status
- [ ] Prepare audit notes template

### Code Audit ⬜
- [ ] Read Domain layer (entities, aggregates)
- [ ] Read Application layer (commands, queries, handlers)
- [ ] Read API layer (controllers, endpoints)
- [ ] Identify integration points (events, external APIs)
- [ ] Trace business workflows and state machines

### Analysis ⬜
- [ ] Document all discoveries in audit notes
- [ ] Compare with existing docs
- [ ] Identify gaps and discrepancies

### Documentation ⬜
- [ ] Create/update docs based on audit
- [ ] Apply /docs-edit-vi-en workflow
- [ ] Ensure EN/VI consistency

### Verification ⬜
- [ ] Cross-check docs vs code
- [ ] Validate all endpoints documented
- [ ] Confirm diagrams match code flow

---

## Related Resources

**Skills:**
- [Documentation Skill](../.agent/skills/documentation/SKILL.md) - Documentation guidelines
- [Mermaid Diagrams Skill](../.agent/skills/mermaid-diagrams/SKILL.md) - Diagram patterns
- [API Design Skill](../.agent/skills/api-design/SKILL.md) - API documentation standards

**Workflows:**
- [/docs-edit-vi-en](./docs-edit-vi-en.md) - Formatting and structure workflow

---

## Example: Complete Audit Session

```bash
# 1. Scope: order-service-net
cd services/order-service-net

# 2. Find key files
find src -name "*.cs" -path "*Domain*" | head -10
find src -name "*Command*.cs"
find src -name "*Controller*.cs"

# 3. Read and analyze (view_file_outline, view_code_item)
# → Extract entities, commands, workflows

# 4. Create audit notes
# → Document all findings

# 5. Compare with current docs
# → Identify gaps

# 6. Update docs following /docs-edit-vi-en
# → Create/update EN/VI files

# 7. Verify
# → Check docs match code
```

**Result:**
- ✅ Documentation reflects actual code
- ✅ No undocumented features
- ✅ No outdated information
- ✅ Bilingual consistency maintained
