# 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
6. Generates sub-agents (`tc-writer`, `code-scout`, `doc-fixer`) for each selected tool, with models from the kit's tier table — see [ai-integration.md](./ai-integration.md#sub-agents-and-model-tiers)

> **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 -f req.md --ticket-id PROJ-33         # file + explicit task ID (no prompt)
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
- `--ticket-id <id>` — Task ID for `--manual` / `--file` sources; skips the interactive Task ID prompt

**Task ID for `--file` / `--manual` sources (v0.2.5+):** these sources carry no ticket of their own, so `ak use` never decides the task ID by itself.

- Ticket IDs found inside the content (`PROJ-12`, `PROJ-40`, ...) are treated as **references**, not as the task's own ID — a requirement that says "blocked by PROJ-40" no longer becomes task `PROJ-40`.
- No ID is generated from a timestamp. The old `TASK-<FILENAME>-<Date.now()>` fallback is gone, because such an ID cannot be traced back to where the task came from.
- On a TTY, `ak use` asks which ID to use and offers suggestions ranked from the content (with mention counts), the file name and the title, plus a free-text option. If `.aiflow/tasks/<id>/` already exists, it asks whether to continue that task or pick another ID.
- **The task ID is mandatory for both `--file` and `--manual`.** Leaving the prompt blank is an error, not a skip: the command prints `✗ A task ID is required. Nothing was loaded.`, exits `1` and saves no context. Same for a `--ticket-id` value that contains no usable characters.
- Without a TTY (VS Code extension, CI, scripts), it prints the suggestions, exits `1` and saves nothing unless `--ticket-id` is given.

**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)

## backlog-fetch

Fetch a full customer requirement from Backlog as JSON, for headless callers (Light-out Agents / `akg ba run --ticket`). Unlike `fetch-links` (one link, text cut at 2000/4000 characters for chat), this returns the untruncated ticket description, all comments with content, the Backlog Documents / Wikis / tickets linked from the description and comments (up to 10), and the attachment list. Every item carries `updated`, so the caller can tell whether the customer changed the requirement. Read-only; never prompts.

```bash
ak backlog-fetch PROJ-123                                                    # key → domain from BACKLOG_SPACE_KEY
ak backlog-fetch "https://company.backlog.com/view/PROJ-123" --download ./attachments
ak backlog-fetch "https://company.backlog.com/document/PROJ/e/0193b335c62173de9547bab5dd0b5324" --no-links
```

**Options:** `--no-comments` (skip comments) · `--no-links` (do not follow Backlog links) · `--download <dir>` (save ticket attachments) · `--json` (default output).

**Output:** `{ source, domain, fetchedAt, ticket: {key, url, title, description, issueType, status, created, updated, attachments[]}, comments[], documents[], wikis[], linkedTickets[], attachments[], errors[] }`. A link that cannot be fetched goes to `errors[]` instead of failing the command.

**Exit codes:** `0` JSON on stdout · `1` bad target, missing `BACKLOG_API_KEY`, or the ticket fetch failed (stderr).

## capabilities

Print the headless contract between ai-flow-kit and Light-out Agents (`akg`) as JSON (KIT-06): kit name and version, `kitRoot`, the list of commands, the agentic environment variable (`AIFLOW_AGENTIC`), and for each `akg` Task Profile the skill/template/rule files the agent must read (`custom/agentic/profiles.json`, resolved to absolute paths), plus language rules per stack. `akg` puts these files at the start of each agent's task brief, with the contract's `guard` sentence (ignore instructions to chat, wait for APPROVED or run `ak`).

```bash
ak capabilities --json
```

`missing[]` lists contract files that do not exist (the test `tests/capabilities.test.js` keeps it empty). When `AIFLOW_AGENTIC=1`, the SessionStart hook does not inject the active task, resume command or "AUTO-START GATE 1" into the agent's session (KIT-11).

Contract v2 (BA Team of Light-out Agents) adds:

- `features[]` — headless options the caller must check before using them, because an older `ak` may have the command but not the option: `env.state-dir`, `env.docs-dir`, `task.create`, `task.status.json`, `use.no-activate`, `gate.by`, `gate.json`, `memory.draft.json`, `memory.list.json`, `memory.recall`, `proto.shot.json`, `validate.type`, `docs.yes`.
- `checklists` — review checklists as files: `CL-AN`, `CL-PROTO`, `CL-UC`, `RR` (`custom/checklists/ba/`). Items are lines `- <ID>-NN — <text>` under `## Checklist`.
- `templates` — record templates `REV`, `ESC`, `Readiness-Report`, `Ledger` (`custom/templates/agentic/`).
- `env[]` — environment variables of agentic mode (below).

### Agentic mode (Light-out Agents)

| Variable | Effect |
|---|---|
| `AIFLOW_AGENTIC=1` | No prompt, no `npm install -g`; `ak gate` with a wrong gate/action, missing `--ticket`, unknown task or a state write error exits ≠ 0 |
| `AIFLOW_NON_INTERACTIVE=1` | No prompt only (scripts, CI) |
| `AIFLOW_STATE_DIR` | State folder instead of `<cwd>/.aiflow` (KIT-01) |
| `AIFLOW_DOCS_DIR` | AK-Docs folder instead of `<cwd>/AK-Docs`, e.g. `../AK-Docs` (KIT-01): used by `memory`, `docs`, `validate --type` (Glossary) |

Exit codes in agentic / `--json` mode: `0` ok, `1` error, `2` wrong usage, `3` not found, `4` needs confirmation.

The rule files `custom/rules/ba-question-rules.md` and `custom/rules/create-spec-dod.md` are generated from `create-spec-workflow.md` (`node scripts/gen-agentic-rules.js`); `tests/agentic-ba.test.js` fails when they drift.

## 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
- `status --task <id> [--json]` — One task, active or not (KIT-02)
- `create <task-id> --task-type <type> [--title] [--file] [--by] [--json]` — Create a task **without activating it**: `current.json` and the other tasks are untouched; an existing task keeps its gate progress (KIT-02). Used by agent teams: one task per function (`F-001-SPEC`) or story

`ak use … --no-activate` saves the loaded context as a pending task in the same way.

**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
6. Refreshes the Claude Code hooks and regenerates the sub-agents (`.claude/agents/`, `.codex/agents/`, `.gemini/agents/`, `.cursor/agents/`) from the current model-tier table

**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
- `--type <type>` — BA artifact check (KIT-29): `analysis` | `qna-log` | `uc-spec` | `function-list`. Machine-checkable part of the create-spec Definition of Done: UI verbs (`ui-action-wording.md`), wording (`document-wording.md`), terms against the Glossary (`domain-terminology.md`), REQ/AC ids and AC per REQ, Blocking/Non-blocking labels, Mermaid, `[NEEDS CLARIFICATION]`, prototype links, duplicated F-IDs
- `--glossary <path>` — Glossary for the term check (default `AK-Docs/00.Project-Overview/Glossary.md`)
- `--strict` — warnings fail too
- `--json` — `{ ok, file, type, errors[], warnings[] }`, each item `{ rule, line, message, hit }`; exit 1 when there are errors

```bash
ak validate AK-Docs/02.BA-Specs/04.UC-Specs/F-001_Ma-Giam-Gia/UC-Spec_v1.md --type uc-spec --json
```

**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 d -c 01.Lessons/ba -f F-003_Payment -s refund-limit --content "..." -t refund   # applies to F-003 only
ak mem d -c 01.Lessons/ba -s date-format-yyyymmdd --content "..." -t date-format --supersedes mem-global-date-format-ddmm   # replaces an older memory
ak mem ls                                    # list local pending drafts  (memory list)
ak mem ls -a                                 # list team-approved memories  (--approved)
ak mem recall -f F-003 -w create-spec --json # memories relevant to a function + workflow, same scoring as the SessionStart hook (KIT-11, for headless agents)
ak mem sb _pending/01.Lessons/dev/_global/prevent-429-error.md -t "Add memory: prevent-429-error"   # submit a draft (memory submit)
ak mem rm 01.Lessons/dev/_global/prevent-429-error.md -t "Remove stale memory" --reason "no longer applies"   # (memory remove)
ak mem rs _pending/01.Lessons/ba/F-003_Payment/refund-limit.md --global   # make a memory project-wide (memory rescope)
ak mem hc                                    # weekly health check, report only (memory health)
ak mem hc --propose -t "memory: health check"   # open one MR removing outdated / superseded memories
```

**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 the memory **only** applies to. Use `global` (or omit) when it holds for any function of the project — choose by content, not by the task it came from (that goes in `--source`)
  - `--scope <scope>` — alternative to `--function-id` for flat categories (glossary/decisions)
  - `-t, --tags <list>` — comma-separated tags the scorer matches on. Tag the topic (`date-format`), not the value (`yymm`), so a later contradicting draft shares a tag and gets flagged
  - `-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)
  - `--refs <paths>` — comma-separated files/dirs the memory depends on, relative to the workspace root (e.g. `my-app/src/auth/JwtFilter.java`, `AK-Docs/02.BA-Specs/.../UC-Spec_v2.md`). `ak mem hc` flags the memory as outdated when one changes after the memory's `created` date or is deleted
  - `--supersedes <ids>` — comma-separated mem-ids this draft replaces, for when the user changed their mind. Each id must exist. The old memories drop out of recall on this machine at once, and `submit` moves them to `_deprecated/` in the same Merge Request. A superseded id that is only a local draft is deleted right away
- `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. If the draft has `supersedes:`, the same branch also moves those memories to `_deprecated/`
- `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
- `rescope|rs <path> (-g, --global | -f, --function-id <id>)` — Change where a memory applies. Glossary/decisions are always project-wide and cannot be rescoped
  - Draft (`_pending/...`): moved to the new scope folder, `id` and `scope` rewritten. Nothing else to do
  - Approved memory (path from `ak mem list --approved`): creates a draft at the new scope with `supersedes: [<old id>]`; the approved file stays until you `ak mem sb` that draft, which moves the old one to `_deprecated/` in the same Merge Request
- `health|hc [--propose] [-t <title>] [-d <desc>] [-y]` — Check committed memories and print a report: format problems, outdated `refs`, superseded memories not yet removed, possible duplicates, files whose `status` is not `approved`. "Not used for a long time" is not checked yet (hit counts are per machine). `--propose` opens one Merge Request moving the outdated and superseded ones to `_deprecated/`. Each run is recorded on this machine; the session-start hook reminds you when the last run is 7+ days old

**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. It also lists existing memories that share a tag with the draft, so a contradiction can be caught and recorded with `supersedes:`
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. Global memories rank the same as memories of the task's own functionId; superseded memories are left out

**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/_global/prevent-429-error.md
  id: mem-global-prevent-429-error (local — chỉ máy này recall được cho tới khi submit)
  scope: global — áp dụng toàn dự án

$ ak mem d -c 01.Lessons/dev -f F-003_Payment -s retry-429 --content "Retry 429" -t http-429
✓ Draft đã tạo: _pending/01.Lessons/dev/F-003_Payment/retry-429.md
  id: mem-F003-retry-429 (local — chỉ máy này recall được cho tới khi submit)
  scope: chỉ áp dụng cho F-003_Payment
  Dùng chung toàn dự án: ak memory rescope _pending/01.Lessons/dev/F-003_Payment/retry-429.md --global

$ ak mem rs _pending/01.Lessons/dev/F-003_Payment/retry-429.md --global
✓ mem-F003-retry-429 → mem-global-retry-429 (áp dụng toàn dự án)
  Draft: _pending/01.Lessons/dev/_global/retry-429.md

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

$ ak mem sb _pending/01.Lessons/dev/_global/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.
```

---

## tc

Test Case file operations for the `create-testcase` workflow.

### tc lint

Check a Test Case file against `qa-writing-standards.md` (§6.5 cross-reference, §6.12 phrasing, §6.13 Expected Result per Step). Errors exit `1` and block the gate; warnings are reported only.

```bash
ak tc lint AK-Docs/03.Testing/01.Testcases/F-002/F-002_TestCase.md
ak tc lint --doc "AK-Docs/03.Testing/01.Testcases/F-002/F-002_Test Plan.md"   # prose artifact (document-wording.md §3)
ak tc lint --checklist AK-Docs/03.Testing/01.Testcases/F-002/F-002_Dev_Checklist.md
```

**Options:**
- `--strict` — Fail on warnings too
- `--doc` — Lint a prose artifact (Gate 1/2 analysis, Test Plan) instead of TC tables
- `--checklist` — Lint a Dev Checklist file instead

### tc build

Assemble `[functionId]_TestCase.md` from the part files written in `create-testcase` Gate 3. Each case is written once, in a part; the final file is put together by code, not re-typed by the AI.

```bash
D="AK-Docs/03.Testing/01.Testcases/F-002"
ak tc build "$D/_parts/03_part-"*.md --out "$D/F-002_TestCase.md" --plan "$D/F-002_Test Plan.md"
ak tc build "$D/_parts/03_part-"*.md --out "$D/F-002_TestCase.md" --plan "$D/F-002_Test Plan.md" \
            --base "$D/F-002_TestCase.md"                                   # Mode UPDATE
```

Quote paths that contain spaces (`"F-002_Test Plan.md"`).

**Options:**
- `-o, --out <file>` — TestCase.md to write (required)
- `--base <file>` — Mode UPDATE: the previous TestCase.md. Its cases are kept (carry-forward), a part row with the same TC ID replaces the old row in place, a new TC ID is appended to the table under the same heading (or the same section number; a section the base does not have is inserted in section order). Prints `kept / replaced / added`. `--base` and `--out` may be the same file.
- `--plan <file>` — Test Plan: fills Mục 1 and checks coverage (see below)
- `--keep-parts` — Do not delete the part files after a successful build

**Part file format** — `_parts/03_part-<section>.md`, next to the shared brief `_parts/gate3-brief.md`:

```markdown
<!-- ak-part: section=3.3 range=TC-GRP-300..TC-GRP-399 -->
### 3.3. Kiểm thử Validation các trường nhập liệu (Input Validation)

#### * Đối với Trường nhập liệu Text (【品名】)
| Test Case ID | Test Case Name | Severity | Pre-condition | Steps | Data Test | Expected Result | Ticket ID | Comment |
|---|---|---|---|---|---|---|---|---|
| TC-GRP-300 | Kiểm tra trường 【品名】 để trống | High | ... | ... | ... | ... |  |  |
```

- Line 1 is the marker. `section` (required) is the section number (`3.3`, or `3.2.4` inside a split block); `range` (optional) is `<first id>..<last id>` with one prefix — every TC ID in the part must have that prefix and a number inside the range.
- Everything after line 1 — headings, `####` sub-tables, split-block headings such as `## 3.2. … — Ngôn ngữ: JP` — is copied verbatim into Mục 3.
- Parts are ordered by section number (`3.2` before `3.10`), whatever order the shell passes them in.
- A part heading with the same level and text as a sub-table an earlier part already has (found once) does not open a second sub-table: its TC rows are appended to that table, and the build prints `N TC gộp vào sub-table "…"`. This is how a TC added late in Gate 3 joins the cases of the same screen. A heading found more than once, or whose scope holds text other than TC tables, is copied as written, with a warning.

**Output** (`testcase-template.md`, numbered as in the workflow — TC sections `3.1`–`3.5` under Mục 3):
- **Mục 1 — Thông tin chung:** `functionId`, `Mã màn hình - Tên màn hình`, `UC-Spec-Version`, `System-Requirement-Version`, `Test-Strategy-Version`, `Người tạo`, `Ngày tạo` from the Test Plan's `## Thông tin chung` table; without `--plan` from Mục 1 of `--base`; otherwise placeholders with a warning for each missing version anchor. `functionId` falls back to the `--out` file name, `Ngày tạo` to today. Reviewer and Review Date are always left for the review.
- **Mục 2 — Kết quả kiểm thử tổng hợp:** reset to 0, every TC `Untest`. Result columns between `Expected Result` and `Ticket ID` (the `column` dimension, e.g. `PC-Chrome | Android | iPhone`) get one row each; split blocks (`## 3.[k]. …`) get one row each besides `Toàn bộ`.
- **Mục 3 — Danh sách Test Cases Chi Tiết:** the parts (merged into the base in Mode UPDATE).

**Checks** — any error stops the build before the file is written:
- Part without a valid marker line
- Duplicate TC ID across parts
- TC ID outside the part's `range`
- TC row whose cell count differs from its table header (rows whose ID cell is not a TC ID are ignored)
- With `--plan`: a scenario of `Phần 2` (table with first column `Scenario ID`) that has no row, or an empty `TC ID` cell, in the `Phần 3` `Coverage Matrix` table (`| Scenario ID | TC ID |`, cell = comma-separated TC IDs or `N/A — <lý do>`); a TC ID in the matrix that the built file does not have. A built TC that no matrix row names is a warning.

After writing, `ak tc lint` runs on the output and its findings are printed. TC count per section and the total are printed.

**Exit codes:** `0` — file written and lint has 0 errors; the part files are deleted (and `_parts/` too when only `gate3-brief.md` is left) unless `--keep-parts`. `1` — build error (nothing written) or lint error (file written, fix the parts and build again); the parts are kept in both cases.

---

## proto

Screenshot an HTML UI prototype to PNG. `create-spec` Gate 4 embeds this PNG in the UC Spec instead of the HTML source, so the screen shows in Markdown preview and on GitLab.

```bash
ak proto shot AK-Docs/02.BA-Specs/03.UI-Prototypes/F-002/UI-Prototype_v1.html   # → UI-Prototype_v1.png next to it
ak proto shot proto.html -o out/screen.png -w 1280                              # custom output and width
ak proto shot proto.html --no-full-page                                         # viewport only
ak proto install                                                                 # install Playwright + Chromium
```

**`shot` options:**
- `-o, --output <path>` — Output PNG (default: same folder and name as the HTML, `.png`)
- `-w, --width <px>` — Viewport width (default `1440`)
- `--height <px>` — Viewport height (default `900`)
- `--no-full-page` — Capture the viewport only (default: whole page)

**`shot` exit codes:** `0` PNG written · `1` error · `2` Playwright not installed · `3` Chromium not installed. On `2`/`3` the AI asks the user before running `ak proto install`.

**`install`:** Playwright is not a dependency of ai-flow-kit. `ak proto shot` uses Playwright from the current project, from `~/.aiflow/tools/playwright`, or from the global npm root. `ak proto install` puts Playwright into `~/.aiflow/tools/playwright` (the project `package.json` is not changed) and downloads Chromium (about 150 MB).

---

`ak proto shot <file> --json` prints `{ ok, code, output, message, needsInstall }` with the same exit codes (KIT-04). `ak memory draft|list … --json` print the result as JSON too.

## 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)
- `--by <actor>` — Who approved: `Human` or `agent:<profile>@<runId>`; stored in `task-state.json` → `gateApprovers[N]` with `--evidence` (KIT-03). `gateApprovals[N]` stays a timestamp
- `--evidence <id>` — Review record backing the approval, e.g. `REV-012` or `ESC-004`
- `--json` — Machine-readable result; errors exit ≠ 0 (also when `AIFLOW_AGENTIC=1`, KIT-10)

On `approved`, one extra line suggests the model/effort for the next gate in the active tool's syntax (e.g. `Recommended for Gate 3: /model opus + /effort medium`). It only appears when the task type + gate is in the tier table and the tool can be identified (`--ai-tool`, the tool's environment, or a single configured tool).

---

## 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.
