## MANDATORY: Strict ML Gate Workflow

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

You have superpowers. When a ticket context exists in `.aiflow/context/current.json`:
- **Consult the "AI Skill Registry"** above to find each skill's `SKILL.md`.
- **AUTO-START Gate 1 immediately** — do NOT wait for the developer to ask.
- **PROJECT CONVENTIONS:** Before writing any output file, read `custom/rules/project-conventions.md`
  and `custom/rules/ml-conventions.md`. These override upstream skill defaults.

---

### Asking Questions (applies to every Gate below)

> Every "ask ONE question at a time" step below follows these four rules.

1. **Never re-ask what was answered or is derivable.** Keep a running *decisions + implied consequences* list: each answer carries its direct consequences, and those consequences are part of the answer, not new questions ("no retry on failure" implies no retry count, no retry interval, no retry on the other channels in the same flow). Match on intent, not wording (`retry` = `re-send` = `try again`). Unsure whether an existing answer covers a case → ask **one** yes/no confirmation, once, instead of a fresh question.
2. **Never ask a blocked question.** A question whose answer is only decidable after another unanswered one → record it as `Blocked-by <parent>` and do not ask this round; re-check it once the parent is answered (already covered → close it, don't ask). No splitting or rewording to get around the lock.
3. **Write it so a non-engineer can answer:** Context (1–3 sentences) → why it matters (real consequence) → one question, one point → options with the consequence of each, plus "Other". Expand every abbreviation on first use. A complex question (2+ conditions, several flows, or anything about ordering/priority/timing) carries a worked example with real numbers and the outcome under each option.
4. **Question count is not a quality metric.** An answer that changes nothing in the output becomes an Assumption, not a question. If DEV asks back "is this question necessary?", withdraw it when it was derivable and re-screen the remaining questions before continuing.

---

### GATE 1 — Problem Framing & Data Understanding (auto-start)

**INVOKE:** `frame-ml-problem` skill, then `explore-data` skill

AI actively reads the ticket and dataset to frame the problem and assess the data:
1. Read `.aiflow/context/current.json` — ticket info
2. **Pre-flight: sync with remote** — run `git status --porcelain`; if working tree is clean, run `git pull --ff-only` to pull the latest source from remote. Skip the pull (with a `⚠️` notice to DEV) if there are uncommitted changes, the branch has diverged, or no remote tracking branch exists.
3. **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 context → suy từ ticketId/input → nếu không có, hỏi DEV xác nhận trực tiếp. KHÔNG ĐƯỢC GHI FILE khi chưa có `functionId`.
4. **Đảm bảo đang làm việc trên branch riêng của ticket (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 ticket này) → 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?" → đồ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 (DEV tự quản lý branch). Nếu branch của ticket đã tồn tại → hỏi DEV 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 DEV xác nhận rõ ràng.
5. Define the prediction target, evaluation metric, baseline, success threshold, and constraints.
6. Run EDA; assess data quality and **leakage** (target leakage, train/test contamination, temporal leakage).
7. If anything is unclear — ask ONE question at a time, wait for reply (see [Asking Questions](#asking-questions-applies-to-every-gate-below)).
8. Output `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md` with:
   - Problem statement, prediction target, and evaluation metric (with justification)
   - Baseline definition and success threshold
   - Data report (shape, quality, missing values, distributions)
   - Leakage assessment (all three types checked)
   - Constraints and effort estimate
9. Display "GATE 1: ML problem doc ready" → wait for **APPROVED**

> **Tip:** If auto-start doesn't trigger, the developer can start this gate by typing: **"start"**, **"Gate 1"** or **"Analyze ticket"**.

DO NOT just check format — **understand the data 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]` immediately when APPROVED is received. Run as-is — do NOT append shell redirects.

---

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

**INVOKE:** `design-experiment` skill, then `superpowers:writing-plans`

- Define the validation strategy (CV scheme/splits, leakage prevention), candidate approaches and feature sets, ablation plan, and experiment-tracking setup.
- Output `AK-Docs/04.Coding/02.Plans/[functionId]/[ticketId].md` with the detailed experiment plan.
- Display: "GATE 2 PAUSED: type APPROVED to start experiments".
- NO EXPERIMENTS OR TRAINING until "APPROVED" is received.

> **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]` immediately when APPROVED is received. Run as-is — do NOT append shell redirects.

---

### GATE 3 — Implement, Train & Iterate (after APPROVED)

Only runs after Gate 2 has been APPROVED.

**INVOKE:** `train-model` skill
- **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.
- For algorithm-optimization tickets EXTRA: `improve-algorithm` skill

**Eval-harness-first rule:** Write the metric/eval harness and establish a reproducible baseline BEFORE iterating on the model. Confirm the baseline runs and is logged — then proceed with tracked experiments.

- Fixed seeds, pinned environment, logged configs — every run.
- Follow the ablation plan: one change at a time, each tracked.

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

---

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

**INVOKE:** `evaluate-model` skill

Mandatory order:
1. `superpowers:verification-before-completion` — eval runs must reproduce before any success claim
2. `evaluate-model` skill — held-out metrics vs baseline and threshold, error analysis, overfitting/leakage/drift checks
3. `impact-analysis` skill — assess data pipeline and downstream blast radius
4. Create `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md` with the eval report and a model card draft (own section in the same file) — developer reviews manually before approving

Then: "GATE 4 PAUSED: type APPROVED or BUG: [description]"
- Coding or pipeline bug → fix → repeat Gate 4.
- Wrong framing, wrong metric, or wrong data → 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]` immediately when APPROVED is received. Run as-is — do NOT append shell redirects.

---

### GATE 5 — Package, Deploy & Handoff (after APPROVED)

Only runs after Gate 4 has been APPROVED.

**INVOKE:** `deploy-model` skill, then `superpowers:requesting-code-review`

- Version the artifact (model, training data version, code commit, config) in the registry.
- Package the full inference pipeline so serving matches training exactly.
- Define the monitoring plan (input drift, prediction distribution, latency, retraining trigger).
- Finalize the model card (intended use, data, metrics, limitations, owner) in `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md`.
- **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 ML problem, experiment plan, eval report/model card), 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?" → đồng ý thì chạy `ak docs submit --title "..." --description "..." --yes`; từ chối thì 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.
- Guide on creating a Pull Request (source code) with the ticket link.

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