---
name: read-study-requirement
description: Gate 1 — AI reads ticket from Backlog/Jira + reads source code, then uses collaborative Q&A and solution proposal. Adds impact analysis and effort estimate. Outputs requirement.md for DEV to approve. Checks that System Requirement (bridged from UC Spec via `create-system-requirement`) exists and matches the current UC Spec version — shows a non-blocking ⚠️ warning and continues otherwise.
keywords: ticket, requirement, study, read, context, backlog, jira, analyze, understand, solution, estimate, system requirement, uc spec
---

# Analyze Requirement — Gate 1

> **GATE 1: Must run before any other gate. Auto-starts when ticket context exists.**
>
> Principle: AI actively participates in understanding requirements — reading ticket + source code, clarifying via collaborative dialogue, proposing solutions, analyzing impact, and estimating effort.

---

## Step 0: System Requirement Check (Pre-flight, non-blocking warning — runs before Mode Selection)

Before reading the ticket in depth, verify the bridge document from UC Spec — this applies to **every mode**, including Fast Track (it's a 2-file header check, not a heavy investigation). **This check never cancels Gate 1** — any gap only produces a ⚠️ yellow warning; Gate 1 always continues with whatever context is available:

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** → `⚠️ CẢNH BÁO: Không tìm thấy UC Spec cho [functionId] — Gate 1 tiếp tục chỉ dựa trên ticket/source code, thiếu ngữ cảnh nghiệp vụ BA đã chốt.` Continue to step 3.
3. Check `AK-Docs/02.BA-Specs/00.Requirements/[functionId]/System-Requirement_v*.md`:
   - **Missing** → `⚠️ CẢNH BÁO: Không tìm thấy System Requirement cho [functionId]. Khuyến nghị chạy "ak use" → "📐 Create System Requirement" trước ticket kế tiếp — Gate 1 vẫn tiếp tục ngay bây giờ dựa trên UC Spec/ticket.`
   - **Exists, but its `UC-Spec-Version` header doesn't match the UC Spec found in step 2** → `⚠️ CẢNH BÁO: System Requirement đang trace theo UC Spec v[X], UC Spec hiện tại là v[Y] — nội dung có thể lỗi thời.` Treat its items as Assumption rather than Fact in Step 1.75.
   - **Exists and matches** → continue silently. Keep this file's path — Step 1 must read it as mandatory input. (Its presence in the repo already means DEV approved and pushed it — approval isn't tracked with a separate header.)

Any warning raised above must also be written into this ticket's requirement doc (Section 1, Facts/Assumptions/Gaps in Step 4) — not just printed and forgotten. If DEV wants the gap closed properly, they can run `ak use` → "📐 Create System Requirement" for `[functionId]` at any point (before or after this ticket) — it's a separate 2-gate task type, not an inline sub-skill here.

---

## Mode Selection

Check `mode` in `.aiflow/context/current.json` before starting:

| Mode | Trigger | Behaviour |
|------|---------|-----------|
| `fast` | `aiflow use TICKET --fast` | Jump to **[Fast Track](#fast-track-mode-fast)** below |
| `full` | `aiflow use TICKET --full` | Use standard steps — full Q&A + all 6 sections |
| `auto` (default) | `aiflow use TICKET` | Standard steps |

---

## Fast Track (mode: fast)

> Target: Gate 1 complete in **< 5 minutes**, minimum token usage.

## Fast Mode Output Rules (CRITICAL)

When creating `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md` during Gate 1:
- You must create the `summary.md` file after Gate 1 is APPROVED, to track session progress.
- Keep `summary.md` concise. Only include short bullet points tracking Gates.
- Do not write verbose implementation details in `summary.md` at Gate 1.

> **Path variables:** `[functionId]` (mã chức năng do dự án quy định, ví dụ `F-001_User-Login`, `AD06`) và `[ticketId]` (= `taskId` trong `.aiflow/context/current.json`) được xác định ở **Gate 1 Pre-flight Bước 0** của workflow — ưu tiên lấy từ context, sau đó suy từ file UC Spec input (nội dung/đường dẫn) rồi hỏi DEV xác nhận. KHÔNG ghi bất kỳ file output nào khi chưa có functionId.

0. **Pre-flight — Sync with remote** (before reading any source file):
   - Run `git status --porcelain` to check for uncommitted changes.
   - Working tree clean → run `git pull --ff-only` to fetch the latest code.
   - Uncommitted changes detected → SKIP pull and notify DEV: `⚠️ Uncommitted changes detected — skipping git pull. Analysing local state.`
   - `git pull --ff-only` fails (branch diverged from remote) → notify DEV: `⚠️ Local branch diverged from remote — skipping pull. Resolve manually before next ticket.` Then continue with local state.
1. Read `.aiflow/context/current.json` — ticket title, description, acceptance criteria
1b. Read `System-Requirement_v{N}.md` for this functionId (confirmed to exist by Step 0) — the authoritative WHAT. Reference its item IDs (`FR-*`, `VR-*`, `ER-*`) instead of restating them.
2. Identify **directly affected files** from ticket text and file names only.
   DO NOT trace data flow or read unrelated source files.
3. Q&A: Ask at most **ONE** question if there is a blocking ambiguity.
   If the ticket + source file names make intent clear → skip Q&A entirely.
   Wait for answer before writing the requirement doc.
4. Output `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md` with **3 sections only**:

```markdown
# Requirement: [Ticket ID] — [Title]

**Date:** [YYYY-MM-DD]  **Mode:** fast  **Status:** ⏸️ Waiting for DEV Approval

## 1. Requirements Summary
[2–4 sentence restatement of what needs to change and why]

**Acceptance Criteria:**
- [ ] [each AC from ticket]

## 3. Files to Create / Modify
| Action | File | Change |
|--------|------|--------|
| Modify | [path] | [what changes] |

## 5. Effort Estimate
| Task | Size |
|------|------|
| Tests | S/M/L |
| Implementation | S/M/L |
| **Total** | **S/M/L** |
```

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

5. Display Gate 1 prompt and wait for `APPROVED`.

> After APPROVED, proceed to Gate 2.
> - **`gen-doc` tasks:** Gate 2 generates the output document immediately (no `plan.md`, no TDD). Self-review + task-summary.md are created automatically.
> - **All other tasks:** Gate 2 plan fills in the implementation details.

---

## Steps

### Step 1: Load Ticket & Read Source Code

0. **Pre-flight — Sync with remote** (run BEFORE reading any source file):
   - Run `git status --porcelain` first. Empty output = clean working tree.
   - Clean working tree → run `git pull --ff-only` to pull the latest code from remote. This guarantees the analysis is based on current source, not stale local state.
   - Uncommitted changes → SKIP pull and notify DEV: `⚠️ Uncommitted changes detected — skipping git pull. Analysing local state.`
   - `git pull --ff-only` fails because the branch has diverged → notify DEV: `⚠️ Local branch diverged from remote — skipping pull. Resolve manually before next ticket.` Continue with local state.
   - Repo has no remote tracking branch (detached HEAD or local-only branch) → skip silently and proceed.
1. Read `.aiflow/context/current.json` — ticket info from Backlog/Jira
1b. Read `System-Requirement_v{N}.md` for this functionId (confirmed to exist and in-sync by Step 0) — this is the authoritative WHAT for the whole functionId. Reference its item IDs (`FR-*`, `NFR-*`, `VR-*`, `ER-*`) in your analysis instead of re-deriving requirements it already covers.
2. **Supplementary Context:** If `current.json` has a `supplementaryContext[]` array, read each item and integrate it as supporting context for your analysis. Items may be:
   - `[ticket]` — linked tickets (related features, dependencies, parent tickets)
   - `[comment]` — specific comments from PM/QA/stakeholders
   - `[file]` — architecture docs, business logic specs, API references
   - `[text]` — any other supplementary information

   If you encounter a backlog/jira URL in the ticket description that is **not** already in `supplementaryContext[]`, run `ak fetch-links <url>` and use the JSON output in your analysis without saving.
3. Read `CLAUDE.md` — understand project architecture, tech stack, conventions
4. Read related source files — trace data flow, identify patterns, dependencies
   - **If GitNexus MCP is available** (`.mcp.json` has `gitnexus` entry): invoke GitNexus MCP tools instead of reading files directly — one call returns full context without multi-file exploration:
     - `gitnexus: context("ClassName")` → 360° view of a symbol (dependencies, callers, methods)
     - `gitnexus: query("keyword or description")` → hybrid search across codebase
     - Saves ~50% of token cost at this step vs reading files manually
   - Áp dụng `custom/rules/investigation-cost-control.md` cho toàn bộ bước này (GitNexus-first → `Explore` sub-agent delegation khi GitNexus không cover → điều tra theo module/concern một lần, không mở lại file cho từng file/dependent riêng lẻ → giữ Investigation Notes table thay vì đọc lại).
   - **If task is a Bug Fix:** Invoke `superpowers:systematic-debugging` to trace root cause before proposing fixes.
5. **Map Dependencies (Impact Investigation).** For each file identified in step 4 as directly affected, find all callers/dependents — apply `impact-analysis` skill **Step 1** (Find all usage):
   - **If GitNexus MCP available:** `gitnexus: impact("ClassName")` → blast radius (callers, dependents, risk score). One call replaces the grep commands below.
   - **Fallback — grep:** search callers/importers of the class/function across the project's languages; check Jobs/Events/Crons calling it indirectly; Frontend components calling related APIs; Tests mocking/stubbing the class.
   - Keep the resulting list of callers/dependents — it feeds Step 3 (Impact Analysis) below. Do not classify risk level yet, only collect the dependency list.
   - This step only runs in `auto`/`full` mode — `fast` mode intentionally skips it (see Fast Track above).
6. Read ticket comments — additional context from PM/team

Do this investigation **before** asking any questions. Come prepared.

---

### Step 1.5: Detect & Read Figma Design (UI tickets only)

Run this only when the ticket touches UI. Skip entirely for non-UI tickets.

1. **Detect a Figma URL** in this order:
   - `current.json` → `description`
   - `current.json` → `supplementaryContext[]` items
   - Pattern: `https://www.figma.com/design/<fileKey>/...?node-id=<nodeId>`
2. **No URL but ticket looks like UI** (mentions screen, page, component, layout, "theo design"):
   ask the DEV **once** to paste a Figma URL. If DEV skips → write "Design: TBD" in the
   Design Analysis section and continue. Do NOT ask again.
3. **URL found** → invoke `figma-to-component` Steps 0–2.5 (verify MCP, read design,
   detect & export images). Then persist the shared artifact:
   - Create `plan/[ticket-id]/design/`
   - Save raw response to `plan/[ticket-id]/design/nodes.json` (cache for later gates)
   - Save exported images to `plan/[ticket-id]/design/images/`
   - Write `plan/[ticket-id]/design/figma-manifest.json` (nodeId → image file) — per-ticket,
     NOT a shared global manifest
   - Write `plan/[ticket-id]/design/design-context.md` using the template below
4. **Figma MCP not connected** → tell DEV to run `aiflow init -a figma` (or `-a figma-desktop`),
   mark Design Analysis as "⚠️ pending MCP", and continue with the non-UI parts of the requirement.
   Do NOT abort the ticket.

**`design-context.md` template:**

```markdown
# Design Context: [ticket-id]

**Figma URL:** <url>   **fileKey:** xxx   **nodeId:** 123-456
**Fetched:** [YYYY-MM-DD]   **Adapter:** figma (REST) | figma-desktop

## 1. Layout Structure
- Node tree: Frame > Header / Body > Card[] / Footer
- Flex direction, gap, padding, alignment per region

## 2. Design Tokens
| Type | Figma value | Project token |
|------|-------------|---------------|
| Color | #3B82F6 | blue-500 / --color-primary |
| Type  | 16/600    | text-base font-semibold |
| Space | 16px      | p-4 / gap-4 |

## 3. Components to build
- [ ] UserCard (variants: default, hover) — nodeId 78-910
- [ ] Header — nodeId 12-3

## 4. Image Map
| nodeId | layer | file |
|--------|-------|------|
| 123-456 | Banner Top | design/images/banner-top-123-456.png |

## 5. Notes
- Anything not mapped 1:1 (custom fonts, effects…)
```

---

### Step 1.75: Classify Facts, Assumptions & Gaps

> Runs in `auto`/`full` mode only. Borrowed from `ba-skills` initial-analysis — structures the investigation before Q&A so questions target real unknowns instead of generic vagueness.

Go through the ticket's requirements/acceptance criteria and, for each one, classify it as:
- **Fact** — explicitly stated in the ticket or confirmed by reading the source code
- **Assumption** — inferred from experience/context/existing patterns, not yet confirmed by the developer
- **Gap** — information missing entirely (not stated, not derivable from code)

While classifying, check each functional requirement against:
- Are there input limits/format constraints?
- What happens on empty/invalid input — any error message defined?
- Is there an implicit business rule not written down?
- What are the alternative/exception flows?

Keep this as a working list (Fact / Assumption / Gap) — it drives which questions to ask in Step 2, and gets written into the requirement doc (Section 1).

---

### Step 2: Clarify Requirements via Q&A

Ask clarifying questions directly — **one question at a time**, wait for the developer's response before asking the next.

**Prioritize questions that resolve unconfirmed Assumptions and Gaps from Step 1.75** over generic vague points — this keeps the Q&A focused on real unknowns.

**When to ask:**
- Business requirements are vague or ambiguous
- Acceptance criteria are not measurable
- Edge cases discovered in source code need input
- Multiple approaches exist and the developer's preference matters

**When NOT to ask:**
- The ticket and source code together make the intent clear → proceed directly

Once you have sufficient clarity, propose **2–3 solution approaches** with trade-offs and a recommendation:
- Present options conversationally, lead with your recommendation
- Get developer confirmation on the chosen approach

**Do NOT proceed to Step 3 until the developer has confirmed the design direction.**

> ⚠️ **DO NOT invoke `superpowers:brainstorming`** — brainstorming's terminal state invokes
> `writing-plans` (Gate 2), which would bypass Gate 1's approval gate. All Q&A happens here.

---

### Step 3: Extend with Impact Analysis & Effort Estimate

After the developer confirms the design direction (Step 2), run full impact analysis on the dependency map gathered in Step 1 — apply `impact-analysis` skill **Step 2–3** (do not re-run Step 1, the dependency list is already collected):

**Impact Analysis:**
- Evaluate each aspect from the dependency map (`impact-analysis` skill Step 2 table): Database/Cache, Background Jobs, Import/Export, Permissions, API/Mobile, Tests
- Classify impact level (`impact-analysis` skill Step 3): 🟢 Low (1 file, no deps) / 🟡 Medium (2–5 files, tests need update) / 🔴 High (6+ files, API breaking change, DB migration) / ⛔ Critical (payment, auth, data integrity)
- List concrete breaking changes and a mitigation for each identified risk
- Base every line on the actual callers/dependents found in Step 1 — not guesswork

**Effort Estimate:**
- Break down into tasks: tests, implementation, migration
- Size each task: S (< 1h) / M (1–4h) / L (4–8h) / XL (8h+, consider splitting)
- If XL → suggest sub-task breakdown

---

### Step 3.5: Reconcile with System Requirement

Compare this ticket's confirmed scope (Steps 1–3) against `System-Requirement_v{N}.md` (read in Step 1):

- Scope already covered by an existing item → reference its ID (e.g. `FR-03`, `ER-02`) in Section 1 of the requirement doc below. Do not restate it.
- Investigation surfaces a case, rule, or exception the UC Spec supports but System Requirement missed → **propose** an addition: show DEV the exact diff (which section, new row) before writing anything.
  - DEV confirms → append to `System-Requirement_v{N}.md` (same version — this does **not** bump `System-Requirement-Version`) + add a `Change Log` row citing this ticket.
  - DEV declines/unsure → leave System Requirement untouched; note the discrepancy in this ticket's own requirement doc (Section 1, Facts/Assumptions/Gaps) instead.
- Scope doesn't trace to System Requirement **or** UC Spec at all → this is the fabrication risk proposal #7 targets. STOP and ask DEV: is this actually in scope for this functionId, or does the UC Spec need a BA update first? Do not proceed on a guess.

---

### Step 4: Write Requirement Document

Save to `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md`:

```markdown
# Requirement: [Ticket ID] — [Title]

**Date:** [YYYY-MM-DD]
**Type:** [feature | bug-fix | refactor | investigation]
**Status:** ⏸️ Waiting for DEV Approval

---

## 1. Requirements Summary

### Description
[Clear technical restatement of the requirement, incorporating all clarifications from Q&A]

### Current Behavior / Business Goal
[What exists now vs what is needed]

### Acceptance Criteria
- [ ] [Criteria 1 — specific, measurable]
- [ ] [Criteria 2]

### Context & Constraints
[Environment, business rules, dependencies, deadlines]

### Facts / Assumptions / Gaps
| Type | Item | Resolution |
|------|------|------------|
| Fact | [explicit in ticket/code] | — |
| Assumption | [inferred, not yet confirmed] | [confirmed by DEV in Q&A / still open] |
| Gap | [missing info] | [resolved via Q&A / still open] |

---

## 2. Source Code Analysis

### Related Files
| File | Role | Current State |
|------|------|---------------|
| [path] | [Controller/Service/...] | [what it does now] |

### Dependency Map
[From Step 1 impact investigation — callers/dependents of each affected file/class]

| File / Class | Callers / Dependents | Found via |
|--------------|----------------------|-----------|
| [path or ClassName] | [list of callers, jobs, frontend components, tests] | GitNexus `impact()` / grep |

### Data Flow
```
[Entry point] → [Service] → [Repository] → [DB/External]
```

### Existing Patterns to Follow
[Patterns in the codebase this change must follow]

### Current Test Coverage
| Area | Test File | Status |
|------|-----------|--------|
| [area] | [file] | [exists / missing] |

---

## 3. Proposed Solution

### Chosen Approach: [Name]
[From brainstorming session — the approach the developer confirmed]

### Alternatives Considered
| Option | Pros | Cons | Why Not Chosen |
|--------|------|------|----------------|
| [Option B] | ... | ... | ... |

### Files to Create / Modify
| Action | File | Change |
|--------|------|--------|
| Create | [path] | [purpose] |
| Modify | [path] | [what changes] |

### Database Changes
| Table | Change | Details |
|-------|--------|---------|
| [table] | [migration type] | [description] |

---

## Design Analysis (UI tickets only)

- **Source:** [Figma URL or "TBD" or "⚠️ pending MCP"]
- **Artifact:** `plan/[ticket-id]/design/design-context.md`
- **Summary:** layout, key components to build, design tokens to map, images exported
- **Impact on approach:** how the design shapes the proposed solution

---

## 4. Impact Analysis

> Based on the Dependency Map (Section 2) — apply `impact-analysis` skill Step 2–3.

**Impact Level:** 🟢 Low / 🟡 Medium / 🔴 High / ⛔ Critical

| Area | Impact | Reason |
|------|--------|--------|
| [Module / DB-Cache / Jobs / Import-Export / Permissions / API-Mobile / Tests] | 🟢 None / 🟡 Minor / 🔴 Major | [why, referencing dependents found in Section 2] |

**Breaking Changes:**
- [ ] None expected
- [ ] [Breaking change if any]

**Risks:**
| Risk | Severity | Mitigation |
|------|----------|------------|
| [description] | Low / Medium / High | [mitigation] |

---

## 5. Effort Estimate

| Task | Size | Notes |
|------|------|-------|
| Tests (TDD) | S/M/L | [N scenarios] |
| Implementation | S/M/L | [complexity] |
| Migration / Integration | S/M/L | [if applicable] |
| **Total** | **S/M/L/XL** | |

> S = <1h · M = 1–4h · L = 4–8h · XL = 8h+ (split recommended)

**Sub-tasks (if XL):**
- [ ] [Sub-task 1]
- [ ] [Sub-task 2]

---

## 6. Testing Plan

### Unit Tests
- [ ] [Scenario to test]

### Integration Tests
- [ ] [API/service flow to test]

### Manual Test Cases
- [ ] [Step-by-step]
```

---

### Step 5: Present to Developer

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⏸️  GATE 1: REQUIREMENT DOCUMENT READY

Ticket: [ticket-id] — [title]
File:   AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md

Summary:
  Type:     [feature / bug-fix / refactor]
  Impact:   [Low / Medium / High]
  Estimate: [S / M / L / XL]
  Approach: [one-line description]

Please review the requirement document.
  → Type APPROVED to proceed to implementation plan
  → Or provide feedback to update the document

⚠️  I will NOT generate code until I receive "APPROVED".
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

---

### Step 6: Handle Feedback

- DEV provides feedback → update `requirement.md` → re-show Gate 1 prompt
- DEV types `APPROVED` → proceed to Gate 2 (Implementation Plan)

---

## What This Skill Delegates vs Owns

| Concern | Handled by |
|---------|-----------|
| Fact/Assumption/Gap breakdown | This skill (inline, borrowed from `ba-skills` initial-analysis) |
| Q&A loop (one question at a time) | This skill (inline) |
| Propose 2–3 solution approaches | This skill (inline) |
| Root cause tracing (bug tasks) | `superpowers:systematic-debugging` |
| Dependency map (find all usage) | `impact-analysis` skill Step 1 methodology (reused inline) |
| Impact analysis (evaluate + classify) | `impact-analysis` skill Step 2–3 methodology (reused inline) |
| Effort estimate | This skill |
| requirement.md template & output | This skill |
| Gate 1 APPROVED gate | This skill |
| System Requirement creation/versioning/sync | `create-system-requirement` task type (separate, own 2 gates) |
| Mid-ticket addition proposal (Step 3.5 triggers it) | `create-system-requirement` owns the write contract (its Step 8) |

---

## Mandatory Rules

- ✅ **MUST** verify System Requirement exists and matches the current UC Spec version (Step 0) before proceeding — show a ⚠️ non-blocking warning and continue otherwise (never cancels Gate 1); record the gap in the requirement doc (Step 4).
- ✅ **MUST** read System Requirement as mandatory input (Step 1) — not optional context.
- ❌ **DO NOT** restate content already covered in System Requirement — reference its item ID instead.
- ❌ **DO NOT** silently accept ticket scope that doesn't trace to System Requirement or UC Spec (Step 3.5) — stop and ask instead of guessing.
- ❌ **DO NOT** invoke `superpowers:brainstorming` — its terminal state calls `writing-plans` and bypasses Gate 1 approval
- ❌ **DO NOT** invoke `superpowers:writing-plans` — that belongs to Gate 2 (`generate-spec` skill)
- ❌ **DO NOT** proceed past Step 2 if design is not confirmed by developer
- ❌ **DO NOT** write code at any point in this skill
- ❌ **DO NOT** skip impact analysis and effort estimate
- ✅ **MUST** run `git status` + `git pull --ff-only` (Pre-flight) before reading source code, when working tree is clean
- ✅ **MUST** read source code before Q&A begins
- ✅ **MUST** (in `auto`/`full` mode) map dependencies (`impact-analysis` Step 1) for every file identified as affected, before Q&A — `fast` mode is exempt by design
- ✅ **MUST** classify Facts/Assumptions/Gaps (Step 1.75) before asking Q&A questions, in `auto`/`full` mode
- ❌ **DO NOT** write the Impact Analysis section from guesswork — it must be based on the Dependency Map found in Step 1
- ✅ **MUST** save `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md`
- ✅ **MUST** display Gate 1 prompt and wait for `APPROVED`
