# Quick Start — AI Flow Kit

> Full workflow: [AIFLOW.md](./AIFLOW.md)

---

## Installation

```bash
npm install -g @relipa/ai-flow-kit

# Beta version (recommend for newest features)
npm install -g @relipa/ai-flow-kit@beta

# Verification
aiflow --version       # or short: aiflow -v

# Uninstall
npm uninstall -g @relipa/ai-flow-kit
```

---

## Project Setup (One-time)

```bash
cd your-project

# Single framework + adapter
aiflow init --framework spring-boot --adapter backlog

# Or multiple
aiflow init --framework spring-boot,reactjs --adapter backlog,jira
```

During init:
- Enter `BACKLOG_API_KEY` and `BACKLOG_SPACE_KEY` when prompted
- Press Enter to keep the old value (if previously set up)
- The package automatically verifies credentials right after input

Results after init:
```
✓ Superpowers skills ready (built-in)
✓ Applied java rules
✓ CLAUDE.md updated for framework: spring-boot
✓ Credentials verified successfully
✓ Superpowers SessionStart hook configured
✨ Initialized AI Flow Kit successfully!
```

Check setup:
```bash
aiflow doctor
```

---

## Complete Developer Workflow (Start → Finish)

> **5-Gate workflow: Gate must pass in order. No skipping.**
>
> See [AIFLOW.md](./AIFLOW.md) for full details on each gate.

### Step 1: Load ticket context

```bash
# Load from Backlog (description only)
aiflow use PROJ-33

# Load with comments (recommended for bug-fix)
aiflow use PROJ-33 -c

# Load from Backlog URL
aiflow use https://mycompany.backlog.com/view/PROJ-33

# Load newest 5 comments
aiflow use PROJ-33 --clast 5

# Multi-target — primary ticket + supplementary sources (v0.1.0+)
aiflow use PROJ-33 PROJ-10 docs/arch.md
# PROJ-33 drives Gate 1; PROJ-10 + docs/arch.md become supplementary context

# Manual input (no Backlog/Jira)
aiflow use --manual

# Load from local file (JSON or plain text)
aiflow use --file task-description.txt
```

> **Auto Link Resolution (v0.1.0+):** Backlog/Jira URLs in the primary ticket's description are auto-fetched and added to `supplementaryContext[]`. Comment links (`#comment-456`, `?focusedCommentId=456`) fetch **only that comment**. AI integrates these supplementary sources in Gate 1 analysis automatically.

Output:
```
✓ Context loaded

  Ticket:   PROJ-33
  Type:     bug-fix
  Title:    [ticket title]
  Status:   In Progress
  Assignee: yourname
```

### Step 2: Open Claude — AI auto-starts

```bash
claude                        # AI auto-starts Gate 1 immediately
```

### Step 3: Approval & Session Refresh

After the AI finishes its task at any Gate (e.g., Gate 1 Requirement Analysis), and you are ready to move to the next gate:

1. Review the output.
2. Type **APPROVED** to finish the current gate.
3. Run **`aiflow task next`**. This command will:
   - Finalize the current gate state.
   - Generate a `task-summary.md` report.
   - Prepare the task for the next stage.
4. **Important:** Open a **fresh chat session** (new chatbox) and type `continue` to start the next gate. This ensures the AI has a clean context.

### Step 4: Resume Task

If you switched tasks or started a new session:

```bash
# Resume the most recent task
aiflow task resume

# Or resume a specific task
aiflow task resume PROJ-33
```
Then open Claude and the AI will auto-detect the current gate and resume exactly where you left off.

> **Note:** `aiflow prompt` is optional — only needed when pasting into Claude Desktop/Web.
>
> **Multi-Tool Support:**
> - If using **Cursor**: Gate Workflow is enforced via `.cursorrules`.
> - If using **Gemini CLI**: Rules are loaded from `GEMINI.md`.
> - If using **Codex** (VS Code extension, ChatGPT desktop app, or CLI): rules are loaded from `AGENTS.md`. Codex has no session-start hook — start a **new** Codex session after `ak use`, then run `/ak-coding`.
> - The AI will automatically detect if you are mid-task by reading `.aiflow/context/current.json`.

### Step 3: GATE 1 — AI Analyzes Requirement

**What happens:** AI reads your ticket + source code + asks questions.

> [!NOTE]
> **Fast Mode** is now the default. AI aims for a quick scan and minimal Q&A to get you coding in < 5 mins.
> Use `aiflow use TICKET --full` if you want the AI to perform a deep, exhaustive analysis (Gate 1 Full).

When you open Claude, AI will **automatically** start analyzing:

1. **Read ticket** from `.aiflow/context/current.json`
2. **Read source code** — understand architecture, related files, data flow
3. **Ask clarifying questions** (one at a time) if anything is unclear
4. **Output** `plan/PROJ-33/requirement.md` containing:
   - Requirements summary (AI's technical understanding)
   - Source code analysis (related files, data flow, patterns)
   - **Proposed solution** with recommendation
   - **Impact analysis** — what areas are affected, risks
   - **Effort estimate** (S/M/L/XL)
   - Testing plan

**Your action:** Review the requirement document.

```
# If satisfied:
APPROVED

# If something needs to change:
"The solution should use Redis cache instead of in-memory"
→ AI updates the document and asks again
```

### Step 4: GATE 2 — Review Implementation Plan

**What happens:** AI creates a detailed coding plan based on the approved requirement.

AI outputs:
- TDD task breakdown (test first → implement → verify)
- Verification strategy (evidence before claims)
- Test commands

**Your action:**

```
# If the plan looks good:
APPROVED

# If you want changes:
"Split task 3 into smaller steps"
→ AI adjusts the plan
```

### Step 5: GATE 3 — AI Generates Code (TDD)

**What happens:** AI writes code following the approved plan.

- Writes tests FIRST → runs → confirms FAIL
- Implements code → tests PASS
- Verifies implementation works

**Your action:** Monitor. No action needed unless AI asks a question.

### Step 6: GATE 4 — Review AI's Work

**What happens:** AI self-reviews before showing you.

AI runs automatically:
1. `verification-before-completion` — all tests PASS
2. `impact-analysis` — no breaking changes
3. Review checklist — all items checked
4. Creates `plan/PROJ-33/summary.md`

Then shows you:
```
⏸️ GATE 4: WAITING FOR DEV REVIEW

Tests: ✅ 12 passed
Impact: 🟢 Low
Checklist: 7/7 ✅
Summary: plan/PROJ-33/summary.md
```

**Your action:**

```
# If everything is OK:
APPROVED

# If there's a bug in the code:
BUG: The cache invalidation doesn't handle concurrent writes

# If the requirement was wrong:
BUG: Actually we need to support pagination, not just single page
→ AI goes back to Gate 1 to update requirement
```

### Step 7: GATE 5 — Create PR & Peer Review

**What happens:** AI helps create the Pull Request.

```bash
git push origin feature/PROJ-33-description
# AI suggests PR title, description, and checklist
```

Ask a teammate to review. They can use `superpowers:receiving-code-review` skill.

After peer reviewer approves → merge → task complete.

### Step 9: Task Management & Session Continuity

Manage multiple tasks and ensure clean transitions between gates to prevent "context pollution" in long AI sessions.

```bash
# Pause current task (saves gate progress)
aiflow task pause --note "Waiting for PM clarification"

# List all tasks
aiflow task list

# Resume a previously paused task
aiflow task resume PROJ-33

# Approve gate and prepare for fresh session (Recommended)
aiflow task next
```

#### Best Practice: Refreshing Sessions
To keep the AI focused and avoid context pollution (where the AI gets confused by long chat history), it is recommended to start a **fresh chat session** after completing each gate.

1. Run `aiflow task next` in your terminal to approve the current gate.
2. Open a **NEW chatbox** (Claude UI, Cursor, etc.).
3. Run `aiflow task resume [ticket-id]` (if not already active).
4. Type **"continue"** — the AI will read the latest state and start the next gate with a clean slate.

#### Resuming Gate 3 (Code Generation)
If you need to switch chatboxes in the middle of a complex coding task (Gate 3):
- Gate 3 progress is saved via `[x]` checkboxes in the plan file (`plan/[id]/plan.md`).
- Simply open a new chatbox, run `aiflow task resume`, and tell the AI to **"continue executing the plan"**.
- The AI will automatically skip finished tasks and pick up exactly where you left off.


---

## Workflow Summary Diagram

```
Developer                          AI                              Peer
   │                                │                                │
   │  aiflow use PROJ-33            │                                │
   │  claude                        │                                │
   │                                │                                │
   │  ─── GATE 1 ──────────────────►│                                │
   │                                │  Read ticket + source code     │
   │                                │  Ask questions (1 at a time)   │
   │  ◄─── requirement.md ─────────│                                │
   │                                │                                │
   │  "APPROVED" ──────────────────►│                                │
   │                                │                                │
   │  ─── GATE 2 ──────────────────►│                                │
   │                                │  Create implementation plan    │
   │  ◄─── plan ───────────────────│                                │
   │                                │                                │
   │  "APPROVED" ──────────────────►│                                │
   │                                │                                │
   │        GATE 3                  │  Write tests → implement       │
   │        (monitor)               │  Verify implementation works   │
   │                                │                                │
   │  ─── GATE 4 ──────────────────►│                                │
   │                                │  Self-review + summary         │
   │  ◄─── summary.md ────────────│                                │
   │                                │                                │
   │  "APPROVED" ──────────────────►│                                │
   │                                │                                │
   │  ─── GATE 5 ─────────────────────────────────────────────────►│
   │                                │                         Review PR
   │  ◄──────────────────────────────────────────── APPROVED ──────│
   │                                │                                │
   │  Merge ✅                      │                                │
```

---

## Use Cases

### Bug Fix

```bash
aiflow use PROJ-33 --with-comments
claude                                # AI auto-starts: analyze bug → trace root cause → propose fix
```

### New Feature

```bash
aiflow use PROJ-99
claude                                # AI auto-starts: analyze requirements → propose architecture
```

### Investigation (no coding)

```bash
aiflow use PROJ-50
claude                                # AI auto-starts: investigate → output findings report
```

### Refactoring

```bash
aiflow use PROJ-77
claude                                # AI auto-starts: analyze impact → plan refactor steps
```

### Impact Analysis (no coding)

```bash
aiflow use PROJ-88
claude                                # AI auto-starts: map dependencies → assess risk → output report
```

### Execute Tests (QA Tester)

Run existing test cases with Playwright — sync scripts, execute, collect evidence, and generate report.

**Entry point 1: from a ticket** (ticket `type` must be `"execute"`)

```bash
aiflow use PROJ-44        # loads ticket with taskType "execute"
claude                    # AI auto-starts execute-flow Gate 1 (pre-flight check)
```

**Entry point 2: from a TC file**

```bash
ak execute ./testcases/AD10.md        # AI starts execute-flow with this TC file
```

**Entry point 3: manual**

```bash
ak execute                            # AI asks: "TC file ở đâu?"
```

Evidence (screenshots/video/trace.zip) lands in `AK-Docs/03.Testing/04.Evidence/{repo}/{featureDir}/run-{N}/` — never deleted between runs. Scripts, result/report/bug docs live in `AK-Docs/03.Testing/` instead (05.Scripts / 02.Reports / 06.Bugs) so they're versioned with the rest of the project's docs, while binary evidence stays out of that git history.

### Figma Design → Code

Turn a Figma design into a React / Next.js / Vue / Angular component automatically.

**Step 1: Set up Figma MCP adapter (one-time)**

Choose one option:

| Option | Command | Requirement |
|--------|---------|-------------|
| Figma Desktop (recommended) | `ak init -a figma-desktop` | Figma Desktop app installed and open |
| Figma REST API | `ak init -a figma` | Figma Personal Access Token (`figd_...`) |

```bash
# Option A: Figma Desktop — no API token needed, uses Desktop session
ak init -a figma-desktop

# Option B: Figma REST API — requires Personal Access Token
ak init -a figma
# Enter your token when prompted (Settings → Security → Personal access tokens)
```

**Step 2: Get the Figma node URL**

In Figma Desktop or web, right-click the frame/component → **Copy link to selection**.

URL format: `https://www.figma.com/design/<fileKey>/...?node-id=<nodeId>`

**Step 3: Trigger the skill in Claude**

```
Generate component from this Figma frame:
https://www.figma.com/design/abc123/MyDesign?node-id=12:34
```

Claude uses the `figma-to-component` skill and auto-detects your framework (Next.js App Router, React, Vue, Angular).

> Full guide: [docs/common/workflows/figma.md](./workflows/figma.md)

---

## All Commands

> **Tip:** All commands support a short alias. Use `ak` instead of `aiflow` and the alias instead of the full command name (e.g. `ak t st` = `ak task status`).

```bash
# Setup
ak init --framework nestjs --adapter backlog   # (ak i -f nestjs -a backlog)
ak init --fw spring-boot --with-rtk            # --fw alias for --framework, RTK: bash compression (60–90%)
ak init --no-rtk                               # skip RTK setup
ak dr                                          # health check  (ak doctor)
ak g                                           # multi-tool guide  (ak guide)
ak g -f                                        # architecture diagram  (ak guide --flow)
ak g -c                                        # command reference  (ak guide --commands)
ak sync                                        # sync aiflow instruction files  (ak sync-skills)

# Execute flow (QA Tester)
ak execute PROJ-44                             # execute từ ticket (taskType phải là "execute")
ak execute ./testcases/AD10.md                 # execute từ TC file
ak execute                                     # execute manual (AI hỏi TC file)

# Per task
ak use PROJ-33                                 # load context (Fast Mode, default) — alias: ak u PROJ-33
ak use PROJ-33 PROJ-10 docs/arch.md            # multi-target: primary + supplementary (v0.1.0+)
ak use PROJ-33 -F                              # Fast Mode explicit  (--fast)
ak use PROJ-33 -U                              # Full Mode  (--full)
ak use -f task.md                              # load from local file  (--file)
ak use PROJ-33 -c                              # load with all comments  (--coms)
ak use PROJ-33 --clast 5                       # newest 5 comments
ak use -m                                      # manual input  (--manual)
ak fetch-links "<backlog-or-jira-url>"         # fetch single link → JSON (used by AI runtime, v0.1.0+)
ak p bug-fix                                   # generate prompt  (ak prompt)
ak p feature -o p.md                           # save prompt to file  (--output)
ak p -L vietnamese                             # Vietnamese prompt  (--lang)
ak p -l                                        # list prompt types  (--list)

# Task management
ak t st                                        # show active and pending tasks  (ak task status)
ak t ls                                        # list all saved tasks  (ak task list)
ak t p                                         # pause current task  (ak task pause)
ak t p -n "waiting for PM"                     # pause with note  (--note)
ak t sw PROJ-99                                # switch to another task  (ak task switch)
ak t r PROJ-33                                 # resume a paused task  (ak task resume)
ak t rst PROJ-33                               # reset to Gate 1  (ak task reset)
ak t rm PROJ-33                                # permanently delete task data  (ak task remove)
ak t n                                         # approve gate & prep next session  (ak task next)

# Context management
ak ctx show                                    # view active context  (ak context show)
ak ctx list                                    # list saved contexts
ak ctx save my-snapshot                        # save named snapshot
ak ctx -l my-snapshot                          # load named snapshot  (--load)
ak ctx clear                                   # clear active context

# Team knowledge
ak mem s "key" "value"                         # save knowledge  (ak memory save)
ak mem g "key"                                 # retrieve  (ak memory get)
ak mem sr "keyword"                            # search  (ak memory search)
ak mem ls                                      # list all  (ak memory list)
ak mem d "key"                                 # delete  (ak memory delete)
ak mem cl                                      # clear all  (ak memory clear)

# Utilities
ak vl src/File.java                            # validate code  (ak validate)
ak vl src/File.java -x                         # validate and auto-fix  (--fix)
ak d "description"                             # detect task type  (ak detect)

# Maintenance
ak rm                                          # remove from project  (ak remove)
ak rm -g                                       # uninstall globally  (--global)
ak up                                          # update to latest  (ak update)
ak up -f                                       # force update  (--force)
npm uninstall -g @relipa/ai-flow-kit                   # standard npm uninstall
```

---

## Documentation Files

After installing `ai-flow-kit`, these docs are available:

| File | Description |
|------|-------------|
| [QUICK_START.md](./QUICK_START.md) | This file — step-by-step guide for developers |
| [AIFLOW.md](./AIFLOW.md) | Complete 5-Gate workflow: who does what, outputs, templates |
| [README.md](./README.md) | Package overview, architecture, all features |
| [CHANGELOG.md](./CHANGELOG.md) | Version history |
| [IMPLEMENTATION_SUMMARY.md](./IMPLEMENTATION_SUMMARY.md) | Technical implementation details |
| [workflows/](./workflows/) | Per-task-type workflow guides |
| [architecture.md](./architecture.md) | System architecture |
| [cli-reference.md](./cli-reference.md) | CLI command reference |
| [configuration.md](./configuration.md) | Configuration guide |
| [troubleshooting.md](./troubleshooting.md) | Common issues & fixes |
| [getting-started.md](./getting-started.md) | Getting started guide |

Access docs after install:
```bash
# Docs are in the package directory
npm root -g     # find global packages directory
# → <path>/@relipa/ai-flow-kit/AIFLOW.md, QUICK_START.md, etc.

# Or use the built-in guide
aiflow guide
```

---

## Troubleshooting

**`aiflow` not found:**
```bash
npm install -g @relipa/ai-flow-kit
```

**Incorrect credentials:**
```bash
# Re-running will prompt again; press Enter to keep the old value
aiflow init --adapter backlog
```

**Context not loading:**
```bash
# Check if credentials are saved
cat .aiflow/credentials.json

# Try loading again
aiflow use PROJ-33
```

**Skills not working in Claude:**
```bash
# init must be run outside the Claude terminal (once)
# Then reopen Claude
aiflow doctor
```

**Need to see all available prompt types:**
```bash
aiflow prompt --list
```

See more: [docs/troubleshooting.md](./docs/troubleshooting.md)
