## MANDATORY: Strict Gate Workflow

> **Absolute Rule: Complete Gate N before entering Gate N+1.**
> **Do not skip, shorten, or merge Gates.**

> **Task type `gen-doc`** uses a **2-gate flow** (Gate 1 + Gate 2 only). See the gen-doc section below — do NOT run Gates 3/4/5 for gen-doc tasks.
> **Task type `ingest-data`** also uses a **2-gate flow** — see the ingest-data section below. For PM/BrSE/Comtor ingesting customer communication (Backlog ticket/comment/Document/Wiki link, SharePoint link, or pasted text) into `AK-Docs/01.QnA/`.

You have superpowers. When a ticket context exists in `.aiflow/context/current.json`:
- **Consult the "AI Skill Registry"** below to find instructions for each skill (`SKILL.md`).
- **AUTO-START Gate 1 immediately** — do NOT wait to be asked.
- Read the context, **check `taskType`**, and follow the matching workflow — NO EXCEPTIONS.
- **PROJECT CONVENTIONS:** Before writing any output file (plan, requirement, summary), read `custom/rules/project-conventions.md`. These rules override upstream skill defaults.

### Quy tắc đặt câu hỏi (áp dụng mọi Gate, mọi workflow bên dưới)

> Mỗi lần workflow ghi "ask ONE question at a time" / "hỏi ONE câu hỏi" đều phải theo 5 quy tắc này.

1. **Không hỏi điều đã có câu trả lời hoặc suy ra được.** Duy trì bảng "Quyết định đã chốt + hệ quả suy ra" trong hội thoại: mỗi câu trả lời kéo theo các hệ quả trực tiếp và hệ quả đó **là một phần của câu trả lời**, không phải câu hỏi mới. Ví dụ "không retry khi gửi thất bại" suy ra: không có số lần retry, không có khoảng cách retry, không retry cho kênh khác trong cùng luồng. So khớp theo ý định nghiệp vụ, không theo chữ (`retry` = `gửi lại` = `thử lại`). Nghi ngờ đáp án cũ có bao phủ hay không → hỏi **một** câu xác nhận yes/no, một lần, thay vì mở câu hỏi mới.
2. **Không hỏi câu đang bị chặn.** Câu hỏi có đáp án chỉ xác định được sau một câu khác chưa được trả lời → ghi `Blocked-by <câu cha>` và **không hỏi** ở vòng này; câu cha được trả lời rồi mới soát lại (đã bao phủ → đóng luôn, không hỏi). Cấm tách nhỏ/diễn đạt lại để hỏi lách.
3. **Viết câu hỏi để người không đọc code cũng trả lời được:** Bối cảnh (1–3 câu, ý cuối nêu chưa chốt thì ảnh hưởng gì) → Câu hỏi đúng một ý → Options kèm hệ quả từng option + "Khác". **KHÔNG** viết mục "Vì sao cần hỏi" thành mục riêng: nội dung đó đã nằm ở ý cuối của Bối cảnh và trong hệ quả từng option, tách ra chỉ làm câu hỏi dài gấp đôi — phản hồi thật từ PM: "nội dung khá rườm rà". Giải nghĩa mọi từ viết tắt ngay lần đầu xuất hiện. Thuật ngữ, tên màn hình, nhãn tiếng Nhật không đứng một mình trong câu tiếng Việt/tiếng Anh — trong câu hỏi lẫn tài liệu `AK-Docs/04.Coding/`: viết tên gọi theo Glossary kèm chữ gốc trong ngoặc ở lần đầu, ví dụ "nhà cung cấp (サプライヤー)" (xem `custom/rules/domain-terminology.md`, mục "Thuật ngữ tiếng Nhật"). Câu hỏi phức tạp (≥2 điều kiện, nhiều luồng, hoặc về thứ tự/ưu tiên/thời điểm) kèm một ví dụ minh hoạ có số liệu thật và kết quả theo từng option.
4. **Số câu hỏi không phải thước đo chất lượng.** Đáp án không làm thay đổi output → ghi Assumption, không hỏi. Người trả lời hỏi ngược "câu này có cần thiết không?" → rút câu hỏi nếu suy ra được và rà lại các câu còn lại trước khi hỏi tiếp.
5. **Tự tìm hiểu trước khi hỏi — chỉ hỏi thứ không quan sát được.** Câu trả lời nằm trong repo, config, tài liệu `AK-Docs/`, ticket, hoặc có quy ước mặc định (vd môi trường và URL, trình duyệt, breakpoint, cách chuẩn bị dữ liệu, thư viện/kiểu test đang dùng, ngôn ngữ tài liệu) → **tự quét, tự điền, không hỏi**; ghi kèm nguồn, không tìm thấy thì dùng mặc định và ghi `[mặc định]`. Chưa quét mà đã hỏi = vi phạm. Chỉ hỏi khi đó là **chính sách/đánh đổi của dự án** (không quan sát được) hoặc **mâu thuẫn/thiếu trong nghiệp vụ**. Muốn chắc về một giá trị đã suy ra → viết khẳng định `Tôi dùng <giá trị> (nguồn: <bằng chứng>) — sai thì báo tôi sửa.` rồi chạy tiếp, không dừng chờ. Nhiều mục thiết lập cùng lúc → gộp vào **một** bảng xác nhận trả lời một lần, không rải thành chuỗi câu hỏi.

---

### Thuật ngữ nghiệp vụ (áp dụng mọi Gate, mọi workflow bên dưới)

Mọi output người khác đọc — `requirement.md`, plan, summary, test plan, test report, bug report, tài liệu `gen-doc`, entry `ingest-data`, câu hỏi trong hội thoại — dùng đúng từ trong `AK-Docs/00.Project-Overview/Glossary.md` và trong tài liệu đã có của cùng ticket / functionId (UC Spec, System Requirement, QnA-Log, test case), theo `custom/rules/domain-terminology.md`:

- Không tự dịch từ dự án (`buyer`, `group`, `product`, `import`), không đổi sang từ đồng nghĩa giữa các tài liệu.
- Không tự đặt tên tiếng Việt / tiếng Anh cho phân hệ, menu, khu vực màn hình ("cửa hàng", "cổng", "trang quản trị", "storefront") — lấy từ Glossary.
- Thuật ngữ tiếng Nhật viết tên gọi theo cột `Viết trong tài liệu` kèm chữ gốc trong ngoặc ở lần đầu; chỗ người đọc phải khớp chữ trên màn hình thì chữ gốc trước.
- Từ chưa có trong Glossary → hỏi user (một câu), rồi ghi vào Glossary ngay.
- Câu mô tả thao tác / kết quả UI dùng động từ và trạng thái chuẩn của `custom/rules/ui-action-wording.md` (`Click button`, `Enter <value> into <field>`, `Displayed`, `Disabled`…); thuật ngữ IT giữ tiếng Anh (field, toast, modal, server, cache, redirect…).

Skill `gate-review` (Step 2b) kiểm lại trước mỗi lần dừng gate.

---

### Pre-flight BẮT BUỘC — Đồng bộ Source & Docs (đầu MỖI Gate)

> Áp dụng cho **mọi Gate** của cả 3 workflow bên dưới ([DEV], [TESTER], [EXECUTE]) — không chỉ Gate 1. Chạy đủ các bước sau **trước khi** thực hiện bất kỳ hành động nào khác của gate đó.

1. **Sync repo source (bên trong, không phải AK-Docs/Shared-Docs):** xác định thư mục repo source hiện tại → `cd` vào đó → chạy `git status --porcelain`; nếu working tree sạch, chạy `git pull --ff-only`. Nếu có thay đổi chưa commit, branch diverged, hoặc không có remote tracking branch → bỏ qua pull (không phải lỗi, không cần cảnh báo).
2. **Sync `AK-Docs/`:** `cd` vào `AK-Docs/` (sibling folder ở workspace root) → chạy `git pull`.
3. **Sync `Shared-Docs/`:** `cd` vào `Shared-Docs/` (sibling folder ở workspace root) → chạy `git pull`.
4. Sau khi xong, `cd` quay lại thư mục làm việc ban đầu trước khi tiếp tục các bước khác của gate.

Nếu `AK-Docs/` hoặc `Shared-Docs/` chưa tồn tại tại workspace root, hoặc không phải git repo → bỏ qua bước tương ứng, không cảnh báo (dự án có thể chưa dùng docs repo riêng).

**Nếu bất kỳ lệnh `git pull` nào ở Bước 1–3 thất bại** (conflict, mất mạng, không có remote, v.v.) → **KHÔNG dừng workflow** — hiển thị cảnh báo và tiếp tục gate với dữ liệu local hiện có:

```
⚠️ CẢNH BÁO: Không thể pull [tên repo] — [lý do lỗi].
→ Đang tiếp tục Gate [N] với dữ liệu local hiện tại, có thể chưa mới nhất.
```

### Workflow Selection

Read `.aiflow/context/current.json` → check the `taskType` field:

| `taskType` value | Workflow to follow |
|---|---|
| `testing` | **[TESTER] 4-Gate Testing Workflow** (below) |
| `execute` | **[EXECUTE] Executing Flow** (below) |
| `feature`, `bug-fix`, `refactor`, `investigation`, `documentation` | **[DEV] 5-Gate Development Workflow** (below) |
| `create-spec` | **[BA] 4-Gate Spec Creation Workflow** (below) |
| `create-testcase` | **[QA] 4-Gate TestCase Creation Workflow** (below) |
| `ingest-data` | **[COMTOR] Ingest Data — 2-Gate Flow** (below) |

If `taskType` is missing or unrecognized, default to the DEV workflow and ask ONE clarifying question.

---

## [DEV] 5-Gate Development Workflow

> **For:** `feature` · `bug-fix` · `refactor` · `investigation` · `documentation`

### Cấu trúc thư mục đầu ra

```
AK-Docs/04.Coding/
├── 00.Overview/_Index.md                          ← Tracker: F-ID | Ticket | Dev | Gate | PR (cập nhật mỗi gate)
├── 01.Requirements/[functionId]/[ticketId].md    ← Gate 1 tạo
├── 02.Plans/[functionId]/[ticketId].md           ← Gate 2 tạo
├── 03.TDD-Notes/[functionId]/[ticketId].md       ← Gate 3 tạo
├── 04.Reviews/[functionId]/[ticketId].md         ← Gate 4 tạo
└── 05.Pull-Requests/[functionId]/[ticketId].md   ← Gate 5 tạo
```

- `[functionId]`: mã định danh chức năng **do dự án quy định** (ví dụ `F-001_User-Login`, `AD06`, `UC-LOGIN`) — không ép format. Một feature có thể có nhiều ticket → folder theo functionId, file theo ticketId.
- `[ticketId]`: lấy từ `taskId` trong `.aiflow/context/current.json` (ví dụ `TICKET-100.md`).

### GATE 1 — AI Analyze Requirement (auto-start)

**INVOKE:** `read-study-requirement` skill

AI actively reads ticket + source code to understand the requirement:

0. **Pre-flight — xác định `functionId` và thư mục đầu ra (BẮT BUỘC):**

   Kiểm tra theo thứ tự ưu tiên:
   1. Trường `functionId` hoặc `screenId` trong `.aiflow/context/current.json`
   2. **Suy ra từ input**: nếu đầu vào có file UC Spec / tài liệu do BA bàn giao (trong `supplementaryContext[]`, description, hoặc file được chỉ định khi `ak use <file>`) → đọc nội dung file để tìm functionId, hoặc suy từ đường dẫn thư mục chứa file (ví dụ file nằm ở `AK-Docs/02.BA-Specs/04.UC-Specs/[functionId]/UC-Spec_v1.md` → lấy `[functionId]`). Có thể tra thêm `AK-Docs/04.Coding/00.Overview/_Index.md` hoặc `AK-Docs/00.Project-Overview/Function-List.md` theo tên feature.
      → Tìm được ứng viên → **hỏi xác nhận** thay vì hỏi trống:
      ```
      functionId của task này có phải là [X] không? (Y / hoặc nhập giá trị đúng)
      ```
   3. Không suy ra được → hỏi DEV trực tiếp:
      ```
      Không tìm thấy functionId trong context.
      Vui lòng cung cấp mã định danh chức năng theo quy ước dự án (ví dụ: F-001_User-Login, AD06):
      ```

   → Đợi DEV trả lời, dùng giá trị này cho toàn bộ 5 Gates. **KHÔNG ĐƯỢC TIẾP TỤC NẾU CHƯA CÓ functionId.**

   Sau đó kiểm tra thư mục `AK-Docs/04.Coding/` trong root dự án — chưa có thì tạo đủ cây thư mục (00.Overview → 05.Pull-Requests) và file tracker `00.Overview/_Index.md`. Thông báo:
   ```
   ✓ Thư mục đầu ra: AK-Docs/04.Coding/
   ✓ functionId: [functionId]  ✓ ticketId: [ticketId]
   → Bắt đầu Gate 1...
   ```

0.5. **Đảm bảo đang làm việc trên branch riêng của ticket (AK-Docs):**

   Trước khi ghi bất kỳ file nào vào `AK-Docs/04.Coding/`, đảm bảo AK-Docs đang ở branch riêng của ticket này, không phải `main` (mọi thay đổi `AK-Docs` phải qua branch + Merge Request, PM duyệt cuối cùng trước khi merge vào `main`):

   1. Kiểm tra `AK-Docs` hiện đang ở branch nào (`git -C AK-Docs branch --show-current`).
   2. Nếu **đã** ở `feature/[ticketId]` (hoặc `feature/[ticketId]-<mô-tả>` của đúng ticket này — resume session trước, hoặc Gate 2/3/4 tiếp nối Gate 1) → bỏ qua, tiếp tục.
   3. Nếu **chưa**: liệt kê branch đã có của ticket — `git -C AK-Docs branch --list "feature/[ticketId]" "feature/[ticketId]-*"`:
      - **Chưa có branch nào** → hỏi DEV: "Chưa có branch riêng cho ticket này trong AK-Docs. Tạo branch `feature/[ticketId]` từ `main` — đồng ý không?" → DEV đồng ý thì chạy `ak docs branch [ticketId] --yes`.
      - **Đã có branch cho ticket này** → hỏi DEV chọn 1 trong 2: làm tiếp trên branch cũ (`ak docs branch [ticketId] --reuse --yes`), hoặc tạo branch mới có hậu tố mô tả phần việc lần này (`ak docs branch [ticketId] <mô-tả> --yes` → `feature/WONDER-1071-create-ui`, `feature/WONDER-1071-update-backend`).
      - **DEV từ chối** → tiếp tục Gate 1 trên nhánh hiện tại của AK-Docs (DEV tự quản lý branch).

   > ❗ Branch chỉ gồm `feature/[ticketId]` — KHÔNG chèn functionId. Format cũ `feature/[functionId]/[ticketId]` đã bỏ vì khi không suy ra được functionId nó sinh ra branch lặp `feature/WONDER-1071/WONDER-1071`.
   > ❌ Không tự thêm `--yes` khi chưa thấy DEV gõ xác nhận rõ ràng trong hội thoại.

1. Read `.aiflow/context/current.json` — ticket info
2. **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file (sync repo source + `AK-Docs/` + `Shared-Docs/`). Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
3. Read source code — architecture, related files, data flow
3.5. **Đọc Dev Checklist của QA (nếu có):** `AK-Docs/03.Testing/01.Testcases/[functionId]/[functionId]_Dev_Checklist.md` — danh sách tự kiểm QA sinh ở Gate 4 của `create-testcase`. Đây là những gì QA sẽ kiểm khi nhận bàn giao, nên đọc **trước khi code** để thiết kế đúng ngay từ đầu:
   - Ghi các điểm checklist chạm tới phần mình sửa vào mục "testing plan" của requirement doc ở bước 5.
   - Dòng checklist nào mâu thuẫn với hiểu biết hiện tại về yêu cầu → đưa vào danh sách câu hỏi ở bước 4.
   - **File chưa tồn tại → bỏ qua, không hỏi, không chặn gate.** QA có thể chưa chạy `create-testcase` cho functionId này.
4. If anything is unclear — ask ONE question at a time, wait for reply (theo [Quy tắc đặt câu hỏi](#quy-tắc-đặt-câu-hỏi-áp-dụng-mọi-gate-mọi-workflow-bên-dưới))
5. Output `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md` with:
   - Requirements summary (ticket summary + AC), source code analysis
   - Proposed solution and approach
   - Impact analysis, effort estimate, testing plan
6. Update tracker row in `AK-Docs/04.Coding/00.Overview/_Index.md`: `| [F-ID] | [ticketId] | [feature] | [dev] | ✅⬜⬜⬜⬜ Gate 1 | - |`
7. **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
8. Display gate pause message from `gate-review` skill — wait for **APPROVED**

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — run `ak review check --gate 1 --ticket [ticket-id]`
→ If passed: run `ak gate 1 approved --ticket [ticket-id]` → proceed to Gate 2
→ If blocked: follow gate-review skill response protocol
→ `taskType` là `feature` / `bug-fix` / `refactor` → cập nhật dòng `[functionId]` trong `AK-Docs/00.Project-Overview/Function-List.md`: `Dev 🔵`, thêm `[ticketId]` vào cột `Tickets` (theo `custom/rules/function-list-status.md`)

> **Tip:** If auto-start doesn't trigger, the developer can start this gate by typing: **"start"**, **"Gate 1"** or **"Analyze ticket"**. If this chat session was already open when the ticket was loaded (`ak use`), those phrases won't mean anything to the AI yet since the `SessionStart` hook did not re-run — run **`/coding`** instead to load the ticket context manually.

DO NOT just check format — **understand the content and propose solutions**.

> **Telemetry:** Run `ak gate 1 start --ticket [ticket-id]` when starting this gate (auto-start or when developer types "start"/"Gate 1"). Run as-is — do NOT append shell redirects like `2>$null` or `>/dev/null`.
> Run `ak gate 1 approved --ticket [ticket-id]` after gate-review verify passes (see When APPROVED received block above). Run as-is — do NOT append shell redirects.

---

### GATE 2 — Implementation Plan (wait for APPROVED)

**INVOKE:** `generate-spec` skill, then `superpowers:writing-plans`

- **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
- Create a detailed TDD implementation plan based on the approved requirement (`AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md`).
- Output `AK-Docs/04.Coding/02.Plans/[functionId]/[ticketId].md` with the detailed TDD implementation plan (step-by-step, file list, test-first order).
- Update tracker row in `AK-Docs/04.Coding/00.Overview/_Index.md` (Gate 2 ✅).
- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — CODE WILL NOT BE GENERATED until APPROVED received.

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — run `ak review check --gate 2 --ticket [ticket-id]`
→ If passed: run `ak gate 2 approved --ticket [ticket-id]` → proceed to Gate 3
→ If blocked: follow gate-review skill response protocol

> **Telemetry:** Run `ak gate 2 start --ticket [ticket-id]` when starting this gate. Run as-is — do NOT append shell redirects.
> Run `ak gate 2 approved --ticket [ticket-id]` after gate-review verify passes (see When APPROVED received block above). Run as-is — do NOT append shell redirects.

---

### GATE 3 — Code Generation (TDD only)

Only runs after Gate 2 has been APPROVED.

**INVOKE:** `superpowers:test-driven-development`
- **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
- **Framework rules (bắt buộc, đọc trước dòng code đầu tiên):** nếu chưa đọc trong session này, đọc đầy đủ file(s) được trỏ ở dòng "> **Rules & code examples:**" đầu CLAUDE.md/AGENTS.md (`.rules/<lang>/<framework>-rules.md` + `-examples.md`). Áp dụng cho MỌI lần sửa code trong Gate này, không chỉ lần đầu.
- Complex feature (3+ files): `superpowers:subagent-driven-development`
- Write tests FIRST — run to confirm FAIL -> implement -> PASS.
- Bug fix EXTRA: `superpowers:systematic-debugging` + `investigate-bug` skill first.
- Output `AK-Docs/04.Coding/03.TDD-Notes/[functionId]/[ticketId].md`:
  - **Test List** — danh sách test viết TRƯỚC khi implement (checklist `- [ ] TC-01: ...`)
  - **Implementation Notes** — ghi chú phát sinh trong quá trình code
- Update tracker row in `AK-Docs/04.Coding/00.Overview/_Index.md` (Gate 3 ✅) when tests PASS.

> **Telemetry:** Run `ak gate 3 start --ticket [ticket-id]` when starting this gate. Run as-is — do NOT append shell redirects.

---

### GATE 4 — AI Self-Review (wait for APPROVED)

**INVOKE:** `review-plan` skill

Mandatory order:
0. **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
1. `superpowers:verification-before-completion` — all tests must PASS
2. `impact-analysis` skill — check for breaking changes
2.5. **Chạy Dev Checklist (nếu file tồn tại):** `AK-Docs/03.Testing/01.Testcases/[functionId]/[functionId]_Dev_Checklist.md` — chạy từng dòng chạm tới phần đã sửa, điền cột `Result` là `OK` / `NG` / `N/A`:
   - `N/A` → ghi lý do vào cột `Note`. `NG` chưa sửa kịp → ghi là known issue vào cột `Note` và nêu trong review doc ở bước 3 để báo QA khi bàn giao.
   - Chạy `ak tc lint --checklist AK-Docs/03.Testing/01.Testcases/[functionId]/[functionId]_Dev_Checklist.md` sau khi điền — còn `error` thì sửa rồi chạy lại.
   - **File chưa tồn tại → bỏ qua bước này, gate chạy bình thường.**
3. Create `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md` — Test Results, Impact Analysis (files changed, affected features, breaking changes), kết quả Dev Checklist nếu có chạy ở bước 2.5, và mục `## Review Record` theo `custom/rules/review-record.md` (bảng tổng hợp comment, chi tiết từng `RC-xx`, lịch sử duyệt gate) — developer reviews manually before approving
5. Update tracker row in `AK-Docs/04.Coding/00.Overview/_Index.md` (Gate 4 ✅)

Then:
- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill. Also accepts `BUG: [description]` (bypasses review check — goes directly to fix cycle).

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — run `ak review check --gate 4 --ticket [ticket-id]`
→ If passed: run `ak gate 4 approved --ticket [ticket-id]` → proceed to Gate 5
→ If blocked: follow gate-review skill response protocol

**When BUG: [description] received (no review check needed):**
- Ghi mỗi lỗi thành một `RC-xx` (`🔴 Open`) trong Review Record trước khi sửa (theo `custom/rules/review-record.md`); sửa xong đặt `🟡 Fixed`, chỉ `✅ Closed` khi DEV APPROVED lần sau
- Coding bug → fix → repeat Gate 4 (re-generate review file, giữ nguyên Review Record và chỉ cập nhật)
- Requirement bug → return to Gate 1

> **Telemetry:** Run `ak gate 4 start --ticket [ticket-id]` when starting this gate. Run as-is — do NOT append shell redirects.
> Run `ak gate 4 approved --ticket [ticket-id]` after gate-review verify passes (see When APPROVED received block above). Run as-is — do NOT append shell redirects.

---

### GATE 5 — Peer Review and Done

Only runs after Gate 4 has been APPROVED.

**INVOKE:** `superpowers:requesting-code-review`

0. **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
0.3. **Ghi kết quả peer review vào Review Record** của `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md` (theo `custom/rules/review-record.md`):
   - Mỗi finding của `requesting-code-review` → một `RC-xx`, Nguồn `AI code review`, Gate `G5`, Mức độ theo bảng quy đổi (Critical → Critical, Important → Major, Minor → Minor), điền Vấn đề, Nguyên nhân, Vị trí.
   - Hiển thị bảng tổng hợp các `RC-xx` mới cho DEV, hỏi một lần: finding nào sửa, finding nào hoãn (kèm ticket follow-up), finding nào không sửa (kèm lý do). Chờ DEV trả lời; không tự quyết.
   - Finding DEV chọn sửa → sửa, chạy lại test, điền Cách sửa + Kiểm chứng, đặt `🟡 Fixed`. Finding hoãn / không sửa → `⏸️ Deferred` / `⚪ Won't fix`, ghi Quyết định theo lời DEV.
   - DEV xác nhận các bản sửa → `✅ Closed`; thêm dòng `G5 Peer review | … | ✅ Done | <mở> / <đóng>` vào lịch sử duyệt gate. Làm trước bước 2 để Review Record đi cùng MR AK-Docs.
0.5. `taskType` là `feature` / `bug-fix` / `refactor` → hỏi DEV một câu: "Còn ticket Dev nào của `[functionId]` chưa xong không?" — chờ trả lời. Không còn → `Dev ✅` trong `AK-Docs/00.Project-Overview/Function-List.md`; còn → giữ `Dev 🔵` (theo `custom/rules/function-list-status.md`). Làm trước bước 2 để thay đổi đi cùng MR AK-Docs.
1. Create `AK-Docs/04.Coding/05.Pull-Requests/[functionId]/[ticketId].md` — PR description gồm:
   - Ticket link, danh sách thay đổi chính, How to Test, Checklist for Reviewer
   - **Related Docs links:** UC Spec (`AK-Docs/02.BA-Specs/04.UC-Specs/[functionId]/`), Test Case (`AK-Docs/03.Testing/01.Testcases/[functionId]/`), Dev Plan (`AK-Docs/04.Coding/02.Plans/[functionId]/[ticketId].md`)
2. **Submit `AK-Docs/04.Coding/` lên remote qua Merge Request TRƯỚC khi tạo Pull Request cho source code:**
   - Soạn title + description cho MR (tóm tắt toàn bộ tài liệu vừa hoàn thành: Requirements, Plan, Review, PR-doc), hiển thị cho DEV xem trước.
   - Hỏi DEV: "Nội dung commit/MR như trên — đồng ý submit AK-Docs không?"
     - DEV đồng ý → chạy `ak docs submit --title "..." --description "..." --yes`
     - DEV từ chối → dừng, để DEV tự commit/tạo MR khi sẵn sàng
   - Thông báo DEV: MR đã mở, chờ **PM review & merge vào `main`** — đây là bước duyệt cuối cùng cho tài liệu, không phải DEV tự merge.
   - ❌ Không tự thêm `--yes` khi chưa thấy DEV gõ xác nhận rõ ràng trong hội thoại.
3. Guide on creating a Pull Request (source code) — dùng nội dung file trên làm PR description.
4. Update tracker row in `AK-Docs/04.Coding/00.Overview/_Index.md` (Gate 5 ✅ Done + PR link).

> **Telemetry:** Run `ak gate 5 start --ticket [ticket-id]` when starting this gate. Run as-is — do NOT append shell redirects.

---

## [TESTER] 4-Gate Testing Workflow

> **For:** `testing`
> **Interaction Rules:** Ask ONE clarifying question at a time — wait for TESTER reply before proceeding. NEVER batch questions.

### GATE 1 — Phân tích & Confirm (auto-start)

**INVOKE:** `test-analysis` skill

0. **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
1. Read `.aiflow/context/current.json` — ticket title, description, acceptance criteria
2. Fetch linked docs if URLs present in description (`ak fetch-links <url>`)
3. Analyze scope, functional flows, non-functional requirements, risks
4. Ask clarifying questions — **ONE at a time**, wait for reply
5. Write `test-plan/test-analysis.md`
6. **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
7. Display gate pause message from `gate-review` skill — wait for **APPROVED**

> **Tip:** TESTER can trigger with: **"start"**, **"Gate 1"** or **"Analyze ticket"**.

```
⏸️ GATE 1: TEST ANALYSIS READY
→ Review: [test-plan/test-analysis.md](test-plan/test-analysis.md)
→ Type APPROVED to proceed to Gate 2
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 1 --ticket [ticket-id]`
→ If passed: `ak gate 1 approved --ticket [ticket-id]` → Gate 2
→ If blocked: follow gate-review skill response protocol
→ Cập nhật dòng `[functionId]` trong `AK-Docs/00.Project-Overview/Function-List.md`: `QA 🔵` (theo `custom/rules/function-list-status.md`)

> **Telemetry:** Run `ak gate 1 start --ticket [ticket-id]` when starting this gate. Run as-is — do NOT append shell redirects.
> Run `ak gate 1 approved --ticket [ticket-id]` after gate-review verify passes (see When APPROVED received block above). Run as-is — do NOT append shell redirects.

---

### GATE 2 — Lập Kế Hoạch Test (4 phases, each needs APPROVED)

Only runs after Gate 1 APPROVED.

> **Rule:** TESTER must approve each phase before AI moves to the next. Never merge phases.

> **Telemetry:** Run `ak gate 2 start --ticket [ticket-id]` when starting Phase 2a. Run as-is — do NOT append shell redirects.

#### Phase 2a — Scenarios & Checklist

**INVOKE:** `generate-testcase` skill (Phase 2a)

- **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
- If TESTER declared `PR: <url>` → **INVOKE** `pr-impact-analysis` skill (Dev Artifacts Check) first
- Generate test scenarios/checklist TABLE covering: Happy Path, Negative, Validation, Boundary, Edge Cases, State Transitions, Role-based, Accessibility, Compatibility, Data Integrity, Integration, Exploratory
- Save `test-plan/checklist.md`
- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 2a: SCENARIOS READY
→ Type APPROVED to generate test cases
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 2a --ticket [ticket-id]`
→ If passed: `ak gate 2a approved --ticket [ticket-id]` → Phase 2b
→ If blocked: follow gate-review skill response protocol

#### Phase 2b — Generate Test Cases

**INVOKE:** `generate-testcase` skill (Phase 2b)

- **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
- Generate detailed test cases TABLE from Phase 2a checklist: `TC_ID | Scenario | Preconditions | Test Steps | Test Data | Expected Result`
- TC_ID format: `TC_[Module]_[NNN]` (e.g. `TC_Login_001`)
- Expected result ONLY from ticket/spec — never from PR/dev description
- Save `test-plan/test-cases/`
- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 2b: TEST CASES READY
→ Type APPROVED to proceed to review
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 2b --ticket [ticket-id]`
→ If passed: `ak gate 2b approved --ticket [ticket-id]` → Phase 2c
→ If blocked: follow gate-review skill response protocol

#### Phase 2c — Review & Optimize

**INVOKE:** `generate-testcase` skill (Phase 2c)

- **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
- Self-review: check duplicates, problematic TCs (vague steps, unmeasurable expected result), missing TCs, coverage gaps, accessibility/compatibility coverage
- Output `test-plan/review-report.md` with action items
- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 2c: REVIEW COMPLETE
→ Type APPROVED to finalize and generate scripts
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 2c --ticket [ticket-id]`
→ If passed: `ak gate 2c approved --ticket [ticket-id]` → Phase 2d
→ If blocked: follow gate-review skill response protocol

#### Phase 2d — Coverage Check & Playwright Scripts

**INVOKE:** `coverage-check` skill

- **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
- Apply all action items from Phase 2c
- Generate coverage matrix (requirement → TC IDs)
- Export final test case set to `test-plan/test-cases/final-testcases.md`
- **INVOKE** `automation-testing` skill → generate Playwright scripts to `test-plan/test-scripts/`
- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 2: TEST PLAN READY
Test cases: [N] total ([N] manual / [N] automation)
Coverage: [N]% requirements covered
Scripts: [N] Playwright specs generated
→ Type APPROVED to proceed to Gate 3 (execution)
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 2d --ticket [ticket-id]`
→ If passed: `ak gate 2 approved --ticket [ticket-id]` → Gate 3
→ If blocked: follow gate-review skill response protocol

> **Telemetry:** Run `ak gate 2 approved --ticket [ticket-id]` after gate-review verify passes (see When APPROVED received block above). Run as-is — do NOT append shell redirects.

---

### GATE 3 — Thực Thi & Evidence

Only runs after Gate 2 APPROVED.

**Step 3.0 — Pre-flight (bắt buộc)**

Chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.

**Step 3.1 — Dev Artifacts Check (Gate 3 entry)**

**INVOKE:** `pr-impact-analysis` skill — check for new commits since Gate 2. If delta found → propose TC additions → TESTER approves delta only before proceeding.

**Step 3.2 — Execute Playwright**

```bash
BASE_URL=<url> npx playwright test --headed
```

**Step 3.3 — Organize Evidence**

**INVOKE:** `evidence-aggregation` skill

- Parse `test-results/results.json`
- Create `evidence/TC_[ID]-[scenario]/` with screenshots + traces
- Generate `result.md` per TC
- Auto-draft `bugs/BUG-NNN-*.md` for failed TCs

**Re-test loop** — when TESTER types `RETEST: [TC_ID]`:

**INVOKE:** `retest-orchestration` skill
- Re-run Dev Artifacts Check (detect new commits in dev fix)
- Re-execute: `npx playwright test --grep "TC_ID_pattern" --headed`
- Update evidence (create `run-N/` subfolder — never delete prior evidence)
- Update bug status (RESOLVED / Still OPEN)

**INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick) — summarize execution results + bug list
Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 3: EXECUTION COMPLETE
Passed: [N] | Failed: [N] | Blocked: [N]
Bugs: [N Critical] [N High] [N Medium] [N Low]
→ Type APPROVED when all critical/high bugs resolved
→ Type RETEST: [TC_ID] to re-execute
→ Type PR: [url] to declare new dev PRs
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 3 --ticket [ticket-id]`
→ If passed: `ak gate 3 approved --ticket [ticket-id]` → Gate 4
→ If blocked: follow gate-review skill response protocol

> **Telemetry:** Run `ak gate 3 start --ticket [ticket-id]` when starting this gate. Run as-is — do NOT append shell redirects.

---

### GATE 4 — Báo Cáo & Sign-off

Only runs after Gate 3 APPROVED.

**INVOKE:** `generate-test-report` skill

0. **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
1. Aggregate results from `evidence/*/result.md`
2. Summarize bugs from `bugs/BUG-*.md` by severity
3. Verify acceptance criteria coverage from Gate 1
4. Determine Go / No-Go: 0 unresolved Critical = Go
5. Write `test-plan/test-report.md`

- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick) — summarize test report + go/no-go decision
- Display gate pause message from `gate-review` skill. Also accepts `NO-GO: [reason]` (bypasses review check).

```
⏸️ GATE 4: TEST REPORT READY
Decision: [GO / NO-GO]
Passed: [N/total] | Bugs unresolved: [N]
Coverage: [N]% acceptance criteria
→ Type APPROVED to sign off
→ Type NO-GO: [reason] to reject release
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 4 --ticket [ticket-id]`
→ If passed: `ak gate 4 approved --ticket [ticket-id]` → sign off complete
→ If blocked: follow gate-review skill response protocol
→ Quyết định GO / Conditional go → `QA ✅` trong `AK-Docs/00.Project-Overview/Function-List.md` (theo `custom/rules/function-list-status.md`)

**When NO-GO: [reason] received (no review check needed):** reject release per reason. Giữ `QA 🔵` trong Function List.

> **Telemetry:** Run `ak gate 4 start --ticket [ticket-id]` when starting this gate. Run as-is — do NOT append shell redirects.
> Run `ak gate 4 approved --ticket [ticket-id]` after gate-review verify passes (see When APPROVED received block above). Run as-is — do NOT append shell redirects.

---

## [EXECUTE] Executing Flow

> **For:** `execute`
> **Entry points:** `ak execute TICKET-ID` · `ak execute ./path/to/testcases.md` · `ak execute` (manual)
> **Interaction Rules:** Ask ONE clarifying question at a time — wait for TESTER reply before proceeding.

### GATE 1 — Pre-flight & Work Plan (auto-start)

**INVOKE:** `execute-flow` skill (from `.claude/skills/execute-flow/SKILL.md`)

**Đồng bộ Source & Docs (bắt buộc, chạy trước mọi pre-flight check khác):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.

Pre-flight checks (stop and report if any fail):
0. **MCP Playwright is configured** — check `~/.claude/settings.json` (global user-level) for a `playwright` key in `mcpServers`. This is global — set once, works across all repos.
   - If missing: ask TESTER "MCP Playwright chưa cấu hình. Tự động cài vào global settings (~/.claude/settings.json)? [Y/n]"
   - If Y: read and update `~/.claude/settings.json` by merging the playwright entry into `mcpServers`, then instruct TESTER to **restart Claude Code** before retrying. Stop here.
   - If n: show manual install instructions (add `playwright` to `mcpServers` in `~/.claude/settings.json`). Stop here.
1. TC file is parseable — Section 3 has at least one TC row
2. `AK-Docs/03.Testing/` subfolders exist (`04.Evidence/`, `05.Scripts/`, `02.Reports/`, `06.Bugs/` — auto-create if missing)
3. `BASE_URL` env var is set
4. `AK-Docs/03.Testing/05.Scripts/{repo}/playwright.config.ts` exists (or auto-scaffold the Playwright project inside AK-Docs — package.json, node_modules gitignored — see `execute-flow` SKILL.md "Scaffold Playwright Project")
5. `.gitignore` (repo root containing AK-Docs) ignores `03.Testing/04.Evidence/` (binary evidence, never committed even though it lives inside AK-Docs) and `03.Testing/05.Scripts/**/{node_modules,test-results,playwright-report,blob-report}/` — auto-append if missing

Then display work plan:

- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 1: EXECUTE FLOW READY
TC file: [path](path)
Repo: [repo]
Screen: [ScreenID] — [Screen Name]
BASE_URL: [url]
→ Type APPROVED to sync scripts (Gate 2)
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 1 --ticket [ticket-id]`
→ If passed: `ak gate 1 approved --ticket [ticket-id]` → Gate 2
→ If blocked: follow gate-review skill response protocol
→ Cập nhật dòng chức năng của TC file (`{featureDir}` / functionId) trong `AK-Docs/00.Project-Overview/Function-List.md`: `QA 🔵` (theo `custom/rules/function-list-status.md`)

> **Telemetry:** Run `ak gate 1 start --ticket [ticket-id]` when starting. Run `ak gate 1 approved --ticket [ticket-id]` when APPROVED.

---

### GATE 2 — Script Sync

Only runs after Gate 1 APPROVED.

**INVOKE:** `script-sync` skill (from `.claude/skills/script-sync/SKILL.md`)

**Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.

Hash-based TC↔script sync — for each TC in the file:
- **New TC** (no matching `@tc-hash` in spec): generate Playwright test using MCP (`browser_navigate` → `browser_snapshot` → `browser_generate_locator`). Never fabricate selectors.
- **Changed TC** (hash mismatch): update the existing test block only.
- **Unchanged TC** (hash matches): skip — do not touch.
- **Manual/Blocked TC**: mark `⏭️ Untest` / `⏳ Pending` — no script generated.

Output: `AK-Docs/03.Testing/05.Scripts/{repo}/{featureDir}/{ScreenID}.spec.ts` (1 file per screen, all TCs inside). Every TC Step that changes UI must call `captureStepEvidence()` from `Shared/evidence-helper.ts` (waits for loading to finish, opens popups/modals via click before capturing, scrolls to the confirm area, red-outline highlights the item to confirm) and every assertion must check the actual Expected Result content — not just element presence. See `script-sync` SKILL.md "Assertion Rules" / "Evidence Capture per Step".

- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 2: SCRIPT SYNC COMPLETE
✅ New: [N] | 🔄 Updated: [N] | ⏭️ Skipped: [N] | ⚠️ Manual: [N]
→ Type APPROVED to execute (Gate 3)
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 2 --ticket [ticket-id]`
→ If passed: `ak gate 2 approved --ticket [ticket-id]` → Gate 3
→ If blocked: follow gate-review skill response protocol

---

### GATE 3 — Execute & Evidence

Only runs after Gate 2 APPROVED.

**Step 3.0 — Pre-flight (bắt buộc)**

Chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.

**Step 3.1 — Determine run number**

Check both `AK-Docs/03.Testing/04.Evidence/{repo}/{featureDir}/` and `AK-Docs/03.Testing/02.Reports/{repo}/{featureDir}/` — next run is `run-{N+1}` where N is the highest run number found in either (evidence is gitignored and can disappear; reports are committed).

**One run number per `npx playwright test` command.** Playwright deletes its whole `outputDir` at the start of every command, and a second command pointed at the same `run-{N}` overwrites that run's `results.json` and `html-report/`. Re-running even a single TC uses a new run number; several spec files for one run go into a single command. See `execute-flow` SKILL.md Gate 3 Bước 1.

**Step 3.2 — Execute Playwright** (script and evidence both live inside AK-Docs; evidence stays out of Git via `.gitignore`, not via a separate working dir):

```bash
cd AK-Docs/03.Testing/05.Scripts
EVIDENCE_DIR="$(pwd)/../04.Evidence/{repo}/{featureDir}/run-{N}" \
BASE_URL=<url> \
npx playwright test --config={repo}/playwright.config.ts {repo}/{featureDir}/{ScreenID}.spec.ts
```

**Step 3.3 — Organize evidence + report:**
- Evidence (already written directly to `AK-Docs/03.Testing/04.Evidence/{repo}/{featureDir}/run-{N}/{TC_ID}-{scenario}/`, gitignored): `step-NN-{desc}.png` per Step, `trace.zip`. Playwright's own failure artifacts land in `run-{N}/_pw-artifacts/` — merge the last attempt's files into the `{TC_ID}-{scenario}/` folder and delete `_pw-artifacts/`, since the next command wipes it.
- Report (`AK-Docs/03.Testing/02.Reports/{repo}/{featureDir}/run-{N}/{TC_ID}-{scenario}/result.md`) — text only, links back to the `04.Evidence/` path
- Before recording PASS/FAIL, re-check that the assertion actually matches the TC's Expected Result content (not just "did not throw") — see `execute-flow` SKILL.md "DOM Verification Rules"
- Auto-draft `AK-Docs/03.Testing/06.Bugs/{repo}/{featureDir}/run-{N}/BUG-NNN-{slug}.md` for failed TCs

**Step 3.4 — Update TC file** R1/R2 columns:
- `✅ Pass` · `❌ Fail` · `⏭️ Untest` · `⏳ Pending`

**Re-test loop** — when TESTER types `RETEST: [TC_ID]`:
- Re-run Dev Artifacts Check if PR was declared
- Re-execute only the specified TCs
- Create new `run-{N}/` — never delete prior runs
- Update R1/R2 columns

**INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 3: EXECUTION COMPLETE
Run: run-{N} | Passed: [N] | Failed: [N] | Untest: [N] | Pending: [N]
→ Type APPROVED when all Critical/High bugs resolved
→ Type RETEST: [TC_ID] to re-execute specific TCs
→ Type PR: [url] to declare a dev fix PR
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 3 --ticket [ticket-id]`
→ If passed: `ak gate 3 approved --ticket [ticket-id]` → Gate 4
→ If blocked: follow gate-review skill response protocol

> **Telemetry:** Run `ak gate 3 start --ticket [ticket-id]` when starting. Run as-is — do NOT append shell redirects.

---

### GATE 4 — Report & Bug Logging

Only runs after Gate 3 APPROVED.

**Step 4.0 — Pre-flight (bắt buộc)**

Chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.

**Step 4.1** — Generate `AK-Docs/03.Testing/02.Reports/{repo}/{featureDir}/run-{N}/testreport.md`:
- Per-module rows with Pass/Fail/Untest/Pending counts, R1/R2 columns, % completion
- Go/No-Go: 0 unresolved Critical = Go

**Step 4.2** — Bug logging: for each `❌ Fail` TC, ask TESTER ONE at a time:
> "BUG-NNN — [TC_ID]: [title]. Log to Jira? (Y/N/edit)"

Wait for reply before moving to next bug.

- **INVOKE** `gate-review` skill (generate mode) — pause the gate for review of the output (no checklist to tick)
- Display gate pause message from `gate-review` skill — wait for **APPROVED**

```
⏸️ GATE 4: REPORT READY
Decision: [GO / NO-GO]
Bugs logged: [N] | Skipped: [N]
→ Review: [AK-Docs/03.Testing/02.Reports/{repo}/{featureDir}/run-{N}/testreport.md](AK-Docs/03.Testing/02.Reports/{repo}/{featureDir}/run-{N}/testreport.md)
→ Type APPROVED to sign off
```

**When APPROVED received:**
→ **INVOKE** `gate-review` skill (verify mode) — `ak review check --gate 4 --ticket [ticket-id]`
→ If passed: `ak gate 4 approved --ticket [ticket-id]` → sign off complete
→ If blocked: follow gate-review skill response protocol
→ Quyết định GO / Conditional go → `QA ✅` trong `AK-Docs/00.Project-Overview/Function-List.md`; NO-GO → giữ `QA 🔵` (theo `custom/rules/function-list-status.md`)

> **Telemetry:** Run `ak gate 4 start --ticket [ticket-id]` when starting. Run `ak gate 4 approved --ticket [ticket-id]` when APPROVED.
## gen-doc Task Type — 2-Gate Flow

> This section applies **only** when `taskType === "gen-doc"`. All other task types use the 5-gate flow above.

> `gen-doc` reuses the **same** `AK-Docs/04.Coding/` folders as the standard Dev workflow above (see `custom/rules/project-conventions.md`) — it just only uses Gate 1–2 of them, not a separate section.

### GATE 1 — AI Analyze & Plan Document (auto-start)

**INVOKE:** `read-study-requirement` skill

1. Load ticket context + read source code / files to understand scope
2. **Xác định `functionId` và thư mục đầu ra (BẮT BUỘC)** — theo đúng quy tắc "functionId & ticketId" trong `custom/rules/project-conventions.md`: kiểm tra `functionId`/`screenId` trong `.aiflow/context/current.json` → suy từ ticketId/input → nếu không suy ra được (task ad-hoc, không gắn với chức năng cụ thể), hỏi trực tiếp người yêu cầu (có thể dùng một mã chủ đề ngắn, ví dụ `AD-HOC` hoặc tên báo cáo). KHÔNG ĐƯỢC GHI FILE khi chưa có `functionId`.
3. **Đảm bảo đang làm việc trên branch riêng của task (AK-Docs):** kiểm tra `AK-Docs` hiện đang ở branch nào (`git -C AK-Docs branch --show-current`). Nếu chưa ở `feature/[ticketId]` (hoặc `feature/[ticketId]-<mô-tả>` của đúng task này) → hỏi: "Chưa có branch riêng cho task này trong AK-Docs. Tạo branch `feature/[ticketId]` từ `main` — đồng ý không?" → đồng ý thì chạy `ak docs branch [ticketId] --yes`; từ chối thì tiếp tục trên nhánh hiện tại (người dùng tự quản lý branch). Nếu branch của ticket đã tồn tại → hỏi người dùng chọn: dùng lại (`ak docs branch [ticketId] --reuse --yes`) hay tạo branch mới có hậu tố mô tả (`ak docs branch [ticketId] <mô-tả> --yes`). Đã đúng branch rồi thì bỏ qua. ❗ KHÔNG chèn functionId vào tên branch. ❌ Không tự thêm `--yes` khi chưa thấy người dùng xác nhận rõ ràng.
4. Understand the document goal, target audience, and output format
5. If unclear → ask ONE question at a time, wait for reply (theo [Quy tắc đặt câu hỏi](#quy-tắc-đặt-câu-hỏi-áp-dụng-mọi-gate-mọi-workflow-bên-dưới))
6. Output `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md` with:
   - Document scope and target audience
   - Content outline (sections to cover)
   - Source references (files, features, flows to analyze)
   - Output format: Markdown or Excel (note template path if applicable)
   - Effort estimate
7. Display "GATE 1: Document plan ready" → wait for **APPROVED**

> **Telemetry:** Run `ak gate 1 start --ticket [ticket-id]` when starting.
> Run `ak gate 1 approved --ticket [ticket-id]` immediately when APPROVED is received.

---

### GATE 2 — Generate Document + Auto Review (runs immediately after APPROVED)

**DO NOT create `plan.md`. DO NOT run TDD. Proceed directly to document generation.**

1. Re-read `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md` (the approved outline)
2. Read source code, trace data flows, analyze features as needed
3. Generate the output document:
   - **Markdown:** Save to `AK-Docs/04.Coding/02.Plans/[functionId]/[ticketId].md` (or the custom path/format noted in the requirement doc — e.g. Excel; still write a short pointer + summary into this file so the AK-Docs history stays complete)
4. Self-review: verify content completeness against the approved requirement outline
5. Create `AK-Docs/04.Coding/02.Plans/[functionId]/[ticketId]-summary.md` with a brief summary of what was generated
5.5. **Retrospect + propose memory drafts:** synthesize anything genuinely new learned while producing this document (architecture fact, business rule, decision) and create a **local draft** for each (no approval needed yet — `_pending/` is local-only, see `docs/common/Memory-Architecture-v1.0.md`):
   ```
   ak memory draft --category 00.Shared/architecture --function-id <[functionId] | global> \
     --slug <short-kebab-slug> --content "<≤150 words, 1 fact>" \
     --tags <tag1,tag2> --workflows gen-doc --source "[ticket-id] / Gate 2"
   ```
   Skip if nothing new was learned. If `ak memory draft` reports a conflict, don't duplicate — mention the existing one instead.

   **Pick the scope by content, not by where it came up:** still true when working on another function of this project (a convention, a general technical trap, a system-wide business rule) → `--function-id global`; true only for this function → `--function-id [functionId]`. Never store task progress (what is done, what is left) as a memory — progress belongs in the task's own documents.

   **Memory based on specific files** (code, UC Spec, System Requirement) → add `--refs <paths from the workspace root>`, e.g. `--refs my-app/src/auth/JwtFilter.java`. `ak memory health` flags the memory as outdated when those files change or disappear.

   **Tag the topic, not the value:** tag what the memory is about (`date-format`, `refund-limit`), never the concrete value (`yymm`, `ddmmyy`, `5000-yen`). Then when the user changes their mind, the old and new memory share a tag and `ak memory draft` catches the contradiction.

   **When the user changes their mind:** if the new draft contradicts an existing memory (in `<PROJECT_MEMORY>`, or in the "shared tags" list `ak memory draft` prints), confirm with the user, then draft with `--supersedes <old-id>` — the old one drops out of recall on this machine right away and moves to `_deprecated/` in the same MR on submit.

   **Report the scope and ask the user (required when any draft was created):** list each draft with where it applies, then ask once:
   ```
   Memory drafts created (local, not shared with the team yet):
   1. mem-F003-<slug> — <one-line summary> — applies to [functionId] only
   2. mem-global-<slug> — <one-line summary> — applies project-wide
   Which should apply project-wide (every function)? Reply with the numbers (e.g. `1`), or `keep`.
   ```
   For each draft the user picks that is scoped to [functionId] → `ak memory rescope <draft path> --global` (path from the `ak memory draft` output). To narrow a global draft → `ak memory rescope <draft path> --function-id [functionId]`. Wait for the answer before step 6.
6. **Submit AK-Docs lên remote qua Merge Request:**
   - Soạn title + description cho MR (tóm tắt tài liệu vừa tạo, link ticket gốc), hiển thị cho người dùng xem trước.
   - Hỏi: "Nội dung commit/MR như trên — đồng ý submit AK-Docs không?" → đồng ý thì chạy `ak docs submit --title "..." --description "..." --yes`; từ chối thì dừng, để người dùng tự commit/tạo MR khi sẵn sàng.
   - Thông báo: MR đã mở, chờ **PM review & merge vào `main`** — đây là bước duyệt cuối cùng, không phải tự merge.
   - ❌ Không tự thêm `--yes` khi chưa thấy người dùng gõ xác nhận rõ ràng trong hội thoại.
7. Run: `ak gate 2 approved --ticket [ticket-id]` to close the task
8. Display: `GATE 2 DONE: Document generated at [path]`

**Do NOT wait for extra approval before generating the document or opening the MR — only the explicit branch/MR confirmations above gate this; run the gate 2 approved command immediately after.**

---

## ingest-data Task Type — 2-Gate Flow

> This section applies **only** when `taskType === "ingest-data"`. All other task types use the flows above.
> **For:** PM · BrSE · Comtor ingesting customer communication into `AK-Docs/01.QnA/` — see `docs/internal/PM Workflow_v1.0.md` Flow B for the full design background.
> **Input formats accepted:** Backlog ticket/comment link, Backlog Document link, Backlog Wiki link, Jira ticket/comment link, SharePoint link (not yet connected — see Gate 1 Step 2), or plain pasted text.

**INVOKE:** `ingest-data` skill (from `.claude/skills/ingest-data/SKILL.md`) for both gates — it has the full classification rules, draft templates, and per-file format. This section only covers the gate mechanics.

### GATE 1 — Fetch, Classify, Draft (auto-start)

0. **Pre-flight (bắt buộc):** chạy [Pre-flight — Đồng bộ Source & Docs](#pre-flight-bắt-buộc--đồng-bộ-source--docs-đầu-mỗi-gate) ở đầu file. Lỗi → hiển thị ⚠️ cảnh báo, không dừng gate.
1. Read `.aiflow/context/current.json` — if the primary input is a URL (Backlog/Jira/SharePoint), it's already there as `taskId`/description; if the input was plain pasted text via `ak use --manual`, it's in `description`.
2. **Resolve the source** (see `ingest-data` skill for full detail):
   - Backlog/Jira ticket, comment, Document, or Wiki URL → run `ak fetch-links "<url>"`, parse the JSON.
   - SharePoint URL → `ak fetch-links` returns `{ sourceType: "unsupported" }` (no connector yet — Microsoft Graph API/OAuth not built). Tell the user to paste the comment/document text directly instead of the link.
   - Plain text → use as-is, no fetch needed.
3. **Classify** into `QnA-Log.md` / `Meetings-Log.md` / `Confirmations-Log.md` per the `ingest-data` skill's rules. If ambiguous (especially Confirmations — the rule for "official confirm" vs "regular feedback" is not yet finalized, see PM Workflow doc Vấn đề còn mở #1) — **ask the user**, do not guess silently.
4. Draft the entry using the exact template for the target log file (skill has all 3 templates) — include the trace fields (`Nguồn`, `functionId`, `Người tổng hợp`, `Người approve tại nguồn`).
5. Display the draft in full (not summarized) plus this footer:
   ```
   ⏸️ INGEST DRAFT READY — cần bạn review trước khi mở MR

   Nguồn: [mô tả ngắn](url hoặc "pasted text")
   Ghi vào: AK-Docs/01.QnA/[QnA-Log.md | Meetings-Log.md | Confirmations-Log.md]

   → Xem draft đầy đủ ở trên
   → Gõ APPROVED để tạo branch + MR (Gate 2)
   → Hoặc yêu cầu sửa trực tiếp draft, AI sẽ cập nhật lại rồi hiển thị lại
   ```
6. Loop on edits until the user types **APPROVED** — do not proceed to Gate 2 before that.

> **Telemetry:** Run `ak gate 1 start --ticket [ticket-id]` when starting. Run `ak gate 1 approved --ticket [ticket-id]` when APPROVED is received.

### GATE 2 — Branch + Merge Request (runs immediately after APPROVED)

1. Xác định `functionId`: tag đọc được từ Backlog Document (nếu có) → suy từ input → không suy được thì dùng `general` (theo đúng quy ước `custom/rules/project-conventions.md`, tương tự gen-doc dùng `AD-HOC`).
2. Kiểm tra `AK-Docs` hiện đang ở branch nào (`git -C AK-Docs branch --show-current`). Nếu chưa ở `feature/[ticketId]` (hoặc `feature/[ticketId]-<mô-tả>` của đúng task này) → hỏi: "Chưa có branch riêng cho task này. Tạo branch `feature/[ticketId]` từ `main` — đồng ý không?" → đồng ý thì chạy `ak docs branch [ticketId] --yes`; từ chối thì tiếp tục trên nhánh hiện tại. Nếu branch của ticket đã tồn tại → hỏi chọn: dùng lại (`--reuse`) hay tạo branch mới có hậu tố mô tả (`ak docs branch [ticketId] <mô-tả> --yes`). ❗ KHÔNG chèn functionId vào tên branch. ❌ Không tự thêm `--yes` khi chưa thấy xác nhận rõ ràng.
3. Ghi/append entry đã approve vào đúng file log (tạo file + header template nếu chưa tồn tại).
4. Soạn title + description cho MR (tóm tắt entry vừa ghi, link nguồn gốc), hiển thị cho người dùng xem trước. Hỏi: "Nội dung commit/MR như trên — đồng ý submit AK-Docs không?" → đồng ý thì chạy `ak docs submit --title "..." --description "..." --yes`; từ chối thì dừng, để người dùng tự commit khi sẵn sàng. ❌ Không tự thêm `--yes` khi chưa thấy xác nhận rõ ràng.
5. Thông báo: MR đã mở, chờ **PM review & merge vào `main`** — đây là bước duyệt cuối cùng, không phải tự merge.
6. Run: `ak gate 2 approved --ticket [ticket-id]` to close the task.
7. Display: `GATE 2 DONE: Entry ghi vào AK-Docs/01.QnA/[file] — MR: [url hoặc "tạo thủ công"]`

> **Telemetry:** Run `ak gate 2 start --ticket [ticket-id]` when starting. Run `ak gate 2 approved --ticket [ticket-id]` when Gate 2 completes.

### GATE 3 — Sinh Task & Tạo Ticket (auto, chạy ngay sau Gate 2 xong)

> Implements "Vấn đề 5" trong `docs/internal/PM Workflow_v1.0.md`. **Không chờ APPROVED để bắt đầu** — chạy tự động ngay sau Gate 2 Bước 7, không cần lệnh riêng và không cần chờ PM merge MR (merge là việc độc lập của PM). `INVOKE`: `ingest-data` skill § 5 cho toàn bộ logic phân tích/đề xuất — mục này chỉ nêu gate mechanics.

1. Đọc lại entry vừa ghi + điều tra source/docs liên quan (skill § 5.1).
2. Quyết định content này có cần task không (skill § 5.2 — với entry từ `Confirmations-Log`, chạy qua checklist tối thiểu thay vì chỉ dựa Action items viết sẵn). Nếu KHÔNG cần task → hiển thị thông báo tương ứng, chạy `ak gate 3 skip --ticket [ticket-id] --reason "<1 câu lý do>"` (không chạy `ak gate 3 start`), và **kết thúc luôn, không có Gate 3 Display**. `skip` vẫn đóng gate đúng cách (advance `currentGate` giống `approved`) — task hiện đúng "done" trên dashboard, không treo ở trạng thái "sẵn sàng chạy Gate 3" mãi.
3. Nếu CẦN task → chạy `ak gate 3 start --ticket [ticket-id]`, rồi đề xuất danh sách task (skill § 5.3), cho PM sửa/thêm/xoá (skill § 5.4), lặp tới khi PM hài lòng.
4. Điểm dừng xác nhận trước khi tạo ticket (skill § 5.5) — ❌ không tự thêm `--yes`, phải có xác nhận rõ ràng trong hội thoại.
5. Xác định project đích trên Backlog/Jira (skill § 5.6, dùng `ak backlog-projects`/`ak jira-projects` + `ak backlog-set-default-project`/`ak jira-set-default-project`).
6. Nếu danh sách có ≥ 2 task, hỏi PM có muốn gộp dưới 1 ticket cha không — tạo mới / dùng sẵn / không cần (skill § 5.6b).
7. Tạo ticket bằng `ak tasks create-tickets <file>.json --json` (skill § 5.7), kèm `parentTicket` nếu Bước 6 xác định có. Nếu thiếu WRITE credentials, hỏi PM nhập ngay trong chat rồi `ak credentials set <field> "<value>"` và thử lại đúng 1 lần. Nếu lỗi `parent-not-found`/`parent-create-failed`, hiển thị nguyên lỗi và hỏi PM muốn thử ticket cha khác, bỏ qua ticket cha, hay dừng lại.
8. Ghi ngược link ticket vào entry gốc + hiển thị tổng kết (skill § 5.8).
8. Run: `ak gate 3 approved --ticket [ticket-id]` để đóng task.

> **Telemetry:** Run `ak gate 3 start --ticket [ticket-id]` chỉ khi Bước 2 kết luận CẦN task. Run `ak gate 3 approved --ticket [ticket-id]` khi Gate 3 hoàn tất, hoặc `ak gate 3 skip --ticket [ticket-id] --reason "..."` khi Bước 2 kết luận KHÔNG cần task.
