# AIFLOW — Software Development Workflow with AI

**Version:** 2.0.0 | **Package:** ai-flow-kit

> This workflow applies to coding tasks: feature, bug-fix, refactor, investigation.
> For document generation tasks, use task type **`gen-doc`** — a 2-gate flow (Gate 1 + Gate 2 only).
> **Absolute Rule: Complete Gate N → Only then can you enter Gate N+1. No exceptions.**

---

## Workflow Overview

```
PM writes ticket on Backlog/Jira
        │
        ▼
⛩️ GATE 1 — AI Analyze Requirement          [AI + DEV]
  AI loads ticket + reads source code
  AI asks clarifying questions until clear
  AI outputs: requirement.md
    (requirements, solution, impact analysis, estimate)
  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: task-summary.md
  DEV reviews → "APPROVED" or "BUG: [description]"
        │ APPROVED
        ▼
⛩️ GATE 5 — Peer Review & PR                [DEV + Peer]
  requesting-code-review skill
  Create Pull Request → merge
        │
        ▼
       DONE
```

---

## Roles

| Role | Responsibility |
|------|---------------|
| **PM** | Write ticket on Backlog/Jira with description, acceptance criteria, context |
| **DEV** | Trigger workflow, review AI outputs at each gate, type APPROVED or provide feedback |
| **AI** | Analyze requirements, propose solutions, generate code (TDD), self-review |

---

## Task Management (Context Switching)

AI Flow Kit allows you to manage multiple tasks in the same repository without losing gate progress.

- **`aiflow task status`**: Show active and pending tasks.
- **`aiflow task pause`**: Save current context and gate progress to `.aiflow/tasks/<taskId>/`.
- **`aiflow task switch <id>`**: Pause current task and switch to another.
- **`aiflow task resume <id>`**: Restore context and gate state. AI auto-resumes from the correct gate.
- **`aiflow task next`**: Approve the current gate, generate `task-summary.md`, clear active context, and prepare the task for a fresh session (Recommended to avoid context pollution).

### Pro-Tip: Fresh Session Workflow
For the best AI performance, run `aiflow task next` after every gate approval, then open a **new chatbox** and type "continue". This clears out long chat history that might confuse the AI.

---

## Gate Details

---

### ⛩️ GATE 1 — AI Analyze Requirement

**Who performs:** AI (analyze) + DEV (review & approve)

**Trigger:**
```bash
aiflow use PROJ-33              # load ticket (fast mode, default)
aiflow use PROJ-33 --full       # load ticket, force full analysis
aiflow use --file task.md        # load task from local text/json file
claude                           # open Claude → AI auto-starts Gate 1
```

> `aiflow prompt` is optional — use it only when pasting into Claude Desktop/Web.
>
> **Tool Support:**
> - **Claude Code:** AI auto-starts Gate 1 via SessionStart hook.
> - **Codex (VS Code extension / ChatGPT desktop app / CLI):** Rules in `AGENTS.md`; no session hook, so start a new session after `ak use` and run `/ak-coding`.
> - **Cursor:** Instructions in `.cursorrules` enforce the Gate Workflow.
> - **Gemini CLI:** Rules in `GEMINI.md` guide the session.
> - **Copilot:** Instructions in `.github/copilot-instructions.md`.

**Gate 1 Modes:**

| Mode | Flag | When to use | Output |
|------|------|-------------|--------|
| `fast` (default) | _(none)_ | Standard tickets, clear intent | Lite 3-section doc (Summary, Files, Estimate). Target < 5 min |
| `full` | `--full` | Complex tickets, force deep analysis | Full 6-section requirement doc |
| `auto` | _(legacy)_ | Same as fast | |

**What AI does (in order):**

| Step | Action | Purpose |
|------|--------|---------|
| 1 | Load ticket from `.aiflow/context/current.json` | Get PM's requirements, comments |
| 2 | Read `CLAUDE.md` + source code | Understand architecture, tech stack, patterns |
| 3 | Investigate related files & data flow | Identify affected areas, dependencies |
| 4 | Ask clarifying questions (one at a time) | Ensure full understanding |
| 5 | Write `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md` | Structured requirement document |

**AI asks questions when:**
- Business requirements are vague or ambiguous
- Acceptance criteria are not measurable
- Edge cases are discovered in source code
- Multiple approaches are possible and need input
- Impact on existing features is unclear

**Requirement Document Output (`AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md`):**

```
├── 1. Requirements Summary
│   ├── Description (AI's understanding in technical language)
│   ├── Current behavior / Business goal
│   ├── Acceptance Criteria (refined, measurable)
│   └── Context & Constraints
├── 2. Source Code Analysis
│   ├── Related files & their roles
│   ├── Data flow diagram
│   ├── Existing patterns to follow
│   └── Current test coverage
├── 3. Proposed Solution & Approach
│   ├── Option A (recommended) — pros/cons
│   ├── Option B (alternative) — pros/cons
│   ├── Chosen approach & rationale
│   ├── Files to create/modify
│   └── Database changes (if any)
├── 4. Impact Analysis
│   ├── Impact level (Low/Medium/High)
│   ├── Affected areas
│   ├── Breaking changes
│   └── Risks & mitigations
├── 5. Effort Estimate
│   ├── Task breakdown with size (S/M/L/XL)
│   └── Sub-task split for XL tasks
└── 6. Testing Plan
    ├── Unit tests
    ├── Integration tests
    └── Manual test cases
```

**Gate 1 Display:**

```
⏸️ GATE 1: REQUIREMENT DOCUMENT READY

Summary:
- Type: [feature / bug-fix / refactor]
- Impact: [Low / Medium / High]
- Estimate: [S / M / L / XL]
- Approach: [brief description]
- Files affected: [N] files

→ Review: AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md
→ Type APPROVED to proceed
→ Or provide feedback to update
```

**Gate 1 Output:**
- `AK-Docs/04.Coding/01.Requirements/[functionId]/[ticketId].md` approved by DEV
- DEV has typed "APPROVED"

---

### ⛩️ GATE 2 — Implementation Plan

**Who performs:** AI (create plan) + DEV (review & approve)

**What AI does:**

1. Read the approved requirement document
2. **Invoke** `superpowers:writing-plans` → create detailed implementation plan
3. Break down into TDD tasks: test first → implement → verify
4. Define verification strategy (evidence before claims)
5. Present plan and wait for APPROVED

**Implementation Plan Structure:**

```
├── Task Breakdown (TDD Order)
│   ├── Task 1: Write test for [scenario]
│   ├── Task 2: Implement [component]
│   ├── Task 3: Write test for [next scenario]
│   └── ...
└── Test Commands
```

**Gate 2 Display:**

```
⏸️ GATE 2: IMPLEMENTATION PLAN READY

Tasks: [N] | Verification: [N] | Test-first tasks: [N]

→ Type APPROVED to start coding
→ Or provide feedback to adjust
```

**Gate 2 Output:**
- Implementation plan approved by DEV
- DEV has typed "APPROVED"

---

### ⛩️ GATE 3 — Code Generation

**Who performs:** AI

**Only runs after Gate 2 APPROVED.**

**Mandatory Order:**

#### Feature task:
1. Complex feature (3+ files) → `superpowers:subagent-driven-development`
2. `superpowers:test-driven-development` — write tests FIRST
3. Run tests → confirm FAIL
4. Implement code → tests PASS
5. Verify implementation works

#### Bug fix task (extra):
1. `superpowers:systematic-debugging` — trace root cause, NO guessing
2. `investigate-bug` skill — trace Controller→Service→Repository
3. Then TDD: write test to reproduce bug → fix → tests PASS

#### Refactor task (extra):
1. Ensure tests cover current behavior
2. Refactor in small steps — keep tests green continuously

**Fast Mode (tdd-lean):**
In fast mode, AI uses the `tdd-lean` skill instead of per-test TDD to save massive token costs:
1. **Batch Red:** Write ALL tests at once. Run once. (Confirm all fail).
2. **Batch Green:** Implement ALL code at once. Run once. (Confirm all pass).
3. **Discipline:** After every run, discard full stack traces and keep ONLY the summary line.

**Gate 3 Output:**
- Code implementation finished
- All tests PASS
- Verified (evidence provided)

---

### ⛩️ GATE 4 — AI Self-Review

**Who performs:** AI (self-review) + DEV (final approve)

**AI runs in mandatory order:**

| Step | Action | Required Result |
|------|--------|------------|
| 1 | `superpowers:verification-before-completion` | All tests PASS |
| 2 | `impact-analysis` skill | No breaking changes outside scope |
| 3 | Create `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md` | File exists and is complete — developer reviews manually before approving |

**If any step fails → AI fixes it first, without showing DEV.**

**Summary report output:**

```
AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md
├── List of changed files + reasons
├── Acceptance Criteria → results (Done/Not Done)
├── Tests: quantity, coverage
├── Impact Analysis: level (Low/Medium/High)
└── Review Checklist: N/N items ✅
```

**Gate 4 Display:**
```
⏸️ GATE 4: WAITING FOR DEV REVIEW

Tests: ✅ [N] passed
Impact: [Low/Medium/High]
Checklist: [N/N] ✅
Summary: AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md

Type APPROVED if OK
Type BUG: [description] if there are issues
```

**DEV Response:**
- `APPROVED` → move to Gate 5
- `BUG: coding bug` → AI fixes → repeat Gate 4
- `BUG: requirement bug` → AI updates requirement doc → back to Gate 1

**Gate 4 Output:**
- `AK-Docs/04.Coding/04.Reviews/[functionId]/[ticketId].md` completed
- DEV has typed "APPROVED"

---

### ⛩️ GATE 5 — Peer Review & Pull Request

**Who performs:** DEV + Peer reviewer

**Only runs after Gate 4 APPROVED.**

**AI invokes:** `superpowers:requesting-code-review`

**AI guides PR creation:**

```markdown
## Pull Request Template

**Title:** [feat/fix/refactor]: [PROJ-XX] [Short description]

**Description:**
Closes [PROJ-XX]

### Changes
- [File A] — [what changed]
- [File B] — [what changed]

### Acceptance Criteria
- [x] [Criteria 1]
- [x] [Criteria 2]

### Testing
- Unit tests: [N] cases
- Integration tests: [N] cases
- Manual test: [tested manually?]

### Impact
[Low/Medium/High] — [short description]

### Reviewer notes
[Anything special for the reviewer to notice]
```

**Peer reviewer checks:**
- Code logic matches requirement document
- Tests are sufficient and meaningful
- No security issues
- Acceptable performance
- Follows team conventions

**Gate 5 Output:**
- PR created with full description
- Peer reviewer APPROVED
- Merged into main/develop

---

## Workflow by Task Type

### Bug Fix
```
Gate 1 (AI analyzes bug: root cause hypothesis + solution + impact + estimate)
→ Gate 2 (implementation plan: test reproduce bug → fix → verify)
→ Gate 3 (systematic-debugging + investigate-bug + TDD fix)
→ Gate 4 (verify fix + no regression)
→ Gate 5 (peer review + PR)
```

### Feature
```
Gate 1 (AI analyzes feature: architecture + solution options + impact + estimate)
→ Gate 2 (implementation plan: TDD task breakdown)
→ Gate 3 (TDD: test first, implement, subagent if complex)
→ Gate 4 (verify all AC done + impact check)
→ Gate 5 (peer review + PR)
```

### Investigation
```
Gate 1 (AI investigates: analyze scope, trace code, document findings + recommendations)
→ DEV reviews → APPROVED
→ DONE (no Gates 2-5, create new ticket if action needed)
```

### Refactor
```
Gate 1 (AI analyzes: current state, target state, impact + estimate)
→ Gate 2 (implementation plan: ensure tests cover behavior → refactor steps)
→ Gate 3 (TDD: cover behavior → refactor → tests green)
→ Gate 4 (verify no regressions)
→ Gate 5 (peer review + PR)
```

### Impact Analysis
```
Gate 1 (AI analyzes: dependency map, risk level, breaking changes, recommendations)
→ DEV reviews → APPROVED
→ DONE (no Gates 2-5, implementation needs a separate ticket)
```

### Generate Document (gen-doc) — 2-Gate Flow
```
Gate 1 (AI reads requirement, plans document: outline, scope, output format, sources)
→ DEV reviews requirement.md → APPROVED
→ Gate 2 (AI generates document immediately: Markdown output.md or Excel)
         (AI self-reviews + creates task-summary.md → task DONE)
→ NO Gate 3/4/5
```

---

## Skills Used in Workflow

| Skill | Gate | Purpose |
|-------|------|---------|
| `read-study-requirement` | Gate 1 | AI reads, analyzes, asks questions, outputs requirement doc |
| `superpowers:systematic-debugging` | Gate 1 (bug) | Trace root cause hypothesis |
| `generate-spec` | Gate 2 | Create implementation plan |
| `superpowers:writing-plans` | Gate 2 | Detailed TDD task breakdown |
| `investigate-bug` | Gate 3 (bug) | Trace data flow per framework |
| `superpowers:test-driven-development` | Gate 3 | TDD workflow |
| `superpowers:subagent-driven-development` | Gate 3 (complex) | Parallel implementation |
| `review-plan` | Gate 4 | Orchestrate self-review |
| `superpowers:verification-before-completion` | Gate 4 | Verify tests pass |
| `impact-analysis` | Gate 4 | Check breaking changes |
| `superpowers:requesting-code-review` | Gate 5 | Peer review workflow |

---

## Commands Reference

```bash
# Setup (once per project)
aiflow init --framework spring-boot --adapter backlog

# Per task (2 commands only)
aiflow use PROJ-33                    # load ticket context (full analysis)
aiflow use PROJ-33 --fast             # fast mode: lite Gate 1 (< 5 min)
aiflow use PROJ-33 --full             # force full Gate 1 analysis
claude                                # AI auto-starts Gate 1

# Optional: generate prompt for Claude Desktop/Web
aiflow prompt bug-fix                 # generate prompt to paste
aiflow prompt feature --output p.md   # save prompt to file

# Task switching (multiple tasks in same repo)
aiflow task status                    # view active + pending tasks
aiflow task pause                     # pause current task
aiflow task pause --note "waiting for PM"
aiflow task switch PROJ-99            # pause current + switch
aiflow task resume PROJ-33            # resume a paused task

# Utilities
aiflow context show                   # view active context
aiflow memory save "key" "value"      # save team knowledge
aiflow doctor                         # health check
aiflow guide                          # view quickstart guide

# Telemetry (team leads)
aiflow telemetry status               # view status
aiflow telemetry enable               # setup tracking
aiflow telemetry disable              # disable tracking
```

---

## Multi-AI Environment Setup

One of the core strengths of `ai-flow-kit` is that the **Gate Workflow** is tool-agnostic. Since state is saved in `.aiflow/context/current.json` and the `AK-Docs/04.Coding/` docs directory, you can switch tools mid-task.

### How to Switch Tools
1. **Analyze (Gate 1)** using Claude Code CLI (great for deep codebase scans).
2. **Review** the `requirement.md` file.
3. **Open Cursor** to perform the coding (Gate 3).
4. Cursor will automatically read `.cursorrules`, detect the active ticket, and see that Gate 1 is already finished.
5. Cursor will proceed to Gate 2 or 3 as appropriate.

### Instruction Files Created
| Tool | File Name | Purpose |
|------|-----------|---------|
| Claude Code | `CLAUDE.md` | Primary rules for the CLI tool. |
| Codex | `AGENTS.md` | Rules for the Codex IDE extension, ChatGPT desktop app, and CLI. Links to `.aiflow/instructions/` for the full workflows. |
| Cursor AI | `.cursorrules` | Project-wide rules for Cursor. |
| Gemini CLI | `GEMINI.md` | Context for Gemini sessions. |
| Copilot | `.github/copilot-instructions.md` | Custom instructions for Copilot. |

---

## FAQ

**Q: PM didn't write enough on the ticket, what happens?**
A: AI at Gate 1 will read what's available, then ask clarifying questions one at a time until the requirement is clear enough to propose a solution.

**Q: Does AI just check format or actually understand the requirement?**
A: AI actively reads source code, traces data flow, identifies related files, and proposes solutions. It asks questions based on what it finds in the code — not just checking if fields exist.

**Q: Gate 1 is taking too long for a simple ticket. What can I do?**
A: Use `aiflow use TICKET-ID --fast` before opening Claude. Fast mode skips the Q&A loop and outputs a lean 3-section requirement doc. Best suited for tickets with ≥ 3 clear, measurable acceptance criteria and no ambiguity. Target: Gate 1 done in < 5 minutes.

**Q: Can I skip Gate 2 for simple tasks?**
A: No. Gate 2 can be brief (simple plan), but DEV must still type "APPROVED" to confirm the approach.

**Q: AI reports test failures at Gate 4, what to do?**
A: AI will try to fix them before showing DEV. If it can't, it will report the reason and ask for DEV's support.

**Q: What's the difference between a requirement bug and a coding bug?**
A: Requirement bug = wrong/missing in requirement doc → back to Gate 1. Coding bug = wrong code but correct requirement → fix at Gate 4.

**Q: Who performs peer review (Gate 5)?**
A: Another developer in the team. Not the code author. The reviewer uses the `superpowers:receiving-code-review` skill.

**Q: Can I work on two tasks in the same repo at the same time?**
A: Yes. Use `aiflow task pause` to save your current progress, then `aiflow use <new-ticket>` to start the new task. Resume later with `aiflow task resume <ticket-id>`. The gate progress is saved automatically — Claude will resume from the correct gate instead of restarting Gate 1.

**Q: If I resume a task, will Claude know which gate to start at?**
A: Yes. The SessionStart hook reads `.aiflow/tasks/<taskId>/task-state.json` and injects gate-aware instructions. If Gate 1 was already approved, Claude will skip to Gate 2, and so on.
**Q: Can I resume a Gate 3 (Code Generation) task in a new chatbox?**
A: Yes. Gate 3 progress is saved via `[x]` checkboxes in `AK-Docs/04.Coding/02.Plans/[functionId]/[ticketId].md`. If you open a new chatbox and say "continue", the AI will automatically skip completed tasks and pick up exactly where it left off.

**Q: How does AI estimate effort?**
A: AI analyzes the scope of changes (files affected, complexity, test requirements) and categorizes: S (< 1h), M (1-4h), L (4-8h), XL (8h+, should split).
