# AI Flow Kit

**All-in-one package for software development teams using Claude AI.**

Developers only need a single command to load ticket context → AI automatically understands the requirements, chooses the workflow, and follows team rules — no long prompts needed, no need to know the templates.

---

## Problems Solved

| Problem | Solution |
|--------|-----------|
| Multi-step, complex installation | `ak init` — 1 command to set up everything |
| Need long prompts for AI to understand | `ak use PROJ-33` — AI automatically reads from ticket |
| Too many templates, not sure which to use | AI auto-detects task type and selects the appropriate skill |
| New plugins (superpowers, MCP...) require manual setup | Package auto-sets up hooks, skills, and MCP on init |
| Missing investigation / bug reproduction flow | Skill `investigate-bug` (inherits systematic-debugging) |
| Missing impact analysis flow | Skill `impact-analysis` |
| Hard to resume tasks | **State Resumption**: Unified `plan/` docs, `task-summary.md` progress tracking, and intelligent session continuity (automatic Gate 3 resumption). |
| BA writing specs without a structured workflow | `ak use PROJ-33` (taskType: spec) → AI follows 4-gate BA workflow (Q&A → Prototype → UC Spec) |
| QA creating test cases manually without structure | `ak use PROJ-33` (taskType: testcase) → AI follows 4-gate QA workflow (Analysis → Scenarios → Detailed TCs → Review) |
| Gate transitions happen without formal approval | Gate review protocol — each gate requires explicit `APPROVED` before AI advances to the next gate |

## Documentation & Guides

> [!TIP]
> After running `ak init`, documentation files are automatically copied to `.aiflow/docs/` in your project for easy access.

- **[Quick Start Guide](https://github.com/example/ai-flow-kit/blob/main/docs/common/QUICK_START.md)** — Step-by-step instructions for developers.
- **[Full Workflow (5 Gates)](https://github.com/example/ai-flow-kit/blob/main/docs/common/AIFLOW.md)** — In-depth look at the Gate process.
- **[Troubleshooting](https://github.com/example/ai-flow-kit/blob/main/docs/common/troubleshooting.md)** — Common issues and fixes.
- **[Integration Guide](https://github.com/example/ai-flow-kit/blob/main/docs/common/ai-integration.md)** — Advanced tool setup (Claude, Codex, Cursor, Gemini).
- **[Changelog](https://github.com/example/ai-flow-kit/blob/main/docs/common/CHANGELOG.md)** — Version history and release notes.

---

## Coding Flow

```
PM writes ticket on Backlog/Jira
        │
        ▼
⛩️ GATE 1 — AI Analyze Requirement          [AI + DEV]
  ak use PROJ-33   →   claude
  AI loads ticket + reads source code
  AI asks clarifying questions (max 1 in Fast mode)
  AI outputs: plan/PROJ-33/requirement.md (Lite in Fast mode)
  DEV reviews → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 2 — Implementation Plan             [AI + DEV]
  AI creates detailed coding plan (TDD steps)
  DEV reviews → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 3 — Code Generation (TDD)           [AI]
  AI writes tests first → implement → tests pass
  Verify implementation works
        │ Code done
        ▼
⛩️ GATE 4 — AI Self-Review                  [AI + DEV]
  AI runs: verification + impact-analysis + checklist
  AI generates: plan/PROJ-33/task-summary.md
  DEV reviews → "APPROVED" or "BUG: [description]"
        │ APPROVED
        ▼
⛩️ GATE 5 — Peer Review & PR                [DEV + Peer]
  Create Pull Request → peer review → merge
        │
        ▼
       DONE
```

---

## Execute Test Flow

```
ak execute PROJ-44  (or ./testcases.md  or  ak execute)
        │
        ▼
⛩️ GATE 1 — Pre-flight & Work Plan           [AI + QA]
  Parse TC file → verify AK-Docs/03.Testing/ subfolders exist
  Check BASE_URL env var + playwright.config.ts + .gitignore covers 04.Evidence/
  Create execution work plan
  QA reviews → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 2 — Script Sync                      [AI]
  Hash-based TC↔script sync
  Generate new / update changed / skip unchanged
  Uses Playwright MCP for selectors — never fabricates
        │ Scripts synced
        ▼
⛩️ GATE 3 — Execute & Evidence               [AI + QA]
  Run: npx playwright test
  Organize evidence per run-{N}/: screenshots, trace.zip, result.md
  Auto-draft bug files for failed TCs
  Support RETEST: [TC_ID] loop
  QA reviews → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 4 — Report & Bug Logging             [AI + QA]
  Generate testreport.md with Go/No-Go recommendation
  Log each failed TC to Jira/Backlog — interactive confirm per bug
  QA reviews → "APPROVED"
        │
        ▼
       DONE
```

> **Entry points:** `ak execute PROJ-44` (from ticket) · `ak execute ./testcases/AD10.md` (from file) · `ak execute` (manual — AI asks for TC file path)

---

## Create Spec Flow

```
ak use PROJ-33  (taskType: spec)  →  claude
        │
        ▼
⛩️ GATE 1 — Phân tích Yêu cầu Ban đầu        [AI + BA]
  AI đọc ticket, phân tích yêu cầu, phân loại Facts vs Assumptions
  AI phát hiện Gaps và tạo danh sách câu hỏi Q&A cần làm rõ
  BA review Q&A → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 2 — Q&A Loop & Confirm               [AI + BA]
  AI cập nhật phân tích theo từng câu trả lời của BA
  AI re-check Q&A đến khi tất cả được xác nhận (Confirmed)
  BA xác nhận toàn bộ Q&A → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 3 — Prototype Design                  [AI + BA]
  AI tạo HTML/CSS prototype cho các màn hình chính
  BA review UI flow → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 4 — UC Spec hoàn chỉnh               [AI + BA]
  AI tạo đầy đủ UC Spec document (flows, business rules, validations)
  BA review → "APPROVED"
        │
        ▼
       DONE
```

> **Entry point:** `ak use PROJ-33` → chọn taskType **"spec"** trong danh sách — AI tự động khởi chạy BA workflow.

---

## Create Testcase Flow

```
ak use PROJ-33  (taskType: testcase)  →  claude
        │
        ▼
⛩️ GATE 1 — Phân tích Yêu cầu & Rủi ro      [AI + QA]
  AI đọc ticket/spec, phân tích scope và rủi ro
  AI đọc source code để tìm validation rules và business logic ẩn
  AI đặt câu hỏi làm rõ yêu cầu
  QA review → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 2 — Xây dựng Scenarios & Checklist   [AI + QA]
  AI generate checklist theo nhóm (Functional, Non-functional, Data, Regression)
  AI kiểm tra Dev Artifacts (PR diff) để bổ sung regression TCs
  AI output: test-plan/checklist.md
  QA review → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 3 — Thiết kế Test Case chi tiết      [AI + QA]
  AI tạo bảng test case đầy đủ (TC_ID, Steps, Expected Result)
  AI áp dụng kỹ thuật: BVA, Equivalence Partitioning, Decision Table
  AI output: test-plan/test-cases/
  QA review → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 4 — Review & Tối ưu                  [AI + QA]
  AI review coverage, loại bỏ duplicate, bổ sung edge cases còn thiếu
  AI export final test case set: test-plan/test-cases/final-testcases.md
  QA review → "APPROVED"
        │
        ▼
       DONE
```

> **Entry point:** `ak use PROJ-33` → chọn taskType **"testcase"** trong danh sách — AI tự động khởi chạy QA workflow.

---

## Create System Requirement Flow

```
ak use PROJ-33  (taskType: create-system-requirement)  →  claude
        │
        ▼
⛩️ GATE 1 — Investigate UC & Draft             [AI + BA/Dev]
  AI resolve UC Spec version hiện tại của functionId
  AI đọc source code + convention error-handling hiện có
  AI dịch từng Flow step + Business Rule → FR/NFR/Validation Rules/Exception Handling
  AI viết Acceptance Test scenarios (Given/When/Then) — mọi item trace về đúng UC, không tự suy diễn
  Q&A từng câu một tới khi hết Gap chưa rõ → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 2 — Finalize & Approve                  [AI + BA/Dev]
  AI quyết định single-file vs split (mặc định 1 file 1-1 với UC Spec,
  chỉ split khi có tín hiệu đo được — fan-out business rule/module, quá nhiều flow, ~400 dòng)
  AI ghi AK-Docs/02.BA-Specs/00.Requirements/[functionId]/System-Requirement_v{N}.md
  (N khớp đúng version UC Spec đã trace, ghi trong header `UC-Spec-Version`)
  Review → "APPROVED"
        │
        ▼
       DONE — Coding Gate 1 (read-study-requirement) mới được phép chạy cho functionId này
```

> **Entry point:** `ak use PROJ-33` → chọn taskType **"📐 Create System Requirement"** trong danh sách. Đây là bước bắt buộc, chạy 1 lần cho mỗi `functionId` (không phải mỗi ticket) — Coding Gate 1 sẽ tự chặn (`⏸️ Gate 1 cancelled`) nếu System Requirement chưa tồn tại hoặc chưa khớp UC Spec version hiện tại.

---

## Ingest Data Flow

```
ak use <link hoặc paste text>  (taskType: ingest-data)  →  claude
        │
        ▼
⛩️ GATE 1 — Fetch, Classify, Draft              [AI + PM/BrSE/Comtor]
  Input: Backlog ticket/comment/Document/Wiki link · Jira ticket/comment link ·
         SharePoint link (chưa có connector — fallback paste text) · text thô
  AI resolve nguồn: `ak fetch-links <url>` (nếu là link) hoặc dùng text trực tiếp
  AI phân loại: QnA-Log / Meetings-Log / Confirmations-Log (hỏi lại nếu chưa rõ)
  AI soạn draft đầy đủ — kèm Nguồn / functionId / Người tổng hợp / Người approve tại nguồn
  Hiển thị draft nguyên văn, lặp sửa theo yêu cầu tới khi → "APPROVED"
        │ APPROVED
        ▼
⛩️ GATE 2 — Branch + Merge Request              [AI, chờ xác nhận từng bước]
  Ghi entry vào AK-Docs/01.QnA/{QnA-Log,Meetings-Log,Confirmations-Log}.md
  `ak docs branch [functionId] [ticketId] --yes` — chỉ chạy sau khi user xác nhận
  `ak docs submit --title "..." --yes` — chỉ chạy sau khi user xác nhận
        │
        ▼
       DONE — chờ PM review & merge MR vào main (không tự merge)
```

> **Entry point:** `ak use` → chọn taskType **"📥 Ingest Data"**, hoặc `ak use "<backlog/jira-url>"` rồi chọn taskType tương ứng. SharePoint chưa fetch được nội dung thật — paste trực tiếp nội dung comment/tài liệu vào chat thay vì dán link (xem `docs/internal/PM Workflow_v1.0.md` "Vấn đề 4").

---

## Installation

```bash
# Stable version (latest)
npm install -g @relipa/ai-flow-kit@latest

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

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

---

## Commands

| Command | Description |
|---------|-------------|
| `ak init` | Setup framework, adapters, and multi-AI rules. |
| `ak use <ticket...>` | Load context from one or more tickets/files. First target is primary; rest become supplementary. |
| `ak execute <target>` | **QA:** Execute test cases — load TC file, sync Playwright scripts, run and collect evidence. |
| `ak fetch-links <url>` | Fetch a Backlog/Jira link and print SupplementaryContext JSON (used by AI at runtime). |
| `ak task` | Manage multiple tasks — pause, switch, resume. |
| `ak task next` | Finalize gate approval and prepare for fresh session. |
| `ak prompt` | Generate tool-optimized prompts (`--env cursor`). |
| `ak sync-skills` | Manually synchronize AI Instruction files with local custom skills. |
| `ak telemetry` | Manage telemetry tracking (enable/disable/status). |
| `ak guide` | View integrated multi-AI integration guide. |
| `ak doctor` | Check setup health and token savings status. |
| `ak update` | Update skills, rules, and templates to the latest version. |
| `ak remove` | Remove ai-flow-kit scaffolding from project. |
| `ak detect "<description>"` | Auto-detect task type from a description string. |
| `ak validate <file>` | Validate code output against team rules. |
| `ak memory` | Save/search team knowledge base. |
| `ak context` | Manage saved contexts (show/list/save/load/delete/clear). |
| `ak gate <n> start\|approved` | Log gate transitions — called automatically by AI. |

### `ak init`

Initial setup for the project. Run once per project.

```bash
# Single framework + adapter
ak init --framework spring-boot --adapter backlog

# Enable token savings tools
ak init --with-rtk                     # RTK: compress bash outputs (60–90% reduction)
# ak init --with-gitnexus               # GitNexus: code intelligence (waits for index)
# ak init --with-gitnexus --no-wait     # GitNexus: index in background

# Multiple frameworks and adapters
ak init --framework spring-boot,reactjs --adapter backlog,jira
```

**What gets automatically set up:**
- `.claude/skills/` — superpowers skills + team custom skills
- `.claude/hooks/session-start.js` — SessionStart hook
- `.claude/settings.json` — hook configuration
- `.rules/` — team coding rules (based on framework language)
- `CLAUDE.md` — framework-specific AI prompt
- `.mcp.json` + Claude Desktop config — MCP adapter
- `.aiflow/credentials.json` — save API credentials

**Supported Frameworks:** `spring-boot`, `laravel`, `php`, `nestjs`, `reactjs`, `nextjs`, `vue-nuxt`, `nodejs-express`, `python`, `python-django`, `python-fastapi`

**Supported Adapters:** `backlog`, `jira`, `google-sheets`, `figma`, `figma-desktop`

**Figma adapters:**

| Adapter | Command | Auth | Requirement |
|---------|---------|------|-------------|
| `figma` | `ak init -a figma` | Personal Access Token (`figd_...`) | None — REST API |
| `figma-desktop` | `ak init -a figma-desktop` | Desktop session (no token needed) | Figma Desktop app installed & open |

> The `figma-desktop` adapter uses the official `@figma/mcp-server` package from Figma Inc. and is the recommended option if you already use Figma Desktop.
> See [Figma workflow guide](docs/common/workflows/figma.md) for usage with the `figma-to-component` skill.

---

### `ak execute <target>`

Execute test cases from a Backlog/Jira ticket, a TC file, or manually. The AI syncs Playwright scripts, runs them, collects evidence, and generates a test report.

```bash
# From a ticket (taskType must be "execute")
ak execute PROJ-44

# From a TC file directly
ak execute ./testcases/AD10.md

# Manual — AI asks for TC file path
ak execute
```

**What happens (4-gate Execute Flow):**
1. **Gate 1 — Pre-flight:** Parse TC file, verify `AK-Docs/03.Testing/` subfolders exist, check `BASE_URL`, `playwright.config.ts`, and `.gitignore` covers `04.Evidence/` — QA reviews → `APPROVED`
2. **Gate 2 — Script Sync:** Hash-based TC↔script sync — gen new, update changed, skip unchanged (never fabricates selectors — uses Playwright MCP)
3. **Gate 3 — Execute & Evidence:** Run Playwright from `AK-Docs/03.Testing/05.Scripts/`, evidence lands in `04.Evidence/` (gitignored) per `run-{N}/`, update TC file R1/R2 columns — QA reviews → `APPROVED`
4. **Gate 4 — Report & Bug Logging:** Generate `testreport.md`, ask per-bug Jira confirmation — QA reviews → `APPROVED`

> **Multi-AI:** Works with Claude, Codex, Gemini, Cursor, Copilot — the execute-flow skill is loaded via `ak init`/`ak up`.

---

### `ak sync-skills`

Synchronize AI instruction files (`CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, etc.), Skills, and Codex assets (`.codex/skills/`, `.codex/config.toml`) without upgrading the package version. 

```bash
ak sync-skills
```

**Features:**
- Intelligent marker-based updates (`<!-- aiflow-kit-start -->`)
- Confirmation prompts before overwriting custom rules
- English notifications and status reports

---

### `ak use <ticket...>`

Load ticket context into `.aiflow/context/current.json`. Accepts **one or more targets** (ticket ID, Backlog/Jira URL, or local file). The first target becomes the **primary context**; any additional targets are appended as **`supplementaryContext[]`** for AI to read alongside the primary.

```bash
# Single target (backward compatible)
ak use PROJ-33
ak use https://mycompany.backlog.com/view/PROJ-33

# Multiple targets — primary + supplementary
ak use PROJ-33 PROJ-10 docs/arch.md
# PROJ-33 drives Gate 1; PROJ-10 + docs/arch.md become supplementary context

# Backlog / Jira ticket
ak use PROJ-123

# Comments
ak use PROJ-33 --with-comments
ak use PROJ-33 --comments-last 5
ak use PROJ-33 --comments-from 3

# Manual input
ak use --manual

# Load from local file (JSON or plain text)
ak use --file task.md      # Auto-generates taskId from filename & prompts for taskType

# Modes (Fast is default)
ak use PROJ-33          # Fast Mode: skip Q&A, target < 5 min
ak use PROJ-33 --full   # Full Mode: deep analysis with Q&A

# Save with custom name
ak use PROJ-33 --save sprint-42-bug
```

> **New in v0.1.0 — Auto Link Resolution:** When the primary ticket description contains Backlog/Jira URLs, `ak use` automatically fetches them and stores results in `supplementaryContext[]`. Comment links (`#comment-456` or `?focusedCommentId=456`) fetch **only that comment**. Capped at 5 auto-resolved links per `use` to keep loads fast.

---

### `ak fetch-links <url>`

Fetch a single Backlog/Jira link and print a `SupplementaryContext` JSON object to stdout. Intended for AI runtime use inside the `read-study-requirement` skill when a link is found in the ticket description that wasn't already resolved at `use` time.

```bash
# Backlog ticket → full ticket JSON
ak fetch-links "https://company.backlog.com/view/PROJ-10"

# Backlog comment → that single comment only
ak fetch-links "https://company.backlog.com/view/PROJ-10#comment-456"

# Jira ticket / comment
ak fetch-links "https://company.atlassian.net/browse/PROJ-10"
ak fetch-links "https://company.atlassian.net/browse/PROJ-10?focusedCommentId=789"
```

Output schema:

```json
{
  "sourceType": "ticket | comment",
  "sourceUrl": "...",
  "ticketId": "PROJ-10",
  "commentId": "456",
  "title": "...",
  "description": "...",
  "content": "...",
  "author": "...",
  "date": "..."
}
```

Exits non-zero with a stderr message if the URL is not a recognised Backlog/Jira pattern or fetching fails.

---

### `ak task`

Manage multiple tasks — pause a task, switch to another, and resume later while keeping full progress.

```bash
ak task status                  # show active task and pending tasks
ak task list                    # list all saved tasks
ak task pause                   # pause current task (saves context + gate progress)
ak task pause --note "waiting for API spec"   # pause with a note
ak task switch PROJ-99          # pause current + switch to another task
ak task resume PROJ-33          # resume a paused task (restores context + gate state)
ak task reset  PROJ-33          # reset to Gate 1 (keeps ticket context, clears progress)
ak task remove PROJ-33          # permanently delete all saved data for the task
ak task next                    # approve current gate + prepare for fresh session
ak task next --ticket PROJ-33   # same, but specify ticket explicitly
```

**Use case — switching tasks mid-flow:**

```bash
# Working on PROJ-33 at Gate 2...
ak task pause               # pauses and saves PROJ-33 progress

ak use PROJ-99              # loads urgent task (auto-pauses current)
claude                      # AI starts Gate 1 for PROJ-99

# Done with PROJ-99, resuming PROJ-33
ak task resume PROJ-33      # restores context
claude                      # AI resumes from Gate 2 automatically
```

Task state (context + gate progress) is saved in `.aiflow/tasks/<taskId>/`.

---

### `ak doctor`

Check if the setup is complete.

```bash
ak doctor
```

```
✓ .claude/skills exists (42 skills)
✓ .rules exists
✓ CLAUDE.md exists
✓ SessionStart hook configured
✓ Version tracking active (v1.0.0)
✨ Everything looks healthy!
```

---

### `ak update`

Update skills, rules, and templates to the latest version.

```bash
ak update
```

---

### `ak validate <file>`

Validate code output against team rules.

```bash
ak validate src/Payment.java --ruleset strict
```

---

### `ak memory`

Draft, submit, and remove entries in the `99.Memory/` Project Brain (`AK-Docs/99.Memory/`) — see [Memory-Architecture-v1.0.md](docs/common/Memory-Architecture-v1.0.md). Drafts are local-only until submitted; PM reviews and merges the Merge Request before a memory becomes team-visible.

```bash
ak memory draft --category 01.Lessons/dev --function-id F-003_Payment \
  --slug prevent-429-error --content "..." --tags payment,http-429 --workflows coding

ak memory list                 # local pending drafts (this machine only)
ak memory list --approved      # team-approved memories

ak memory submit <pendingPath> --title "..."   # move draft to destination, open MR
ak memory remove <path> --title "..." --reason "..."  # propose removal (soft by default)
```

---

## Available Skills

### Custom skills (team-specific)

| Skill | Trigger | Description |
|-------|---------|-------|
| `investigate-bug` | "fix bug", "error", "crash" | Investigate bugs via data flow, inherits `systematic-debugging` |
| `impact-analysis` | "impact scope", "breaking change" | Analyze the impact when changing code |
| `generate-spec` | "new feature", "spec", "design" | Write technical specs, integrates `brainstorming` |
| `report-customer` | "customer report", "incident" | Write incident reports for Customer Service |
| `figma-to-component` | "figma", "design", "generate component" | Read Figma design → generate React/Next.js App Router/Vue/Angular component. [Workflow guide](docs/common/workflows/figma.md) |
| `generate-testcase` | "create testcase", "test case", "QA checklist" | Generate detailed test cases from requirements (4-phase: Analysis → Checklist → TC Table → Review) |
| `execute-flow` | "execute test", "run test", taskType: execute | 4-gate test execution orchestrator with Playwright MCP |
| `create-spec` | taskType: spec | BA 4-gate UC Spec workflow (Q&A → Prototype → UC Spec) |
| `create-testcase` | taskType: testcase | QA 4-gate testcase creation workflow (Analysis → Scenarios → TCs → Review) |

### Superpowers skills (upstream, inherited from obra/superpowers)

| Skill | Description |
|-------|-------|
| `systematic-debugging` | Core debugging methodology — NO FIX WITHOUT ROOT CAUSE |
| `brainstorming` | Explore requirements before coding |
| `writing-plans` | Create bite-sized implementation plans |
| `executing-plans` | Execute plans with review checkpoints |
| `test-driven-development` | RED→GREEN→REFACTOR |
| `subagent-driven-development` | Dispatch subagents for independent tasks |
| `requesting-code-review` | Review code before merging |
| `verification-before-completion` | Verify before claiming done |
| `using-git-worktrees` | Isolated workspace for feature work |
| `finishing-a-development-branch` | Complete branch and merge options |

---

## Framework Templates

| Framework | Language | Rules applied |
|-----------|---------|--------------|
| `spring-boot` | Java 17+ | `rules/java/` |
| `laravel` | PHP 8.1+ | `rules/php/` |
| `php` | PHP 8.1+ (no framework) | `rules/php/` |
| `nestjs` | TypeScript | `rules/javascript/` |
| `reactjs` | TypeScript | `rules/javascript/` |
| `nextjs` | TypeScript | `rules/javascript/` |
| `vue-nuxt` | TypeScript | `rules/javascript/` |
| `nodejs-express` | JavaScript/TypeScript | `rules/javascript/` |
| `python` | Python (no framework) | — |
| `python-django` | Python | — |
| `python-fastapi` | Python | — |

---

## Project Structure

```
ai-flow-kit/
├── README.md                        # Main documentation
├── bin/aiflow.js                    # CLI entry
├── docs/
│   ├── common/                      # Published with package
│   │   ├── QUICK_START.md           # Quick start guide
│   │   ├── AIFLOW.md                # Workflow (5 Gates) detail
│   │   ├── CHANGELOG.md             # Version history
│   │   ├── cli-reference.md         # Full CLI reference
│   │   └── workflows/               # Per-task workflow guides
│   └── project/                     # Project template files
│       └── ARCHITECTURE.md          # Architecture doc template
├── scripts/
│   ├── init.js                      # Project initialization
│   ├── update.js                    # Version management
│   ├── doctor.js                    # Health check
│   ├── use.js                       # Context loading (Backlog/Jira)
│   ├── config.js                    # Config system
│   ├── detect.js                    # Task type detection
│   ├── validate.js                  # Code validation
│   ├── memory.js                    # Knowledge management
│   └── hooks/session-start.js       # SessionStart hook (Node.js)
├── custom/
│   ├── skills/                      # Team-specific AI skills
│   ├── rules/java/                  # Java/Spring Boot rules
│   ├── rules/php/                   # PHP/Laravel rules
│   ├── rules/javascript/            # JS/TS rules
│   ├── templates/                   # Framework tool templates
│   ├── prompts/                     # Task prompt templates
│   └── mcp-presets/                 # Backlog/Jira/Sheets config
└── upstream/                        # obra/superpowers (inherited)
```

---

## Adding new frameworks / adapters

**New Framework:** create `custom/templates/<name>.md` + `custom/rules/<lang>/`

**New Adapter:** create `custom/mcp-presets/<name>.json`

**Custom skill:** create `custom/skills/<name>/SKILL.md`

Then run `ak update` or `ak sync-skills` to apply.

---

## Usage Environments

| Environment | Experience | Notes |
|-----------|------------|---------|
| Claude Code CLI (`claude`) | ⭐⭐⭐⭐⭐ | Full auto — skills, hook, automatically loaded context |
| Codex — VS Code extension, ChatGPT desktop app, `codex` CLI | ⭐⭐⭐⭐ | `AGENTS.md` + auto-discovered `.codex/skills/` → `/ak-coding`. No session hook: start a new session after `ak use` |
| Claude Extension (VS Code) | ⭐⭐⭐ | `ak prompt <type>` → copy paste |
| Antigravity / Cursor | ⭐⭐⭐ | `ak prompt <type>` → copy paste |

---

## Release Notes

> Summary of major changes per version. See full details in [CHANGELOG.md](docs/common/CHANGELOG.md).

### v0.2.0 — 2026-08-04
- **New `create-system-requirement` task type (2-Gate):** bridges a UC Spec (BA) into a Dev-facing System Requirement scoped to a `functionId` (not a ticket) — Gate 1 investigates the UC + source code and drafts FR/NFR/Validation Rules/Exception Handling + Given/When/Then acceptance tests, Gate 2 finalizes and writes `AK-Docs/02.BA-Specs/00.Requirements/[functionId]/System-Requirement_v{N}.md`. Coding Gate 1 (`read-study-requirement`) now **blocks** with a Step 0 pre-check if this document is missing or stale against the current UC Spec version. See [Create System Requirement Flow](#create-system-requirement-flow).
- **New `ingest-data` task type (2-Gate) — for PM/BrSE/Comtor:** ingest a Backlog ticket/comment/Document/Wiki link, a Jira link, a SharePoint link, or pasted text into `AK-Docs/01.QnA/{QnA-Log,Meetings-Log,Confirmations-Log}.md`. Gate 1 fetches + classifies + drafts the entry for self-review; Gate 2 opens the branch + Merge Request via the existing `ak docs branch`/`ak docs submit`. SharePoint has no connector yet (no Microsoft Graph API/OAuth) — falls back to pasted text. See [Ingest Data Flow](#ingest-data-flow) and `docs/internal/PM Workflow_v1.0.md`.
- **`ak fetch-links` / `link-resolver.js` now fetch Backlog Document and Wiki links**, not just ticket/comment — `fetchBacklogDocument`, `fetchBacklogDocumentComment`, `fetchBacklogWiki`. Auto-resolution from a ticket description (`ak use`) still only follows ticket/comment links, capped at 5 — Document/Wiki/SharePoint are explicit single-URL lookups only.
- **`ak use` now captures `projectId`/`projectKey`** from the loaded Backlog/Jira ticket (`.aiflow/context/current.json` and `.aiflow/state.json`) — a first step toward letting a future "create ticket" flow default to the right Backlog/Jira project instead of asking every time.
- Fixed: **`ak use`'s "Task type:" selector crashed** (`CATEGORY_COLOR[cat] is not a function`) whenever it rendered the **"📐 Create System Requirement"** entry — the `"Dev"` category had no color mapping. Added.
- `docs/common/Docs-Management-Flow.md`'s branch+MR flow now explicitly covers `AK-Docs/01.QnA/`, not just `02.BA-Specs/`/`03.Testing/`/`04.Coding/`/`99.Memory/`.

### v0.1.9 — 2026-08-04
- **Codex (OpenAI) support — `ak init --env codex`:** One install covers all three local Codex surfaces, which share the same `CODEX_HOME` config, skills and MCP setup: the **VS Code extension**, **Codex mode in the ChatGPT desktop app**, and the **`codex` CLI**. Generates `AGENTS.md`, `.codex/skills/` (all kit skills, auto-discovered — the kit's `SKILL.md` layout is already Codex-compatible), `.codex/config.toml` (MCP servers mirrored from `.mcp.json`), and `.aiflow/instructions/`.
- **Four Codex entry-point skills:** `/ak-coding`, `/ak-create-spec`, `/ak-create-testcase`, `/ak-ask` — the same workflows Claude Code exposes as slash commands.
- **New "pointer" instruction-file layout:** Codex truncates the combined `AGENTS.md` chain at `project_doc_max_bytes` (32 KiB by default) and the full workflow set is ~115 KB, so inlining it the way `CLAUDE.md` does would silently cut instructions off mid-gate. `AGENTS.md` stays ~20 KB and links to `.aiflow/instructions/` instead. Existing tools are unaffected.
- **`ak doctor` gained a Codex section:** checks `AGENTS.md` against the active byte budget, the skill mirror, the workflow files, and MCP drift between `.mcp.json` and `.codex/config.toml`.
- **`ak remove` never deletes a hand-edited `.codex/config.toml`** — only one still carrying the `# ai-flow-kit managed` header. Same rule on write: an unmanaged config is left alone and the generated version goes to `.aiflow/reference/`.
- Fixed (critical): **`ak init`/`ak update` duplicated instruction-file content on every run for multi-framework projects**, and silently dropped the first framework's rules — each framework now gets its own marker block, replaced in place on re-run.
- Fixed: Gate 4/5 of the TESTER workflow pointed at `custom/skills/test-skills/...` paths that don't exist in a scaffolded project; `/coding` couldn't find the workflow under a pointer-layout instruction file.
- Removed: `review-checklist.md` (+ ML/Java variants) — an unverified "tick each item" list at Gate 4 that no CLI ever enforced. The `gate-review` checkbox mechanism that `ak review check` does enforce is untouched.

### v0.1.8 — 2026-07-24
- **`aiflow-help` skill — the AI can now answer questions about ai-flow-kit itself:** install/setup, roles, `AK-Docs` structure, CLI commands, the memory workflow. Triggers on an `AKQ:`/`[AKQ]:` prefix or a kit-usage question even with no ticket loaded, answers from `docs/common/INDEX.md` with the source file cited, and says plainly when a topic isn't documented instead of guessing.
- **`ak ask "<question>"`:** deterministic local keyword search across `docs/common/*.md` — no LLM, no network. Headings are weighted above body text; prints the top matches with the nearest heading and a snippet. Useful on Cursor/Gemini CLI, which have no semantic skill routing.
- **`/ak-ask "<question>"`:** explicit slash command for when a natural-language question would otherwise be mistaken for ticket work.
- **6 docs promoted `docs/internal/` → `docs/common/`:** `Project-Structure.md`, `BA-Specs-Structure.md`, `Coding-Structure.md`, `Testing-Structure.md`, `Memory-Architecture-v1.0.md`, `Docs-Management-Flow.md` — now shipped to every project via `.aiflow/docs/`, which is what makes the folder-structure questions answerable at all.
- Fixed: **`ak update` never refreshed `.aiflow/docs`** — it synced rules, framework files and commands but never called `copyDocsToProject`. Projects initialized before this release only got new docs by re-running `ak init`.

### v0.1.7 — 2026-07-20
- **`99.Memory/` Project Brain (Phase 1):** New git-based, human-approved team knowledge base in `AK-Docs/99.Memory/` — replaces the dead `.aiflow/memory/` JSON store. AI drafts lessons/facts/decisions locally; a human submits them via Merge Request, PM approves.
- **`ak memory draft|list|submit|remove`:** New CLI (`scripts/memory-store.js` + rewritten `scripts/memory.js`), reusing the same branch-then-MR pattern as `ak docs branch`/`ak docs submit`.
- **Session-start auto-recall:** `session-start.js` now loads the memory index plus the top-N memories relevant to the active ticket's functionId/workflow/tags into every session automatically.
- **Retrospect step added to every Gate workflow** (DEV, BA, QA): drafts a memory at the end of each gate — and immediately when a human gives `BUG:`/`REVISION:` feedback, not deferred to hindsight.
- **`ak init`/`ak update`** auto-bootstrap the `99.Memory/` skeleton, committed locally but never auto-pushed (`main` is a protected branch).
- Docs: new `docs/internal/Memory-Architecture-v1.0.md` describing the 4 operating flows (Init/Store/Load/Remove) and the scoring model.

### v0.1.6 — 2026-07-13
- **Mandatory Source & Docs sync at the start of every Gate** across DEV/TESTER/EXECUTE/BA/QA workflows — a shared pre-flight procedure pulls the source repo plus `AK-Docs`/`Shared-Docs` before each gate; failures warn but never block.
- **New `gen-doc` task type (2-Gate):** lightweight flow for ad-hoc documentation tasks — plan → generate + self-review, no TDD/coding gates.
- **Figma wired into the DEV workflow end-to-end (Gate 1→4):** design fetched once and cached, then reused through spec/implementation/review; new anti-429 rate-limit guard for Figma MCP calls.
- **`ak docs branch` / `ak docs submit`:** new CLI for the AI to create a docs branch and open a Merge Request — the same "never commits/pushes unasked" guarantee as elsewhere, extended to `AK-Docs`/`Shared-Docs`.
- Fixed: `ak prompt <type>` and `ak init`'s `.gitignore` still referencing the deprecated `plan/` convention.

### v0.1.5 — 2026-07-01
- **DEV workflow output migrated `plan/[ticket-id]/` → `AK-Docs/04.Coding/`** — same folder-per-feature/file-per-ticket convention BA/QA already used; new Gate 3 (`03.TDD-Notes/`) and Gate 5 (`05.Pull-Requests/`) artifacts.
- **Mandatory `functionId` pre-flight** extended to the DEV workflow (BA/QA already had it) — resolved from context, inferred from input, or asked directly; no gate output is written without it.
- **New `/coding` slash command** — manual fallback to start/resume the DEV workflow when the SessionStart auto-start message doesn't re-fire (e.g. ticket switched via `ak use` in another terminal while a session is already open).
- Testing skills consolidated into `custom/skills/test-skills/`; skill filenames standardized to English kebab-case.

### v0.1.4 — 2026-06-29
- **Create Spec Flow (4-Gate BA Workflow):** New `taskType: "spec"` — Q&A Analysis → Prototype Design → UC Spec. AI follows UCflow process guided by `ba-skills/` sub-skills.
- **Create Testcase Flow (4-Gate QA Workflow):** New `taskType: "testcase"` — Requirement Analysis → Scenario Building → Detailed TC Design → Review & Optimize. AI applies BVA, Equivalence Partitioning, Decision Table techniques.
- **BA Skills Library:** New `ba-skills/` skill set covering initial analysis, Q&A generation, business rules, UC spec writing, and Mermaid flow diagrams.
- **Test Skills Library:** New `test-skills/` skill set with 20+ sub-skills covering UI testing, business testing, data testing, integration testing, and domain-specific (CMS, E-commerce) test patterns.
- **Gate Review Protocol:** Explicit QA/BA `APPROVED` required at each gate before AI advances — eliminates silent gate skipping.
- **`gate-review` skill:** New orchestration skill that enforces the gate review protocol across all workflow types (coding, execute, spec, testcase).
- Documentation: README updated with Coding Flow, Create Spec Flow, Create Testcase Flow diagrams; `aiflow` CLI alias fully renamed to `ak` throughout.

### v0.1.3 — 2026-06-18
- **Execute Test Flow (4-Gate):** New `ak execute` command + `execute-flow` skill — Pre-flight → Script Sync → Execute & Evidence → Report & Bug Logging.
- **`script-sync` skill:** Hash-based TC↔Playwright script sync — gen new, update changed, skip unchanged. Uses MCP browser tools for selectors, never fabricates.
- **`ak execute` command** (`ak ex` alias): Standalone QA entry point — accepts ticket ID, TC file path, or interactive mode.
- **▶️ Execute Test** added to `ak use` type selector; `taskType: "execute"` routes AI to execute-flow skill automatically.
- **Playwright harness scaffold** (`ak scaffold playwright`): Creates full `ak-test/{repo}/` structure with config, fixtures, and page objects.
- Fixes: `screenId` casing ambiguity, `--reporter` flag overriding config reporters, Gate 1 missing `playwright.config.ts` check.

### v0.1.2 — 2026-06-13
- **Testing Workflow (4-Gate):** New `taskType: "testing"` — Test Analysis → Test Planning → Test Execution → Test Report. AI auto-routes skill per gate.
- **`python-ml` framework:** Supports scikit-learn / PyTorch / TensorFlow / MLflow / Wandb. Auto-detected from `requirements.txt` / `pyproject.toml`.
- **Task type selector in `ak use`:** Interactive list after loading ticket — auto-detects and pre-selects task type.
- **Critical fix — `update`/`init` not updating CLAUDE.md/GEMINI.md:** Fixed 3 compounding causes (`framework` singular vs. plural, missing `force: true`, per-file confirm dialogs).
- **Backup before overwrite:** AI instruction files backed up to `.aiflow/bk/YYYY-MM-DD_HH-MM_<filename>` before any overwrite.
- **`ak update` no longer wipes `.claude/`:** Now clears only `.claude/skills/`, preserving `settings.json` and hooks.

### v0.1.1 — 2026-06-08
- **Ubuntu/Linux clipboard in `ak prompt`:** Auto-detects display server (Wayland/X11) and package manager — offers to install clipboard tool if missing.
- **`figma-to-component` image detection & export:** Scans node tree for image nodes, exports to `public/assets/figma/`, renders with `<Image>`/`<img>`.
- **`figma-to-component` MCP pre-check (Step 0):** Verifies MCP connected before running; stops with setup instructions if not.
- **`figma-to-component` CSS tooling detection:** Branches on Tailwind / CSS Modules / styled-components / vanilla CSS; maps Figma Styles/Variables to existing tokens.
- **Critical fix — `figma-to-component` source/installed divergence:** Synced both copies to canonical version with correct tool names and 4-tier framework detection.

### v0.1.0 — 2026-05-28
- Multi-target `ak use` — load multiple tickets/files in a single call (primary + supplementary).
- Auto link resolution — auto-fetch Backlog/Jira URLs found in the ticket description (capped at 5 links).
- Comment-aware resolution — `#comment-456` links fetch only that specific comment.
- New `ak fetch-links <url>` command for AI runtime use.
- SessionStart hook renders the `supplementaryContext[]` block into the prompt.
- Added Jest test suite (20+ unit tests for `link-resolver`).

### v0.0.9 — 2026-05-25
- New `figma-desktop` adapter (uses `@figma/mcp-server`, no token required).
- `figma-to-component` skill supports Next.js App Router and Angular.
- `ak gate N start|approved` auto-syncs `task-state.json`.
- New `project-conventions.md` — enforces Gate 2 plan output at `plan/[ticket-id]/plan.md`.
- WSL clipboard support in `ak prompt`.
- Fixes: wrong Figma tool names, PAT verify using wrong auth header, `currentGate` not advancing.

### v0.0.8 — 2026-05-14
- New CLI alias `ak` (short for `aiflow`) + aliases for every sub-command.
- Flexible comment loading options: `--coms`, `--cid`, `--clast`, `--cfrom`, `--cto`.
- Fixed Backlog comment pagination (switched to `minId`-based).
- v0.0.8-beta.1: Actually removed auto-commit + added PreToolUse hook blocking `git commit/add/push`.

### v0.0.7 — 2026-05-08
- `ak use --file` auto-generates `taskId` from filename + interactive `taskType` prompt.
- Auto-generates `task-summary.md` at each gate transition.
- Added NestJS and PHP Plain framework support.
- New `ak sync-skills` command.
- Marker-based update for `CLAUDE.md`, `GEMINI.md`, `.cursorrules`.
- Auto-manages `.gitignore` for generated files.

### v0.0.6 — 2026-04-29
- **Fast Mode** enabled by default (reduced Q&A, single-session implementation).
- New `ak task` command group (status/list/pause/switch/resume).
- Integrated RTK token compression (60–90% savings).
- `--file` loader supports plain-text input.

### v0.0.5 — 2026-04-23
- Telemetry MVP — opt-in tracking, HMAC-SHA256 signed payload, no prompt content logged.
- New `ak gate <n> <action>` command for AI to call automatically on gate transitions.
- Safe overwrite flow in `ak init` (backs up existing files before overwrite).

### v0.0.1 — 2026-04-13
- Initial release: `ak` CLI, 5-Gate workflow, 7 custom skills, support for Claude Code / Gemini / Copilot.

---

## Troubleshooting

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

**Backlog load fails:**
```bash
ak doctor
# Re-setup credentials
ak init --adapter backlog
```

**Skills not loading in Claude:**
```bash
# Ensure init was run outside Claude terminal (session-start hook needs restart)
ak doctor
```

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