# /setup-ai-first — Khởi tạo Spec-Driven Docs trong một dự án

Dẫn người dùng qua một setup một-lần tạo mọi thư mục cần thiết, cài CLAUDE.md, và verify môi trường.

## Gate
{{include:steps/gate.md}}

*Lưu ý: Với lệnh này — **bỏ qua Gate Step 1, 2, và 3** (chưa có file input và chưa có project context). Chỉ chạy Step 0-B (model check). Project root là **thư mục làm việc hiện tại**. Đi thẳng tới Precondition Check bên dưới.*

---

## Precondition Check

Kiểm tra đã setup chưa:
- Nếu cả `CLAUDE.md` **và** `.agent/project-context.yaml` đều tồn tại → hỏi: "Dự án này đã được khởi tạo. Chạy lại setup để regenerate file config? (Y/N)"
  - N → dừng
  - Y → tiếp tục (file có sẵn được giữ — mỗi bước sẽ đề nghị merge/skip)
- Nếu chỉ có `specs/` hoặc phát hiện setup một phần → tiếp tục bình thường (an toàn chạy lại)

## Step 0.5 — Loại dự án

Hỏi người dùng:

```
Dự án này thuộc loại nào?
  1. Single-service  — một codebase, một platform (setup chuẩn)
  2. Umbrella repo   — repo này chứa nhiều service submodule (microservices / multi-app)
  3. PO Spec repo    — chỉ docs, không có code chạy được (chỉ PRD + design-spec)
```

Lưu câu trả lời thành `project_type`. Mặc định `1` nếu user không trả lời.

Dựa trên câu trả lời:

**project_type = 1 (Single-service):** Tiếp tục setup chuẩn bên dưới.

**project_type = 2 (Umbrella):** Hỏi hai câu follow-up:
- "Path tới spec submodule (vd `free-trial-specs`)? Nhấn Enter để skip."
- "Liệt kê các service dạng cặp `domain:module`, ngăn cách bởi dấu phẩy
  (vd `user:java-spring,order:java-spring`). Nhấn Enter để skip."

Rồi:
- Skip tạo bất kỳ artifact `specs/` nào (mọi spec — PRD, BDD, tech-docs, design-spec — sống trong spec submodule theo bố cục feature-package `specs/{domain}/{prd-slug}/`)
- Chỉ tạo: `.trace/`, `.agent/review/` ở cấp umbrella
  *(Trừ khi user yêu cầu rõ tạo cấu trúc đầy đủ)*
- Sinh `.agent/project-context.yaml` ở umbrella mode với services và spec_source đã cung cấp
- Skip tạo `CLAUDE.md` (umbrella không có một tech stack đơn)
- Sau setup, nhắc: "Mở từng service submodule riêng trong Claude Code để cài framework ở đó nếu cần."

**project_type = 3 (PO Spec repo):**
- Tạo base dir: `specs/product-definition/`, `specs/domain-knowledge/`, `feedback/`, `.agent/review/`
- Artifact theo từng feature (`specs/{domain}/{prd-slug}/{ {TICKET-ID}-{prd-slug}.md, bdd/, tech-docs/, design-spec/}`) được tạo on demand bởi các lệnh generate — ĐỪNG tạo trước
- Skip: `.trace/` (theo service, sống cạnh code trong mỗi service submodule)
- Sinh `CLAUDE.md` tối thiểu chỉ với §1 (project overview) và §7 (git conventions)
- Hỏi người dùng: **"Liệt kê các business domain của bạn (vd auth, payment, loyalty):"** — lưu thành domain list cho `project-context.yaml` và nhắc PO các tên này phải được dùng nhất quán ở row `| **Domain** |` của bảng Metadata trong mọi PRD
- Thông báo:
  - Lệnh cho PO repo: `/define-product`, `/generate-prd`, `/review-context`, `/generate-design-spec`
  - **Quan trọng cho handoff team dev:** Mọi PRD phải có row `| **Domain** | {domain} |` trong **bảng Metadata**. Team dev dùng nó để route BDD/code sinh ra tới đúng service submodule. Tên domain không nhất quán sẽ phá routing.
  - Bảng Metadata PRD (do `/generate-prd` điền sẵn theo template):
    ```
    | **Domain** | {domain} |       ← phải khớp một key trong services config của team dev
    | **Ticket** | {TICKET-ID} |
    | **Status** | draft | approved |
    ```

## Step 1 — Tạo cấu trúc thư mục

Tạo các thư mục này (skip nếu đã tồn tại):

```
{project-root}/
├── specs/
│   ├── product-definition/   ← Output của /define-product
│   └── domain-knowledge/     ← business dictionary & domain context
├── .trace/                   ← .trace/{domain}/{prd-slug}/{UC-ID}-{platform}.tsv
└── .agent/
    └── review/
```

**Bố cục feature-package** — artifact spec theo từng feature KHÔNG được tạo trước. Mỗi lệnh generate
tự tạo folder của nó on demand dưới `specs/{domain}/{prd-slug}/`:

```
specs/{domain}/{prd-slug}/
├── {TICKET-ID}-{prd-slug}.md ← /generate-prd  (vd SEG01-segment-scoring-service.md)
├── bdd/                      ← /generate-bdd (file .feature)
├── tech-docs/                ← /generate-tech-docs
└── design-spec/              ← /generate-design-spec (chỉ platform FE/App)
```

*Tạo base dir nào tuỳ theo `project_type` set ở Step 0.5:*

| project_type | Tạo | Skip |
|---|---|---|
| **1 — Single-service** | Cấu trúc base ở trên (`specs/product-definition/`, `specs/domain-knowledge/`, `.trace/`, `.agent/review/`) | folder theo feature (tạo on demand) |
| **2 — Umbrella** | Chỉ `.trace/` + `.agent/review/` (ở umbrella root) | Mọi thứ khác — **toàn bộ spec sống trong spec submodule (`spec_source`)** dưới `specs/{domain}/{prd-slug}/`; service submodule chỉ chứa **code + `.trace/`** |
| **3 — PO Spec repo** | `specs/product-definition/`, `specs/domain-knowledge/`, **`feedback/`**, `.agent/review/` (folder `specs/{domain}/{prd-slug}/` theo feature tạo on demand) | `.trace/` (theo service, sống cạnh code trong mỗi service submodule) |

## Step 2 — Tạo CLAUDE.md

*Bỏ qua hoàn toàn step này nếu `project_type = 2` (Umbrella) — umbrella không có một tech stack đơn.*
*Với `project_type = 3` (PO Spec repo) — tạo CLAUDE.md tối thiểu chỉ với §1 (project overview) và §7 (git conventions). Skip §2–§6.*

Kiểm tra `CLAUDE.md` tồn tại chưa:
- Có → hỏi "Merge template hay skip?"
- Không → tạo từ template bên dưới

Sau khi tạo, hướng dẫn: "Mở CLAUDE.md và điền các giá trị `{{PLACEHOLDER}}` bằng thông tin dự án của bạn."

### CLAUDE.md Template

```
# §1. Project Overview
Project: {{PROJECT_NAME}}
Language: {{LANGUAGE}}
Framework: {{FRAMEWORK}}
Build: {{BUILD_COMMAND}}
Test: {{TEST_COMMAND}}
Domains: {{COMMA_SEPARATED_DOMAINS}}

# §2. Architecture
layers: "{{LAYER_STACK}}"
# Example: Controller → Facade → Service → Repository
rules:
  - "Controllers must not contain business logic"
  - "Services own transaction boundaries"

# §3. Coding Standards
naming:
  classes: "{{NAMING_CONVENTION}}"
  methods: "{{METHOD_CONVENTION}}"
response_wrapper: "{{WRAPPER}}"
forbidden:
  - "Magic numbers"
  - "Debug print statements"

# §4. Traceability
# Every controller method must be tagged:
# @trace.implements={UC-ID}-{SC-ID}
# @trace.source=specs/{domain}/{prd-slug}/bdd/{UC-ID}.feature  ← adjust if specs_dir differs in .agent/project-context.yaml
# Tests must be tagged:
# @trace.verifies={UC-ID}

# §5. Error Handling
not_found: "{{NOT_FOUND_EXCEPTION}}"
http_codes: { get: 200, create: 201, not_found: 404, validation: 400 }

# §6. Build & Test
build_command: "{{BUILD_COMMAND}}"
test_command: "{{TEST_COMMAND}}"
run_command: "{{RUN_COMMAND}}"

# §7. Git Conventions
branch_feature: "feature/{{TICKET_PREFIX}}-{N}-{slug}"
commit_feature: "feat({{TICKET_PREFIX}}-{N}): {description}"
```

## Step 3 — Tạo project-context.yaml

*Với `project_type = 2` (Umbrella):*
- *Nếu `.agent/project-context.yaml` đã được sinh bởi `--init --umbrella` → mở nó và verify/sửa section `services` (domain key, path, module). Skip copy template bên dưới.*
- *Nếu chưa sinh → hỏi: "Path spec submodule?" và "Services (cặp domain:module)?" rồi sinh config umbrella (xem Step 0.5 cho format).*

Tạo `.agent/project-context.yaml` dùng `.agent/templates/project-context.yaml` làm template nguồn.

Copy template và hướng dẫn: "Mở `.agent/project-context.yaml` và điền mọi giá trị `{{PLACEHOLDER}}`. Section `paths` đã được cấu hình sẵn với default hợp lý — chỉnh nếu dự án dùng tên thư mục khác."

## Step 4 — Tạo business-dictionary.md

*Skip Step 4 và 5 nếu `project_type = 2` (Umbrella) — business dictionary và core entities sống trong spec submodule và do team PO quản lý. Team dev đọc chúng từ `{spec_source}/specs/domain-knowledge/`.*


Tạo `specs/domain-knowledge/business-dictionary.md` nếu chưa tồn tại:

```markdown
# Business Dictionary — {{PROJECT_NAME}}

> Thuật ngữ chuẩn cho dự án này. Mọi PRD, BDD spec, và code phải theo các thuật ngữ này.
> Managed by: PO / SA team.

## Canonical Terms

| Canonical Term | Description / Context |
|----------------|----------------------|
| {Term}         | {Short description, usage scope} |

## Banned Terms

| ❌ Do NOT use | ✅ Use instead    | Reason |
|---------------|-------------------|--------|
| {banned}      | {canonical}       | {why}  |

## Status / Enum Registry

| Entity | Field   | Allowed Values     |
|--------|---------|--------------------|
| {Entity} | status | {value1, value2} |
```

Hướng dẫn: "Mở `specs/domain-knowledge/business-dictionary.md` và thêm thuật ngữ dự án của bạn. File này sẽ được mọi lệnh đọc để enforce naming nhất quán."

## Step 5 — Tạo core-entities.md

Tạo `specs/domain-knowledge/core-entities.md` nếu chưa tồn tại:

```markdown
# Core Entities — {{PROJECT_NAME}}

> Glossary entity máy-đọc-được cho phát triển có AI hỗ trợ.
> Được mọi lệnh nạp để AI biết domain model của bạn mà không cần đọc source code.
> Managed by: Tech Lead / Architect.
>
> HOW TO USE:
> - Add one `## Entity: {Name}` section per domain entity (aggregate root, value object, etc.)
> - Keep field descriptions concise — this is a REFERENCE, not API docs
> - Update this file whenever you add/rename fields or change business invariants

---

## Entity: {EntityName}

**Purpose**: {1-2 sentences — what this entity represents and why it exists in the domain}
**Domain**: {domain}
**Storage**: {e.g., `orders` table in PostgreSQL | `orders` collection in MongoDB}
**Owner service**: {service/module that owns this entity}

| Field        | Type    | Nullable | Description                         |
|--------------|---------|----------|-------------------------------------|
| id           | UUID    | No       | Primary key                         |
| {field_name} | {type}  | Yes/No   | {short description}                 |
| status       | Enum    | No       | See Status Registry in business-dictionary.md |

**Business invariants:**
- {Rule 1: e.g., "status can only transition: PENDING → ACTIVE → CLOSED"}
- {Rule 2: e.g., "total must equal sum of line items"}

**Relationships:**
- `{EntityA}` 1:N `{EntityB}` — {one sentence description}
- `{EntityA}` N:N `{EntityC}` via `{junction_table}` — {description}

---

## Entity: {AnotherEntity}

*(Add more entities following the same pattern above)*
```

Hướng dẫn: "Mở `specs/domain-knowledge/core-entities.md` và định nghĩa các domain entity chính. Bắt đầu với aggregate root. File này được mọi lệnh AI nạp — định nghĩa tốt ở đây tiết kiệm đáng kể qua-lại khi sinh code."

## Step 6 — Cài VS Code Extension (Khuyến nghị)

Khuyến nghị user cài extension VS Code **Spec Driven Docs Tools** — nó cung cấp panel Review Board + Living Documentation tích hợp với workflow này.

```bash
code --install-extension SpecDrivenDocsTools.spec-driven-docs-tool
```

Hoặc: VS Code → `Ctrl+Shift+P` → **"Extensions: Install from Marketplace"** → tìm **Spec Driven Docs Tools**.

**Nó làm gì:**
- 📋 **Review Board** — UI trực quan để review findings từ `/refine-prd`, `/review-context`, `/review-tech-docs`
- 📊 **Living Documentation** — dashboard traceability dựa trên `.trace/*.tsv`

## Step 7 — Verify

Checklist tuỳ theo `project_type`:

**project_type = 1 (Single-service):**
- [ ] `specs/` tồn tại
- [ ] `specs/product-definition/` tồn tại
- [ ] `specs/domain-knowledge/` tồn tại
- [ ] `.trace/` tồn tại
  *(folder `specs/{domain}/{prd-slug}/` theo feature tạo on demand — không check ở đây)*
- [ ] `.agent/project-context.yaml` tồn tại
- [ ] `CLAUDE.md` tồn tại
- [ ] `specs/domain-knowledge/business-dictionary.md` tồn tại
- [ ] `specs/domain-knowledge/core-entities.md` tồn tại

**project_type = 2 (Umbrella):**
- [ ] `.agent/project-context.yaml` tồn tại với `setup.mode: umbrella`
- [ ] Section `services` có ít nhất một entry với đúng domain key
- [ ] Path `spec_source` tồn tại (vd thư mục `my-project-specs/` có mặt)
- [ ] `.agent/review/` tồn tại
- [ ] Spec submodule đã init: `git submodule status` không hiện prefix `-`

**project_type = 3 (PO Spec repo):**
- [ ] `specs/product-definition/` tồn tại
- [ ] `specs/domain-knowledge/` tồn tại
- [ ] `feedback/` tồn tại
  *(folder `specs/{domain}/{prd-slug}/` theo feature tạo on demand — không check ở đây)*
- [ ] `.agent/review/` tồn tại
- [ ] `.agent/project-context.yaml` tồn tại
- [ ] `CLAUDE.md` tồn tại (tối thiểu)
- [ ] `specs/domain-knowledge/business-dictionary.md` tồn tại
- [ ] `specs/domain-knowledge/core-entities.md` tồn tại

## Output

{{include:steps/report-footer.md}}

```
/setup-ai-first Hoàn tất ✅
```

Output tuỳ theo `project_type`:

**Single-service:**
```
Next:
  1. Điền CLAUDE.md (thay các giá trị {{PLACEHOLDER}})
  2. Điền .agent/project-context.yaml
  3. Điền specs/domain-knowledge/business-dictionary.md
  4. Điền specs/domain-knowledge/core-entities.md
  5. git add và commit 4 file đó
  6. Cài VS Code extension:
     code --install-extension SpecDrivenDocsTools.spec-driven-docs-tool
  7. /define-product để bắt đầu feature đầu tiên
```

**Umbrella:**
```
Next:
  1. Review .agent/project-context.yaml:
     - Cập nhật services[].path khớp tên thư mục submodule thực tế
     - Cập nhật domain key của services khớp row `Domain` (bảng Metadata) trong các file PRD
     - Xác nhận path spec_source đúng

  2. Chạy /sync — một lệnh lo mọi thứ còn lại:
     /sync
     → git pull + submodule init + spec submodule update
     → Tự tạo .agent/project-context.yaml cho mỗi service submodule
       (phát hiện module từ pom.xml / go.mod / package.json / pubspec.yaml v.v.)
     → Sync Living Docs panel
     → Refresh spec-manifest.yaml

  3. Bắt đầu sinh:
     /generate-bdd {spec_source}/specs/{domain}/{prd-slug}/{TICKET-ID}-{prd-slug}.md
```

**PO Spec repo:**
```
Next:
  1. Điền .agent/project-context.yaml:
     - domains: [liệt kê mọi business domain — chúng thành row `Domain` (bảng Metadata) trong PRD]
     - project.name, project.description
  2. Điền specs/domain-knowledge/business-dictionary.md  ← canonical terms
  3. Điền specs/domain-knowledge/core-entities.md        ← entity glossary
  4. git add và commit các file đó
  5. Cài VS Code extension:
     code --install-extension SpecDrivenDocsTools.spec-driven-docs-tool
  6. /define-product để bắt đầu feature đầu tiên

⚠️  Nhắc handoff team dev:
  - Mỗi PRD phải có row `Domain` (bảng Metadata) khớp một trong domains list của bạn
  - Khi team dev setup umbrella repo của họ, họ map các tên domain này
    tới path service submodule trong section services của project-context.yaml
  - Chia sẻ tên domain với team dev trước khi họ cấu hình umbrella
```
