---
name: create-system-requirement
description: Bridges UC Spec (BA, Gate 4) to Dev — investigates source code and translates the UC into System Requirement (Functional/Non-Functional Requirements, Business Rules → Validation Rules, Exception/Error Handling, Acceptance Tests). Runs once per functionId per UC Spec version, ideally BEFORE the first coding ticket. Gate 1 (`read-study-requirement`) warns (non-blocking) if this is missing or out of sync with the current UC Spec version — this skill is how DEV closes that gap.
keywords: system requirement, uc spec, functionId, trace, acceptance test, exception handling, business rule, matching, version sync
---

# Create System Requirement — Bridge Gate (before Gate 1)

> **Runs once per functionId per UC Spec version — NOT per ticket.**
>
> Principle: System Requirement is the Dev-facing translation of UC Spec (User Requirement). It must trace 1-1 to a specific UC Spec version, cover the full UC (flows, business rules, exceptions, acceptance criteria), and never invent content the UC Spec doesn't support. If anything is unclear, ask until it's Confirmed — do not guess.

---

## Trigger

`create-system-requirement` is its own **task type** — 2 gates, selectable in the "Task type:" prompt of `ak use` (or auto-detected by `aiflow prompt "..."` — see `scripts/detect.js`). It is not invoked inline from within a coding ticket's session; it runs as its own task, tied to the `functionId` (not to a coding ticket).

- **Gate 1** = Steps 0–4 below (resolve UC Spec, [RESYNC only: diff scope — Step 1.5], investigate source code, draft, 1-1 traceability audit, Q&A until every Gap is Confirmed).
- **Gate 2** = Steps 5–7 below (split decision, write output, present for APPROVED).

**Hand-off from coding Gate 1 Pre-flight** (`read-study-requirement`, Step 0) when:
- No `System-Requirement_v*.md` exists yet for this `functionId`, **or**
- The existing one's `UC-Spec-Version` header does not match the UC Spec's current version.

Any of these → coding Gate 1 shows a ⚠️ non-blocking warning and **continues** (it does not cancel). DEV can close the gap at any point — before or after the current ticket — by starting a new task with `ak use`, picking **"📐 Create System Requirement"** at the Task type prompt, and running it through both gates to APPROVED. Approval itself isn't tracked inside the document — the file only lands in `AK-Docs/` (and gets committed/pushed) once DEV has approved it, so its presence there is the approval signal.

---

## Steps

> Steps 0–4 (plus Step 1.5, RESYNC mode only) = **Gate 1** (investigate & draft). Steps 5–7 = **Gate 2** (finalize & approve). Run `aiflow task next` between them like any other gated task.

### Step 0: Pre-flight — Resolve functionId & Versions [Gate 1]

0. `git status --porcelain` → clean tree → `git pull --ff-only`; dirty tree → skip pull, notify DEV (same rule as `read-study-requirement` Step 1.0).
1. Resolve `functionId` from `.aiflow/context/current.json` (or ask DEV once if absent).
2. Locate the current UC Spec: `AK-Docs/02.BA-Specs/04.UC-Specs/[functionId]/UC-Spec_v{N}.md` (highest non-archived version). **Not found → STOP.** Tell DEV the UC Spec must exist and be PM-signed-off before System Requirement can be created — this skill never fabricates a UC.
3. Check `AK-Docs/02.BA-Specs/00.Requirements/[functionId]/System-Requirement_v*.md`:
   - **None exists** → Mode = `CREATE` (go to Step 1).
   - **Exists, `UC-Spec-Version` matches current UC Spec version** → nothing to do — this task is not needed; tell DEV the coding Gate 1 (`read-study-requirement`) can proceed directly.
   - **Exists, `UC-Spec-Version` is older** → Mode = `RESYNC` (go to Step 1; Step 1.5 diffs against the existing file before investigation starts, instead of starting blank).

---

### Step 1: Read UC Spec (full) [Gate 1]

Read all 5 sections of the UC Spec end-to-end — General Info + Main/Alternative/Exception Flows, Screen Description, UI Components, Activity Diagram, Business Rules (BR1 Validation / BR2 Saving / BR3 Authorization, or whatever domains the BA defined). Do not skim — every Functional Requirement, Validation Rule, Exception, and Acceptance Test written later must trace back to something read here.

**If the UC Spec has a Q&A/Decision appendix** (e.g. "Phụ lục C" listing `OQ-01` → `OQ-NN` decisions BA confirmed with the customer/stakeholder, or an equivalent embedded decision log) → **read it in full, not just skim for headers.** This is not optional bookkeeping — every business Decision drafted in Step 3 that traces back to one of these entries **must** cite its `OQ-xx` ID (see Step 3's Classification convention). Skipping this appendix is the single most common way a System Requirement ends up with zero decision traceback despite the source being right there — see `docs/internal/Token Problems.md` §4 (Opus vs Sonnet comparison) for a real example of this gap.

**If the UC Spec references a numbered/enumerated list from elsewhere** (e.g. "23 hạng mục TO-BE ở Phụ lục E", a bug ticket's numbered checklist, a review-session's numbered follow-up items) → note the exact count and list now. Step 3 must produce an explicit crosswalk against every one of these numbers — do not let any of them get silently absorbed into a broader FR/VR without a traceable pointer.

`RESYNC` mode: also read the previous `System-Requirement_v{N-1}.md` in full — it's the diff baseline for Step 1.5.

---

### Step 1.5: RESYNC Diff — Xác Định Phạm Vi Trước Khi Điều Tra [Gate 1, chỉ Mode RESYNC]

> Chuyển từ Step 3 lên đây (bản gốc trước đây diff ở bước draft, tức là *sau* khi đã tốn token điều tra toàn bộ — xem `docs/internal/Token Problems.md` §2.3/§3.3, Vấn đề C). Logic diff không đổi, chỉ đổi thời điểm chạy: **trước Step 2**, để kết quả diff trở thành phạm vi điều tra, không chỉ phạm vi viết.

Diff `UC-Spec_v{N}.md` (đọc ở Step 1) với `UC-Spec_v{N-1}.md` mà `System-Requirement_v{N-1}.md` đang trace tới, theo từng section: Main Flow, Alternative/Exception Flow, mỗi Business Rule. Phân loại mỗi phần thành:
- **Không đổi** — carry forward nguyên trạng FR/VR/ER/AT + `Implementation Reference` tương ứng từ `System-Requirement_v{N-1}.md` sang bản mới, không điều tra lại (Step 2), không viết lại (Step 3).
- **Đổi/mới** — đưa vào phạm vi điều tra của Step 2 và phạm vi draft mới của Step 3.
- **Bị xoá khỏi UC Spec** — đánh dấu remove, ghi lý do vào Change Log (Section 9), không giữ lại item mồ côi.

Không được **âm thầm bỏ** 1 item mà không ghi rõ lý do vào Change Log — dù là carry-forward, đổi, hay xoá.

---

### Step 2: Investigate Source Code [Gate 1]

Same methodology as `read-study-requirement` Step 1 (steps 4–5), reused here:
- Read `CLAUDE.md` for architecture/conventions.
- Find modules/files that implement or would implement this UC's Main Flow (existing feature being extended, or nearest analogous feature for a new one).
- **If GitNexus MCP available:** `gitnexus: query()` / `gitnexus: context()` for the relevant area — same token-saving shortcut as `read-study-requirement`.
- Identify **existing error-handling conventions** (error code format, message structure, exception class hierarchy) — the Exception & Error Handling section (Step 4 below) must reuse these, not invent a new convention.
- Identify **existing data model / API surface** touched by this UC (tables, DTOs, endpoints) — feeds Section 6.1 of the output.
- Identify whether this UC integrates with any system **outside** the app's own UI/DB (third-party API, webhook, message queue, etc.) — the UC Spec won't describe this since it's UI/flow-focused; if found, feeds Section 6.3. If there's none, skip Section 6.3 entirely rather than leaving it as empty boilerplate.

This step exists so System Requirement reflects what the system *can actually do today*, not just what the UC Spec says in the abstract.

#### Token/session cost control (investigate once, not once per rule)

This is the single most expensive step in the whole skill — most of the session budget goes here, not into drafting. Apply `custom/rules/investigation-cost-control.md` (GitNexus-first → `Explore` sub-agent delegation → investigate per module/concern, not per Business Rule → running Investigation Notes table, UC ref → file:line → 1-line finding). Step 3 drafting must read from that table, not trigger a fresh file read per FR/VR/ER item — only re-open a file if the table doesn't already answer the question at hand.

Two ways to spend the resulting savings, not to skip investigation: (a) let a cheaper/faster model draft Sections 1–5 from a *smaller, denser* Investigation Notes table instead of raw exploration noise, or (b) reinvest the savings into the Step 3.5 traceability audit below, which is where the Opus/Sonnet quality gap in practice tends to show up (missed edge cases), not in prose quality.

**Mode RESYNC — điều tra chỉ theo phạm vi diff (xem Vấn đề C, `docs/internal/Token Problems.md` §2.3/§3.3/§4.2):** dùng kết quả Step 1.5 (đã tính trước khi vào Step 2 này) làm **phạm vi điều tra** — chỉ GitNexus/Explore/đọc file cho module liên quan tới phần "Đổi/mới"; phần "Không đổi" giữ nguyên `Implementation Reference` từ `System-Requirement_v{N-1}.md`, không điều tra lại.

⚠️ **Rủi ro cần biết (không phải giải pháp triệt để):** UC Spec không đổi 1 Flow không có nghĩa code phía dưới Flow đó không đổi (Dev có thể đã refactor độc lập từ lần System Requirement trước). Trước khi bỏ qua điều tra 1 phần không nằm trong diff, chạy 1 check rẻ: `git log --since="<ngày System-Requirement_v{N-1} được approve>" -- <đường dẫn các file/module đã liệt kê ở Section 6.1 "System Areas Summary" của v{N-1}>`. Có commit mới chạm module đó → vẫn điều tra lại phần đó dù UC Spec không đổi. Check này **không triệt để 100%** (không bắt được file hoàn toàn mới, ngoài danh sách Section 6.1 đã biết) — nhưng rẻ hơn nhiều so với điều tra lại toàn bộ, và thu hẹp đúng loại rủi ro "RESYNC trở thành nguồn gây stale/lỗi thời" mà không huỷ bỏ mức tiết kiệm token của RESYNC.

---

### Step 3: Draft Content — Translate UC → System Requirement [Gate 1]

For every row in the UC Spec's Main Flow, Alternative/Exception Flows, and Business Rules, produce at least one corresponding item below, and record the UC reference it came from. Nothing goes into the draft without a traced source (UC Spec) or a confirmed answer from DEV — no invented content.

- **Functional Requirements** — one per distinct system behavior, not one per numbered UC Flow step. **A single Main Flow step frequently bundles several independent behaviors — split them.** Worked example: a UC Flow step written as "khách xem giỏ hàng, hệ thống tự làm mới định kỳ" actually contains at least 3 distinct behaviors that each need their own FR: (1) load/display cart, (2) auto-refresh cadence + price re-sync, (3) quantity-limit enforcement on the input field. Bundling all 3 under one "FR-01: View cart" loses testability — each behavior needs its own trace target so an Acceptance Test can point at exactly one of them. Rule of thumb: if you can write a Given/When/Then for it that doesn't also require describing an unrelated behavior, it's a separate FR.
- **Non-Functional Requirements** — from BR3-type rules (security, authz) or explicit constraints in the UC Spec / ticket context; do not invent performance/scale numbers that aren't stated anywhere — mark as Gap and ask instead.
- **Business Rules → Validation Rules** — translate each BR into a concrete system-level rule, cross-referenced with the existing pattern found in Step 2 (or flagged if no existing pattern applies).
- **Exception & Error Handling** — one per Exception Flow, using the error-handling convention found in Step 2.
- **Acceptance Test Scenarios** — Given/When/Then, at least one per Main Flow outcome + one per Alternative/Exception Flow, **and at least one per Validation Rule / Exception & Error Handling item** (not just per Flow) — Step 3.5 Direction C below audits this and will bounce the draft back here if any VR/ER has zero AT. This is the concrete deliverable requested by proposal #1 (acceptance tests generated from the spec, not copied from the ticket). Tag each scenario with the Requirement IDs it exercises (**Requirement Coverage**) so QA can trace AT → FR/VR/ER without re-reading the whole document.

**Investigate-once cost control does not license coarser requirements.** `investigation-cost-control.md` (Step 2) is about not re-reading the same file — it says nothing about how many FR/VR/AT items the UC Spec's content should produce. Bundling multiple distinct behaviors into one coarser FR/VR to cut the item count is **not** a valid way to save token budget — it directly causes the completeness gaps this Step keeps guarding against (missed items, weak AT coverage, thin traceability). If token budget is tight, spend the savings from Step 2's cost control on drafting more items at the correct granularity, not on drafting fewer, bigger ones.

**Source Checklist Crosswalk — mandatory if Step 1 flagged a numbered/enumerated source list:** build an explicit table, one row per numbered source item, mapping it to the FR/VR/ER/AT code(s) it became — or, if the item turned out not to correspond to anything real in the codebase, a `Deviation — escalate to BA` entry (do not silently drop it, do not silently fold it into another item without a pointer). Place this table in Section 0 alongside the Traceability Matrix. Do not collapse a run of source items into one summary row (e.g. "BR-001–BR-031 → VR-001–VR-031, same numbering") even when the mapping is 1-1 and repetitive — write out every row; a PM/reviewer scanning Section 0 should be able to confirm each numbered item individually without cross-referencing the UC Spec side by side.

**`RESYNC` mode:** dùng lại đúng phân loại đã tính ở Step 1.5 (không diff lại lần 2) — carry forward các item "Không đổi" nguyên trạng, chỉ draft mới cho phần "Đổi/mới", ghi các item "Bị xoá" vào Change Log. Never silently drop an item without noting why in the Change Log.

#### Writing style & layering (applies to every item in Sections 1–4)

Every item is a stack of layers, each aimed at a different reader — write each layer, don't blend them. The field name alone tells the reader who it's for — see the "Ai đọc field nào" table at the top of the template. **Do not** tag individual field labels with `[Role]` — that mapping is fixed for the whole document and stated once, up top; repeating it on every item is noise, not signal.

1. **Requirement** — the system behavior in plain business language. No framework names, class names, method names, or library calls (`Rule::unique`, `FormRequest`, `Middleware`, `permission_handle()`, enum class names, etc.). PM must be able to read this layer alone and understand what the system does.
   - ❌ `Rule::unique(...)` → ✅ "The system validates that the Tag name is unique among active Tags."
   - ❌ `permission_handle()` → ✅ "Only users with CREATE permission can create Tags."
   - When a technical concept (e.g. an enum) has a business meaning, state the business impact first (e.g. "Newly created Tags are assigned the default status PENDING") and put the raw technical value in Implementation Reference as a `Tech Reference:` line — **never invent or assume what an enum/status value means in business terms unless the PM has confirmed it**; if unconfirmed, ask in Step 4 or leave it as the raw value with a Gap/Assumption tag. Every `Tech Reference:` line also gets a row in Section 6.2 (Glossary / Term Mapping) — write it once there, don't leave it scattered only inside individual items.
2. **System Behavior** — how the system processes it, still in plain language (conditions, order of checks, what triggers what). This is what BA/Tester use to write test cases.
3. **Error Response** (Validation Rules and Exception & Error Handling only) — the expected result for Tester: keep the HTTP status code (never drop it — Tester needs it), paired with a friendly label and the user-facing message, e.g. `HTTP 422 (Validation Error) — "..."`.
4. **Implementation Reference** — file/class/method/framework rule, for Developer cross-check only. This is where all the technical detail from Step 2 belongs — it never appears in layers 1–2. **Keep it to one line**: `file:line` (or class/method) plus at most one short clause of context. Do not write multi-sentence prose explaining why the current code is wrong or what the fix should look like — Dev reads the code directly for that; this field is a pointer, not a code review.

Keep each layer short — one requirement, one behavior, one result. If a sentence needs 2–3 clauses to say, split it into separate `Requirement` / `System Behavior` / `Result` lines instead of one long sentence.

Classify every item as **Gap** (missing entirely) / **Assumption** (inferred, unconfirmed) / **Decision** (a choice made and confirmed during Q&A) / **Deviation** (implementation differs from what the UC Spec states) — only when one of these applies. A plain fact (explicit in UC Spec or confirmed in code) needs no tag; do not mark every item "Fact" by default, since a Requirement is a fact unless flagged otherwise. This replaces the old Fact/Assumption/Gap convention from `read-study-requirement` Step 1.75 for this skill's output — `read-study-requirement` itself is unaffected.

**Writing the `Classification` value** — one decision → one line: `[state] — [ID] ([who decided]): [content, one clause]`, e.g. `Decision — OQ-42 (BA): keep the losing customer's cart unchanged`. **Two or more decisions** (e.g. BA decided part of it, Dev decided the rest) → do NOT chain them with `;` in one sentence (unreadable, even to a Tech Lead) — one sub-bullet per decision instead, same `[ID] ([who]): [content]` format:
```
- **Classification:** Gap → Decision
  - OQ-35 (BA): chose the order-attempt-token mechanism to prevent duplicate orders
  - D-03 (Dev): server responds HTTP 200 with the original order; token expires after 30 minutes
```
`OQ-xx` = a decision inherited from BA (originally from the UC Spec). `D-xx` = a decision made while drafting this System Requirement — log it in Section 8 (Decision Log).

---

### Step 3.5: Traceability Verification — 1-1 Gap Audit [Gate 1]

Step 3 asks for a traced source on every item *while drafting*, but drafting under time/token pressure is not a reliable substitute for actually checking. Run this as a separate, explicit pass over the finished draft — using Section 0 (Traceability Matrix) as the working artifact — before opening Q&A in Step 4. This is a checklist walk, not a re-investigation; it should be cheap.

**Direction A — UC Spec → System Requirement (coverage: did we forget anything?):** Walk every row of the UC Spec read in Step 1 — each Main/Alternative/Exception Flow step, each Business Rule, each NFR, each Pre/Post-Condition — and confirm the Traceability Matrix lists at least one FR/NFR/VR/ER against it.
- Listed → leave as is.
- Missing → **Gap — Missing Coverage.** Add a row to Section 7 tagged `Gap` citing the UC reference, and add it to the Step 4 Q&A queue. Do not invent an item just to fill the matrix cell, and do not quietly drop the row.

**Direction B — System Requirement → UC Spec (grounding: did we invent anything?):** Walk every FR/NFR/VR/ER/AT item drafted in Sections 1–5 and re-check its `Traced UC Ref`/`Traced UC BR`/`Requirement Coverage` line against the actual UC Spec text from Step 1 (not from memory of having read it).
- Traces to real content → leave as is.
- Doesn't trace to anything that's actually there (invented, or drifted onto an unrelated UC item) → **Gap — Unsupported Item.** Either correct the trace to the right UC reference, or if truly ungrounded, remove the item and note why in Section 7/Change Log.

**Direction C — Acceptance Test coverage (did we leave anything untested?):** Walk every VR and ER drafted in Sections 3–4 and confirm it appears in at least one AT's `Requirement Coverage` line in Section 5.
- Covered → leave as is.
- Zero AT references it → **Gap — Missing Acceptance Test.** Draft the missing AT now (back in Step 3's Section 5) before continuing — do not let a VR/ER ship with no way for QA to verify it landed. This directly targets the completeness gap documented in `docs/internal/Token Problems.md` §4 (a real run left ~45% of VRs with no AT).

**Direction D — Decision traceback (did we cite where each Decision actually came from?):** Walk every item tagged `Classification: ... Decision` in Sections 1–5. If Step 1 found a Q&A/Decision appendix (`OQ-xx` or equivalent) in the UC Spec, every one of these Decision lines **must** cite the matching ID.
- Cites an ID that's actually in the appendix → leave as is.
- Tagged Decision but missing an ID, or the appendix exists but was never consulted → **Gap — Missing Decision Traceback.** Go back to the appendix, find the matching entry (or confirm there isn't one — in which case this is a Dev-made decision, log it as `D-xx` in Section 8 instead, not `OQ-xx`), and fill it in. Do not leave a Decision line unattributed when a source for it exists.

Record the result as four counts — `UC items matched: X/Y`, `Unsupported items removed: Z`, `VR/ER without AT: W` (must be 0 before Gate 2), and `Decisions missing traceback: V` (must be 0 before Gate 2 when a Decision appendix exists) — and carry them into the Gate 2 prompt (Step 7). Any finding from this pass is a Gap and follows the same hard rule as Step 4 below: **do not proceed to Gate 2 while it's unresolved** — either resolve it via Q&A or get an explicit DEV/PM acknowledgement that it's accepted as a known, tracked gap (never a silent pass-through).

---

### Step 4: Clarify via Q&A (ask until Confirmed) [Gate 1]

- Ask **one question at a time**, prioritizing unresolved Assumptions/Gaps from Step 3 and any coverage/grounding Gaps surfaced by Step 3.5.
- **Do not run `aiflow task next` into Gate 2 while any Gap remains unresolved.** This is the hard rule from proposal #7 — no fabrication, no "reasonable default" for missing UC content. If DEV genuinely cannot answer (needs PM), stop and record it as an unresolved Gap in Section 7 rather than guessing.
- Do NOT invoke `superpowers:brainstorming` (same reason as `read-study-requirement`: its terminal state bypasses this gate's approval).
- All Gaps Confirmed (including Step 3.5's) → present a short Gate 1 summary, wait for DEV to run `aiflow task next` before continuing to Step 5.

---

### Step 5: Decide Single File vs Split [Gate 2]

**Default: one file.** `System-Requirement_v{N}.md` mirrors `UC-Spec_v{N}.md` 1-1 — most UCs stay a single, reviewable document. Split is the exception, triggered by any ONE of:

| Signal | Threshold | Split by |
|---|---|---|
| Business-rule domain fan-out | 2+ BR domains (e.g. Validation, Authorization) each with 8+ concrete rules, touching different system layers | One sub-file per domain |
| Module/service fan-out | Step 2 investigation shows 3+ separately deployable modules/services with little shared logic (e.g. separate microservice + separate batch job) | One sub-file per module |
| Flow-count overload | 6+ Alternative/Exception flows AND draft would exceed ~300 lines | Split Exception & Error Handling into its own sub-file; keep Functional Requirements + Acceptance Tests together |
| Size ceiling | Draft exceeds ~400 lines even without the above | Split along whichever axis (domain or module) holds the most content — never split by raw line count alone with no semantic seam |

**Anti-pattern — do not split for this, escalate instead:** if the UC Spec itself reads like 2+ independent use cases bundled together (no shared Business Rule, no shared data entity, could be tested/shipped separately) → **stop, do not split System Requirement to cope.** Flag to BA that the UC Spec's granularity may need revisiting (per the kit's own convention, 1 UC should be 1 Function-ID). Splitting Dev's document to paper over a BA-side granularity problem just hides it.

**When split occurs:** keep one master `System-Requirement_v{N}.md` as the index — holds header/metadata, the full Traceability Matrix, links to each sub-file, and the Change Log. Sub-files: `System-Requirement_v{N}_[Domain].md` (e.g. `_Validation.md`, `_BackendAPI.md`). The mandatory `UC-Spec-Version` header lives on the master file only.

---

### Step 6: Write Output [Gate 2]

Save to `AK-Docs/02.BA-Specs/00.Requirements/[functionId]/System-Requirement_v{N}.md` (`N` = the UC Spec version this was traced against — **not** an independent counter):

```markdown
# System Requirement: [functionId] — [Feature Name]

**Date:** [YYYY-MM-DD]
**System-Requirement-Version:** v{N}
**UC-Spec-Version:** [functionId] @ v{N}   <!-- MANDATORY — the 1-1 matching anchor -->
**Source UC Spec:** AK-Docs/02.BA-Specs/04.UC-Specs/[functionId]/UC-Spec_v{N}.md

---

## Who reads what field (stated once — not repeated per item)

The field → reader mapping is fixed for the whole document, so it's declared once here instead of tagged on every item:

| Field | Who needs it |
|---|---|
| `Requirement` | PM/BrSE/Comtor, Tester |
| `System Behavior` | Tester |
| `Error Response` | Tester (full line, incl. HTTP code) — PM/BrSE/Comtor only needs the user-facing message |
| `Traced UC Ref` / `Traced UC BR` / `Traced Exception Flow` | PM/BrSE/Comtor (cross-check against UC Spec) |
| `Classification` | PM/BrSE/Comtor — this is the "needs a decision" / "already decided" signal |
| `Implementation Reference` / `Tech Reference` | Dev |
| Section 5 (Acceptance Test Scenarios) | Tester |

**Dev and AI read the entire document**, every field, regardless of the table above — Dev needs it to implement, AI needs it across multiple gates (coding Gate 3, testcase generation, traceability audit).

---

## Executive Summary
- **Purpose:** [1 sentence — what this document covers and why it exists]
- **Implementation status:** [e.g. Not started / In progress / Matches UC Spec v{N}]
- **Traceability coverage (from Step 3.5 audit):** [X]/[Y] UC Spec items have a matching System Requirement item · [Z] unsupported item(s) removed · [W] VR/ER without an Acceptance Test (must be 0) · [V] Decision(s) missing traceback to the source appendix (must be 0)
- **Key deviations from UC Spec:** [bullet list of Deviation-tagged items, or "None identified"]
- **Action needed from PM:** [bullet list of unresolved Gaps/Assumptions needing PM input, or "None — ready for Dev handoff"]

> This section alone should give PM the full picture in about 30 seconds — everything below is supporting detail for BA/Tester/Dev.

---

## 0. Traceability Matrix
| UC Reference (Flow / BR) | System Requirement Item(s) |
|---|---|
| Main Flow step 3 | FR-01 |
| Exception Flow B | FR-05, ER-02 |
| BR1.1 | VR-01 |

<!-- Never collapse a run of items into one summary row (e.g. "BR-001–BR-031 → VR-001–VR-031, same numbering") even when the mapping is 1-1 — write out every row. -->

### 0.1 Source Checklist Crosswalk *(include only if Step 1 flagged a numbered/enumerated source list — e.g. "Phụ lục E", a ticket's numbered checklist; omit this subsection entirely if there's no such list)*
One row per numbered source item — every number must appear exactly once, mapped to what it became:

| # (source) | Source description | Became | Note |
|---|---|---|---|
| 1 | [short description from the source list] | FR-03 | |
| 2 | [...] | Deviation — Section 7 | not found in current code, escalated to BA |

## 1. Functional Requirements

Each item below is layered: **Requirement** (business language, for PM) → **System Behavior** (for BA/Tester) → **Implementation Reference** (for Dev, technical detail only — never appears in the layers above it).

### FR-01: [short business-behavior title]
- **Requirement:** [system behavior in business language, no framework/class/method names]
- **System Behavior:** [how the system processes it — conditions, order of checks]
- **Traced UC Ref:** Main Flow #3
- **Classification:** [Gap | Assumption | Decision | Deviation — omit this line if it's a plain fact]
- **Implementation Reference:** [file:line / class / method — one line, no multi-sentence explanation]

<!-- repeat FR-02, FR-03, ... in the same block format -->

## 2. Non-Functional Requirements

### NFR-01: [short title]
- **Requirement:** [business language — e.g. performance/security expectation]
- **System Behavior:** [how it's enforced, in plain language]
- **Traced UC Ref:** BR3.1
- **Classification:** [Gap | Assumption | Decision | Deviation — omit if plain fact]
- **Implementation Reference:** [file:line / class / method]

## 3. Business Rules → Validation Rules

### VR-01: [short title]
- **Requirement:** [e.g. "Tag name must be unique among active Tags."]
- **System Behavior:** [e.g. "The system checks the Tag name against all active Tags before saving."]
- **Error Response:** HTTP 422 (Validation Error) — "[user-facing message]"
- **Traced UC BR:** BR1.1
- **Classification:** [Gap | Assumption | Decision | Deviation — omit if plain fact]
- **Implementation Reference:** [e.g. `Rule::unique(...)` in `StoreTagRequest`]

## 4. Exception & Error Handling

### ER-01: [trigger condition, in business language]
- **Requirement:** [e.g. "Only users with CREATE permission can create Tags."]
- **System Behavior:** [e.g. "The request is rejected because the caller lacks the required permission."]
- **Error Response:** HTTP 403 (Forbidden) — "[user-facing message]"
- **Traced Exception Flow:** Exception Flow B
- **Classification:** [Gap | Assumption | Decision | Deviation — omit if plain fact]
- **Implementation Reference:** [existing error code/class/middleware]

## 5. Acceptance Test Scenarios
### AT-01: [Scenario] (Main Flow)
- **Given** ...
- **When** ...
- **Then** ...
- **Requirement Coverage:** FR-01, FR-03

### AT-02: [Scenario] (Exception Flow B)
- **Given** ...
- **When** ...
- **Then** ...
- **Requirement Coverage:** VR-01, ER-01

## 6. Existing System Context

### 6.1 System Areas Summary
Summary only — deeper implementation detail belongs in each item's **Implementation Reference** above, not here.

| Area | Summary |
|---|---|
| API | ... |
| Model | ... |
| Validation | ... |
| Migration | ... |
| Test | ... |

### 6.2 Glossary / Term Mapping
Every `Tech Reference:` used in Sections 1–4 gets one row here — a single place to look up what a business term maps to in code, instead of hunting through every item. Only include terms with a PM-confirmed business meaning (Decision) or the PM-unconfirmed raw value tagged accordingly — never a guessed meaning.

| Business Term | Technical Reference | Classification |
|---|---|---|
| [e.g. "default status PENDING"] | `TagStatusEnum::PENDING` | Decision (PM-confirmed [date]) / Assumption (unconfirmed) |

### 6.3 External System Interfaces *(optional — include only if this UC integrates with a system outside the app's own UI/DB, e.g. third-party API, webhook, message queue)*
The UC Spec describes UI/business flow, not external integration contracts — capture those here when they exist. Omit this subsection entirely if the UC has no external interface.

| Interface | Direction | Protocol/Format | Note |
|---|---|---|---|
| [e.g. Payment Gateway API] | Outbound | REST/JSON | ... |

## 7. Assumptions / Gaps / Decisions / Deviations
Only items tagged Gap / Assumption / Decision / Deviation land here — a plain fact is the default, unmarked state of every item above and is not repeated in this table.

| Type | Item | Resolution |
|---|---|---|

## 8. Decision Log
Short lookup table — do not restate the full question/answer, that detail already lives in the `Classification` line of the item it applies to (writing it twice is redundant). Just enough to trace back: decision ID → who decided → date → one-line summary.

| ID | Decided by | Date | Summary |
|---|---|---|---|
| OQ-xx | PM/BA | [YYYY-MM-DD] | [one line — full detail lives in the matching item in Sections 1–4] |

Unresolved Gaps stay listed in Section 7, not here — this table only holds decisions that **already have** an answer.

## 9. Change Log
| Date | Ticket | Change | Note |
|---|---|---|---|
| [YYYY-MM-DD] | — | Initial creation from UC Spec v{N} | |
```

Output language: auto-detect from the ticket/task input — see `custom/rules/output-language.md` (Vietnamese input → Vietnamese output; otherwise English).

---

### Step 7: Present for Approval [Gate 2]

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⏸️  GATE 2: SYSTEM REQUIREMENT READY

FunctionId: [functionId]
UC Spec:    v{N} (AK-Docs/02.BA-Specs/04.UC-Specs/[functionId]/UC-Spec_v{N}.md)
File:       AK-Docs/02.BA-Specs/00.Requirements/[functionId]/System-Requirement_v{N}.md
Mode:       CREATE | RESYNC

Coverage:
  Functional Requirements: [N]   Acceptance Tests: [N]
  Validation Rules:        [N]   Exception Handling: [N]
  Open Gaps:                [N]  ← must be 0 to approve

Traceability Audit (Step 3.5):
  UC Spec items matched 1-1:      [X]/[Y]
  Unsupported items removed:      [Z]
  VR/ER without an Acceptance Test: [W]  (must be 0 to approve)
  Decisions missing traceback:      [V]  (must be 0 to approve, when a Decision appendix exists)
  ⚠️  [N] unresolved gap(s) from this audit — see Section 7   (omit this line if 0)

Please review — matching 1-1 with UC Spec v{N} is the point of this document.
  → Type APPROVED (then run `aiflow task next`) to close this task and clear
    the Gate 1 warning for tickets on this functionId
  → Or provide feedback to update
  → Non-tech reviewer (PM/Comtor/BrSE/Tester)? See
    docs/common/System-Requirement-Read-Guide.md for what Classification/
    Implementation Reference/Tech Reference mean, which fields you can skip,
    an FAQ, and a review checklist.

⚠️  Until this task is APPROVED, coding Gate 1 for this functionId will keep
    showing a non-blocking warning (it does not cancel).
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

- Any Gap still open → cannot approve; go back to Step 4 (re-open Gate 1).
- DEV feedback → update draft → re-show prompt.
- `APPROVED` → task is done — commit/push the file so it becomes visible to PM; coding Gate 1 unlocks.

---

### Step 8: Later Update (invoked from inside coding Gate 1, not standalone)

`read-study-requirement` Step 3 (end of Gate 1, per ticket) may discover a case, rule, or exception that the UC Spec supports but the current System Requirement missed. That step **proposes** an addition — presents the diff to DEV, does not write directly — and on confirmation appends it to the master file's relevant section plus a `Change Log` row (`Ticket: [ticketId]`). This skill owns the template/contract for that row; `read-study-requirement` owns triggering it.

This does not bump `System-Requirement-Version` — the version stays tied to the UC Spec version. Only a new UC Spec version triggers `RESYNC` (Step 0).

---

## What This Skill Delegates vs Owns

| Concern | Handled by |
|---|---|
| Source code investigation methodology | `custom/rules/investigation-cost-control.md` (GitNexus MCP / `Explore` sub-agents / Investigation Notes table — shared across skills, Step 2 cost-control) |
| RESYNC diff scope (which Flow/BR changed) | This skill (inline, Step 1.5 — runs before Step 2, scopes both investigation and drafting) |
| Gap/Assumption/Decision/Deviation classification | This skill (inline, Step 3 — output-only convention, distinct from `read-study-requirement` Step 1.75's Fact/Assumption/Gap) |
| 1-1 traceability audit (UC ↔ System Requirement) | This skill (inline, Step 3.5 — separate from Step 3's while-drafting tracing) |
| Q&A loop (one question at a time, no fabrication) | This skill (inline) |
| UC Spec structure/content | `skill-ba-uc-template-v1.md` (read-only reference, never edited by this skill) |
| Split decision | This skill (Step 5) |
| Mid-ticket addition proposals | `read-study-requirement` Step 3 triggers; this skill owns the write contract |
| Gate/approval mechanics | This skill (Step 7) |

---

## Mandatory Rules

- ❌ **DO NOT** create System Requirement content that isn't traced to the UC Spec or a DEV-confirmed answer — no invented Functional Requirements, error messages, or NFR numbers.
- ❌ **DO NOT** proceed to Step 5 while any Gap is unresolved — this includes Step 3.5's traceability-audit Gaps, not just Step 3/Step 4's.
- ❌ **DO NOT** bundle multiple distinct system behaviors into one coarser FR/VR to reduce item count/token cost — granularity follows the UC Spec's actual content, not the investigation budget (see Step 3's worked example).
- ✅ **MUST** read any Q&A/Decision appendix in the UC Spec (Step 1) in full, and cite the matching `OQ-xx` on every Classification: Decision line that traces back to it (Step 3.5 Direction D checks this).
- ✅ **MUST** build the Section 0.1 Source Checklist Crosswalk when the UC Spec references a numbered/enumerated source list — one row per number, no silent absorption into a broader item.
- ✅ **MUST** run Step 3.5 Directions C and D (Acceptance Test coverage, Decision traceback) before Q&A closes, alongside Directions A/B — report all four counts in the Step 7 Gate 2 prompt.
- ❌ **DO NOT** approve Gate 2 while any VR/ER has zero Acceptance Test coverage, or any Decision is missing its traceback where a source appendix exists.
- ✅ **MUST** run Step 3.5's 1-1 traceability audit (both directions — UC→SR coverage and SR→UC grounding) before Q&A closes; report its counts in the Step 7 Gate 2 prompt so DEV/PM see explicit match numbers, not just a claim of completeness.
- ❌ **DO NOT** re-investigate a file from scratch for every Business Rule that touches it (Step 2) — investigate per module/concern once, keep an Investigation Notes table, and prefer GitNexus MCP or `Explore` sub-agent delegation over serial multi-file reads in the main session.
- ✅ **MUST** (Mode RESYNC) run Step 1.5's diff **before** Step 2 — the diff result is what scopes Step 2's investigation, not just Step 3's draft. Do not investigate the whole UC again "to be safe" when in RESYNC mode.
- ✅ **MUST** (Mode RESYNC) run the git-log safety-check described in Step 2 before treating a UC-unchanged section as safe to skip — this is a cheap check, not optional, and it is the only guard against code that drifted independently of the UC Spec.
- ❌ **DO NOT** split into multiple files unless a Step 5 threshold is actually met — default is one file.
- ❌ **DO NOT** split to paper over a UC Spec that bundles multiple independent use cases — escalate to BA instead.
- ❌ **DO NOT** run this skill if the UC Spec isn't PM-signed-off yet — this skill never substitutes for missing UC Spec content.
- ❌ **DO NOT** bump `System-Requirement-Version` independently of the UC Spec version.
- ✅ **MUST** read the full UC Spec (Step 1) before drafting anything.
- ✅ **MUST** investigate source code (Step 2) before drafting Exception/Error Handling or Existing System Context.
- ✅ **MUST** carry the mandatory `UC-Spec-Version` header on the master file.
- ✅ **MUST** surface a ⚠️ non-blocking warning (never a cancel) from the Gate 1 Pre-flight check until this skill reaches APPROVED.
- ✅ **MUST** write the `Requirement` and `System Behavior` layer of every FR/NFR/VR/ER item in business language — no framework, class, or method names (those belong only in `Implementation Reference`).
- ✅ **MUST** keep the HTTP status code in every `Error Response` line, paired with a friendly label and the user-facing message (e.g. `HTTP 422 (Validation Error) — "..."`) — never drop the code for readability.
- ✅ **MUST** tag each Acceptance Test with its `Requirement Coverage` (the FR/VR/ER IDs it exercises).
- ❌ **DO NOT** tag every item "Fact" — a plain fact is the unmarked default; only tag `Gap`, `Assumption`, `Decision`, or `Deviation` when one applies.
- ❌ **DO NOT** state or assume the business meaning of an enum/status value (e.g. what `PENDING` "means" for the business) unless the PM has confirmed it — reference the raw technical value in `Implementation Reference` and tag it `Assumption` or `Gap` until confirmed.
- ✅ **MUST** mirror every `Tech Reference:` used in Sections 1–4 as a row in Section 6.2 (Glossary / Term Mapping) — don't leave the mapping only inside individual items.
- ❌ **DO NOT** tag individual field labels with `[Role]` (e.g. `**Requirement [PM/BrSE/Comtor]:**`) — the field → reader mapping is declared once in the "Who reads what field" table at the top and never repeated per item; that repetition was tried and reverted for being pure noise once the convention is stated.
- ❌ **DO NOT** include Section 6.3 (External System Interfaces) when the UC has no integration outside the app's own UI/DB — omit the subsection entirely rather than leaving an empty table.
- ❌ **DO NOT** restate a full question/answer in Section 8 (Decision Log) when the same decision is already explained inline in an item's `Classification` line — Section 8 is a short lookup table (ID → who → date → one-line summary) that points back to the item, not a duplicate narrative.
- ❌ **DO NOT** write multi-sentence prose in `Implementation Reference` explaining why current code is wrong or how to fix it — one line (`file:line` + at most one short clause) is enough; Dev reads the code itself for the rest.
- ❌ **DO NOT** chain two or more decisions into one `Classification` sentence with `;` (e.g. "BA decided OQ-35...; DEV decided D-03...") — split into one sub-bullet per decision (`[ID] ([who]): [content]`), see "How to write Classification" above. This was reported as hard to read even by a Tech Lead.
