---
description: "AI Workflow Engine - Core Workflow Rules (State Enforcement + Context Loading + Auto-Apply + Command Integration)"
globs: "**/*"
alwaysApply: true
priority: 0
version: 3.0.0
tags: [workflow, state-enforcement, context-loading, command-integration, critical, all-states]
lastUpdated: 2025-11-28
requirement: REQ-MDC-OPTIMIZATION-001
---

# 🤖 AI WORKFLOW ENGINE - CORE RULES

⚠️  **CRITICAL:** This rule applies to EVERY conversation (alwaysApply: true)

## 📋 AT CONVERSATION START (MANDATORY)

### Step 1: Get Current Workflow State

**You MUST call this command FIRST:**

```bash
npx ai-workflow task status --json --silent
```

**What this gives you:**
- Current task ID and goal
- Current workflow state
- Task priority
- Queue information
- Checklist items (if available)

**If command fails (exit code ≠ 0):**
1. Check error message from JSON output
2. Fallback: Read `.ai-context/STATUS.txt`
3. If no task: Create new task with `npx ai-workflow task create "<goal>"`

**Error Handling:**
```bash
# Check exit code
npx ai-workflow task status --json --silent
echo $?  # Must be 0 for success

# If exit code ≠ 0:
# 1. Read error from JSON output: {"status":"error","error":"...","exitCode":1}
# 2. Use file fallback: Read .ai-context/STATUS.txt
# 3. Investigate and fix issue
```

### Step 2: Parse nextActions (if present)

**After getting state, check for nextActions in JSON output:**

```json
{
  "status": "success",
  "data": {
    "id": "task-123",
    "goal": "Implement feature",
    "state": "IMPLEMENTING"
  },
  "nextActions": [
    {
      "type": "command",
      "action": "npx ai-workflow checklist status --json --silent",
      "reason": "Get checklist for current state",
      "required": true
    }
  ]
}
```

**You MUST:**
1. Parse `nextActions` array from JSON output
2. For each action with `required: true`, execute it
3. Use output for next steps

### Step 2.5: Execute Required nextActions

**After parsing nextActions, you MUST execute required actions:**

**Filter Required Actions:**
1. Filter actions where `required === true` → **Required Actions**
2. Filter actions where `required !== true` → **Optional Actions**

**Priority:**
1. **Required Actions First:** Execute all `required: true` actions automatically
2. **Optional Actions:** Consider executing if contextually appropriate
3. **Discovery Actions:** Use as fallback if no other actions available

**Execute Actions by Type:**

#### Type: `'command'`
**Execute CLI command via terminal:**
```bash
# Example: If action.action = "npx ai-workflow checklist status --json --silent"
npx ai-workflow checklist status --json --silent
echo $?  # Check exit code (must be 0 for success)
```

**You MUST:**
1. Execute the command shown in `action` field using `run_terminal_cmd` tool
2. Check exit code: `result.exitCode` (must be 0 for success)
3. If exit code ≠ 0:
   - Log error: `❌ Command failed: [command]`
   - Log exit code and stderr
   - Continue with next action (don't stop chain)
4. If exit code = 0:
   - Parse JSON output from `result.stdout`
   - Recursively process `nextActions` from output (if present)
   - Respect depth limit (max 10 actions in chain)

#### Type: `'read_file'`
**Read file content:**
```bash
# Example: If action.action = ".ai-context/STATUS.txt"
# Use read_file tool to read the file
```

**You MUST:**
1. Read the file at path in `action` field using `read_file` tool
2. Use file content for context (e.g., read STATUS.txt to understand current state)
3. No nextActions from file read (file read is terminal)

#### Type: `'check_state'`
**Manual verification required:**

**You MUST:**
1. Log the `reason` for user awareness: `⚠️  [reason]`
2. Display the `action` description
3. Wait for user input or manual verification
4. Don't auto-execute check_state actions

**Chain Depth Limits:**
- **Maximum depth:** 10 actions in chain
- **Circular dependency detection:** Track executed actions to prevent loops
- **Stop if limit reached:** Log warning and stop chain execution

**Error Handling:**
- If action execution fails: Log error, continue with next action
- If JSON parsing fails: Use stderr if available, skip nextActions
- If orchestrator fails: Command still succeeds, continue without nextActions

### Step 3: Get Checklist for Current State

**After getting state, get checklist:**

```bash
npx ai-workflow checklist status --json --silent
```

**What this gives you:**
- Checklist items for current state
- Completed vs pending items
- Required vs optional items

**You MUST:**
1. Review all checklist items
2. Complete required items before progressing state
3. Mark items complete with evidence: `npx ai-workflow checklist check <id> --evidence <type> --description "<description>"`

### Step 4: Get Active Patterns

**Get patterns relevant to current state:**

```bash
# Get current state first (from Step 1)
STATE=$(npx ai-workflow task state --json --silent | jq -r '.state')
npx ai-workflow pattern list --state $STATE --json --silent
```

**What this gives you:**
- Mandatory patterns for current state
- Recommended patterns
- Pattern validation rules

### Step 5: Confirm Context Loaded

**Your FIRST response must start with:**

```
✓ Workflow Context:
  Task: [goal from command output or STATUS.txt]
  State: [state from command output or STATUS.txt]  
  Roles: [active roles from checklist or NEXT_STEPS.md]
```

**Example:**
```
✓ Workflow Context:
  Task: Implement user authentication with JWT
  State: IMPLEMENTING
  Roles: Security Engineer, QA Engineer

[Then answer user's question...]
```

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 🚨 CRITICAL UNIVERSAL RULES (APPLY TO ALL STATES)

### 1. NEVER Code at Planning States

**UNDERSTANDING & DESIGNING are for PLANNING ONLY:**
- ❌ NEVER write production code
- ❌ NEVER modify existing code files
- ❌ NEVER create components/modules
- ❌ NEVER refactor code

**Why:** Code without proper understanding = bugs and rework

**When you CAN code:** IMPLEMENTING state and after

**🚨 MANDATORY PRE-ACTION CHECK:**

Before ANY code-related action, you MUST:

1. **Check State First:**
   ```bash
   npx ai-workflow task state --json --silent
   # Or read: .ai-context/STATUS.txt
   ```

2. **If State is UNDERSTANDING or DESIGNING:**
   ```
   ❌ BLOCKED! Cannot code at planning states!
   
   Required Response:
   "🚫 Cannot proceed with coding. Current state is {STATE}.
   
   At {STATE} state, I can only:
   - UNDERSTANDING: Ask questions, understand requirements
   - DESIGNING: Design solution, plan architecture
   
   To code, I must first:
   1. Complete understanding/design
   2. Progress to IMPLEMENTING state
   3. THEN I can write code
   
   Let me continue with understanding/design first..."
   ```

3. **NEVER Override This Block:**
   - Even if user says "just code it" → Still block
   - Even if user says "skip understanding" → Still block
   - Even if user seems impatient → Still block
   - **EXCEPTION:** User explicitly says "progress to IMPLEMENTING" → Then progress state first, then code

---

### 2. NEVER Skip Tests (MANDATORY!)

**Tests are REQUIRED before ANY commit:**
- ❌ NEVER suggest commits without tests
- ❌ NEVER say "tests can be added later"
- ❌ NEVER claim work is "done" without tests

**Required:** TESTING state with passing tests

**Why:** Untested code = production bugs

---

### 3. NEVER Commit Without Validation

**Commits ONLY allowed at READY_TO_COMMIT state:**
- ❌ NEVER commit from any other state
- ❌ NEVER use --no-verify flag
- ❌ NEVER bypass pre-commit hooks

**Required sequence:**
```
REVIEWING → Run validation → Pass → READY_TO_COMMIT → Commit
```

**Why:** Quality gates prevent broken code from being committed

---

### 4. ALWAYS Check Task Scope Before Work

**Before writing code, changing files, or implementing features:**

1. **Check Active Task**
   ```bash
   npx ai-workflow task status --json --silent
   ```

2. **Verify Work Scope**
   - Does user request match active task goal?
   - Is this work within current task scope?
   - Or is this NEW work requiring NEW task?

3. **Decision Matrix**

   **✅ CONTINUE with active task IF:**
   - Work directly fulfills current task goal
   - Logical extension of current task
   - Same feature/bug/requirement

   **❌ CREATE NEW TASK IF:**
   - User requests different feature
   - User requests different bug fix
   - Scope significantly different
   - Previous task completed

4. **Action Required**

   **If NEW task needed:**
   ```bash
   # Check if current task is done
   npx ai-workflow task status --json --silent
   
   # If completed or different scope:
   npx ai-workflow task create "<new work description>"
   
   # Verify new task created
   npx ai-workflow task status --json --silent
   ```

   **Then proceed with work.**

---

### 5. ALWAYS Progress Sequentially

**State progression is LINEAR - cannot skip:**
```
UNDERSTANDING
  ↓ Requirements clear
DESIGNING
  ↓ Design approved
IMPLEMENTING
  ↓ Code written
TESTING
  ↓ Tests passing
REVIEWING
  ↓ Validation passed
READY_TO_COMMIT
  ↓ Committed
DONE
```

**Cannot skip states!** Each has specific completion criteria.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 🔍 QUICK STATE LOOKUP TABLE

**Use this for quick reference, then read full state file for details:**

| # | State Name | Purpose | Can Code? | Can Test? | Can Commit? | Read File |
|---|-----|---|-----|-----|----|-----|
| 1 | **UNDERSTANDING** | Understand requirements | ❌ | ❌ | ❌ | state-behaviors/UNDERSTANDING.md |
| 2 | **DESIGNING** | Design solution | ❌ | ❌ | ❌ | state-behaviors/DESIGNING.md |
| 3 | **IMPLEMENTING** | Write production code | ✅ | ❌ | ❌ | state-behaviors/IMPLEMENTING.md |
| 4 | **TESTING** | Write comprehensive tests | ✅ | ✅ | ❌ | state-behaviors/TESTING.md |
| 5 | **REVIEWING** | Review code quality | ✅ | ✅ | ❌ | state-behaviors/REVIEWING.md |
| 6 | **READY_TO_COMMIT** | Commit validated work | ✅ | ✅ | ✅ | state-behaviors/READY_TO_COMMIT.md |

**→ After identifying your state, READ the corresponding state-behaviors/*.md file!**

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 📖 STATE PROGRESSION FLOW

```
┌─────────────────────────────────────────────────────────────┐
│ START → Get state via command or STATUS.txt                 │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│ STATE 1: UNDERSTANDING                                       │
│ ✅ DO: Ask questions, read code, analyze                    │
│ ❌ DON'T: Code, test, commit                                │
│ → Next: Get user approval → sync --state DESIGNING         │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│ STATE 2: DESIGNING                                           │
│ ✅ DO: Design architecture, plan implementation             │
│ ❌ DON'T: Write code, test, commit                          │
│ → Next: Get approval → sync --state IMPLEMENTING            │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│ STATE 3: IMPLEMENTING                                        │
│ ✅ DO: Write production code, implement features            │
│ ❌ DON'T: Write tests yet, commit                           │
│ → Next: Code done → sync --state TESTING                    │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│ STATE 4: TESTING                                             │
│ ✅ DO: Write tests, verify coverage, run tests              │
│ ❌ DON'T: Add new features, commit                          │
│ → Next: Tests pass → sync --state REVIEWING                 │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│ STATE 5: REVIEWING                                           │
│ ✅ DO: Review quality, check requirements                   │
│ ❌ DON'T: Major changes, commit                             │
│ → Next: Run validation → Passes → Auto READY_TO_COMMIT       │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│ STATE 6: READY_TO_COMMIT                                    │
│ ✅ DO: Stage files, commit with message, complete task      │
│ ❌ DON'T: Use --no-verify, bypass hooks                     │
│ → Next: Commit → Complete task → DONE                       │
└─────────────────────────────────────────────────────────────┘
```

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 🚫 COMMON VIOLATIONS TO AVOID

### ❌ Violation 1: Coding Too Early
```
User: "Add authentication feature"
AI at UNDERSTANDING: [Starts writing code] ← WRONG!

✅ Correct:
AI at UNDERSTANDING: "Let me understand requirements first:
  1. What authentication method? (JWT, OAuth, etc.)
  2. Where should users login?
  3. ..."
```

### ❌ Violation 2: Skipping Tests
```
AI at IMPLEMENTING: "Code done! Ready to commit!" ← WRONG!

✅ Correct:
AI at IMPLEMENTING: "Code done. May I progress to TESTING 
to write tests?"
```

### ❌ Violation 3: Committing Without Validation
```
AI at REVIEWING: "git commit -m '...'" ← WRONG!

✅ Correct:
AI at REVIEWING: "Let me run validation first:
  npx ai-workflow validate --json --silent"
```

### ❌ Violation 4: Skipping States
```
AI jumps: UNDERSTANDING → IMPLEMENTING ← WRONG! (Skipped DESIGN)

✅ Correct:
UNDERSTANDING → DESIGNING → IMPLEMENTING
```

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 📚 EXAMPLE: CORRECT WORKFLOW

**User Request:** "Add user authentication"

### ✅ Step 1: UNDERSTANDING State
```
AI: ✓ State: UNDERSTANDING
    Let me understand requirements:
    1. What authentication method?
    2. Session storage approach?
    3. Security requirements?
    [Asks 10+ questions...]
    
    Summary: [After user answers]
    May I progress to DESIGNING?
    
User: Yes

AI: [Runs: npx ai-workflow sync --state DESIGNING --json --silent]
```

### ✅ Step 2: DESIGNING State
```
AI: ✓ State: DESIGNING
    Design proposal:
    - AuthContext (React Context)
    - JWT tokens in httpOnly cookies
    - Login/Register components
    - Protected routes
    
    Files to create:
    - src/contexts/AuthContext.tsx
    - src/components/Login.tsx
    
    Design approved?
    
User: Yes

AI: [Runs: npx ai-workflow sync --state IMPLEMENTING --json --silent]
```

### ✅ Step 3: IMPLEMENTING State
```
AI: ✓ State: IMPLEMENTING
    [Writes AuthContext.tsx]
    [Writes Login.tsx]
    [Writes AuthService.ts]
    
    Implementation complete. Build passing.
    May I progress to TESTING?
    
User: Yes

AI: [Runs: npx ai-workflow sync --state TESTING --json --silent]
```

### ✅ Step 4-6: Continue Through States...
[TESTING → REVIEWING → READY_TO_COMMIT → DONE]

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 🎯 QUICK DECISION TREE

**Before taking ANY action, ask yourself:**

```
Q: What state am I currently in?
A: [Call: npx ai-workflow task state --json --silent OR Read STATUS.txt]

Q: What does user want me to do?
A: [Parse request]

Q: Is this action allowed in current state?
A: [Check Quick Lookup Table above + Read state-behaviors/{STATE}.md]

Decision:
├─ If ALLOWED → Proceed
├─ If FORBIDDEN → Explain why, suggest proper state
└─ If UNSURE → Read full state file, then decide
```

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 📝 FILES TO READ FOR FULL DETAILS

**State-specific behavior files (read based on current state):**

- `.cursor/rules/state-behaviors/UNDERSTANDING.md`
- `.cursor/rules/state-behaviors/DESIGNING.md`
- `.cursor/rules/state-behaviors/IMPLEMENTING.md`
- `.cursor/rules/state-behaviors/TESTING.md`
- `.cursor/rules/state-behaviors/REVIEWING.md`
- `.cursor/rules/state-behaviors/READY_TO_COMMIT.md`

**Each file contains:**
- Full list of allowed actions
- Full list of forbidden actions
- Detailed progression protocol
- Examples and best practices
- Self-check guidelines

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## 🎯 SUMMARY

**This file provides:**
- ✅ Quick reference for all states
- ✅ Critical universal rules
- ✅ State progression flow
- ✅ Common violations to avoid
- ✅ Pointers to full state documentation
- ✅ Command integration for data retrieval

**For full details:**
- 📖 Read `.cursor/rules/state-behaviors/{YOUR_STATE}.md`

**Remember:**
1. Call `npx ai-workflow task status --json --silent` first (or read STATUS.txt as fallback)
2. Parse nextActions if present
3. Get checklist for current state
4. Read corresponding state-behaviors/*.md file
5. Apply universal rules from this file
6. Follow state-specific rules from state file
7. Progress sequentially through states

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

**Priority:** 0 (HIGHEST - Read FIRST before all other .mdc files!)  
**Version:** 3.0.0  
**Purpose:** Core workflow enforcement with command integration  
**Maintenance:** Update template, then run: `npx ai-workflow migrate --update-mdc-files`

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

**END OF CORE WORKFLOW RULES**
