# CLI Reference

Complete reference for all `ak` / `aiflow` commands.

> **Short alias:** `ak` is the preferred short form of `aiflow`. Every command also has a short alias shown in the format `command|alias`.

## Commands Overview

```bash
ak --help                        # Show all commands
ak <command> --help              # Show command help
ak <alias> --help                # Also works with aliases
```

### Quick Alias Reference

| Full command | Short | Full command | Short |
|---|---|---|---|
| `ak init` | `ak i` | `ak use` | `ak u` |
| `ak execute` | `ak ex` | `ak prompt` | `ak p` |
| `ak detect` | `ak d` | `ak task` | `ak t` |
| `ak context` | `ak ctx` | `ak checkpoint` | `ak cp` |
| `ak validate` | `ak vl` | `ak memory` | `ak mem` |
| `ak guide` | `ak g` | `ak remove` | `ak rm` |
| `ak update` | `ak up` | `ak sync-skills` | `ak sync` |
| `ak doctor` | `ak dr` | `ak telemetry` | `ak tel` |
| `ak ask` | `ak ask` | | |

| `task` sub-command | Short | `memory` sub-command | Short |
|---|---|---|---|
| `ak t status` | `ak t st` | `ak mem draft` | `ak mem d` |
| `ak t list` | `ak t ls` | `ak mem list` | `ak mem ls` |
| `ak t pause` | `ak t p` | `ak mem submit` | `ak mem sb` |
| `ak t switch` | `ak t sw` | `ak mem remove` | `ak mem rm` |
| `ak t resume` | `ak t r` | | |
| `ak t reset` | `ak t rst` | | |
| `ak t remove` | `ak t rm` | | |
| `ak t next` | `ak t n` | | |

## init

Initialize AI Flow Kit in your project.

```bash
ak init                                      # basic initialization
ak init -f laravel                           # with framework  (--framework)
ak init -a jira                              # with adapter  (--adapter)
ak init -f laravel -a jira                   # full setup
ak init -f spring-boot --with-rtk            # enable RTK compression
ak init --no-rtk                             # skip RTK setup
```

**Options:**
- `-f, --framework <types>` (alias: `--fw`) — Framework templates, comma-separated (e.g. `spring-boot,reactjs`)
- `-a, --adapter <types>` — MCP adapters (jira, backlog, google-sheets)
- `-e, --env <types>` — AI tools to configure (claude, cursor, gemini, copilot, codex, generic). Default excludes `generic`. Selecting `codex` also writes `AGENTS.md`, `.codex/skills/`, `.codex/config.toml` and `.aiflow/instructions/` — see [ai-integration.md](./ai-integration.md#4-codex-openai).
- `--with-rtk` — Force enable RTK token compression hook
- `--no-rtk` — Skip RTK setup even if RTK is detected

**What it does:**
1. Creates `.claude/skills/` with all available skills
2. Creates `.rules/` with team rules (including `java/spring-boot-examples.md` for Spring Boot projects)
3. Creates `.aiflow/` with version tracking
4. Sets up framework instruction file (`CLAUDE.md`, `.cursorrules`, etc.):
   - **File already exists** → saves aiflow template to `.aiflow/reference/<file>` for comparison. Your existing file is untouched — you own it.
   - **File does not exist** → creates it in the project root.
5. Optionally configures MCP adapter

> **Note:** `CLAUDE.md` and other AI instruction files are project files — commit them to your repo. Run `aiflow init` once to generate them, then maintain them yourself. On subsequent `aiflow init` runs they will not be overwritten.

**Example:**
```bash
$ aiflow init --framework laravel --adapter jira
Initializing ai-flow-kit (v1.0.0)...
✓ Copied skills to .claude/skills
✓ Copied rules to .rules
✓ Set up CLAUDE.md for framework: laravel
✓ Updated MCP configuration for jira

✨ Initialized AI Flow Kit successfully!
```

## use

Load context from one or more tickets, files, or manual entry. **Accepts variadic targets** (v0.1.0+) — the first target is the primary context (drives Gate 1); any additional targets are appended as `supplementaryContext[]`.

```bash
ak use JIRA-123                              # single target — load from Jira
ak use BACKLOG-456                           # single target — load from Backlog
ak use PROJ-33 PROJ-10 docs/arch.md          # multi-target — primary + supplementary (v0.1.0+)
ak use BACKLOG-456 -F                        # fast mode  (--fast)
ak use BACKLOG-456 -U                        # full mode  (--full)
ak use -m                                    # manual entry  (--manual)
ak use -f path/to/context.json               # load from file  (--file)
ak use BACKLOG-456 -c                        # load with all comments  (--coms)
ak use BACKLOG-456 --clast 5                 # last 5 comments
ak use BACKLOG-456 --cid 42                  # specific comment
ak use 1.0.0                                 # switch between versions
```

**Arguments:**
- `[targets...]` — One or more targets. Each target can be a ticket ID (`PROJ-33`), a Backlog/Jira URL, or a local file path. First target = primary; rest = supplementary.

**Options:**
- `-m, --manual` — Manual context entry
- `-f, --file <path>` — Load from file (JSON or plain text)
- `-s, --save <name>` — Save as named context
- `-c, --coms` — Load all comments (alias for `--with-comments`)
- `--with-comments` — Include all ticket comments
- `--cid <id>` — Load a specific comment by ID
- `--clast <n>` — Only fetch last N comments
- `--cfrom <id>` — Fetch comments from ID N onward
- `--cto <id>` — Fetch comments up to ID N
- `-F, --fast` — Fast mode: AI skips Q&A, lite 3-section requirement doc (< 5 min Gate 1)
- `-U, --full` — Full mode: force complete Gate 1 analysis with Q&A

**Auto link resolution (v0.1.0+):** When the primary ticket description contains Backlog/Jira URLs, `ak use` auto-fetches them and appends to `supplementaryContext[]`. Comment URLs (`#comment-456` or `?focusedCommentId=456`) resolve to **that single comment only**. Capped at 5 auto-resolved links per `use`; per-link errors are logged without aborting the command.

**`supplementaryContext[]` schema** (persisted in `.aiflow/context/current.json`):

```json
{
  "sourceType": "ticket | comment | file | text",
  "sourceUrl": "https://...",
  "sourcePath": "docs/arch.md",
  "ticketId": "PROJ-10",
  "commentId": "456",
  "title": "...",
  "description": "...",
  "content": "...",
  "author": "...",
  "date": "..."
}
```

**What it does:**
1. Loads the first target as primary context (fetches from MCP adapter / file / manual entry)
2. Loads each remaining target as a supplementary item
3. Scans the primary description for Backlog/Jira URLs and auto-resolves them
4. Saves the merged context (including `mode` and `supplementaryContext[]`) to `.aiflow/context/current.json`
5. Updates state tracking

**Example:**
```bash
$ aiflow use JIRA-123
Fetching context from Jira...
✓ Title: Fix payment processing error
✓ Description: 2000+ words pulled
✓ Acceptance criteria: 3 items
✓ Saved to .aiflow/context/current.json

Ready to prompt! Run: aiflow prompt bug-fix

$ aiflow use PROJ-33 PROJ-10 docs/arch.md
✓ Loaded primary: PROJ-33
✓ Supplementary: PROJ-10 (ticket), docs/arch.md (file)
✓ Auto-resolved 2 link(s) from description
```

## execute (alias: `ex`)

Execute test cases via the 4-gate Executing Flow. Syncs Playwright scripts, runs them, collects evidence, and generates a test report.

```bash
ak execute PROJ-44                           # from ticket (taskType must be "execute")
ak execute ./testcases/AD10.md               # from TC file
ak execute                                   # manual — AI asks for TC file
```

**Arguments:**
- `[target]` — Optional. A ticket ID (`PROJ-44`), a path to a TC file (`./testcases/AD10.md`), or omitted for manual entry.

**What it does (4 gates):**
1. **Gate 1 — Pre-flight:** Parse TC file, verify `AK-Docs/03.Testing/` subfolders and `AK-Docs/03.Testing/05.Scripts/{repo}/playwright.config.ts` exist (auto-scaffold if missing), check `BASE_URL`
2. **Gate 2 — Script Sync:** Hash-based sync — gen new TCs, update changed, skip unchanged. Uses Playwright MCP for real selectors (never fabricates). Every step captures evidence via `evidence-helper.ts` and asserts on actual Expected Result content (see "DOM Verification Rules" in `execute-flow` SKILL.md).
3. **Gate 3 — Execute & Evidence:** Run Playwright from `AK-Docs/03.Testing/05.Scripts/`, evidence written into `AK-Docs/03.Testing/04.Evidence/{repo}/{featureDir}/run-{N}/` via `EVIDENCE_DIR`, update TC file R1/R2 columns (`✅ Pass` · `❌ Fail` · `⏭️ Untest` · `⏳ Pending`)
4. **Gate 4 — Report & Bug Logging:** Generate `testreport.md` in AK-Docs, confirm each bug with TESTER before logging to Jira

**Output structure:**
```
AK-Docs/03.Testing/
├── 04.Evidence/{repo}/{featureDir}/run-{N}/            # gitignored — screenshots, trace.zip
│   └── {TC_ID}-{scenario}/
├── 05.Scripts/{repo}/{featureDir}/{ScreenID}.spec.ts   # runnable Playwright project
├── 02.Reports/{repo}/{featureDir}/run-{N}/
│   ├── {TC_ID}-{scenario}/result.md
│   └── testreport.md
└── 06.Bugs/{repo}/{featureDir}/run-{N}/BUG-NNN-{slug}.md
```

**Example:**
```bash
$ ak execute ./testcases/AD10.md
⏸️ GATE 1: EXECUTE FLOW READY
TC file: testcases/AD10.md
Repo: repo-fe | Screen: AD10 — Create Product
BASE_URL: http://localhost:3000
→ Type APPROVED to sync scripts (Gate 2)
```

---

## fetch-links

Fetch a single Backlog/Jira URL and print a `SupplementaryContext` JSON object to stdout. Intended for AI runtime use inside the `read-study-requirement` skill — when AI encounters a link in the ticket description that wasn't already resolved by `ak use`, it can call this command and integrate the JSON output.

```bash
ak fetch-links "https://company.backlog.com/view/PROJ-10"                   # full ticket
ak fetch-links "https://company.backlog.com/view/PROJ-10#comment-456"        # single comment
ak fetch-links "https://company.atlassian.net/browse/PROJ-10"                # Jira ticket
ak fetch-links "https://company.atlassian.net/browse/PROJ-10?focusedCommentId=789"  # Jira comment
```

**Arguments:**
- `<url>` — Backlog or Jira URL (ticket or comment)

**What it does:**
1. Loads stored credentials from `.aiflow/credentials.json`
2. Classifies the URL (Backlog vs Jira, ticket vs comment)
3. Fetches via the appropriate adapter API
4. Prints the resulting `SupplementaryContext` JSON to stdout

**Exit codes:**
- `0` — Success, JSON written to stdout
- `1` — URL not recognised as Backlog/Jira, or fetch failed (error message on stderr)

## task (alias: `t`)

Manage multiple tasks — pause, switch, and resume while preserving gate progress.

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

**Sub-commands (with aliases):**
- `status|st` — Show active task and all pending tasks
- `list|ls` — List all saved tasks with gate state
- `pause|p [-n <text>]` — Save current progress and clear active task
- `switch|sw <ticket-id>` — Pause current task + load/switch to another
- `resume|r <ticket-id>` — Restore a paused task as active
- `reset|rst <ticket-id>` — Reset gate progress to Gate 1; prompts to optionally delete `plan/<id>/` files
- `remove|rm <ticket-id>` — Permanently delete all saved data for the task
- `next|n [-t <id>]` — Approve current gate and prepare next session

**What it does:**
1. Saves a snapshot of the current context (`current.json`) to `.aiflow/tasks/<taskId>/context.json`
2. Detects current gate from `plan/` artifacts (`requirement.md`, `plan.md`, `summary.md`)
3. Writes `.aiflow/tasks/<taskId>/task-state.json` with status, gate, and approvals
4. On resume: restores context as `current.json` and sets status back to `active`
5. The **SessionStart hook** reads `task-state.json` on next `claude` launch and injects gate-aware instructions — Claude resumes from the correct gate instead of restarting Gate 1

**Gate detection from `plan/` files:**
| File present | Inferred gate |
|---|---|
| (none) | Gate 1 |
| `plan/<id>/requirement.md` | Gate 2 |
| `plan/<id>/plan.md` | Gate 3 |
| `plan/<id>/summary.md` | Gate 5 |
| `plan/<id>/output.md` _(gen-doc)_ | Done (Gate 2 complete) |

**Example workflow:**
```bash
# Mid-task on PROJ-33 (Gate 2 in progress)...
aiflow task pause --note "waiting for DB schema confirmation"
# ✓ Task PROJ-33 paused at Gate 2.

aiflow use PROJ-99        # load urgent task
claude                    # AI auto-starts Gate 1 for PROJ-99

# Back to PROJ-33
aiflow task resume PROJ-33
# ✓ Resumed task: PROJ-33
#   Gate:  2 (Implementation Plan)

claude                    # AI resumes from Gate 2 — no restart
```

**Reset workflow** — run a task from scratch after deleting generated code:
```bash
aiflow task reset PROJ-33
# Reset task: PROJ-33
#   • .aiflow/tasks/PROJ-33/task-state.json  (Gate 3 → 1, approvals cleared)
# ? Also delete 2 plan file(s) in plan/PROJ-33/? › No
# ? Proceed with reset? › Yes
# ✓ Task PROJ-33 reset to Gate 1.

claude   # AI auto-starts Gate 1 as if the task is brand new
```

**Remove workflow** — permanently clean up a cancelled task:
```bash
aiflow task remove PROJ-33
# Remove task: PROJ-33
#   • .aiflow/tasks/PROJ-33/  (context snapshot + gate state)
#   • .aiflow/context/current.json  (this is the active task)
#   • plan/PROJ-33/  (2 files):
#       - plan/PROJ-33/requirement.md
#       - plan/PROJ-33/plan.md
# ? This cannot be undone. Proceed? › No
```

---

## prompt (alias: `p`)

Generate an AI prompt with context, rules, and template.

```bash
ak p bug-fix                                 # generate bug fix prompt
ak p feature                                 # generate feature prompt
ak p investigation                           # generate investigation prompt
ak p refactor                                # generate refactor prompt
ak p impact                                  # generate impact analysis prompt
ak p gen-doc                                 # generate document generation prompt (2-gate)
ak p -l                                      # list all prompt types  (--list)
ak p bug-fix -o p.md                         # save to file  (--output)
ak p bug-fix -L vietnamese                   # Vietnamese language  (--lang)
ak p bug-fix -d comprehensive                # comprehensive detail  (--detail)
```

**Options:**
- `<type>` — Prompt type (bug-fix, feature, investigation, refactor, impact, docs, gen-doc)
- `-l, --list` — List available prompt types
- `-o, --output <file>` — Save to file instead of printing
- `-L, --lang <lang>` — Language (english, vietnamese)
- `-d, --detail <level>` — Detail level (minimal, standard, comprehensive)

**What it does:**
1. Loads current context (from `aiflow use`)
2. Loads prompt template for the type
3. Loads framework rules
4. Loads team rules and best practices
5. Merges everything into a complete prompt
6. Prints to console (or saves/copies)

**Example:**
```bash
$ aiflow prompt bug-fix
═══════════════════════════════════════════════════════════════
BUG FIX INVESTIGATION PROMPT
═══════════════════════════════════════════════════════════════

## Context
Title: Payment processing fails on checkout
Description: Users report seeing payment error when... [2000+ words]

## Framework Rules (Laravel)
- Use Laravel's built-in tools...
- Keep Controllers thin...

## Team Rules
- Use strict typing...
- Follow PSR-12 styling...

## Task
Investigate the bug following this process:
1. Understand the error context...
[Complete prompt ready to copy to Claude]
```

## detect (alias: `d`)

Auto-detect task type from a description.

```bash
ak d "Payment integration is broken"         # detect from description
ak d                                         # detect from current context
ak d "Add new feature" -v                    # show confidence  (--verbose)
ak d "description" -t 90                     # set threshold  (--threshold)
```

**Options:**
- `<description>` — Description to analyze
- `-v, --verbose` — Show detection reasoning
- `-t, --threshold <number>` — Confidence threshold (0-100)

**What it does:**
1. Analyzes description for keywords
2. Classifies as bug-fix, feature, refactor, investigation, etc
3. Shows confidence score
4. Suggests appropriate skill

**Example:**
```bash
$ aiflow detect "Users can't save their orders"
🐛 Bug Fix (98% confidence)

Detected keywords:
- "can't save" → bug pattern
- Specific area → likely regression

Suggested skill: investigate-bug

Next: aiflow prompt bug-fix
```

## context (alias: `ctx`)

Manage task contexts (save, load, list, delete).

```bash
ak ctx list                                  # list saved contexts
ak ctx -s "checkout-fix"                     # save current context  (--save)
ak ctx -l "checkout-fix"                     # load saved context  (--load)
ak ctx -d "checkout-fix"                     # delete saved context  (--delete)
ak ctx clear                                 # clear all contexts
ak ctx show                                  # show current context
```

**Options:**
- `-s, --save <name>` — Save current context
- `-l, --load <name>` — Load saved context
- `-d, --delete <name>` — Delete saved context
- `--clear` — Clear all contexts
- `--show` — Show current context details

**What it does:**
1. Lists, saves, loads, or deletes contexts
2. Manages context history in `.aiflow/context/history/`
3. Makes it easy to switch between tasks

**Example:**
```bash
$ aiflow context --list
Saved contexts:
  1. checkout-fix (saved 2 hours ago)
  2. payment-integration (saved yesterday)
  3. user-auth-bug (saved 3 days ago)

$ aiflow context --load checkout-fix
✓ Loaded: checkout-fix
✓ Ready to prompt!
```

## update (alias: `up`)

Update to the latest version.

```bash
ak up                                        # update to latest
ak up -f                                     # force update  (--force)
```

**Options:**
- `-f, --force` — Force update even if already latest

**What it does:**
1. Checks for newer version
2. Downloads assets (skills, rules, templates)
3. Updates `.claude/` and `.rules/`
4. Optionally deletes old version
5. Updates state tracking

**Example:**
```bash
$ aiflow update
Updating from v1.0.0 to v1.1.0...
✓ Downloaded skills for v1.1.0
✓ Downloaded rules for v1.1.0

Keep old version (v1.0.0)? (y/n) y
✓ Kept v1.0.0

You can switch back with: aiflow use 1.0.0

✨ Update completed!
```

## sync-skills (alias: `sync`)

Manually synchronize AI Instruction files with local custom skills.

```bash
ak sync                                      # sync AI Instruction files
```

**What it does:**
1. Reads all active local skills and upstream skills
2. Generates the updated AI Skill Registry table
3. Safely updates the AI Instruction blocks (`<!-- aiflow-kit-start -->`) in your project's `CLAUDE.md`, `GEMINI.md`, or `.cursorrules` without wiping your custom rules
4. If no marker blocks are found, it asks for confirmation to overwrite with the correct structure

**Example:**
```bash
$ aiflow sync-skills
⟳ Syncing AI Instruction files...
  ✓ Updated AI Flow block in CLAUDE.md
✨ Sync completed!
```

## doctor (alias: `dr`)

Health check for your setup.

```bash
ak dr                                        # run health check
ak dr -v                                     # verbose output  (--verbose)
ak dr -t PROJ-33                             # token breakdown for ticket  (--ticket)
```

**Options:**
- `-t, --ticket <id>` — Show token breakdown for specific ticket
- `-v, --verbose` — Show detailed checks

**What it does:**
1. Checks for required directories
2. Validates configuration files
3. Checks MCP adapter setup
4. Verifies framework template
5. Reports issues and fixes

**Example:**
```bash
$ aiflow doctor
Running health check for AI Flow Kit...

✓ .claude/skills exists
✓ .rules exists
✓ CLAUDE.md exists
✓ Version tracking active (v1.0.0)
✓ Jira adapter configured
✓ Laravel framework template loaded

✨ Everything looks healthy! You are ready to fly.
```

## validate (alias: `vl`)

Validate AI output against team rules and quality standards.

```bash
ak vl output.php                             # validate a file
ak vl output.php -r strict                   # strict rule set  (--ruleset)
ak vl output.php -v                          # detailed report  (--verbose)
ak vl output.php -x                          # auto-fix trailing whitespace  (--fix)
```

**Options:**
- `<file>` — File to validate
- `-r, --ruleset <set>` — Rule set (default, strict, lenient)
- `-v, --verbose` — Detailed report
- `-x, --fix` — Auto-fix trailing whitespace

**What it does:**
1. Loads validation rules from `custom/rules/`
2. Checks code style, naming, security, etc
3. Reports violations
4. Optionally suggests fixes

**Example:**
```bash
$ aiflow validate src/Payment.php
Validating against ruleset: default

✓ Code style: OK
⚠ Naming: Variable $p should be $payment
✓ Security: OK
✗ Testing: Missing test file

Issues found: 2 warnings, 1 error
Suggestions: Add test case, rename variable
```

## telemetry (alias: `tel`)

Manage usage telemetry.

```bash
ak tel status                                # view status, buffer size, last flush
ak tel enable                                # interactive setup (URL, secret, email)
ak tel disable                               # disable tracking (config retained)
ak tel flush                                 # force-send buffered events now
```

**Sub-commands:**
- `status` — View current status, buffer size, last flush time
- `enable` — Interactive setup (Apps Script URL, team secret, email)
- `disable` — Disable tracking; configuration is retained
- `flush` — Force-send all buffered events immediately

---

## memory (alias: `mem`)

Manage the `99.Memory/` Project Brain — a git-based, human-approved team knowledge base living inside `AK-Docs/99.Memory/`. AI (or you) drafts a memory locally, then submits it as a Merge Request for a teammate/PM to approve. See `docs/common/Memory-Architecture-v1.0.md` for the full design.

> **Note:** This replaces the older `.aiflow/memory/` JSON store (`save/get/search/delete/clear`) retired in v0.1.7 — that command set no longer exists.

```bash
ak mem d -c 01.Lessons/dev -s prevent-429-error --content "Retry with backoff on 429 from payment gateway" -t payment,retry
ak mem ls                                    # list local pending drafts  (memory list)
ak mem ls -a                                 # list team-approved memories  (--approved)
ak mem sb 01.Lessons/dev/prevent-429-error.md -t "Add memory: prevent-429-error"   # submit a draft (memory submit)
ak mem rm 01.Lessons/dev/prevent-429-error.md -t "Remove stale memory" --reason "no longer applies"   # (memory remove)
```

**Sub-commands (with aliases):**
- `draft|d --category <cat> --slug <slug> --content <text> [options]` — Create a local memory draft in `_pending/` (not yet shared with the team)
  - `-c, --category <cat>` — e.g. `00.Shared/architecture`, `01.Lessons/dev`, `02.Instincts/approved`
  - `-s, --slug <slug>` — short kebab-case name, e.g. `prevent-429-error`
  - `--content <text>` — memory body (≤150 words, 1 fact)
  - `-f, --function-id <id>` — functionId this memory is scoped to (omit for a global/cross-project fact)
  - `--scope <scope>` — alternative to `--function-id` for flat categories (glossary/decisions)
  - `-t, --tags <list>` — comma-separated tags the scorer matches on
  - `-w, --workflows <list>` — comma-separated workflows (coding, create-spec, create-testcase, gen-doc, all)
  - `--source <text>` — ticket/Gate this was learned from
  - `--confidence <n>` — AI self-rated 0.3–0.7 (default 0.5)
- `list|ls [-a, --approved]` — List local pending drafts, or team-approved memories with `--approved`
- `submit|sb <path> --title <title> [-d <desc>] [-y]` — Move a pending draft (path from `ak mem list`) to its destination in `AK-Docs/99.Memory/` and open a Merge Request
- `remove|rm <path> --title <title> [--reason <text>] [--hard] [-y]` — Propose removing an approved memory (path from `ak mem list --approved`); soft-remove moves it to `_deprecated/`, `--hard` deletes it outright

**What it does:**
1. `draft` writes a frontmatter'd Markdown file to `AK-Docs/99.Memory/_pending/` on your machine only — recallable locally, but not yet shared with the team
2. `submit` creates a branch in `AK-Docs`, moves the file out of `_pending/` to its real category path, commits, pushes, and opens a Merge Request (same branch+MR flow as `ak docs branch`/`ak docs submit`)
3. A teammate (PM by convention) reviews and merges the MR — that's the point it becomes recallable for everyone else
4. `session-start` hook auto-injects the `MEMORY.md` index plus top-N relevant approved memories into every new session — no manual recall needed once merged

**Example:**
```bash
$ ak mem d -c 01.Lessons/dev -s prevent-429-error --content "Retry with backoff on 429 from payment gateway" -t payment,retry
✓ Draft đã tạo: _pending/01.Lessons/dev/prevent-429-error.md
  id: mem-payment-prevent-429-error (local — chỉ máy này recall được cho tới khi submit)

$ ak mem ls
Pending drafts (local):
  mem-payment-prevent-429-error  _pending/01.Lessons/dev/prevent-429-error.md
    type=lesson scope=payment workflows=all

$ ak mem sb 01.Lessons/dev/prevent-429-error.md -t "Add memory: prevent-429-error"
✓ Branch memory/prevent-429-error created in AK-Docs
✓ Merge Request opened — waiting for approval
```

## guide (alias: `g`)

Show quickstart guide.

```bash
ak g                                         # full guide
ak g -f                                      # architecture & flow only  (--flow)
ak g -c                                      # command reference only  (--commands)
```

**Options:**
- `-f, --flow` — Show architecture & flow diagram only
- `-c, --commands` — Show command reference only

---

## ask

Search ai-flow-kit's own docs for an answer about the kit itself — install, roles, folder structure, CLI commands, memory draft/submit, troubleshooting. This is the deterministic fallback the `aiflow-help` skill uses (and that works with no LLM at all): local keyword search over `docs/common/*.md`, no network call.

```bash
ak ask "how do I install ai-flow-kit"
ak ask "submit memory"
ak ask "switch between cursor and claude code"
ak ask "some obscure question" -n 5          # show up to 5 results  (--limit)
```

**Arguments:**
- `<question>` — Free-text question (English or Vietnamese)

**Options:**
- `-n, --limit <n>` — Max number of results to show (default 3)

**What it does:**
1. Scans every `docs/common/*.md` file (including `workflows/`)
2. Scores each file by how many query terms it contains, weighting heading matches higher
3. Prints the top matches with the nearest heading and a snippet, ranked by score

See also `docs/common/INDEX.md` for the curated topic map this search complements, and the `/ak-ask "<question>"` slash command for asking the same kind of question directly inside a Claude Code chat (explicit trigger for the `aiflow-help` skill, no terminal needed).

**Example:**
```bash
$ ak ask "submit memory"

Results for "submit memory":

  docs/common/cli-reference.md  (score 14)
  → memory (alias: `mem`)
    ...`submit|sb <path> --title <title> [-d <desc>] [-y]` — Move a pending draft...

See docs/common/INDEX.md for the full topic map.
```

---

## gate (AI workflow logging)

Called automatically by AI during gate workflow — not intended for manual use.

```bash
# Log gate N started
aiflow gate <n> start --ticket <id>

# Log gate N approved
aiflow gate <n> approved --ticket <id>
```

**Arguments:**
- `<n>` — Gate number (1-5)
- `<action>` — `start` or `approved`

**Options:**
- `--ticket <id>` — Ticket ID associated with the gate transition
- `--ai-tool <tool>` — AI tool that triggered the gate (e.g. claude, cursor, gemini)

---

## remove (alias: `rm`)

Remove ai-flow-kit from project, a cached version, or uninstall globally.

```bash
ak rm                                        # remove from project
ak rm -g                                     # uninstall globally  (--global)
ak rm --version 1.0.0                        # remove cached version from .aiflow/
```

**Options:**
- `--version <ver>` — Remove a specific cached version from `.aiflow/versions/`
- `-g, --global` — Uninstall the global npm package (removes `aiflow` command)

---

## Global Options

These work with any command:

```bash
ak --version                     # Show installed version  (-v, -V)
ak <command> --help              # Show help for a command  (-h)
```

## Exit Codes

- `0` — Success
- `1` — General error
- `2` — Command not found
- `3` — Invalid arguments
- `4` — Configuration error
- `5` — MCP adapter error

---

See [Getting Started](./getting-started.md) for tutorials and [Configuration](./configuration.md) for detailed options.
