## 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.

### 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 **chưa** ở branch `feature/[functionId]/[ticketId]`:
      - Hỏi DEV: "Chưa có branch riêng cho ticket này trong AK-Docs. Tạo branch `feature/[functionId]/[ticketId]` từ `main` — đồng ý không?"
      - DEV đồng ý → chạy `ak docs branch [functionId] [ticketId] --yes`
      - 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)
   3. Nếu **đã** ở đúng branch (ví dụ resume từ session trước, hoặc Gate 2/3/4 tiếp nối Gate 1) → bỏ qua, tiếp tục.

   > ❌ 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
4. If anything is unclear — ask ONE question at a time, wait for reply
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) — write `.aiflow/review/gate-1-[ticket-id].md`
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

> **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) — write `.aiflow/review/gate-2-[ticket-id].md`
- Display gate pause message from `gate-review` skill — CODE WILL NOT BE GENERATED until all items checked and 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
3. Create `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md` — Test Results, Impact Analysis (files changed, affected features, breaking changes) — 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) — write `.aiflow/review/gate-4-[ticket-id].md`
- 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):**
- Coding bug → fix → repeat Gate 4 (re-generate review file)
- 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.
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) — write `.aiflow/review/gate-1-[ticket-id].md`
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

> **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) — write `.aiflow/review/gate-2a-[ticket-id].md`
- 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) — write `.aiflow/review/gate-2b-[ticket-id].md`
- 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) — write `.aiflow/review/gate-2c-[ticket-id].md`
- 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) — write `.aiflow/review/gate-2d-[ticket-id].md`
- 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) — write `.aiflow/review/gate-3-[ticket-id].md` — 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) — write `.aiflow/review/gate-4-[ticket-id].md` — 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

**When NO-GO: [reason] received (no review check needed):** reject release per reason.

> **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) — write `.aiflow/review/gate-1-[ticket-id].md`
- 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

> **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) — write `.aiflow/review/gate-2-[ticket-id].md`
- 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 `AK-Docs/03.Testing/04.Evidence/{repo}/{featureDir}/` — next run is `run-{N+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`
- 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) — write `.aiflow/review/gate-3-[ticket-id].md`
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) — write `.aiflow/review/gate-4-[ticket-id].md`
- 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

> **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/[functionId]/[ticketId]` → hỏi: "Chưa có branch riêng cho task này trong AK-Docs. Tạo branch `feature/[functionId]/[ticketId]` từ `main` — đồng ý không?" → đồng ý thì chạy `ak docs branch [functionId] [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). Đã đúng branch rồi thì bỏ qua. ❌ 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
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] \
     --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.
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/[functionId]/[ticketId]` → hỏi: "Chưa có branch riêng cho task này. Tạo branch `feature/[functionId]/[ticketId]` từ `main` — đồng ý không?" → đồng ý thì chạy `ak docs branch [functionId] [ticketId] --yes`; từ chối thì tiếp tục trên nhánh hiện tại. ❌ 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.
