#!/usr/bin/env bash ################################################################################ # Flow Framework Deployment Script # # Self-contained script with all framework content embedded. # Distribute this single file to install the Flow framework. # # Version: 1.6.12 # Generated by build-standalone.sh ################################################################################ set -e FLOW_VERSION="1.6.12" # Colors RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' CYAN='\033[0;36m' NC='\033[0m' # Commands list - auto-generated at build time from framework/SLASH_COMMANDS.md COMMANDS=( "flow-blueprint" "flow-init" "flow-migrate" "flow-plan-update" "flow-phase-add" "flow-phase-start" "flow-phase-complete" "flow-task-add" "flow-task-start" "flow-task-complete" "flow-iteration-add" "flow-brainstorm-start" "flow-brainstorm-subject" "flow-brainstorm-review" "flow-brainstorm-complete" "flow-implement-start" "flow-implement-complete" "flow-status" "flow-summarize" "flow-next-subject" "flow-next-iteration" "flow-next" "flow-rollback" "flow-verify-plan" "flow-compact" "flow-plan-split" "flow-backlog-add" "flow-backlog-view" "flow-backlog-pull" ) # Deprecated commands (renamed/removed in v1.0.11+) - cleaned up during --force DEPRECATED_COMMANDS=( "flow-phase" "flow-task" "flow-iteration" "flow-brainstorm_start" "flow-brainstorm_subject" "flow-brainstorm_resolve" "flow-brainstorm_complete" "flow-implement_start" "flow-implement_complete" "flow-update-plan-version" "flow-brainstorm-resolve" # Removed in v1.0.12 - redundant command ) FORCE=false print_help() { cat </ {inside=1; next} found && inside && // {exit} found && inside {print} ' <<'COMMANDS_DATA_EOF' # Flow Framework - Slash Commands File. This file contains all slash command definitions for the Flow framework. Copy these to `.claude/commands/` when ready to use. --- ## Command Guidelines **IMPORTANT**: Every command must: 1. **Read the framework guide** at the start to understand patterns and structure 2. **Find and parse .flow/PLAN.md** to understand current state 3. **Follow framework patterns exactly** (status markers, section structure, etc.) 4. **Update .flow/PLAN.md** according to framework conventions 5. **Provide clear next steps** to the user **File Locations**: - **Plan File**: `.flow/PLAN.md` (Flow manages the plan from this directory) - **Framework Guide**: Search in order: 1. `.flow/framework/DEVELOPMENT_FRAMEWORK.md` (primary - in user's project) 2. `.claude/DEVELOPMENT_FRAMEWORK.md` (project root) 3. `./DEVELOPMENT_FRAMEWORK.md` (project root) 4. `~/.claude/flow/DEVELOPMENT_FRAMEWORK.md` (global) - **Examples**: `.flow/framework/examples/` (reference files for AI to learn from) **Finding PLAN.md** (all commands except `/flow-blueprint` and `/flow-migrate`): - Primary location: `.flow/PLAN.md` - If not found, search project root and traverse up - If still not found: Suggest `/flow-blueprint` (new project) or `/flow-migrate` (existing docs) **Status Markers** (use consistently): - ✅ Complete - ⏳ Pending - 🚧 In Progress - 🎨 Ready for Implementation - ❌ Cancelled - 🔮 Deferred **Tool Usage for Pattern Matching**: When commands instruct you to "Find", "Look for", or "Locate" patterns in PLAN.md: - **Use Grep tool** for: - Simple pattern existence checks (does pattern exist?) - Counting occurrences (`grep -c`) - Reading specific sections with context (`grep -A`, `-B`, `-C`) - Examples: Finding phase markers, checking status, locating sections - **Use awk** ONLY for: - Extracting content between two patterns (range extraction) - Example: `awk '/start_pattern/,/end_pattern/ {print}'` - **Prefer Grep over awk** for simple tasks - it's more efficient and clearer **Examples**: ```bash # ✅ GOOD - Use Grep for pattern checking grep "^### Phase 4:" PLAN.md grep -c "^#### ⏳ Task" PLAN.md grep -A 2 "^## 📋 Progress Dashboard" PLAN.md # ✅ GOOD - Use awk for range extraction awk '/^##### Iteration 5:/,/^#####[^#]|^####[^#]/ {print}' PLAN.md awk '/\*\*Subjects to Discuss\*\*:/,/\*\*Resolved Subjects\*\*:/ {print}' PLAN.md # ❌ BAD - Don't use awk for simple existence checks awk '/^### Phase 4:/ {print}' PLAN.md # Use grep instead ``` --- ## /flow-blueprint **File**: `flow-blueprint.md` ```markdown --- description: Create new multi-file Flow project structure from scratch --- You are executing the `/flow-blueprint` command from the Flow framework. **Purpose**: Create a brand new multi-file Flow project structure from scratch. **🔴 REQUIRED: Read Framework Quick Reference & Templates First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-600 (Quick Reference section) - if not already in context - **Read file templates**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2101-2600 (DASHBOARD.md, PLAN.md, task-N.md templates) - **Read examples**: `.flow/framework/examples/` directory for real-world examples **Multi-File Architecture**: This command creates: - `DASHBOARD.md` - Progress tracking (single source of truth, user's main workspace) - `PLAN.md` - Static context (overview, architecture, scope) - `phase-N/` directories (if enough info provided) - `phase-N/task-M.md` files (if enough info provided) **IMPORTANT**: This command ALWAYS creates fresh files, overwriting any existing. Use `/flow-migrate` to convert existing docs or `/flow-plan-update` to migrate old single-file plans. **💡 TIP FOR USERS**: Provide rich context! The more details you provide upfront, the better the plan. **Good example** (explicit tasks = creates phase directories + task files): ``` /flow-blueprint "WebSocket Chat App 1. Create Bun.js web server with Express 2. Implement Socket.IO for real-time messaging 3. Build frontend app to communicate with WebSocket server Testing: Simulation-based per service" ``` **Minimal example** (AI will ask follow-up questions, may only create DASHBOARD + PLAN): ``` /flow-blueprint "websocket server" ``` **Instructions**: 1. **INPUT VALIDATION** (Run BEFORE reading framework): **Step 1: Quick Scan**: ``` IF $ARGUMENTS is empty OR just whitespace: REJECT: "❌ Missing project description. Provide at least a project name or brief description." STOP ``` **Step 2: Detect Blueprint Mode**: **Mode A: SUGGEST Structure** (User wants AI to design) - Trigger: NO explicit structure markers in $ARGUMENTS - Examples: "websocket server", "user auth system" - Behavior: Ask questions, generate suggested structure **Mode B: CREATE Explicit Structure** (User designed it) - Trigger: Contains numbered lists, "Phase N:", "Task N:", or bullet structure - Examples: - "1. server, 2. socket.io, 3. frontend" - "Phase 1: Foundation\n- Task 1: Setup\nPhase 2: Implementation" - Behavior: Honor user's structure exactly (with [TBD] for missing metadata) **Step 3: Semantic Check** (Mode A only): - If too vague ("help", "project", "thing"): ``` "🤔 Need more context. What are you building? Examples: - 'WebSocket chat server with Socket.IO' - 'User authentication system with JWT' Or provide explicit structure: 1. [First step] 2. [Second step] 3. [Third step]" ``` **Step 4: Dry-Run Preview** (Mode B only): - Parse structure and show what will be created: ``` "📋 Detected explicit structure. I will create: Phase 1: Bun.js Web Server ⏳ - phase-1/task-1.md (Create Express server) Phase 2: Socket.IO Implementation ⏳ - phase-2/task-1.md (Implement real-time messaging) Phase 3: Frontend App ⏳ - phase-3/task-1.md (Build WebSocket client) Also creating: DASHBOARD.md, PLAN.md Proceed? (yes/no)" ``` 2. **Read framework guide AND examples** (after validation): - Search for .flow/framework/DEVELOPMENT_FRAMEWORK.md (`.flow/`, `.claude/`, `./`, `~/.claude/flow/`) - Search for examples in `.flow/framework/examples/` (DASHBOARD.md, PLAN.md, task files) - Read to understand: - Multi-file structure (DASHBOARD vs PLAN vs task files) - File templates - Required sections - Status markers 3. **Analyze feature request** (Mode-specific): **If Mode A (SUGGEST)**: - Extract: requirements, constraints, references, testing - If minimal context, prepare to ask questions **If Mode B (CREATE)**: - Parse structure (phases/tasks from numbered lists or explicit markers) - Extract metadata if provided - Use [TBD] for missing metadata 4. **Gather information** (Mode A only): a. **Reference implementations**: - If mentioned in args, read and analyze - Otherwise ask: "Reference implementation to analyze? (path or 'no')" b. **Testing methodology**: - If provided in args, use directly - Otherwise ask: ``` "How do you prefer to verify implementations? - Simulation-based (per-service): scripts/{service}.scripts.ts - Unit tests: Jest/Vitest after implementation - TDD: Tests before implementation - Manual QA: No automated tests - Custom: Describe your approach Also tell me: - Test file naming? (e.g., {service}.scripts.ts, {feature}.test.ts) - Test file location? (e.g., scripts/, __tests__/, tests/) - When to create NEW vs add to existing?" ``` c. **Estimate phase/task structure** (Mode A only): - Based on requirements, estimate phases needed - Ask: "I'm thinking X phases: [list]. Does this structure make sense? Any changes?" d. **Ask about Key Decisions** (IMPORTANT - human-in-loop): - If you identify design decisions during structure creation, **ASK USER IMMEDIATELY**: ``` "I identified a decision point: [question]" "- Option A: [description]" "- Option B: [description]" "Your choice? (or say 'decide later' to add to Key Decisions section)" ``` - **If user chooses**: Document choice in PLAN.md Architecture section or relevant file - **If user says "decide later"**: Add to DASHBOARD.md Key Decisions section as unresolved - **DO NOT** create unresolved Key Decisions without asking user first - Examples of decisions to ask about: - Version numbering (v1.X.0 vs v2.0.0) - Architecture patterns (REST vs GraphQL, SQL vs NoSQL) - Testing approach (if not already gathered in step 4b) - Deployment strategy (if relevant to project) 5. **Determine what files to create**: **ALWAYS CREATE**: - `DASHBOARD.md` (required - single source of truth for progress) - `PLAN.md` (required - static context) **CREATE phase-N/ directories + task files IF**: - Mode B (explicit structure) → Always create - Mode A with rich context (clear tasks identified) → Create - Mode A with minimal context → Don't create yet (user adds with /flow-phase-add later) 6. **Generate files**: **💡 BEST PRACTICE - Turn-Based Approach**: For large projects with many phases/tasks, use a turn-based approach to manage context: 1. **First turn**: Create PLAN.md only (architecture, scope, overview) 2. **Second turn**: Create DASHBOARD.md (list all phases/tasks structure) 3. **Third+ turns**: Create task files incrementally (Phase 1, then Phase 2, etc.) This prevents context overflow and allows human review between steps. **When to use turn-based**: - 3+ phases with multiple tasks each - Complex projects requiring detailed task descriptions - When human wants to review structure before task file creation **When to use single-turn**: - Small projects (1-2 phases, few tasks) - Clear structure from user's description - Minimal task file content needed a. **Create PLAN.md FIRST** (turn 1 if using turn-based approach): - Use template from .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2232-2321 - Include (MINIMAL - no assumptions): - Header with purpose - Overview (Purpose, Goals - text format NO checklists, Scope V1 only) - Architecture (high-level system context if info provided) - DO/DON'T Guidelines - Notes & Learnings (empty initially) - **DO NOT INCLUDE** (unless user explicitly requests): - V2/V3 Scope sections - Testing Strategy section (user decides during brainstorming) - Development Phases section - Future Enhancements section - **If turn-based**: Stop here, confirm with user, ask if ready for DASHBOARD b. **Create DASHBOARD.md SECOND** (turn 2 if using turn-based approach): - Use template from .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2102-2200 - Fill in project name, purpose - Current Work: Set to Phase 1, Task 1, Iteration 1 (if phases created) OR "No phases yet" (if not) - Progress Overview: List all phases/tasks structure (with iteration counts) - Completion Status: 0% initially - Next Actions: "Use /flow-phase-add to add first phase" OR "Use /flow-phase-start to begin" - Last Updated: Current timestamp - **If turn-based**: Stop here, ask user which phase to create task files for first c. **Create phase-N/ directories** (turn 3+ if using turn-based approach): - Create one directory per phase - Naming: `phase-1/`, `phase-2/`, etc. d. **Create phase-N/task-M.md files** (turn 3+ if using turn-based approach): - Use template from .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2383-2472 (task with iterations) - **ALL tasks have iterations** (no standalone tasks) - **CRITICAL: Create task files for EVERY task listed in DASHBOARD.md** - If DASHBOARD.md shows "Task 1: Name" under Phase 2, then `phase-2/task-1.md` MUST exist - NEVER create incomplete structures where DASHBOARD promises tasks that don't exist - If uncertain about task details, use [TBD] placeholders - but file must exist - **If turn-based**: Create one phase at a time (e.g., all Phase 1 tasks, then ask before Phase 2) - Fill in: - Task name and purpose - Phase link back to DASHBOARD.md - Status: ⏳ PENDING initially - Task Overview with "Why This Task" - Dependencies (if known) - At least 1 iteration per task (with placeholder goal) - Task Notes section (empty initially) - **Context management**: For large projects, ask user after each phase if ready to continue 7. **Verify completeness** (self-check): - [ ] DASHBOARD.md created with all required sections? - [ ] PLAN.md created with minimal required sections (no assumptions)? - [ ] phase-N/ directories created (if applicable)? - [ ] phase-N/task-M.md files created with iterations (if applicable)? - [ ] **CRITICAL: Every task listed in DASHBOARD.md has a corresponding task file?** - Parse DASHBOARD.md "Progress Overview" section - For each task entry (e.g., "Task 1: Name"), verify phase-N/task-M.md exists - **NEVER create "phantom tasks"** - if DASHBOARD lists it, file MUST exist - [ ] DASHBOARD.md Current Work points to correct location? 8. **Confirm to user**: **If using turn-based approach**: - After PLAN.md: "✨ Created PLAN.md. Review the architecture and scope. Ready to create DASHBOARD.md?" - After DASHBOARD.md: "✨ Created DASHBOARD.md with [X] phases, [Y] tasks. Which phase should I create task files for first? (Suggest: Phase 1)" - After each phase's tasks: "✅ Created [N] task files for Phase [X]. Ready to create Phase [X+1] task files?" **If Mode A (SUGGEST) with phases created** (single-turn approach): ``` "✨ Created multi-file Flow project structure: 📂 Files Created: - DASHBOARD.md (your main workspace - single source of truth) - PLAN.md (static context - minimal assumptions) - phase-1/ with [X] task files (all with iterations) - phase-2/ with [Y] task files (all with iterations) 📊 Structure: [X] phases, [Y] tasks, [Z] iterations 🎯 Next Steps: - Use `/flow-status` to see current state - Use `/flow-phase-start` to begin Phase 1 - Use `/flow-brainstorm-start` when ready to design first iteration" ``` **If Mode A (SUGGEST) without phases** (minimal context): ``` "✨ Created initial Flow project structure: 📂 Files Created: - DASHBOARD.md (your main workspace) - PLAN.md (static context - V1 scope only) 📝 Note: No phases created yet (need more context) 🎯 Next Steps: - Use `/flow-phase-add "Phase Name"` to add your first phase - Then use `/flow-task-add "Task Name"` to add tasks - Or re-run `/flow-blueprint` with more detailed requirements" ``` **If Mode B (CREATE)**: ``` "✨ Created multi-file Flow project from your explicit structure: 📂 Files Created: - DASHBOARD.md (single source of truth) - PLAN.md (minimal assumptions) - phase-1/ → [X] tasks (all with iterations) - phase-2/ → [Y] tasks (all with iterations) - phase-3/ → [Z] tasks (all with iterations) 📊 Structure: [X] phases, [Y] tasks (as you specified) 📝 [TBD] placeholders: [list sections with [TBD]] 🎯 Next Steps: - Use `/flow-status` to see current state - Refine [TBD] sections during brainstorming - Use `/flow-phase-start` to begin work" ``` **Output**: Create multi-file Flow project structure and confirm to user. --- ## /flow-init **File**: `flow-init.md` ```markdown --- description: Install/update complete Flow framework (commands, skills, framework files) --- You are executing the `/flow-init` command from the Flow framework. **Purpose**: Download and install Flow framework files directly from GitHub repository. **🟢 NO FRAMEWORK READING REQUIRED - This is the installation command** **Instructions**: 1. **Detect installation mode**: Check if `.claude/commands/` directory exists with flow-*.md files: ```bash if [ -d ".claude/commands" ] && ls .claude/commands/flow-*.md >/dev/null 2>&1; then echo "UPDATE" else echo "INSTALL" fi ``` 2. **Show what will be installed** and get user confirmation: ``` 📥 Flow Framework [MODE - INSTALL or UPDATE] I will download and install from GitHub (khgs2411/flow): ✓ 29 slash commands → .claude/commands/ ✓ 8 agent skills → .claude/skills/ ✓ 1 Claude agent → .claude/agents/ ✓ Framework docs → .flow/framework/ ✓ Example files → .flow/framework/examples/ Total download size: ~210KB [If UPDATE mode: ⚠️ Existing Flow files will be overwritten] Proceed with installation? (y/n) ``` 3. **If user declines**, stop and show: ``` ⚠️ Installation cancelled. Run /flow-init again when ready. ``` 4. **If user approves**, execute installation using Bash tool: Run this complete bash script: ```bash # Base URL for GitHub raw files BASE_URL="https://raw.githubusercontent.com/khgs2411/flow/master" echo "📦 Installing Flow framework..." echo "" # Create directories mkdir -p .claude/commands mkdir -p .claude/skills mkdir -p .claude/agents mkdir -p .flow/framework/examples/phase-1 mkdir -p .flow/framework/examples/phase-2 echo "📝 Downloading slash commands from framework/commands/..." # Download all 29 commands COMMANDS=( "flow-backlog-add" "flow-backlog-pull" "flow-backlog-view" "flow-blueprint" "flow-brainstorm-complete" "flow-brainstorm-review" "flow-brainstorm-start" "flow-brainstorm-subject" "flow-compact" "flow-implement-complete" "flow-implement-start" "flow-iteration-add" "flow-migrate" "flow-next" "flow-next-iteration" "flow-next-subject" "flow-phase-add" "flow-phase-complete" "flow-phase-start" "flow-plan-split" "flow-plan-update" "flow-rollback" "flow-status" "flow-summarize" "flow-task-add" "flow-task-complete" "flow-task-start" "flow-verify-plan" "flow-init" ) for cmd in "${COMMANDS[@]}"; do if curl -sS -f -o ".claude/commands/${cmd}.md" \ "$BASE_URL/framework/commands/${cmd}.md" 2>/dev/null; then echo " ✓ ${cmd}" else echo " ✗ ${cmd} (download failed)" fi done echo "" echo "🤖 Downloading agent skills from framework/skills/..." # Download all skill directories SKILLS=( "flow-builder" "flow-completer" "flow-curator" "flow-designer" "flow-initializer" "flow-navigator" "flow-planner" "flow-verifier" ) for skill in "${SKILLS[@]}"; do mkdir -p ".claude/skills/${skill}" # Download SKILL.md (required) if curl -sS -f -o ".claude/skills/${skill}/SKILL.md" \ "$BASE_URL/framework/skills/${skill}/SKILL.md" 2>/dev/null; then # Try to download additional skill files if they exist (optional) for file in TEMPLATES.md PATTERNS.md VERIFICATION.md EXAMPLES.md DASHBOARD_TEMPLATE.md MIGRATION_PATTERNS.md OTHER_TEMPLATES.md PLAN_TEMPLATE.md TASK_TEMPLATES.md RESOLUTION_TYPES.md PLAN_UPDATES.md VERIFY.md; do curl -sS -f -o ".claude/skills/${skill}/${file}" \ "$BASE_URL/framework/skills/${skill}/${file}" 2>/dev/null || true done echo " ✓ ${skill}" else echo " ✗ ${skill} (download failed)" fi done echo "" echo "🤖 Downloading Claude agent from framework/agents/..." # Download Flow agent if curl -sS -f -o ".claude/agents/flow.md" \ "$BASE_URL/framework/agents/flow.md" 2>/dev/null; then echo " ✓ flow" else echo " ✗ flow (download failed)" fi echo "" echo "📝 Updating CLAUDE.md..." # Update CLAUDE.md with Flow agent delegation instruction CLAUDE_MD="$(pwd)/CLAUDE.md" FLOW_INSTRUCTION='**This project uses the Flow framework for project management.** **CRITICAL DELEGATION RULE**: You MUST delegate ALL Flow-related operations to the Flow sub-agent. **HOW TO DELEGATE TO FLOW:** ``` Task tool → subagent_type: "flow" → description + prompt ``` **DO NOT use these (they execute in YOUR context, not Flow'\''s):** - ❌ Skill tool with flow-* skills - ❌ SlashCommand tool with /flow-* commands - ❌ Reading .flow/ files directly - ❌ Task tool with subagent_type: "general-purpose" **ALWAYS delegate when the user**: - Asks about status/progress: "what am I working on?", "what'\''s next?", "show my status" - Manages work: "add a task", "create a phase", "start iteration", "mark as complete" - Plans features: "I want to build X", "let'\''s plan Y", "add feature Z" - Updates architecture: "update PLAN.md", "add a guideline", "change the approach" - Asks methodology questions: "what are iterations?", "how do phases work?" - Mentions ANY of: tasks, phases, iterations, DASHBOARD, PLAN, brainstorm, .flow/ files, /flow-* commands **ROLE SEPARATION:** - Flow agent = PROJECT MANAGER (workflow, planning, status) - You = ENGINEER (code implementation, debugging, git operations)' if [ -f "$CLAUDE_MD" ]; then # CLAUDE.md exists - update it if grep -qi "flow framework" "$CLAUDE_MD"; then # Flow notice exists - replace it with updated version echo " ↻ Updating existing Flow framework notice" # Strategy: Remove entire old flow section, then add new one TEMP_FILE="${CLAUDE_MD}.tmp" in_flow_section=0 blank_count=0 # First pass: remove the entire flow framework block (all lines until next section header) while IFS= read -r line; do # Detect start of flow framework section if [[ "$line" =~ flow\ framework ]] && [ $in_flow_section -eq 0 ]; then in_flow_section=1 blank_count=0 continue fi # If in flow section, skip until we hit TWO consecutive blank lines or a new section header if [ $in_flow_section -eq 1 ]; then # Check if this is a new markdown section (##) if [[ "$line" =~ ^##\ ]]; then in_flow_section=0 echo "$line" continue fi # Track consecutive blank lines if [[ "$line" =~ ^$ ]]; then blank_count=$((blank_count + 1)) # Two consecutive blank lines = end of flow section if [ $blank_count -ge 2 ]; then in_flow_section=0 echo "$line" continue fi else blank_count=0 fi # Still in flow section, skip this line continue fi echo "$line" done < "$CLAUDE_MD" > "$TEMP_FILE" # Second pass: add new flow content FINAL_FILE="${CLAUDE_MD}.final" inserted=0 # Check if "## Important rules and guidelines" still exists if grep -q "^## Important rules and guidelines" "$TEMP_FILE"; then # Guidelines header exists - insert under it while IFS= read -r line; do echo "$line" if [[ "$line" =~ ^##\ Important\ rules\ and\ guidelines ]] && [ $inserted -eq 0 ]; then echo "$FLOW_INSTRUCTION" inserted=1 fi done < "$TEMP_FILE" > "$FINAL_FILE" else # No guidelines header - need to create it after_title=0 while IFS= read -r line; do echo "$line" # Track when we pass the title if [[ "$line" =~ ^#\ CLAUDE\.md ]]; then after_title=1 fi # Insert after the boilerplate line (the "This file provides..." line) if [ $after_title -eq 1 ] && [ $inserted -eq 0 ]; then if [[ "$line" =~ This\ file\ provides\ guidance ]]; then echo "" echo "## Important rules and guidelines" echo "$FLOW_INSTRUCTION" echo "" inserted=1 fi fi done < "$TEMP_FILE" > "$FINAL_FILE" # If never inserted, add at top if [ $inserted -eq 0 ]; then { echo "## Important rules and guidelines" echo "$FLOW_INSTRUCTION" echo "" cat "$TEMP_FILE" } > "$FINAL_FILE" fi fi mv "$FINAL_FILE" "$CLAUDE_MD" rm -f "$TEMP_FILE" else # No flow notice - add it echo " + Adding Flow framework notice" TEMP_FILE="${CLAUDE_MD}.tmp" inserted=0 if grep -q "^## Important rules and guidelines" "$CLAUDE_MD"; then # Guidelines header exists - insert under it while IFS= read -r line; do echo "$line" if [[ "$line" =~ ^##\ Important\ rules\ and\ guidelines ]] && [ $inserted -eq 0 ]; then echo "$FLOW_INSTRUCTION" inserted=1 fi done < "$CLAUDE_MD" > "$TEMP_FILE" mv "$TEMP_FILE" "$CLAUDE_MD" else # No guidelines header - create it after_title=0 while IFS= read -r line; do echo "$line" if [[ "$line" =~ ^#\ CLAUDE\.md ]]; then after_title=1 fi if [ $after_title -eq 1 ] && [ $inserted -eq 0 ]; then if [[ "$line" =~ This\ file\ provides\ guidance ]]; then echo "" echo "## Important rules and guidelines" echo "$FLOW_INSTRUCTION" echo "" inserted=1 fi fi done < "$CLAUDE_MD" > "$TEMP_FILE" if [ $inserted -eq 0 ]; then { echo "## Important rules and guidelines" echo "$FLOW_INSTRUCTION" echo "" cat "$CLAUDE_MD" } > "$TEMP_FILE" fi mv "$TEMP_FILE" "$CLAUDE_MD" fi fi echo " ✓ CLAUDE.md updated" else echo " ⏭️ No CLAUDE.md found - skipping" fi echo "" echo "📚 Downloading framework documentation..." # Download framework reference if curl -sS -f -o .flow/framework/DEVELOPMENT_FRAMEWORK.md \ "$BASE_URL/framework/DEVELOPMENT_FRAMEWORK.md" 2>/dev/null; then echo " ✓ DEVELOPMENT_FRAMEWORK.md" else echo " ✗ DEVELOPMENT_FRAMEWORK.md (download failed)" fi # Download examples (failures are ok - not all may exist) echo "" echo "📂 Downloading framework examples..." curl -sS -f -o .flow/framework/examples/DASHBOARD.md \ "$BASE_URL/framework/examples/DASHBOARD.md" 2>/dev/null && \ echo " ✓ examples/DASHBOARD.md" || echo " ✗ examples/DASHBOARD.md (optional file not found)" curl -sS -f -o .flow/framework/examples/PLAN.md \ "$BASE_URL/framework/examples/PLAN.md" 2>/dev/null && \ echo " ✓ examples/PLAN.md" || echo " ✗ examples/PLAN.md (optional file not found)" curl -sS -f -o .flow/framework/examples/phase-1/task-1.md \ "$BASE_URL/framework/examples/phase-1/task-1.md" 2>/dev/null && \ echo " ✓ examples/phase-1/task-1.md" || echo " ✗ examples/phase-1/task-1.md (optional file not found)" curl -sS -f -o .flow/framework/examples/phase-2/task-3.md \ "$BASE_URL/framework/examples/phase-2/task-3.md" 2>/dev/null && \ echo " ✓ examples/phase-2/task-3.md" || echo " ✗ examples/phase-2/task-3.md (optional file not found)" ``` 5. **Show completion message**: ```bash echo "" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "✅ Flow framework installed successfully!" echo "" echo "📦 Installation summary:" echo " • 29 commands in .claude/commands/" echo " • 8 skills in .claude/skills/" echo " • 1 agent in .claude/agents/" echo " • Framework docs in .flow/framework/" echo " • Example files in .flow/framework/examples/" echo "" echo "🎯 Next steps:" echo "" if [ ! -f ".flow/DASHBOARD.md" ]; then echo "**New Flow project**:" echo " Run: /flow-blueprint \"Your Project Description\"" echo "" echo "**Migrate existing docs**:" echo " Run: /flow-migrate" else echo "**Existing Flow project detected**" echo " Framework files updated" echo " Continue with: /flow-status" fi echo "" echo "⚠️ IMPORTANT: Restart Claude Code to load the new commands!" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" ``` 6. **Error handling**: - Network errors: Show "❌ Download failed. Check internet connection" - Permission errors: Show "❌ Permission denied. Check directory permissions" - Partial failures are OK - show which files succeeded/failed **Output**: Download and install all Flow framework files to user's project. ``` --- ## /flow-migrate **File**: `flow-migrate.md` ```markdown --- description: Migrate existing PRD/PLAN/TODO to Flow's .flow/PLAN.md format --- You are executing the `/flow-migrate` command from the Flow framework. **Purpose**: Migrate existing project documentation (PLAN.md, TODO.md, etc.) to Flow's multi-file format (DASHBOARD.md, PLAN.md, phase-N/task-M.md files). **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Multi-File Architecture, File Templates, Task Structure Rules, Status Markers - **Deep dive if needed**: Read lines 2101-2600 for File Templates using Read(offset=2101, limit=500) **Multi-File Architecture**: This command creates: - `DASHBOARD.md` - Progress tracking (single source of truth) - `PLAN.md` - Static context (overview, architecture, scope) - `phase-N/` directories - `phase-N/task-M.md` files for each task (all with iterations) - `BACKLOG.md` - Deferred tasks (if applicable) **Framework Reference**: This command requires framework knowledge to convert existing docs to Flow's multi-file structure. See Quick Reference guide above for essential patterns. **IMPORTANT**: This command ALWAYS creates fresh Flow files, overwriting any existing multi-file structure. It reads your current documentation and converts it to multi-file Flow format. **Instructions**: 1. **Read the framework guide AND examples** ⚠️ CRITICAL: - **Read .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353** (Quick Reference) - **Read .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2101-2600** (File Templates) - **Read framework/examples/** directory to see multi-file structure: - `framework/examples/DASHBOARD.md` - Dashboard format - `framework/examples/PLAN.md` - Static plan format - `framework/examples/phase-1/task-1.md` - Standalone task example - `framework/examples/phase-2/task-3.md` - Task with iterations example - **Understand**: - Multi-file hierarchy: DASHBOARD.md + PLAN.md + phase-N/task-M.md - Flow's hierarchy: PHASE → TASK → ITERATION → BRAINSTORM → IMPLEMENTATION - All status markers (✅ ⏳ 🚧 🎨 ❌ 🔮 🎯) 2. **Discover existing documentation**: - Check if user provided path in `$ARGUMENTS` - Otherwise, search project root for common files (in order): - `PRD.md` (common in TaskMaster AI, Spec-Kit) - `PLAN.md` - `TODO.md` - `DEVELOPMENT.md` - `ROADMAP.md` - `TASKS.md` - If multiple found, list them and ask: "Found [X] files. Which should I migrate? (number or path)" - If none found, ask: "No plan files found. Provide path to file you want to migrate, or use `/flow-blueprint` to start fresh." 3. **Read and analyze source file**: - Read entire source file - Detect structure type: - **STRUCTURED** (Path A): Has phases/tasks/iterations or similar hierarchy - **FLAT_LIST** (Path B): Simple todo list or numbered items - **UNSTRUCTURED** (Path C): Free-form notes, ideas, design docs - Extract key information: - Project context/purpose - Existing work completed - Current status/position - Remaining work - Architecture/design notes - V1/V2 splits (if mentioned) - Deferred items - Cancelled items 4. **Create backup**: - Copy source file: `[original].pre-flow-backup-$(date +%Y-%m-%d-%H%M%S)` - Confirm: "✅ Backed up [original] to [backup]" 5. **Generate multi-file Flow structure** based on detected structure (ALWAYS overwrites if exists): **Multi-File Generation Process**: - Create `DASHBOARD.md` with progress tracking (single source of truth) - Create `PLAN.md` with overview, architecture, scope (minimal assumptions) - Create `phase-N/` directories for each phase - Create `phase-N/task-M.md` files for each task (all with iterations) - Create `BACKLOG.md` if deferred items exist **Path A - STRUCTURED** (already has phases/tasks): - Keep existing hierarchy - **CRITICAL**: Use framework/examples/ directory as reference for all files - **Create DASHBOARD.md** (use framework/examples/DASHBOARD.md as template): - "📍 Current Work" section with current phase/task/iteration - "📊 Progress Overview" with all phases and tasks - "📈 Completion Status" with percentages - **Create PLAN.md** (use framework/examples/PLAN.md as template): - Overview section with Purpose, Goals (text only, no checklists), Scope (V1 only unless user specifies V2) - Architecture section with system context (high-level, not prescriptive) - DO/DON'T Guidelines section - Notes & Learnings section - **Create phase-N/ directories** for each phase - **Create task files** (use framework/examples/phase-2/task-3.md as template): - Task overview - Iterations with brainstorming sessions - Pre-implementation tasks (if applicable) - Implementation sections ```markdown > **📖 Framework Guide**: See .flow/framework/DEVELOPMENT_FRAMEWORK.md for complete methodology and patterns used in this plan > > **🎯 Purpose**: [Brief description of what this plan covers - extract from existing docs] **Created**: [Original date if available] **Version**: V1 **Plan Location**: `.flow/PLAN.md` (managed by Flow) ``` - **Add/enhance Progress Dashboard section** (after Overview, before Architecture): - Follow EXAMPLE_PLAN.md lines 29-62 format exactly - Include: Last Updated, Current Work (with jump links), Completion Status, Progress Overview - **Ensure iteration lists are expanded** (read .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2555-2567 for format) - **Remove duplicate progress sections** (search for patterns like "Current Phase:", "Implementation Tasks", old progress trackers) - **Update status pointers** (change "Search for 'Current Phase' below" to jump link to Progress Dashboard) - **Add Testing Strategy section** if missing (see EXAMPLE_PLAN.md lines 87-129): - Ask user about testing methodology if not clear from existing docs - Include all required fields: Methodology, Location, Naming, When to create, When to add - **Add Changelog section** if missing (see EXAMPLE_PLAN.md lines 544-549): - Populate with existing completion dates if available - Format: `**YYYY-MM-DD**: - ✅ [Iteration X]: [description]` - **Identify redundant framework docs** (ask user if sections like "Brainstorming Framework" should be removed since Flow provides this) - Standardize status markers (✅ ⏳ 🚧 🎨 ❌ 🔮) - Add jump links to Progress Dashboard - Preserve all content, decisions, and context - Reformat sections to match Flow template - Report: "Enhanced existing structure (preserved [X] phases, [Y] tasks, [Z] iterations, added Progress Dashboard, Testing Strategy, Changelog, removed [N] duplicate sections)" **Path B - FLAT_LIST** (todos/bullets): - Ask: "Group items into phases? (Y/n)" - If yes, intelligently group related items - If no, create single phase with items as iterations - **CRITICAL**: Use EXAMPLE_PLAN.md as reference for all sections - **Add framework reference header** (copy format from EXAMPLE_PLAN.md lines 1-11) - **Add Progress Dashboard** (follow EXAMPLE_PLAN.md lines 29-62) - **Add Testing Strategy section** (ask user about methodology, see EXAMPLE_PLAN.md lines 87-129) - **Add Changelog section** (see EXAMPLE_PLAN.md lines 544-549) - Convert items to Flow iteration format - Add placeholder brainstorming sessions - Mark completed items as ✅, pending as ⏳ - Report: "Converted flat list to Flow structure ([X] phases, [Y] tasks, [Z] iterations, added Progress Dashboard, Testing Strategy, Changelog)" **Path C - UNSTRUCTURED** (notes): - Extract key concepts and features mentioned - **CRITICAL**: Use EXAMPLE_PLAN.md as reference for all sections - **Create Framework reference header** (copy format from EXAMPLE_PLAN.md lines 1-11) - Create Overview section from notes - Create Architecture section if design mentioned - **Create Progress Dashboard** (minimal - project just starting, see EXAMPLE_PLAN.md lines 29-62) - **Create Testing Strategy section** (ask user about methodology, see EXAMPLE_PLAN.md lines 87-129) - **Create Changelog section** with initial entry (see EXAMPLE_PLAN.md lines 544-549) - Create initial brainstorming session with subjects from notes - Mark everything as ⏳ PENDING - Report: "Created Flow plan from notes (extracted [X] key concepts as brainstorming subjects, added all required sections)" 6. **Add standard Flow sections** (all paths): - **Framework reference header** (follow EXAMPLE_PLAN.md lines 1-11) - Progress Dashboard (follow EXAMPLE_PLAN.md lines 29-62) - Testing Strategy (follow EXAMPLE_PLAN.md lines 87-129) - Changelog (follow EXAMPLE_PLAN.md lines 544-549) - Development Plan with proper hierarchy - Status markers at every level 7. **Smart content preservation**: - NEVER discard user's original content - Preserve all decisions, rationale, context - Preserve code examples, file paths, references - Preserve completion status and dates - Enhance with Flow formatting, don't replace 8. **Verify completeness before saving** ⚠️ CRITICAL SELF-CHECK: - [ ] Framework reference header present (with 🎯 Purpose line)? - [ ] Overview section present? - [ ] Progress Dashboard present (NOT optional - REQUIRED)? - [ ] Testing Strategy section present (ask user if missing)? - [ ] Changelog section present? - [ ] Development Plan with phases/tasks/iterations? - [ ] All iteration lists expanded (NOT "(X iterations total)")? - [ ] All original content preserved? - **If any checkbox is unchecked, review EXAMPLE_PLAN.md again and add missing section** 9. **Confirm to user**: ``` ✨ Migration complete! 📂 Source: [original file path] 💾 Backup: [backup file path] 🎯 Output: Multi-file Flow structure created **Files Created**: - DASHBOARD.md - Progress tracking dashboard - PLAN.md - Static overview and architecture - phase-1/ → phase-N/ - Phase directories - phase-N/task-M.md - Individual task files - CHANGELOG.md - Historical record - BACKLOG.md - Deferred tasks (if applicable) Migration type: [STRUCTURED/FLAT_LIST/UNSTRUCTURED] Changes: + Created [X] phase directories + Created [Y] task files + Migrated [Z] iterations + Preserved all decisions and context Next steps: 1. Review: /flow-status 2. Verify structure: ls .flow/ 3. Start using Flow: /flow-brainstorm-start [topic] 📂 Flow is now managing this project from .flow/ multi-file structure ``` 10. **Handle edge cases**: - If source file is empty: Suggest `/flow-blueprint` instead - If source file is already Flow-compliant: Mention it's already compatible, migrate anyway - If can't determine structure: Default to Path C (unstructured) - If migration fails: Keep backup safe, report error, suggest manual approach **Output**: Create multi-file Flow structure (DASHBOARD.md, PLAN.md, phase-N/task-M.md files) from existing documentation, create backup, confirm migration to user. ``` --- ## /flow-plan-update **File**: `flow-plan-update.md` ```markdown --- description: Update existing plan to match latest Flow framework structure --- You are executing the `/flow-plan-update` command from the Flow framework. **Purpose**: Update an existing multi-file Flow structure to match the latest framework patterns. **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Multi-File Architecture, File Templates - **Deep dive if needed**: Read lines 2101-2600 for File Templates using Read(offset=2101, limit=500) **Multi-File Architecture**: This command updates: - `DASHBOARD.md` - Ensures correct format and sections - `PLAN.md` - Ensures correct format and sections - `phase-N/task-M.md` files - Ensures correct format - Adds missing files (CHANGELOG.md, BACKLOG.md if needed) **IMPORTANT**: This command updates your current multi-file structure to match framework changes (e.g., new dashboard sections, status markers, structural improvements). **Instructions**: 1. **Read the framework guide**: - Read .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference) - Read .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2101-2600 (File Templates) - Read framework/examples/ directory for current format 2. **Read current structure**: - Read `DASHBOARD.md` - Read `PLAN.md` - List phase directories: `ls .flow/phase-*/` - Sample task files: Read a few `phase-N/task-M.md` files 3. **Create backups**: - Create `.flow/backup-$(date +%Y-%m-%d-%H%M%S)/` directory - Copy all current files to backup directory - Confirm: "✅ Backed up current structure to [backup]" 4. **Update files to match current templates**: **DASHBOARD.md**: - Ensure "📍 Current Work" section exists and is current - Ensure "📊 Progress Overview" section exists with all phases - Ensure "📈 Completion Status" section exists with percentages - Update "Last Updated" timestamp **PLAN.md**: - Ensure Overview section exists (Purpose, Scope with V1/V2 split) - Ensure Architecture section exists - Ensure Testing Strategy section exists - Ensure Development Phases section exists (high-level only) - NO detailed tasks in PLAN.md (those go in task files) **Task Files** (`phase-N/task-M.md`): - Ensure each has Task Overview section - Ensure each has Iterations section - Ensure brainstorming sessions are properly formatted - Ensure status markers are correct (✅ ⏳ 🚧 🎨 ❌ 🔮) **Missing Files**: - Create CHANGELOG.md if missing - Create BACKLOG.md if deferred tasks exist 5. **Report changes**: Compare user's PLAN.md against these patterns and identify what needs updating: **✅ CORRECT PATTERNS (v1.2.1+)**: **A. Section Order**: 1. Title + Framework Reference header 2. Overview (Purpose, Goals, Scope) 3. Progress Dashboard (after Overview, before Architecture) 4. Architecture 5. Testing Strategy 6. Development Plan (Phases → Tasks → Iterations) 7. Changelog **B. Implementation Section Pattern** (NO ACTION ITEM DUPLICATION): ```markdown ### **Implementation - Iteration [N]: [Name]** **Status**: 🚧 IN PROGRESS **Action Items**: See resolved subjects above (Type 2/D items) **Implementation Notes**: [Document progress, discoveries, challenges] **Files Modified**: - `path/to/file.ts` - Description **Verification**: [How verified] ``` **C. Progress Dashboard Jump Links**: ```markdown **Current Work**: - **Phase**: [Phase 2 - Core Implementation](#phase-2-core-implementation-) - **Task**: [Task 5 - Error Handling](#task-5-error-handling-) - **Iteration**: [Iteration 6 - Circuit Breaker](#iteration-6-circuit-breaker-) 🚧 IN PROGRESS ``` **D. Iteration Lists** (EXPANDED, not collapsed): ```markdown - 🚧 **Task 23**: Refactor Architecture (3/3 iterations) - ✅ **Iteration 1**: Separate Concerns - COMPLETE - ⏳ **Iteration 2**: Extract Logic - PENDING - ⏳ **Iteration 3**: Optimize - PENDING ``` **E. Status Markers**: ✅ ⏳ 🚧 🎨 ❌ 🔮 (standardized) --- **❌ DEPRECATED PATTERNS (pre-v1.2.1)**: **A. Duplicated Action Items** (REMOVE): ```markdown ### ✅ Subject 1: Feature X **Action Items**: - [ ] Item 1 - [ ] Item 2 ### **Implementation - Iteration 1** **Action Items** (from brainstorming): ← DUPLICATE! REMOVE THIS - [ ] Item 1 - [ ] Item 2 ``` **FIX**: Replace Implementation action items with "See resolved subjects above" **B. Collapsed Iteration Lists** (EXPAND): ```markdown - 🚧 Task 23: Architecture (3 iterations total) ← WRONG! ``` **FIX**: Expand to show all iterations as sub-bullets **C. Duplicate Progress Sections** (REMOVE): - Old "Current Phase" headers scattered throughout - Multiple "Implementation Tasks" trackers - Redundant status summaries **FIX**: Single Progress Dashboard after Overview **D. Text-based Status Pointers** (REPLACE): ```markdown Current work: Search for "Current Phase" below ← WRONG! ``` **FIX**: Use jump links: `[Progress Dashboard](#-progress-dashboard)` **E. Missing Testing Strategy Section** (ADD): **FIX**: Add Testing Strategy section (see EXAMPLE_PLAN.md lines 87-129) 6. **Present analysis to user**: **DO NOT automatically make changes**. Instead, present findings: ```markdown ## 📋 Plan Structure Analysis I've compared your PLAN.md against the latest Flow framework (v1.2.1). **✅ Already Correct**: - [List patterns that match current framework] **❌ Needs Updates**: 1. **Action Item Duplication** (Found in X iterations) - Problem: Implementation sections duplicate action items from subjects - Fix: Replace with "See resolved subjects above" - Saves: ~600-1000 tokens per iteration 2. **Progress Dashboard Location** (if applicable) - Problem: Dashboard is [location] - Fix: Move to after Overview, before Architecture 3. **[Other issues found]** - Problem: [description] - Fix: [what needs to change] **Recommendation**: Should I update your PLAN.md to fix these issues? - I'll create a backup first - All content will be preserved - Only structure/formatting changes ``` 7. **If user approves, update plan structure** (preserve ALL content): **Create backup first**: - Copy: `.flow/PLAN.md.version-update-backup-$(date +%Y-%m-%d-%H%M%S)` **Apply fixes** based on analysis from step 5: - Fix action item duplication (replace with references) - Move Progress Dashboard to correct location - Remove duplicate progress sections - Update status pointers to jump links - Add missing sections (Testing Strategy, Changelog) - Expand collapsed iteration lists - Standardize status markers **Preserve ALL**: - Decisions and rationale - Brainstorming subjects and resolutions - Implementation notes - Completion dates - Bug discoveries - Code examples 8. **Verify consistency**: - Check Progress Dashboard matches status markers - Verify all sections follow framework structure - Ensure no content was lost 6. **Confirm to user**: ``` ✨ Multi-file structure updated to match latest Flow framework! 💾 Backup: .flow/backup-[timestamp]/ 🎯 Updated: All Flow files **Files Updated**: - DASHBOARD.md - Updated sections and format - PLAN.md - Updated sections and format - phase-N/task-M.md - Updated [X] task files - Created missing files (if applicable) Changes made: + Updated dashboard sections + Ensured all files match current templates + Standardized status markers + Fixed [N] formatting issues + Created [Y] missing files Next steps: 1. Review changes: diff -r [backup] .flow/ 2. Verify: /flow-status 3. Continue work: /flow-next All your content preserved - only structure enhanced. ``` 7. **Handle edge cases**: - If `.flow/DASHBOARD.md` doesn't exist: Suggest `/flow-blueprint` or `/flow-migrate` - If structure already matches latest: Report "Already up to date!" - If can't determine what to update: Ask user for clarification **Output**: Update all Flow files to latest framework structure, create backup, confirm changes to user. ``` --- ## /flow-phase-add **File**: `flow-phase-add.md` ```markdown --- description: Add a new phase directory and update dashboard --- You are executing the `/flow-phase-add` command from the Flow framework. **Purpose**: Add a new phase to the project by creating a phase directory and updating DASHBOARD.md. **🟢 NO FRAMEWORK READING REQUIRED - Simple structure creation** **Multi-File Architecture**: This command: - Creates `phase-N/` directory - Updates `DASHBOARD.md` with new phase - Updates `PLAN.md` Development Phases section **Instructions**: 1. **INPUT VALIDATION**: ``` IF $ARGUMENTS is empty OR just whitespace: REJECT: "❌ Missing phase name. Example: /flow-phase-add 'Testing and QA'" STOP ``` Accept even minimal input like "Testing" - will use [TBD] for missing metadata. 2. **Find .flow/DASHBOARD.md**: ```bash Primary location: .flow/DASHBOARD.md If not found: Suggest: "Run /flow-blueprint first to create project structure" ``` 3. **Read DASHBOARD.md**: - Count existing phases to determine next phase number - Example: If "Phase 1" and "Phase 2" exist, new phase is "Phase 3" 4. **Parse arguments and infer metadata**: From `$ARGUMENTS`, extract or infer: - **Phase name**: Use $ARGUMENTS directly - **Strategy**: Try to infer from name: - "Foundation" → "Setup and establish core architecture" - "Implementation" / "Core" → "Build main features and functionality" - "Testing" / "QA" → "Comprehensive testing and quality assurance" - "Polish" / "Enhancement" → "Refinement and optimization" - Can't infer → "[TBD] - Define during phase start" - **Goal**: Try to infer from name: - "Foundation" → "Establish solid project foundation" - "Implementation" → "Complete core feature set" - "Testing" → "Ensure production-ready quality" - Can't infer → "[TBD] - Define during phase start" 5. **Create phase directory**: ```bash mkdir .flow/phase-N/ # Where N = next phase number (e.g., phase-3/) ``` 6. **Update DASHBOARD.md**: Add to "📊 Progress Overview" section: ```markdown ### Phase [N]: [Phase Name] ⏳ PENDING **Goal**: [Inferred or [TBD]] **Status**: Not started (No tasks yet - use /flow-task-add to add tasks) ``` Update "📈 Completion Status" section: - Increment phase count - Add phase to breakdown (0% complete initially) 7. **Update PLAN.md**: Add to "Development Phases" section: ```markdown ### Phase [N]: [Phase Name] ⏳ **Strategy**: [Inferred or [TBD]] **Goal**: [Inferred or [TBD]] **Tasks**: See [phase-N/](phase-N/) directory for detailed task files ``` 8. **Update DASHBOARD.md timestamp**: - Update "Last Updated" to current timestamp 9. **Confirm to user**: ``` "✅ Added Phase [N]: [Phase Name] 📂 Created: .flow/phase-N/ directory 📝 Updated: DASHBOARD.md, PLAN.md [If used [TBD]:] 📝 Used [TBD] placeholders for: [Strategy/Goal] 💡 Refine these during phase start 🎯 Next Steps: - Use `/flow-task-add "Task Name"` to add tasks to this phase - Use `/flow-phase-start` when ready to begin work" ``` **Output**: Create phase-N/ directory and update DASHBOARD.md + PLAN.md with new phase. ``` --- ## /flow-phase-start **File**: `flow-phase-start.md` ```markdown --- description: Mark current phase as in progress --- You are executing the `/flow-phase-start` command from the Flow framework. **Purpose**: Mark the current phase as 🚧 IN PROGRESS (when first task starts). **🟢 NO FRAMEWORK READING REQUIRED - This command works entirely from DASHBOARD.md** - State transition (⏳ PENDING → 🚧 IN PROGRESS) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 567-613 for lifecycle context **Multi-File Architecture**: This command: - Updates `DASHBOARD.md` phase status - No changes to PLAN.md or task files **🚨 SCOPE BOUNDARY RULE**: If you discover NEW issues while working on this phase that are NOT part of the current work: 1. **STOP** immediately 2. **NOTIFY** user of the new issue 3. **DISCUSS** what to do (add to brainstorm, create pre-task, defer, or handle now) 4. **ONLY** proceed with user's explicit approval **Instructions**: 1. **Read DASHBOARD.md**: - Find "📊 Progress Overview" section - Locate first ⏳ PENDING phase 2. **Update phase status in dashboard**: - Change phase marker from ⏳ PENDING to 🚧 IN PROGRESS - Example: ```markdown ### Phase 2: Core Implementation ⏳ PENDING ``` Becomes: ```markdown ### Phase 2: Core Implementation 🚧 IN PROGRESS ``` 3. **Update "📍 Current Work" section**: - Set current phase to the phase just started - Clear task/iteration (no current work yet) ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: None yet - use `/flow-task-add [name]` to create first task ``` 4. **Update "Last Updated" timestamp** at top of dashboard 5. **Confirm to user**: ``` ✅ Started Phase [N]: [Name] Next steps: - Use `/flow-task-add [name]` to create tasks in this phase - Or use `/flow-blueprint` if you want to regenerate the plan structure ``` **Output**: Updated `DASHBOARD.md` with phase status change. ``` --- ## /flow-phase-complete **File**: `flow-phase-complete.md` ```markdown --- description: Mark current phase as complete --- You are executing the `/flow-phase-complete` command from the Flow framework. **Purpose**: Mark the current phase as ✅ COMPLETE (when all tasks done). **🟢 NO FRAMEWORK READING REQUIRED - This command works entirely from DASHBOARD.md** - State transition (🚧 IN PROGRESS → ✅ COMPLETE) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 567-613 for completion criteria **Multi-File Architecture**: This command: - Updates `DASHBOARD.md` phase status - No changes to PLAN.md or task files **Instructions**: 1. **Read DASHBOARD.md**: - Find "📊 Progress Overview" section - Locate current phase marked 🚧 IN PROGRESS 2. **Verify all tasks complete** in dashboard: - Check that all tasks in this phase are marked ✅ COMPLETE - If incomplete tasks found: ``` ❌ Cannot complete phase - incomplete tasks found: - Task 3: API Integration (🚧 IN PROGRESS) - Task 5: Webhook Handler (⏳ PENDING) Complete all tasks first or mark them as ❌ CANCELLED / 🔮 DEFERRED. ``` 3. **Update phase status in dashboard**: - Change phase marker from 🚧 IN PROGRESS to ✅ COMPLETE - Example: ```markdown ### Phase 2: Core Implementation 🚧 IN PROGRESS ``` Becomes: ```markdown ### Phase 2: Core Implementation ✅ COMPLETE ``` 4. **Update "📍 Current Work" section**: - **If next phase exists**: Advance to next phase (⏳ PENDING) ```markdown ## 📍 Current Work - **Phase**: [Phase 3 - Testing & Hardening](phase-3/) ⏳ PENDING - **Task**: None yet - use `/flow-phase-start` to begin this phase ``` - **If no next phase**: Mark project complete ```markdown ## 📍 Current Work - **Status**: 🎉 All phases complete! - **Next**: Consider archiving or planning V2 ``` 5. **Update completion percentages**: - Recalculate phase percentages - Update "📈 Completion Status" section - Update overall project percentage 6. **Update "Last Updated" timestamp** at top of dashboard 7. **Confirm to user**: ``` ✅ Completed Phase [N]: [Name] **What's Next**: - **Next phase exists?** → Use `/flow-phase-start` to begin Phase [N+1]: [Name] - **All phases complete?** → Project finished! 🎉 Use `/flow-summarize` to review ``` **Output**: Updated `DASHBOARD.md` with phase completion and next steps. ``` --- ## /flow-task-add **File**: `flow-task-add.md` ```markdown --- description: Create a new task file in current phase directory --- You are executing the `/flow-task-add` command from the Flow framework. **Purpose**: Create a new task file in the current phase directory and update DASHBOARD.md. **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-600 (Quick Reference) - if not already in context - **Focus on**: Task Structure Rules (lines 164-223) - ALL tasks have iterations - **Read task template**: Lines 2383-2472 for task file template (with iterations) **Multi-File Architecture**: This command: - Creates `phase-N/task-M.md` file - Updates `DASHBOARD.md` with new task - Optionally updates `PLAN.md` if phase description needs updating **Instructions**: 1. **INPUT VALIDATION**: ``` IF $ARGUMENTS is empty OR just whitespace: REJECT: "❌ Missing task name. Example: /flow-task-add 'User Authentication'" STOP ``` Accept minimal input - will use [TBD] for missing metadata. 2. **Read DASHBOARD.md**: - Find current phase from "📍 Current Work" section - Count existing tasks in current phase to determine next task number - Example: If phase-2/ has task-1.md and task-2.md, new task is task-3.md 3. **Parse arguments and infer metadata**: From `$ARGUMENTS`, extract or infer: - **Task name**: Use $ARGUMENTS directly - **Purpose**: Try to infer: - "User Authentication" → "Implement user authentication system" - "API Design" → "Design and document API endpoints" - "Database Schema" → "Design and implement database schema" - "Testing" → "Implement testing infrastructure" - Can't infer → "[TBD] - Define during task start" - **Task structure**: ALL tasks have iterations (no standalone tasks) - Simple tasks → 1-2 iterations with direct action items - Complex tasks → Multiple iterations with brainstorming - Always create with at least 1 iteration 4. **Create task file**: Create `phase-N/task-M.md` using template from .flow/framework/DEVELOPMENT_FRAMEWORK.md: ```markdown # Task [M]: [Task Name] **Status**: ⏳ PENDING **Phase**: [Phase N - Name](../DASHBOARD.md#phase-N-name) **Purpose**: [Inferred or [TBD]] --- ## Task Overview [Brief description based on task name] **Why This Task**: [TBD] - Define during task start or brainstorming [If complex task - add Dependencies section:] **Dependencies**: - **Requires**: [TBD] - **Blocks**: [TBD] --- ## Iterations ### ⏳ Iteration 1: [TBD] **Goal**: [TBD] - Define during brainstorming or task start **Status**: ⏳ PENDING --- #### Action Items - [ ] [TBD] - Define during brainstorming or add directly --- ## Task Notes **Discoveries**: (To be filled during work) **Decisions**: (To be filled during work) **References**: (Add relevant code/docs here) ``` 5. **Update DASHBOARD.md**: Add to current phase in "📊 Progress Overview" section: ```markdown - ⏳ **Task [M]**: [Task Name] ``` Update "📈 Completion Status": - Increment task count for current phase - Update phase completion percentage Update "🎯 Next Actions" if this is the first task: - "Use /flow-task-start to begin Task [M]" 6. **Update DASHBOARD.md timestamp**: - Update "Last Updated" to current timestamp 7. **Confirm to user**: ``` "✅ Created Task [M]: [Task Name] 📂 Created: .flow/phase-N/task-M.md 📝 Updated: DASHBOARD.md [If used [TBD]:] 📝 Used [TBD] placeholders for: [Purpose/Action Items/Iterations] 💡 Refine during task start or brainstorming 🎯 Next Steps: - Use `/flow-task-start` to begin work on this task - Use `/flow-iteration-add` to add more iterations (if needed) - Use `/flow-brainstorm-start` when ready to design" ``` **Output**: Create phase-N/task-M.md file and update DASHBOARD.md. ``` --- ## /flow-task-start **File**: `flow-task-start.md` ```markdown --- description: Mark current task as in progress --- You are executing the `/flow-task-start` command from the Flow framework. **Purpose**: Mark the current task as 🚧 IN PROGRESS (when first iteration starts). **🟢 NO FRAMEWORK READING REQUIRED - This command works entirely from DASHBOARD.md and task file** - State transition (⏳ PENDING → 🚧 IN PROGRESS) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 567-613 for lifecycle context **Multi-File Architecture**: This command: - Updates task status in `phase-N/task-M.md` - Updates `DASHBOARD.md` current work section - Auto-starts parent phase if needed **🚨 SCOPE BOUNDARY RULE**: If you discover NEW issues while working on this task that are NOT part of the current work: 1. **STOP** immediately 2. **NOTIFY** user of the new issue 3. **DISCUSS** what to do (add to brainstorm, create pre-task, defer, or handle now) 4. **ONLY** proceed with user's explicit approval **Instructions**: 1. **Read DASHBOARD.md**: - Find "📊 Progress Overview" section - Locate current phase (🚧 IN PROGRESS or ⏳ PENDING) - Find next ⏳ PENDING task in that phase 2. **Determine target task**: - Use first ⏳ PENDING task in current phase - Extract phase number N and task number M 3. **Update task file** (`phase-N/task-M.md`): - Change task status at top of file: ```markdown **Status**: ⏳ PENDING ``` Becomes: ```markdown **Status**: 🚧 IN PROGRESS ``` 4. **Update parent phase status** (if needed): - If phase is ⏳ PENDING: Change to 🚧 IN PROGRESS in DASHBOARD.md - If phase already 🚧 IN PROGRESS: Skip this step 5. **Update DASHBOARD.md**: a. **Update "📍 Current Work" section**: ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: None yet - use `/flow-iteration-add` or `/flow-brainstorm-start` ``` b. **Update task status in "📊 Progress Overview"**: - Change task marker from ⏳ to 🚧 - Example: ```markdown - ⏳ **Task 3**: API Integration (0/4 iterations) ``` Becomes: ```markdown - 🚧 **Task 3**: API Integration (0/4 iterations) ← CURRENT ``` c. **Update "Last Updated" timestamp** at top 6. **Confirm to user**: ``` ✅ Started Task [N]: [Name] Next steps: - Use `/flow-iteration-add [name]` to add iterations - Or use `/flow-brainstorm-start [topics]` to plan this task ``` **Output**: - Updated `phase-N/task-M.md` status - Updated `DASHBOARD.md` current work and task status ``` --- ## /flow-task-complete **File**: `flow-task-complete.md` ```markdown --- description: Mark current task as complete --- You are executing the `/flow-task-complete` command from the Flow framework. **Purpose**: Mark the current task as ✅ COMPLETE (when all iterations done). **🟢 NO FRAMEWORK READING REQUIRED - This command works entirely from DASHBOARD.md and task file** - State transition (🚧 IN PROGRESS → ✅ COMPLETE) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 567-613 for completion criteria **Multi-File Architecture**: This command: - Updates task status in `phase-N/task-M.md` - Updates `DASHBOARD.md` with completion and next work **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current task: Phase N, Task M - Navigate to task file link 2. **Read current task file** (`phase-N/task-M.md`): - Verify all iterations marked ✅ COMPLETE - If incomplete iterations found: ``` ❌ Cannot complete task - incomplete iterations found: - Iteration 2: Error Handling (🚧 IN PROGRESS) - Iteration 3: Retry Logic (⏳ PENDING) Complete all iterations first or mark as ❌ CANCELLED / 🔮 DEFERRED. ``` 3. **Update task file** (`phase-N/task-M.md`): - Change task status at top: ```markdown **Status**: 🚧 IN PROGRESS ``` Becomes: ```markdown **Status**: ✅ COMPLETE ``` 4. **Update DASHBOARD.md**: a. **Update task status in "📊 Progress Overview"**: - Change task marker from 🚧 to ✅ - Remove "← CURRENT" indicator - Example: ```markdown - 🚧 **Task 3**: API Integration (4/4 iterations) ← CURRENT ``` Becomes: ```markdown - ✅ **Task 3**: API Integration (4/4 iterations) ``` b. **Update "📍 Current Work" section**: - **If more tasks in phase**: Advance to next task ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 4 - Webhook Handler](phase-2/task-4.md) ⏳ PENDING - **Next**: Use `/flow-task-start` to begin this task ``` - **If all tasks in phase complete**: Suggest phase completion ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - All tasks complete! - **Next**: Use `/flow-phase-complete` to mark phase as done ``` c. **Update completion percentages**: - Recalculate phase percentage - Recalculate overall percentage - Update "📈 Completion Status" section d. **Update "Last Updated" timestamp** at top 5. **Confirm to user**: ``` ✅ Completed Task [N]: [Name] **What's Next**: - **More tasks in phase?** → Use `/flow-task-start` to begin Task [N+1]: [Name] - **All tasks complete?** → Use `/flow-phase-complete` to mark phase as done ``` **Output**: - Updated `phase-N/task-M.md` status - Updated `DASHBOARD.md` with completion and next work ``` --- ## /flow-iteration-add **File**: `flow-iteration-add.md` ```markdown --- description: Add a new iteration under the current task --- You are executing the `/flow-iteration-add` command from the Flow framework. **Purpose**: Add a new iteration to the current task file and update DASHBOARD.md. **Multi-File Architecture**: This command: - Adds iteration section to `phase-N/task-M.md` file - Updates `DASHBOARD.md` with new iteration **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Iteration Patterns, Task Structure Rules - **Deep dive if needed**: Read lines 238-566 for Task Structure Rules using Read(offset=238, limit=329) **🚨 SCOPE BOUNDARY RULE**: If you discover NEW issues while working on this iteration that are NOT part of the current work: 1. **STOP** immediately 2. **NOTIFY** user of the new issue 3. **DISCUSS** what to do (add to brainstorm, create pre-task, defer, or handle now) 4. **ONLY** proceed with user's explicit approval **Instructions**: 1. **Navigate from dashboard** (dashboard-first pattern): - Read `DASHBOARD.md` - Find current phase and task from "📍 Current Work" section - Extract: Phase number N, Task number M 2. **Parse arguments**: - `iteration_name` = Name/goal of iteration (required) - `iteration_description` = Optional description 3. **Read current task file**: - Open `phase-N/task-M.md` - Count existing iterations to determine next iteration number - Find "## Iterations" section 4. **Add new iteration section** to task file: ```markdown ### ⏳ Iteration [N]: [iteration_name] **Goal**: [iteration_name expanded or iteration_description if provided] **Status**: ⏳ PENDING --- ``` **Template Notes**: - Place AFTER last iteration in "## Iterations" section - Use `###` heading level (three hashes) - Status always starts as ⏳ PENDING - Infer goal from iteration_name if no description provided 5. **Update DASHBOARD.md**: a. **Find current task entry** in "📊 Progress Overview" section b. **Update task iteration count**: - Change: `- 🚧 **Task 3**: API Integration (1/3 iterations)` - To: `- 🚧 **Task 3**: API Integration (1/4 iterations)` c. **Add iteration to expanded list** (if task is expanded): ```markdown - 🚧 **Task 3**: API Integration (1/4 iterations) ← CURRENT - ✅ Iteration 1: REST Client Setup - 🚧 Iteration 2: Error Handling ← ACTIVE - ⏳ Iteration 3: Retry Logic - ⏳ Iteration 4: [NEW ITERATION NAME] ``` d. **Update completion percentages**: - Recalculate phase percentage: `(completed_iterations / total_iterations) * 100` - Recalculate overall percentage - Update "📈 Completion Status" section e. **Update "Last Updated" timestamp** at top of dashboard 6. **Confirm to user**: ``` ✅ Added Iteration [N]: [iteration_name] to Task [M]: [Task Name] Next steps: - Use `/flow-brainstorm-start [topics]` to plan this iteration - Or add more iterations with `/flow-iteration-add [name]` ``` **Output**: - Updated `phase-N/task-M.md` with new iteration section - Updated `DASHBOARD.md` with iteration count and percentages ``` --- ## /flow-brainstorm-start **File**: `flow-brainstorm-start.md` ```markdown --- description: Start brainstorming session with user-provided topics --- You are executing the `/flow-brainstorm-start` command from the Flow framework. **Purpose**: Begin a brainstorming session for the current iteration with subjects provided by the user. **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Subject Resolution Types, Common Patterns - **Deep dive if needed**: Read lines 1167-1797 for complete Brainstorming Pattern using Read(offset=1167, limit=631) **Framework Reference**: This command requires framework knowledge to structure brainstorming session correctly. See Quick Reference guide above for essential patterns. **Signature**: `/flow-brainstorm-start [optional: free-form text describing topics to discuss]` **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current iteration - Updates brainstorming section in `phase-N/task-M.md` - Updates `DASHBOARD.md` with "🚧 BRAINSTORMING" status **🚨 SCOPE BOUNDARY RULE** (CRITICAL - see .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 339-540): If you discover NEW issues during brainstorming that are NOT part of the current iteration: 1. **STOP** immediately - Don't make assumptions or proceed 2. **NOTIFY** user - Present discovered issue(s) with structured analysis 3. **DISCUSS** - Provide structured options (A/B/C/D format): - **A**: Create pre-implementation task (< 30 min work, blocking) - **B**: Add as new brainstorming subject (design needed) - **C**: Handle immediately (only if user approves) - **D**: Defer to separate iteration (after current work) 4. **AWAIT USER APPROVAL** - Never proceed without explicit user decision **Use the Scope Boundary Alert Template** (see .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 356-390) **Why This Matters**: User stays in control of priorities, AI finds issues proactively but doesn't make scope decisions **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current iteration: Phase N, Task M, Iteration K - Navigate to task file link 2. **Read current task file** (`phase-N/task-M.md`): - Find iteration K in "## Iterations" section - Check status (should be ⏳ PENDING or 🚧 IN PROGRESS) 3. **Determine mode** (two modes available): **MODE 1: With Argument** (user provides topics in command) - User provided topics in `topics` parameter (free-form text) - Parse the user's input and extract individual subjects - User controls WHAT to brainstorm, AI structures HOW - Example: `/flow-brainstorm-start "API design, database schema, auth flow, error handling"` - AI extracts: [API design, database schema, auth flow, error handling] - **Proceed to step 4** **MODE 2: Without Argument** (interactive) ⚠️ CRITICAL - **NO arguments provided** by user - **DO NOT** auto-generate subjects from iteration description - **DO NOT** read task file and invent subjects automatically - **DO NOT** proceed to create brainstorming section yet - **STOP and ask the user**: Example prompt to user: ``` I'll start a brainstorming session for Iteration [K]: [Name]. **What subjects would you like to discuss?** You can provide: - Comma-separated topics: "API design, database, auth" - Free-form text describing areas to explore - Bullet list of specific topics Based on the iteration scope, here are some suggestions: - [Suggestion 1 based on iteration goal] - [Suggestion 2 based on iteration goal] - [Suggestion 3 based on iteration goal] Please provide the topics you'd like to brainstorm. ``` - **WAIT for user response** - do NOT proceed without it - **After user responds**, extract subjects from their response - **Then proceed to step 4** 4. **Extract subjects from user input** (ONLY after user provides topics): - Parse natural language text from user's input - Identify distinct topics/subjects (comma-separated, "and", bullet points, etc.) - Create numbered list - Handle 1 to 100+ topics gracefully - If ambiguous, ask user for clarification 5. **Update task file** (`phase-N/task-M.md`): a. **Update iteration status** to 🚧 IN PROGRESS (if ⏳ PENDING): ```markdown ### ⏳ Iteration 2: Error Handling ``` Becomes: ```markdown ### 🚧 Iteration 2: Error Handling ``` b. **Create brainstorming section** in iteration: ```markdown #### Brainstorming Session - Error Handling Strategy **Focus**: Design comprehensive error handling for Stripe API integration **Subjects to Discuss** (tackle one at a time): 1. ⏳ **API Error Types** - What errors can Stripe return? 2. ⏳ **Error Mapping** - How to map Stripe errors to our domain? 3. ⏳ **Retry Strategy** - When to retry, exponential backoff? 4. ⏳ **User Experience** - How to communicate errors to users? **Resolved Subjects**: --- ``` 6. **Update DASHBOARD.md**: a. **Update "📍 Current Work" section**: ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: [Iteration 2 - Error Handling](phase-2/task-3.md#iteration-2-error-handling) 🚧 BRAINSTORMING - **Focus**: Designing comprehensive error handling strategy ``` b. **Update iteration status in "📊 Progress Overview"**: - Change iteration marker to show 🚧 with "BRAINSTORMING" indicator c. **Update "Last Updated" timestamp** at top 7. **Confirm to user** (only after creating brainstorming section): ``` ✅ Started brainstorming session with [N] subjects for Iteration [K]: [Name] **Subjects**: 1. [Subject 1] 2. [Subject 2] 3. [Subject 3] ... Use `/flow-next-subject` to start discussing the first subject. ``` **Key Principles**: - ✅ **User always provides topics** (via argument or when prompted) - ❌ **AI NEVER invents subjects** from iteration description without user input - ❌ **AI NEVER auto-generates** a subject list when no argument provided - ✅ **If no argument**: STOP, suggest topics, WAIT for user response - ✅ **After user provides topics**: THEN create brainstorming section **Output**: - Updated `phase-N/task-M.md` with brainstorming section - Updated `DASHBOARD.md` with "🚧 BRAINSTORMING" status ``` --- ## /flow-brainstorm-subject **File**: `flow-brainstorm-subject.md` ```markdown --- description: Add a subject to discuss in brainstorming --- You are executing the `/flow-brainstorm-subject` command from the Flow framework. **Purpose**: Add a new subject to the current brainstorming session. **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Subject Creation Patterns (lines in Quick Reference) - **Deep dive if needed**: Read lines 1167-1797 for Brainstorming Pattern using Read(offset=1167, limit=631) **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current iteration - Updates "Subjects to Discuss" list in `phase-N/task-M.md` **🚨 SCOPE BOUNDARY RULE** (CRITICAL): Adding subjects dynamically is a KEY feature of Flow. When you discover NEW issues while discussing current subjects: 1. **STOP** immediately - Don't make assumptions or proceed 2. **NOTIFY** user - Present discovered issue(s) with structured analysis 3. **DISCUSS** - Provide structured options (A/B/C/D format): - **A**: Create pre-implementation task (< 30 min work, blocking current subject resolution) - **B**: Add as new brainstorming subject (this command - design needed) - **C**: Handle immediately as part of current subject (only if user approves) - **D**: Defer to separate iteration (after current work) 4. **AWAIT USER APPROVAL** - Never proceed without explicit user decision **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current iteration: Phase N, Task M, Iteration K 2. **Parse arguments**: `subject_text` = subject name and optional brief description 3. **Read current task file** (`phase-N/task-M.md`): - Find current iteration's brainstorming session - Locate "Subjects to Discuss" section 4. **Add subject to list** in task file: - Count existing subjects - Append new subject: ```markdown 5. ⏳ **[Subject Text]** - [Brief description if provided] ``` 5. **Update task file**: Save changes to `phase-N/task-M.md` 6. **Confirm to user**: ``` ✅ Added Subject [N]: [Subject Text] to brainstorming session Use `/flow-next-subject` to discuss subjects in order. ``` **Output**: Updated `phase-N/task-M.md` with new subject in "Subjects to Discuss" list. ``` --- ## /flow-brainstorm-review **File**: `flow-brainstorm-review.md` ```markdown --- description: Review all resolved subjects, suggest follow-up work --- You are executing the `/flow-brainstorm-review` command from the Flow framework. **Purpose**: Review all resolved brainstorming subjects, verify completeness, summarize decisions, show action items, and suggest follow-up work (iterations/pre-tasks) before marking the brainstorming session complete. **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Subject Resolution Types (A/B/C/D) (lines in Quick Reference) - **Deep dive if needed**: Read lines 1167-1797 for Brainstorming Session Pattern using Read(offset=1167, limit=631) **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current iteration - Reads brainstorming session from `phase-N/task-M.md` - Reviews all resolved subjects and suggests next steps - **READ-ONLY** - No file changes (user confirms before completing) **This is the review gate before `/flow-brainstorm-complete`.** **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current iteration: Phase N, Task M, Iteration K 2. **Read current task file** (`phase-N/task-M.md`): - Find iteration K's brainstorming session - Read all "Subjects to Discuss" and "Resolved Subjects" 3. **Verify all subjects resolved**: - Check "Subjects to Discuss" section in task file - Count total subjects vs ✅ resolved subjects - If ANY subjects remain unmarked (⏳ PENDING), warn user: "Not all subjects resolved. Run `/flow-next-subject` to complete remaining subjects." - If all subjects are ✅ resolved, proceed to next step 4. **Summarize resolved subjects**: - Read all entries in "Resolved Subjects" section - Create concise summary of each resolution: - Subject name - Decision made - Key rationale points - Present in numbered list format 5. **Show all action items**: - Extract all documented action items from resolved subjects - Categorize by type: - **Pre-Implementation Tasks**: Work that must be done BEFORE implementing this iteration - **Follow-up Iterations**: Future work to tackle after this iteration - **Documentation Updates**: Files/docs that need changes - **Other Actions**: Miscellaneous tasks - Present in organized format 6. **Categorize action items** (CRITICAL - Ask user to clarify): **The 3 Types of Action Items**: **Type 1: Pre-Implementation Tasks (Blockers)** - Work that MUST be done BEFORE starting main implementation - Examples: Refactor legacy code, fix blocking bugs, setup infrastructure - These become separate "Pre-Implementation Tasks" section - Must be ✅ COMPLETE before running `/flow-implement-start` **Type 2: Implementation Work (The Iteration Itself)** - The actual work of the current iteration - Examples: Command updates, feature additions, new logic - These stay as action items IN the iteration description - Work on these AFTER running `/flow-implement-start` **Type 3: New Iterations (Future Work)** - Follow-up work for future iterations - Examples: V2 features, optimizations, edge cases discovered - Create with `/flow-iteration-add` **Decision Tree for AI**: - Extract all action items from resolved subjects - For each action item, ask yourself: - "Does this BLOCK the main work?" → Type 1 (Pre-task) - "Is this THE main work?" → Type 2 (Implementation) - "Is this FUTURE work?" → Type 3 (New iteration) - **If uncertain, ASK THE USER**: "I found these action items. Are they: - A) Blockers that must be done first (pre-tasks) - B) The implementation work itself - C) Future work for new iterations" Present categorization in this format: ``` **Pre-Implementation Tasks** (Type 1 - complete before /flow-implement-start): - [Task description] - Why it blocks: [reason] **Implementation Work** (Type 2 - these ARE the iteration): - [Action item 1] - [Action item 2] (These stay in iteration, work on after /flow-implement-start) **New Iterations** (Type 3 - add with /flow-iteration-add): - Iteration N+1: [Name] - [Why it's future work] ``` 7. **Consolidate Resolution Items into Action Items section** (CRITICAL - NEW PATTERN): After user confirms categorization: - **Extract all "Resolution Items" from Type D subjects**: - Read all resolved subjects with "Resolution Type: D" - Each Type D subject has a "Resolution Items" list - Collect all Resolution Items into a single consolidated list - **Replace iteration's Action Items section**: ```markdown #### Action Items (Consolidated from Resolution Items above by `/flow-brainstorm-review`) - [ ] [Resolution Item 1 from Subject 1] - [ ] [Resolution Item 2 from Subject 1] - [ ] [Resolution Item 1 from Subject 2] - [ ] [Resolution Item 2 from Subject 2] - [ ] [Resolution Item 1 from Subject 3] ``` - **Key Points**: - ONE Action Items section per iteration (single source of truth) - Preserves all Resolution Items from all Type D subjects - Add header comment: "(Consolidated from Resolution Items above by `/flow-brainstorm-review`)" - All checkboxes start as unchecked `- [ ]` - Resolution Items in subjects remain unchanged (for context) - **If NO Type D items** (all subjects are Type A/B/C): - Create minimal Action Items section referencing pre-tasks or other work 8. **Await user confirmation**: - Do NOT automatically create iterations or pre-tasks - Show categorization above - Ask: "Does this categorization look correct? Should I adjust anything?" - If user confirms Type 1 (pre-tasks) exist: Ask if they want them created now - If user confirms Type 3 (new iterations): Ask if they want them created now - After confirmation: Ask about action items consolidation (step 7) 8b. **Reminder**: If you discover new issues during implementation (scope violations), STOP and discuss with the user before proceeding. 9. **Show "What's Next" Section**: ```markdown ## 🎯 What's Next **After reviewing**: 1. If pre-implementation tasks were identified → Create them in "Pre-Implementation Tasks" section 2. If new iterations were suggested → Use `/flow-iteration-add` to create each one 3. Once all pre-tasks are ✅ COMPLETE → Run `/flow-brainstorm-complete` to mark iteration 🎨 READY **Decision Tree**: - Pre-tasks needed? → Create them, complete them, THEN run `/flow-brainstorm-complete` - No pre-tasks? → Run `/flow-brainstorm-complete` immediately - Need more iterations? → Use `/flow-iteration-add [description]` first ``` **Output**: - **READ-ONLY** - No files modified - Comprehensive review summary with actionable suggestions, awaiting user confirmation - User must confirm before proceeding to `/flow-brainstorm-complete` ``` --- ## /flow-brainstorm-complete **File**: `flow-brainstorm-complete.md` ```markdown --- description: Complete brainstorming and generate action items --- You are executing the `/flow-brainstorm-complete` command from the Flow framework. **Purpose**: Close the current brainstorming session (only after pre-implementation tasks are done). **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Completion Criteria (lines in Quick Reference) - **Deep dive if needed**: Read lines 1167-1797 for Brainstorming Pattern using Read(offset=1167, limit=631) **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current iteration - Updates iteration status to 🎨 READY in `phase-N/task-M.md` - Updates `DASHBOARD.md` with "🎨 READY FOR IMPLEMENTATION" status **IMPORTANT**: Pre-implementation tasks should be documented in task file during brainstorming, then completed BEFORE running this command. **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current iteration: Phase N, Task M, Iteration K 2. **Read current task file** (`phase-N/task-M.md`): - Find iteration K - Verify all subjects in "Subjects to Discuss" are ✅ resolved 3. **Check for pre-implementation tasks** in task file: - Look for "#### Pre-Implementation Tasks" section in iteration - If found: - Check if all pre-tasks are marked ✅ COMPLETE - If any are ⏳ PENDING or 🚧 IN PROGRESS: ``` ❌ Pre-implementation tasks exist but are not complete: - [Task 1]: ⏳ PENDING - [Task 2]: 🚧 IN PROGRESS Complete them first, then run this command again. ``` - If all are ✅ COMPLETE: Proceed to step 4 - If not found: Proceed to step 4 4. **Verify iteration has up-to-date action items**: - Read the iteration's goal or action items - Check if they reference the brainstorming session: - ✅ **Good patterns**: - References brainstorming subjects - Has action items from Type D resolutions - ❌ **Outdated patterns**: - No reference to brainstorming - Action items don't match resolved subjects - **If action items are outdated**: - Warn user: "The iteration's action items don't reference the brainstorming session. Should I update them to match the brainstorming subjects?" - Wait for user confirmation - **If action items are up-to-date**: Proceed to step 5 5. **Update task file** (`phase-N/task-M.md`): a. **Update iteration status** from 🚧 to 🎨: ```markdown ### 🚧 Iteration 2: Error Handling ``` Becomes: ```markdown ### 🎨 Iteration 2: Error Handling ``` b. **Add completion note** after brainstorming session: ```markdown **Brainstorming Status**: ✅ COMPLETE **Pre-Implementation Tasks**: ✅ COMPLETE (if applicable) **Ready for**: `/flow-implement-start` ``` 6. **Update DASHBOARD.md**: a. **Update "📍 Current Work" section**: ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: [Iteration 2 - Error Handling](phase-2/task-3.md#iteration-2-error-handling) 🎨 READY FOR IMPLEMENTATION - **Next**: Use `/flow-implement-start` to begin implementation ``` b. **Update iteration status in "📊 Progress Overview"**: - Change iteration marker to show 🎨 READY c. **Update "Last Updated" timestamp** at top d. **Reminder**: If you discover new issues during implementation (scope violations), STOP and discuss with the user before proceeding. 7. **Confirm to user**: ``` ✅ Brainstorming session complete! Iteration [K]: [Name] marked 🎨 READY FOR IMPLEMENTATION **Next Step**: Use `/flow-implement-start` to begin implementation ``` **Output**: - Updated `phase-N/task-M.md` with 🎨 READY status - Updated `DASHBOARD.md` with "🎨 READY FOR IMPLEMENTATION" ``` --- ## /flow-implement-start **File**: `flow-implement-start.md` ```markdown --- description: Begin implementation of current iteration --- You are executing the `/flow-implement-start` command from the Flow framework. **Purpose**: Begin implementation phase for the current iteration. **🟢 NO FRAMEWORK READING REQUIRED - This command works from DASHBOARD.md and task file** - State transition (🎨 READY/⏳ PENDING → 🚧 IMPLEMENTING) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1798-1836 for implementation workflow **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current work - Updates iteration status in `phase-N/task-M.md` - Updates `DASHBOARD.md` current work section - **Prerequisite**: Brainstorming must be ✅ COMPLETE and all pre-implementation tasks done **🚨 SCOPE BOUNDARY RULE** (CRITICAL - see .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 339-540): If you discover NEW issues during implementation that are NOT part of the current iteration's action items: 1. **STOP** immediately - Don't make assumptions or proceed 2. **NOTIFY** user - Present discovered issue(s) with structured analysis 3. **DISCUSS** - Provide structured options (A/B/C/D format): - **A**: Create pre-implementation task (< 30 min work, blocking) - **B**: Add as new brainstorming subject (design needed) - **C**: Handle immediately (only if user approves) - **D**: Defer to separate iteration (after current work) 4. **AWAIT USER APPROVAL** - Never proceed without explicit user decision **Use the Scope Boundary Alert Template** (see .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 356-390) **Exception**: Syntax errors or blocking bugs in files you must modify (document what you fixed in Implementation Notes) **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current task: Phase N, Task M, Iteration K - Navigate to task file link 2. **Read current task file** (`phase-N/task-M.md`): - Find iteration K in "## Iterations" section - Check iteration status (should be 🎨 READY or ⏳ PENDING) 3. **Read Testing Strategy** (CRITICAL): - Read `PLAN.md` "## Testing Strategy" section - Understand verification methodology (simulation, unit tests, TDD, manual QA) - Note file locations, naming conventions - **IMPORTANT**: Follow Testing Strategy exactly - do NOT violate conventions 4. **Verify readiness** (if iteration was 🎨 READY): - Brainstorming should be marked ✅ COMPLETE - All pre-implementation tasks should be ✅ COMPLETE - If not ready: Warn user and ask to complete brainstorming/pre-tasks first 5. **Handle ⏳ PENDING iterations** (no brainstorming yet): - Ask user: "Previous iteration complete. Do you want to brainstorm this iteration first (recommended) or skip directly to implementation?" - **User chooses brainstorm**: "Please run `/flow-brainstorm-start` first" - **User chooses skip**: Proceed with implementation 6. **Update task file** (`phase-N/task-M.md`): a. **Update iteration status** from 🎨/⏳ to 🚧 IN PROGRESS: ```markdown ### 🎨 Iteration 2: Error Handling ``` Becomes: ```markdown ### 🚧 Iteration 2: Error Handling ``` b. **Create implementation section** in task file: ```markdown #### Implementation - Iteration 2: Error Handling **Status**: 🚧 IN PROGRESS (2025-01-15) **Action Items**: See resolved subjects above (Type D items) **Implementation Notes**: [Leave blank - filled during work] **Files Modified**: [Leave blank - filled as work progresses] **Verification**: [Leave blank - how work verified] --- ``` **IMPORTANT**: Implementation section REFERENCES subjects (don't duplicate action items) 7. **Update parent task status** (if needed): - If task is ⏳ PENDING: Change to 🚧 IN PROGRESS in task file AND DASHBOARD.md - If task already 🚧: Skip 8. **Update DASHBOARD.md**: a. **Update "📍 Current Work" section**: ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: [Iteration 2 - Error Handling](phase-2/task-3.md#iteration-2-error-handling) 🚧 IMPLEMENTING - **Focus**: Implementing comprehensive error handling with retry logic ``` b. **Update iteration status in "📊 Progress Overview"**: - Change iteration marker from 🎨/⏳ to 🚧 - Add "← ACTIVE" indicator c. **Update "Last Updated" timestamp** at top 9. **Confirm to user**: ``` ✅ Started implementation of Iteration [K]: [Name] Action items from brainstorming subjects: - [List Type D action items from resolved subjects] Follow Testing Strategy in PLAN.md for verification. ``` **Output**: - Updated `phase-N/task-M.md` with implementation section - Updated `DASHBOARD.md` current work ``` --- ## /flow-implement-complete **File**: `flow-implement-complete.md` ```markdown --- description: Mark current iteration as complete --- You are executing the `/flow-implement-complete` command from the Flow framework. **Purpose**: Mark the current iteration as complete. **🟢 NO FRAMEWORK READING REQUIRED - This command works from DASHBOARD.md and task file** - State transition (🚧 IMPLEMENTING → ✅ COMPLETE) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1798-1836 for completion criteria **Multi-File Architecture**: This command: - Updates iteration status in `phase-N/task-M.md` - Updates `DASHBOARD.md` completion percentages - Advances to next iteration or suggests task completion **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current iteration: Phase N, Task M, Iteration K - Navigate to task file link 2. **Read current task file** (`phase-N/task-M.md`): - Find iteration K in "## Iterations" section - Verify iteration marked 🚧 IN PROGRESS 3. **Verify completion**: - Check brainstorming action items (if brainstorming was done) - If unchecked items remain: Ask "There are unchecked action items. Are you sure you want to mark complete?" 4. **Check for existing verification information**: - Read Implementation Notes section in task file - Review recent conversation (last 5-10 messages) for testing/verification discussion - If verification info found: Skip to step 6 (don't ask redundant questions) - If NO verification info found: Proceed to step 5 5. **Prompt for verification notes** (ONLY if not already available): ``` How did you verify this iteration works? - Tests run? (unit, integration, simulation) - Manual checks? - Code review? ``` 6. **Update task file** (`phase-N/task-M.md`): a. **Update iteration status** from 🚧 to ✅: ```markdown ### 🚧 Iteration 2: Error Handling ``` Becomes: ```markdown ### ✅ Iteration 2: Error Handling ``` b. **Update implementation section**: ```markdown #### Implementation - Iteration 2: Error Handling **Status**: ✅ COMPLETE (2025-01-15) **Implementation Notes**: - Created `src/integrations/stripe/ErrorMapper.ts` (98 lines) - Created `src/integrations/stripe/RetryPolicy.ts` (76 lines) - Updated StripeClient with error handling and retry **Files Modified**: - `src/integrations/stripe/StripeClient.ts` - Added error handling - `src/integrations/stripe/ErrorMapper.ts` - Created - [... more files ...] **Verification**: - ✅ All error mapping tests passing - ✅ Retry logic tests passing - ✅ Integration test with Stripe API successful ``` 7. **Check if task/phase complete**: - Count iterations: How many ✅ COMPLETE vs total? - If all iterations complete: Task is ready for `/flow-task-complete` 8. **Update DASHBOARD.md**: a. **Update iteration status in "📊 Progress Overview"**: - Change iteration marker from 🚧 to ✅ - Update iteration count: `(1/4 iterations)` → `(2/4 iterations)` b. **Update "📍 Current Work" section**: - **If more iterations**: Advance to next iteration ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: [Iteration 3 - Retry Logic](phase-2/task-3.md#iteration-3-retry-logic) ⏳ PENDING - **Next**: Use `/flow-brainstorm-start` or `/flow-implement-start` ``` - **If all iterations complete**: ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - All iterations complete! - **Next**: Use `/flow-task-complete` to mark task as done ``` c. **Update completion percentages**: - Recalculate phase percentage - Recalculate overall percentage - Update "📈 Completion Status" section d. **Update "Last Updated" timestamp** at top 9. **Confirm to user**: ``` ✅ Completed Iteration [K]: [Name] **What's Next**: - **More iterations?** → Use `/flow-brainstorm-start` or `/flow-implement-start` for next iteration - **All iterations done?** → Use `/flow-task-complete` to mark task as complete **Current state**: [X]/[Y] iterations complete ``` **Output**: - Updated `phase-N/task-M.md` with completion status - Updated `DASHBOARD.md` with progress and next work ``` --- ## /flow-status **File**: `flow-status.md` ```markdown --- description: Show current position and project progress --- You are executing the `/flow-status` command from the Flow framework. **Purpose**: Display current work position and project progress from the dashboard. **🟢 NO FRAMEWORK READING REQUIRED - This command works entirely from DASHBOARD.md** - Dashboard-first approach - reads ONLY DASHBOARD.md - Extremely efficient: <100 lines to read vs thousands in old architecture - This is the REFERENCE MODEL command - simplest example of multi-file navigation **Multi-File Architecture**: Flow now uses separate files: - `DASHBOARD.md` - Progress tracking (⭐ read by this command) - `PLAN.md` - Static context (not read by this command) - `phase-N/task-M.md` - Task details (not read by this command) **Instructions**: 1. **Find .flow/DASHBOARD.md**: ```bash # Primary location .flow/DASHBOARD.md # If not found Suggest: "/flow-blueprint to create new project" or "/flow-plan-update to migrate old single-file plan" ``` 2. **Read DASHBOARD.md** (entire file): ```bash # Simply read the whole file - it's small and focused Read: .flow/DASHBOARD.md ``` DASHBOARD.md contains everything you need: - Current work pointer (Phase/Task/Iteration) - Progress overview for all phases - Completion percentages - Next actions - Recent activity - Last updated timestamp 3. **Extract key information**: From "📍 Current Work" section: - Current Phase (number and name) - Current Task (number and name) - Current Iteration (number and name) - Current status emoji (⏳ 🚧 🎨 ✅ etc.) - Focus description From "📊 Progress Overview" section: - All phases with their status - Tasks within each phase - Iteration counts per task - Completion indicators From "📈 Completion Status" section: - Phases: X/Y complete - Tasks: X/Y complete - Iterations: X/Y complete - Overall percentage From "🎯 Next Actions" section: - Immediate actions (today) - Short-term actions (this week) - Upcoming milestones 4. **Display formatted status**: ``` # [Project Name] - Status 📍 **Current Work** Phase [N]: [Name] [Status] └─ Task [M]: [Name] [Status] └─ Iteration [K]: [Name] [Status] **Focus**: [Current focus description from dashboard] --- 📊 **Progress Overview** ### Phase 1: [Name] [Status] - Task 1: [Name] [Status] ([X/Y iterations]) - Task 2: [Name] [Status] ([X/Y iterations]) ### Phase 2: [Name] [Status] ← CURRENT - Task 1: [Name] [Status] ([X/Y iterations]) - Task 2: [Name] [Status] ([X/Y iterations]) ← CURRENT ### Phase 3: [Name] [Status] ... --- 📈 **Completion** - Phases: [X/Y] ([percentage]%) - Tasks: [X/Y] ([percentage]%) - Iterations: [X/Y] ([percentage]%) - **Overall**: [percentage]% --- 🎯 **Next Actions** Immediate: - [Action 1] - [Action 2] Short-term: - [Goal 1] - [Goal 2] --- 📝 **Recent Activity** [Show 3-5 most recent items from dashboard] --- **Last Updated**: [Timestamp from dashboard] ``` 5. **Suggest next action** (based on current iteration status): Read the current iteration status from dashboard and suggest: **If ⏳ PENDING**: → "Use `/flow-brainstorm-start` to begin brainstorming this iteration" **If 🚧 IN PROGRESS (Brainstorming)**: → "Use `/flow-next-subject` to continue brainstorming" → Or check "Next Actions" section in dashboard for specific guidance **If 🚧 IN PROGRESS (Implementing)**: → "Continue implementation. Use `/flow-implement-complete` when done" **If 🎨 READY**: → "Use `/flow-implement-start` to begin implementation" **If ✅ COMPLETE**: → "Use `/flow-iteration-add` to add next iteration" → Or if task complete: "Use `/flow-task-complete` to finish this task" 6. **Optional: Verify dashboard is up-to-date**: Check "Last Updated" timestamp: - If recent (< 1 hour): All good - If stale (> 24 hours): Suggest running `/flow-verify-plan` to check consistency Note: Don't read task files to verify - that's `/flow-verify-plan`'s job. This command trusts the dashboard. **Key Principle**: DASHBOARD.md is the source of truth for current state. This command simply displays what's in the dashboard - it doesn't validate against task files (that's what `/flow-verify-plan` does). **Output**: Formatted status display with current position, progress overview, completion stats, and next action suggestion. ``` --- ## /flow-summarize **File**: `flow-summarize.md` ```markdown --- description: Generate summary of all phases/tasks/iterations --- You are executing the `/flow-summarize` command from the Flow framework. **Purpose**: Generate high-level overview of entire project structure and completion state. **🟢 NO FRAMEWORK READING REQUIRED - This command works from DASHBOARD.md and task files** - Uses DASHBOARD.md for high-level view - Reads task files for detailed iteration status - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 105-179 for hierarchy context **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` for overall structure - Reads all `phase-N/task-M.md` files for detailed status - Generates comprehensive summary from all files **Use case**: "Bird's eye view" of project health, progress across all phases, quick status reports **Comparison to other commands**: - `/flow-status` = "Where am I RIGHT NOW?" (micro view - reads DASHBOARD.md only) - `/flow-summarize` = "What's the WHOLE PICTURE?" (macro view - reads all files) - `/flow-verify-plan` = "Is this accurate?" (validation) **Instructions**: 1. **Read DASHBOARD.md**: - Extract current work position - Get all phases and tasks from "📊 Progress Overview" - Get completion percentages from "📈 Completion Status" 2. **Read all task files**: - List all phase directories: `ls .flow/phase-*/` - For each phase, list task files: `ls .flow/phase-N/` - Read each `phase-N/task-M.md` to get: - Task status - All iterations with status markers - Brainstorming status (if applicable) 3. **Generate structured summary** (compact, scannable format): ``` 📊 Flow Summary Version: [V1/V2/V3] Status: [Current phase/task/iteration from metadata] Phase [N]: [Name] [Status] [%] - Task [N]: [Name] [Status] - Iter [N-N] [Status]: [Concise description] - Iter [N] 🚧 CURRENT: [What you're working on] - Iter [N] ⏳: [What's next] Phase [N]: [Name] [Status] [%] - Task [N-N]: [Grouped if similar] [Status] - Task [N]: [Name] [Status] Deferred to V2: - [Iteration/feature name] - [Iteration/feature name] --- TL;DR: [One punchy sentence about overall state] ``` 4. **Formatting rules**: - **Compact**: Group consecutive completed iterations (e.g., "Iter 1-5 ✅") - **Scannable**: Use emojis (✅ ⏳ 🚧 🎨) and percentages prominently - **Highlight**: Mark CURRENT work explicitly in bold or with flag - **Indent**: Phase (no indent), Task (- prefix), Iteration (-- or nested -) - **Defer section**: Show V2/future items at bottom - **Skip noise**: Don't list every task name if they're obvious/sequential - **Focus on active work**: Emphasize in-progress and next items 5. **Example output** (payment gateway): ``` 📊 Flow Summary Version: V1 Status: Phase 2, Task 5, Iteration 2 - In Progress Phase 1: Foundation ✅ 100% - Task 1-2: Setup, API, Database schema ✅ Phase 2: Core Implementation 🚧 75% - Task 3-4: Payment processing, Webhooks ✅ - Task 5: Error Handling - Iter 1 ✅: Retry logic - Iter 2 🚧 CURRENT: Circuit breaker - Iter 3 ⏳: Dead letter queue Phase 3: Testing & Integration ⏳ 0% - Task 6: Integration tests (pending) Deferred to V2: - Advanced features (monitoring, metrics) - Name generation --- TL;DR: Foundation done, core payment flow working, currently building circuit breaker for error handling. ``` **Example output** (RED project - showing V1/V2 split): ``` 📊 Flow Summary - RED Ability Generation === V1 - Core System === Phase 1: Foundation ✅ 100% - Task 1-4: Constants, enums, types, refactoring ✅ Phase 2: Core Implementation 🚧 85% - Iter 1-5 ✅: Tier gen, slots, filtering, selection, template parsing - Iter 6 🚧 NEXT: Green.generate() integration (ties everything together) - Iter 7 ⏳: Blue validation (input guards) - Iter 9 ⏳ LAST: Red API wrapper (exposes Blue → Green) Phase 3: Testing - Script-based testing (Blue → Green flow) Deferred to V2: - Iter 8: Name generation (stub returns "Generated Ability") - Database persistence - Stats-based damage calculations === V2 - Enhanced System (Phase 4) === Enhancements: - Potency system (stats × formulas replace fixed damage) - Name generation (124 weighted prefix/suffix combos) - 12 new placeholders (conditionals, resources, targeting) - Damage variance (±10% for crits) - Points & Luck systems - Database persistence --- TL;DR: V1 = Basic working system with hardcoded damage ranges (85% done, integration next) V2 = Dynamic formulas, character stats integration, full feature set ``` 6. **Add deferred/cancelled sections**: ``` 🔮 Deferred Items: - Iteration 10: Name Generation (V2 - complexity, needs 124 components) - Task 12: Advanced Features (V2 - out of V1 scope) - Feature X: Multi-provider support (V3 - abstraction layer) ❌ Cancelled Items: - Task 8: Custom HTTP Client (rejected - SDK is better) - Subject 3: GraphQL API (rejected - REST is sufficient) ``` 7. **Smart verification** (active work only): - Skip ✅ COMPLETE items (verified & frozen) - Verify 🚧 ⏳ 🎨 items match Progress Dashboard - Check ❌ items have reasons - Check 🔮 items have reasons + destinations - Report: ``` 🔍 Verification (Active Work Only): ✅ All active markers (🚧 ⏳) match Progress Dashboard ⏭️ Skipped 18 completed items (verified & frozen) ``` 8. **Handle multiple versions**: - If PLAN.md has V2/V3 sections, use `=== V1 Summary ===` separator - V1 gets full Phase/Task/Iteration breakdown - V2+ get high-level "Enhancements" list (not full iteration tree) - Separate TL;DR line for each version 9. **After generating summary**: - "Use `/flow-status` to see detailed current position" - "Use `/flow-verify-plan` to verify accuracy against actual code" **Manual alternative**: - Read entire PLAN.md manually - Create outline of all phases/tasks/iterations - Count completions and calculate percentages - Format into hierarchical view **Output**: Hierarchical summary of entire project structure with completion tracking. ``` --- ## /flow-next-subject **File**: `flow-next-subject.md` ```markdown --- description: Discuss next subject, capture decision, and mark resolved --- You are executing the `/flow-next-subject` command from the Flow framework. **Purpose**: Show next unresolved subject, present options collaboratively, include your recommendation with rationale, wait for user decision, then mark as ✅ resolved. **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Subject Resolution Types (lines in Quick Reference) - Types A/B/C/D decision matrix - **Deep dive if needed**: Read lines 1167-1797 for Brainstorming Pattern using Read(offset=1167, limit=631) **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current iteration - Reads/updates brainstorming session in `phase-N/task-M.md` - Marks subjects ✅ resolved in task file **Framework Reference**: This command requires framework knowledge to properly categorize resolution types. See Quick Reference guide above for essential patterns. **🚨 SCOPE BOUNDARY RULE** (CRITICAL - see .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 339-540): If you discover NEW issues while discussing subjects that are NOT part of the current iteration: 1. **STOP** immediately - Don't make assumptions or proceed 2. **NOTIFY** user - Present discovered issue(s) with structured analysis 3. **DISCUSS** - Provide structured options (A/B/C/D format): - **A**: Create pre-implementation task (< 30 min work, blocking) - **B**: Add as new brainstorming subject (design needed) - **C**: Handle immediately (only if user approves) - **D**: Defer to separate iteration (after current work) 4. **AWAIT USER APPROVAL** - Never proceed without explicit user decision **Use the Scope Boundary Alert Template** (see .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 356-390) **Why This Matters**: User stays in control of priorities. AI finds issues proactively but doesn't make scope decisions. **New Collaborative Workflow** (two-phase approach): ``` Phase 1 (Present): /flow-next-subject → present subject + options → ask user → 🛑 STOP & WAIT Phase 2 (Capture - triggered by user response): User responds → capture decision → document → mark ✅ → auto-advance to next ``` **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current iteration: Phase N, Task M, Iteration K 2. **Read current task file** (`phase-N/task-M.md`): - Find iteration K's brainstorming session - Locate "Subjects to Discuss" section 3. **Find first unresolved subject**: Look for first ⏳ subject in the list 4. **If found** (subject needs discussion): **Step A: Present subject** - Display subject name and description - Present relevant context from iteration goal - **DO NOT read codebase files** - **DO NOT analyze existing implementation** - **DO NOT create detailed solutions** - Keep it brief - this is just presenting the topic **Step B: Present options and STOP** ⚠️ CRITICAL - **DO NOT research code** before presenting options - **DO NOT read files** to understand current implementation - **DO NOT create detailed architecture diagrams** - Suggest 2-4 high-level options/approaches based on GENERAL knowledge - Present each option with brief pros/cons (1-2 sentences each) - Format as numbered list for clarity - Include option for "Your own approach" - Include your recommendation with rationale - Ask user explicitly: "Which option do you prefer? Or provide your own approach." - **🛑 STOP HERE - Wait for user response (do NOT proceed to capture decision)** - **DO NOT** decide on behalf of user - **DO NOT** document any decision yet - **DO NOT** create massive detailed resolutions - Command execution ends here - user will respond in next message **Step C: Capture user's decision** (only execute AFTER user responds) - Read user's response from their message - If decision is clear: proceed to document it - If unclear: ask clarifying questions - If rationale not provided: ask "What's your reasoning for this choice?" - Optional: "Any action items to track for this decision?" - **KEEP DOCUMENTATION CONCISE** (1-3 paragraphs, not 336 lines!) - **NO massive architecture diagrams** unless user explicitly provides one - **NO detailed implementation plans** - save for implementation phase - Capture: Decision + Rationale + Action Items (if any) **Step D: Document resolution in task file** - Mark subject ✅ in "Subjects to Discuss" list (in `phase-N/task-M.md`) - Add **CONCISE** resolution section under "Resolved Subjects": ```markdown ### ✅ **Subject [N]: [Name]** **Decision**: [User's decision from their response - 1-2 sentences] **Rationale**: - [Reason 1 from user or follow-up] - [Reason 2] **Action Items** (if any): - [ ] [Item 1 - brief, not detailed implementation steps] - [ ] [Item 2] --- ``` - **Example of TOO MUCH**: 336 line resolution with interfaces, diagrams, detailed architecture - **Example of GOOD**: 10-20 line resolution with decision, rationale, 3-5 action items **Step E: Auto-advance OR prompt for review** - Save changes to `phase-N/task-M.md` - Show progress: "[N] of [Total] subjects resolved" - Check if more ⏳ subjects exist: - **If YES** (more pending): Auto-show next unresolved subject - **If NO** (all resolved): Show workflow prompt below 5. **If all resolved** (this was the last subject): - **Show brief summary** of decisions made - **⚠️ CRITICAL - Show "What's Next" Section (MANDATORY - AI MUST NOT SKIP THIS)**: ```markdown ✅ All subjects resolved! ## 🎯 What's Next **REQUIRED NEXT STEP**: Run `/flow-brainstorm-review` to: - Analyze all resolved subjects - Categorize action items (pre-tasks vs implementation vs new iterations) - Generate follow-up work suggestions - Prepare for implementation **DO NOT run `/flow-brainstorm-complete` yet** - review comes first! **Workflow Reminder**: 1. ✅ NOW: `/flow-brainstorm-review` (analyze & suggest) 2. THEN: Create any pre-tasks if needed 3. THEN: Complete pre-tasks (if any) 4. FINALLY: `/flow-brainstorm-complete` (mark 🎨 READY) **Why this order matters**: Review identifies blockers (pre-tasks) that must be done before implementation starts. ``` - **AI BEHAVIOR**: Do NOT suggest `/flow-brainstorm-complete` or any other command. The "What's Next" section MUST explicitly guide to `/flow-brainstorm-review` first. **Key Principle**: Moving to next subject implies current is resolved. No separate "resolve" command needed. **Output**: Updated `phase-N/task-M.md` with subject resolution and show next subject. ``` --- ## /flow-next-iteration **File**: `flow-next-iteration.md` ```markdown --- description: Show next iteration details --- You are executing the `/flow-next-iteration` command from the Flow framework. **Purpose**: Display details about the next pending iteration in the current task. **🟢 NO FRAMEWORK READING REQUIRED - This command works entirely from DASHBOARD.md and task file** - Finds next ⏳ PENDING iteration in current task - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 567-613 for iteration context **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current task - Reads `phase-N/task-M.md` to find next pending iteration **Pattern**: Works like `/flow-next-subject` but for iterations - shows what's coming next. **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current task: Phase N, Task M 2. **Read current task file** (`phase-N/task-M.md`): - Find "## Iterations" section - Look for first iteration marked ⏳ PENDING 3. **Find next pending iteration**: First ⏳ PENDING iteration in task file 4. **If found, display iteration details**: ``` 📋 Next Iteration: **Iteration [N]**: [Name] **Goal**: [What this iteration builds] **Status**: ⏳ PENDING **Approach**: [Brief description from iteration section if available] --- Ready to start? Use `/flow-brainstorm-start [topic]` to begin. ``` 5. **If NOT found (no pending iterations)**: - Check if current iteration is in progress: "Still working on Iteration [N]: [Name]. Use `/flow-implement-complete` when done." - Otherwise: "No more iterations in current task. Use `/flow-iteration-add [description]` to create next iteration, or `/flow-task-complete` if task is done." 6. **Show progress**: "Iteration [current] of [total] in current task" **Output**: Display next iteration details and suggest appropriate next action. ``` --- ## /flow-next **File**: `flow-next.md` ```markdown --- description: Smart helper - suggests next action based on current context --- You are executing the `/flow-next` command from the Flow framework. **Purpose**: Auto-detect current context and suggest the next logical step. **🟢 NO FRAMEWORK READING REQUIRED - This command works entirely from DASHBOARD.md and task file** - Smart navigation using Dashboard and current context - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 3277-3356 for decision tree reference **Multi-File Architecture**: This command: - Reads `DASHBOARD.md` to find current work - Reads `phase-N/task-M.md` to determine current state - Suggests next command based on context **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current iteration: Phase N, Task M, Iteration K 2. **Read current task file** (`phase-N/task-M.md`): - Find iteration K - Check iteration status (⏳ 🚧 🎨 ✅) 3. **Determine current context**: - Check if in brainstorming session: - Look for "Subjects to Discuss" section - Count unresolved subjects (⏳ markers) - Check for pre-implementation tasks: - Look for "#### Pre-Implementation Tasks" section - Count pending vs complete - Check if in main implementation: - Look for "#### Implementation" section 4. **Suggest next command based on context**: **Determine exact state**: **If status = ⏳ PENDING**: → "Use `/flow-brainstorm-start [topic]` to begin this iteration" **If status = 🚧 IN PROGRESS**: **Check phase progression** (in this order): 1. **Check unresolved subjects**: If any "⏳" subjects in "Subjects to Discuss": → "Use `/flow-next-subject` to resolve next subject" Show: "X subjects remaining: [list]" 2. **Check pre-implementation tasks**: If "### **Pre-Implementation Tasks:**" section exists: Count pending tasks (^#### ⏳) If pending > 0: → "Continue with Task X: [Name]" Show: "[X/Y] pre-implementation tasks complete" If pending = 0: → "Pre-implementation complete. Use `/flow-brainstorm-complete`" 3. **Check main implementation**: If "### **Implementation**" section exists: → "Continue main implementation" Show: "Use `/flow-implement-complete` when done" 4. **Default** (subjects resolved, no pre-tasks): → "Use `/flow-brainstorm-complete` to finish brainstorming" **If status = 🎨 READY**: → "Use `/flow-implement-start` to begin implementation" **If status = ✅ COMPLETE**: → "Use `/flow-next-iteration` to move to next iteration" 4. **Show current status summary**: Brief summary of where you are **Output**: Suggest appropriate next command based on context. ``` --- ## /flow-rollback **File**: `flow-rollback.md` ```markdown --- description: Undo last plan change --- You are executing the `/flow-rollback` command from the Flow framework. **Purpose**: Undo the last change made to plan files (DASHBOARD.md or task files). **🟢 NO FRAMEWORK READING REQUIRED - This command works from plan files** - Undoes last change using CHANGELOG.md - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1969-2014 for rollback patterns **Multi-File Architecture**: This command can rollback: - DASHBOARD.md status updates (phase/task/iteration status changes) - Task file changes (iteration added, status updated) - File moves (task archived, moved to backlog) **Instructions**: 1. **Read CHANGELOG.md**: - Look for "📝 Recent Activity" section - If no CHANGELOG.md or no recent entries: "No recent changes to rollback." 2. **Identify last change**: - Parse last entry in CHANGELOG.md - Extract what was changed: - "Phase N started" → DASHBOARD.md phase status - "Task M completed" → DASHBOARD.md + task file status - "Iteration K added" → Task file iteration section - "Task M moved to backlog" → File moved to backlog/ - "Task M archived" → File moved to archive/ 3. **Ask for confirmation**: - Display last change details: ``` Last change ([Date/Time]): - Action: [Description] - File(s): [Affected files] - Change: [What was modified] Rollback this change? (yes/no) ``` 4. **If confirmed, revert change based on type**: **A. Status change rollback**: - Read DASHBOARD.md - Revert status marker to previous state - Example: `🚧 IN PROGRESS` → `⏳ PENDING` - Update task file status marker if applicable **B. File move rollback**: - Move file back: `backlog/phase-N-task-M.md` → `phase-N/task-M.md` - Or: `archive/phase-N/task-M.md` → `phase-N/task-M.md` - Update DASHBOARD.md to remove archived/backlog markers - Update BACKLOG.md or CHANGELOG.md accordingly **C. Section added rollback**: - Remove last added section from task file - Example: Remove last iteration, pre-task, or brainstorm subject - Update DASHBOARD.md if iteration count changed **D. Checkbox rollback**: - Uncheck last checked checkbox in task file - Find Implementation section, uncheck last ✅ item 5. **Update CHANGELOG.md**: Add rollback entry ```markdown ### [Date/Time] - 🔄 Rolled back: [Description of reverted change] ``` 6. **Confirm to user**: ``` ✅ Rolled back: [Description of change] **Reverted**: - File: [file path] - Change: [what was undone] CHANGELOG.md updated with rollback entry. ``` **Limitation**: Can only rollback one step at a time. For major reverts, manually edit files or use git to revert commits. **Output**: Revert last change in plan files, update CHANGELOG.md. ``` --- ## /flow-verify-plan **File**: `flow-verify-plan.md` ```markdown --- description: Verify plan file matches actual codebase state --- You are executing the `/flow-verify-plan` command from the Flow framework. **Purpose**: Verify that plan files (DASHBOARD.md, PLAN.md, task files) are synchronized with actual project state. **🔴 REQUIRED: Read Framework Quick Reference First** - **Read once per session**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 (Quick Reference section) - if not already in context from earlier in session, read it now - **Focus on**: Framework Structure validation, Status Markers (in Quick Reference) - **Deep dive if needed**: Read lines 105-179 for Framework Structure using Read(offset=105, limit=75) **Multi-File Architecture**: This command verifies: - `DASHBOARD.md` - Progress tracking and current work pointers - `PLAN.md` - Static overview (architecture, testing, constraints) - `phase-N/task-M.md` - Individual task files with iterations - Task files contain actual action items and implementation details **Context**: - **Framework Guide**: .flow/framework/DEVELOPMENT_FRAMEWORK.md (auto-locate in `.claude/`, project root, or `~/.claude/flow/`) - **Working Files**: .flow/DASHBOARD.md, .flow/PLAN.md, .flow/phase-N/task-M.md - **Use case**: Run before starting new AI session or compacting conversation to ensure context is accurate **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section for current phase/task/iteration - Extract current phase number, task number, iteration number - Note current iteration status (🚧 IN PROGRESS or 🎨 READY) 2. **Read current task file**: - Locate `.flow/phase-N/task-M.md` based on DASHBOARD.md - Find current iteration section (marked 🚧 IN PROGRESS or 🎨 READY) - Read "Implementation - Iteration [N]" section - Identify all action items - Note which items are marked as ✅ complete 3. **Verify claimed completions against actual project state**: - For each ✅ completed action item, check if it actually exists: - "Create UserAuth.ts" → Verify file exists using Glob or Read - "Add login endpoint" → Search for login endpoint in code using Grep - "Update database schema" → Check schema files exist - List any discrepancies found 4. **Check for unreported work**: - Look for modified files that aren't mentioned in task file - Check git status (if available) for uncommitted changes - Identify files that were changed but not documented 5. **Verify DASHBOARD.md accuracy**: - Check that current work pointers match actual task file statuses - Verify completion percentages align with actual work done - Check that phase/task/iteration hierarchy is consistent 6. **Report findings**: ``` 📋 Plan Verification Results: **Current Work** (from DASHBOARD.md): - Phase [N], Task [M], Iteration [K] **Task File**: [phase-N/task-M.md](phase-N/task-M.md) ✅ Verified Complete: - [List action items that are correctly marked complete] ❌ Discrepancies Found: - [List action items marked complete but evidence not found] - [List DASHBOARD.md pointers that don't match task files] 📝 Unreported Work: - [List files changed but not mentioned in task file] Status: [SYNCHRONIZED / NEEDS UPDATE] ``` 7. **If discrepancies found**: - Ask user: "Plan files are out of sync with project state. Update files now? (yes/no)" - If yes: Update plan files to reflect actual state: - Update task file (phase-N/task-M.md): Uncheck items that aren't actually done - Update DASHBOARD.md: Fix current work pointers, completion percentages - Add notes about files modified in task file "Implementation Notes" section - Update status markers if needed - If no: "Review discrepancies above and update plan files manually." 8. **If synchronized**: - "Plan files are synchronized with project state. Ready to continue work." **Manual alternative**: - Review DASHBOARD.md for current work location - Read current task file manually - Check each completed action item exists in codebase - Use `git status` and `git diff` to verify changes - Update task file and DASHBOARD.md to match reality **Output**: Verification report and optional plan file updates. ``` --- ## /flow-compact **File**: `flow-compact.md` ```markdown You are executing the `/flow-compact` command from the Flow framework. **Purpose**: Generate comprehensive conversation report for context transfer to new AI instance. **🟢 NO FRAMEWORK READING REQUIRED - This command works from plan files** - Generates comprehensive report using DASHBOARD.md, PLAN.md, and task file content - Uses `/flow-status` dashboard-first logic for current position - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2327-2362 for context preservation patterns **Multi-File Architecture**: This command reads: - `DASHBOARD.md` - Current work location and progress overview - `PLAN.md` - Architecture, testing strategy, constraints (static context) - `phase-N/task-M.md` - Current task file with iterations, brainstorming, implementation **Context**: - **Framework Guide**: .flow/framework/DEVELOPMENT_FRAMEWORK.md (auto-locate in `.claude/`, project root, or `~/.claude/flow/`) - **Working Files**: .flow/DASHBOARD.md, .flow/PLAN.md, .flow/phase-N/task-M.md - **Use case**: Before compacting conversation or starting new AI session - ensures zero context loss **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section for current phase/task/iteration - Read "📊 Progress Overview" for completed work - Read "🎯 Next Actions" for pending items - Read "📝 Recent Activity" for conversation history - Read "💡 Key Decisions This Week" for important context 2. **Read PLAN.md**: - Extract "## 🎯 Project Goal" for feature overview - Read "## 🏗️ Architecture" section for technical context - Read "## 🧪 Testing Strategy" for quality requirements - Read "## 📋 Constraints" for limitations - Read "## 🎓 Learning Goals" for educational objectives 3. **Read current task file** (from DASHBOARD.md pointers): - Locate `.flow/phase-N/task-M.md` - Read "Task Overview" section (purpose, dependencies, scope) - Read current iteration brainstorming subjects (decisions, rationale) - Read "Implementation - Iteration [N]" section (action items, progress) - Read "Task Notes" section (discoveries, decisions, references) 4. **Generate comprehensive report covering**: **Current Work Context**: - What feature/task are we working on? (from DASHBOARD.md) - What phase/task/iteration are we in? (with status) - What was the original goal? (from PLAN.md + task Purpose) **Conversation History**: - What decisions were made during brainstorming? (from task file subjects) - What subjects were discussed and resolved? (with resolution types) - What pre-implementation tasks were identified and completed? (from task file) - What action items were generated? (from Implementation section) **Implementation Progress**: - What has been implemented so far? (from task file Implementation Notes) - What files were created/modified? (from Files Modified section) - What verification was done? (from Verification section) - What remains incomplete? (unchecked action items) **Challenges & Solutions**: - What blockers were encountered? (from Implementation Notes) - How were they resolved? (from Pre-Implementation Tasks or notes) - What design trade-offs were made? (from brainstorming rationale) **Next Steps**: - What is the immediate next action? (from DASHBOARD.md "🎯 Next Actions") - What are the pending action items? (from current iteration) - What should the next AI instance focus on? **Important Context**: - Any quirks or special considerations (from Task Notes) - Technical constraints (from PLAN.md + Task Overview dependencies) - User preferences or decisions that must be preserved (from decisions) 5. **Report format**: ``` # Context Transfer Report ## Generated: [Date/Time] ## Current Status [Phase/Task/Iteration with status markers] ## Feature Overview [What we're building and why] ## Conversation Summary [Chronological summary of discussions and decisions] ## Implementation Progress [What's done, what's in progress, what's pending] ## Key Decisions & Rationale [Critical decisions made with reasoning] ## Files Modified [List with brief description of changes] ## Challenges Encountered [Problems and how they were solved] ## Next Actions [Immediate next steps for new AI instance] ## Critical Context [Must-know information for continuation] ``` 5. **Important guidelines**: - **Do NOT include generic project info** (tech stack, architecture overview, etc.) - **Focus ENTIRELY on the feature at hand** and this conversation - **Do NOT worry about token output length** - comprehensive is better than brief - **Include WHY, not just WHAT** - decisions need context - **Be specific** - reference exact file names, function names, line numbers - **Preserve user preferences** - if user made specific choices, document them 6. **After generating report**: - "Context transfer report generated. Copy this report to a new AI session to continue work with zero context loss." - "Use `/flow-verify-plan` before starting new session to ensure plan files (DASHBOARD.md, task files) are synchronized." **Manual alternative**: - Read entire conversation history manually - Read DASHBOARD.md for current status - Read current task file for detailed context - Read PLAN.md for architectural constraints - Summarize key points, decisions, and progress - Document in separate notes file **Output**: Comprehensive context transfer report. ``` --- ## Installation Instructions To use these commands: 1. **Copy individual command files** to `.claude/commands/`: ```bash mkdir -p .claude/commands # Copy each command section above into separate .md files # Example: flow-blueprint.md, flow-phase.md, etc. ``` 2. **Or use the copy-paste method**: - Copy the content between the code blocks for each command - Create corresponding `.md` files in `.claude/commands/` - File names should match command names (e.g., `flow-blueprint.md`) 3. **Test with `/help`**: Run `/help` in Claude Code to see your new commands listed --- ## Command Execution Flow ``` /flow-blueprint ↓ Creates PLAN.md with skeleton ↓ /flow-brainstorm_start ↓ /flow-brainstorm-subject (repeat as needed) ↓ /flow-brainstorm_resolve (for each subject) ↓ Complete pre-implementation tasks (if any) ↓ /flow-brainstorm_complete ↓ /flow-implement-start ↓ Work through action items (check them off) ↓ /flow-implement-complete ↓ Repeat for next iteration ``` **Helper commands** available at any time: - `/flow-status` - Check current position - `/flow-next` - Auto-advance to next step - `/flow-rollback` - Undo last change - `/flow-phase-add`, `/flow-task-add`, `/flow-iteration-add` - Add structure as needed - `/flow-plan-split` - Archive old completed tasks to reduce PLAN.md size --- ## /flow-plan-split **File**: `flow-plan-split.md` ```markdown --- description: Archive old completed tasks to reduce PLAN.md size --- You are executing the `/flow-plan-split` command from the Flow framework. **Purpose**: Archive old completed tasks to reduce DASHBOARD.md clutter while preserving full project history in `archive/` directory. **🟢 NO FRAMEWORK READING REQUIRED - This command works from plan files** - Moves completed task FILES to archive/ directory (keeps recent 3 tasks visible) - Updates DASHBOARD.md and CHANGELOG.md to reflect archived tasks - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 2363-2560 for archival patterns **Multi-File Architecture**: This command: - Moves `phase-N/task-M.md` files to `archive/phase-N/task-M.md` - Updates `DASHBOARD.md` to mark tasks as archived - Updates `CHANGELOG.md` to reference archived task files **Context**: - **Framework Guide**: .flow/framework/DEVELOPMENT_FRAMEWORK.md (auto-locate in `.claude/`, project root, or `~/.claude/flow/`) - **Working Files**: .flow/DASHBOARD.md, .flow/phase-N/task-M.md - **Archive Directory**: .flow/archive/ (task files moved here) - **Changelog**: .flow/CHANGELOG.md (updated with archive references) **When to Use**: When DASHBOARD.md has 10+ completed tasks, causing clutter or difficult navigation. **Archiving Strategy - Recent Context Window**: - **Keep visible in DASHBOARD.md**: Current task + 3 previous tasks (regardless of status) - **Archive**: All ✅ COMPLETE tasks older than "current - 3" - **Always Keep Visible**: Non-complete tasks (⏳ 🚧 ❌ 🔮 🎨) regardless of age **Instructions**: 1. **Read DASHBOARD.md**: - Find "📍 Current Work" section - Extract current task number (e.g., Task 13) - Find "📊 Progress Overview" to list all tasks 2. **Calculate archiving threshold**: - Threshold = Current task number - 3 - Example: Current = 13, Threshold = 10 - **Archive candidates**: Tasks 1-9 (if ✅ COMPLETE) - **Keep visible**: Tasks 10, 11, 12, 13 (current + 3 previous) 3. **Identify archivable tasks**: - Find all tasks with number < threshold AND status = ✅ COMPLETE - List task files: `phase-N/task-M.md` for each archivable task - **IMPORTANT**: Keep non-complete tasks visible (⏳ 🚧 ❌ 🔮 🎨) even if old 4. **Move task files to archive**: - Create `archive/` directory if doesn't exist - For each archivable task: - Create phase directory in archive: `archive/phase-N/` if needed - Move `phase-N/task-M.md` to `archive/phase-N/task-M.md` - Preserve full task content (iterations, brainstorming, everything) 5. **Update CHANGELOG.md**: **If .flow/CHANGELOG.md does NOT exist** (first archive): ```markdown # Project Changelog This file contains historical records of completed tasks moved to archive. ## 📦 Archived Tasks ### Phase N: [Phase Name] - **Task M**: [Task Name] - [archive/phase-N/task-M.md](archive/phase-N/task-M.md) - Completed: [Date] - Archived: [Date] --- **Last Updated**: [Date] **Total Archived**: [Count] tasks ``` **If .flow/CHANGELOG.md ALREADY exists**: - Read existing CHANGELOG.md - Add new archived tasks under appropriate phase sections - Update "Last Updated" and "Total Archived" count - Maintain phase hierarchy (don't duplicate phase headers) 6. **Update DASHBOARD.md**: **A. Update Progress Overview**: - Add 📦 marker to archived tasks - Format: `- ✅📦 Task 5: Feature Name (archived)` - Keep task in list but mark as archived - Update completion percentages to reflect remaining visible tasks **B. Update phase headers** (if all phase tasks archived): ```markdown ### Phase 1: Foundation ✅ COMPLETE **Goal**: [Phase goal] **Status**: 100% complete ([N] tasks archived to [archive/phase-1/](archive/phase-1/)) ``` 7. **Verify and confirm**: - Count archived files - Calculate DASHBOARD.md size reduction - Confirm to user: ``` ✅ Plan split complete! **Archived**: [X] tasks to .flow/archive/ **Files moved**: - phase-1/task-1.md → archive/phase-1/task-1.md - phase-1/task-2.md → archive/phase-1/task-2.md ... **DASHBOARD.md**: Updated to mark [X] tasks as 📦 archived **CHANGELOG.md**: Updated with archive references **Recent context**: Kept Task [threshold] through Task [current] visible Your Progress Dashboard still shows complete project history. Archived task files available in .flow/archive/ ``` **Edge Cases**: - **No old completed tasks**: "No tasks to archive. All completed tasks are within recent context window (current + 3 previous)." - **Current task < 4**: "Current task is Task [N]. Need at least Task 4 to enable archiving (keeps current + 3 previous)." - **Non-complete old tasks**: Keep visible in DASHBOARD.md: "Task [N] kept visible (not complete - status: [status])" **Output**: Move task files to archive/, update DASHBOARD.md and CHANGELOG.md (full history preserved). ``` --- ## /flow-backlog-add **File**: `flow-backlog-add.md` ```markdown --- description: Move task(s) to backlog to reduce active plan clutter --- You are executing the `/flow-backlog-add` command from the Flow framework. **Purpose**: Move pending tasks to BACKLOG.md to reduce active dashboard clutter while preserving all task content. **🟢 NO FRAMEWORK READING REQUIRED - This command works from DASHBOARD.md and task files** - Moves task files to backlog directory (token efficiency feature) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 3407-3682 for backlog management patterns **Multi-File Architecture**: This command: - Moves `phase-N/task-M.md` files to `backlog/` directory - Updates `DASHBOARD.md` to remove tasks from active view - Creates/updates `BACKLOG.md` with references to backogged tasks **Key Insight**: Backlog is for **token efficiency**, not prioritization. Tasks aren't "low priority" - they're just "not now" (weeks/months away). **Signature**: `/flow-backlog-add ` or `/flow-backlog-add -` **Examples**: - `/flow-backlog-add 14` - Move Task 14 to backlog - `/flow-backlog-add 14-22` - Move Tasks 14 through 22 to backlog **Instructions**: 1. **Read DASHBOARD.md**: - Find "📊 Progress Overview" section - Locate tasks by number 2. **Parse arguments**: - Single task: `task_numbers` = task number (e.g., "14") - Range: `task_numbers` = start-end (e.g., "14-22") - Extract task number(s) to move 3. **Validate tasks**: - Find task files: `phase-N/task-M.md` - Check task status - warn if moving tasks that are 🚧 IN PROGRESS or ✅ COMPLETE - Recommended: Only move ⏳ PENDING tasks - If user confirms moving non-pending tasks, proceed 4. **Move task files to backlog**: - Create `backlog/` directory if doesn't exist - For each task: - Move `phase-N/task-M.md` to `backlog/phase-N-task-M.md` - Preserve all content (iterations, brainstorming, everything) 5. **Update BACKLOG.md**: **If BACKLOG.md does NOT exist** (first time): ```markdown # Project Backlog This file lists tasks moved to backlog/ directory to reduce active dashboard size. **Backlog Info**: - Task files moved to backlog/ directory - Tasks retain original numbers for easy reference - Full content preserved (brainstorming, iterations, everything) - Pull tasks back when ready to work on them **Last Updated**: [Current date] **Tasks in Backlog**: [Count] --- ## 📋 Backlog Tasks - **Task [N]**: [Name] - [backlog/phase-N-task-M.md](backlog/phase-N-task-M.md) - **Task [N]**: [Name] - [backlog/phase-N-task-M.md](backlog/phase-N-task-M.md) ``` **If BACKLOG.md ALREADY exists**: - Read existing BACKLOG.md - Update "Last Updated" timestamp - Update "Tasks in Backlog" count - Add tasks to "📋 Backlog Tasks" list 6. **Update DASHBOARD.md**: - Remove tasks from "📊 Progress Overview" section - Or mark as moved: `- ⏳ Task 14: Potency system (moved to backlog)` - Update completion percentages 7. **Reset task status to ⏳ PENDING** (in backlog files): - Open each backlog file - Change task status to ⏳ PENDING - Fresh start when pulled back 8. **Verify and confirm**: - Count moved files - Confirm to user: ``` ✅ Moved to backlog! **Backlogged**: [N] task(s) to backlog/ directory **Files moved**: Task [list of numbers] **Location**: backlog/phase-N-task-M.md Use `/flow-backlog-view` to see backlog contents. Use `/flow-backlog-pull ` to bring a task back when ready. ``` **Edge Cases**: - **Task doesn't exist**: "Task [N] not found" - **Invalid range**: "Invalid range format. Use: /flow-backlog-add 14-22" - **Empty range**: "No tasks found in range 14-22" - **Already in backlog**: Check backlog/ directory first, warn if task already there **Output**: Move task files to backlog/ directory, update DASHBOARD.md and BACKLOG.md. ``` --- ## /flow-backlog-view **File**: `flow-backlog-view.md` ```markdown --- description: Show backlog contents (tasks waiting) --- You are executing the `/flow-backlog-view` command from the Flow framework. **Purpose**: Display backlog showing all tasks currently in backlog directory. **🟢 NO FRAMEWORK READING REQUIRED - This command works from BACKLOG.md and backlog/ directory** - Simple read operation (shows backlog list) - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 3407-3682 for backlog context **Multi-File Architecture**: This command: - Reads `BACKLOG.md` for task list - Lists files in `backlog/` directory **Instructions**: 1. **Check if BACKLOG.md exists**: - If NOT found: "📦 Backlog is empty. Use `/flow-backlog-add ` to move tasks." - If found: Proceed to step 2 2. **Read BACKLOG.md**: - Extract "Last Updated" timestamp - Extract "Tasks in Backlog" count - Read "📋 Backlog Tasks" section for task list 3. **Verify backlog/ directory**: - List files in `backlog/` directory - Confirm task files exist: `backlog/phase-N-task-M.md` 4. **Display backlog contents**: ``` 📦 Backlog Contents ([N] tasks): **Last Updated**: [Date] **Tasks Waiting**: - **Task 14**: Potency system - [backlog/phase-2-task-14.md](backlog/phase-2-task-14.md) - **Task 15**: Points & Luck systems - [backlog/phase-2-task-15.md](backlog/phase-2-task-15.md) - **Task 16**: Database persistence - [backlog/phase-3-task-16.md](backlog/phase-3-task-16.md) --- **Next Steps**: - Use `/flow-backlog-pull ` to move a task back to active work - Example: `/flow-backlog-pull 14` brings Task 14 back to its original phase ``` 5. **Optional: Show task details** (if user wants more info): - Can read full task file from backlog/ on request - Default view is just list (lightweight) **Output**: Display backlog list with task files and guidance. ``` --- ## /flow-backlog-pull **File**: `flow-backlog-pull.md` ```markdown --- description: Pull task from backlog back into active plan --- You are executing the `/flow-backlog-pull` command from the Flow framework. **Purpose**: Move a task from BACKLOG.md back to PLAN.md with sequential renumbering in active phase. **🟢 NO FRAMEWORK READING REQUIRED - This command works from DASHBOARD.md, BACKLOG.md, and task files** - Moves task file back from backlog/ to phase directory - Optional background reading (NOT required): .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 3407-3682 for backlog patterns **Multi-File Architecture**: This command: - Moves `backlog/phase-N-task-M.md` back to `phase-N/task-M.md` - Updates `DASHBOARD.md` to show task - Updates `BACKLOG.md` to remove task **Signature**: `/flow-backlog-pull [position]` **Examples**: - `/flow-backlog-pull 14` - Pull Task 14 back to its original phase - `/flow-backlog-pull 14 add to phase 5` - Pull Task 14 to Phase 5 instead **Instructions**: 1. **Check if BACKLOG.md exists**: - If NOT found: "📦 Backlog is empty. Nothing to pull." - If found: Proceed 2. **Parse arguments**: - Required: `task_number` - Task number to pull (e.g., "14") - Optional: `position` - Positioning instruction (e.g., "add to phase 5") 3. **Validate task exists in backlog**: - Read BACKLOG.md to find task entry - Find backlog file: `backlog/phase-N-task-M.md` - If NOT found: "Task [N] not found in backlog. Use `/flow-backlog-view` to see available." - If found: Proceed 4. **Determine target phase**: - **Default**: Use task's original phase (from filename `phase-N-task-M.md`) - **With position instruction**: Parse for target phase - "add to phase 5" → Move to phase-5/ - **If phase doesn't exist**: Create phase directory 5. **Determine new task number**: - List existing tasks in target phase - Find highest task number - New task number = highest + 1 - Example: phase-2/ has task-1.md, task-2.md → new task is task-3.md 6. **Move task file back**: - Move `backlog/phase-N-task-M.md` to `phase-N/task-K.md` (K = new number) - Update task metadata in file: - Update task number in header - Reset status to ⏳ PENDING - Preserve all content (iterations, brainstorming, everything) 7. **Update BACKLOG.md**: - Remove task from "📋 Backlog Tasks" list - Decrement "Tasks in Backlog" count - Update "Last Updated" timestamp 8. **Update DASHBOARD.md**: - Add task to "📊 Progress Overview" in target phase - Mark as ⏳ PENDING - Update phase task count - Update completion percentages 9. **Verify and confirm**: ``` ✅ Pulled from backlog! **Task**: Task [old-number] → Task [new-number] **File**: backlog/phase-N-task-M.md → phase-N/task-K.md **Phase**: Phase [N]: [Name] **Status**: ⏳ PENDING (ready to start) **Backlog**: [N-1] tasks remaining Use `/flow-task-start` to begin this task when ready. ``` **Edge Cases**: - **Backlog empty**: "Backlog is empty. Nothing to pull." - **Task not in backlog**: "Task [N] not in backlog." - **Target phase doesn't exist**: Create phase directory - **No active phase**: Ask user which phase to add task to **Output**: Move task file from backlog/ to phase directory, update DASHBOARD.md and BACKLOG.md. ``` COMMANDS_DATA_EOF } get_framework_content() { cat <<'FRAMEWORK_DATA_EOF' # Quick Reference for AI (Read This First!!) > **Purpose**: This section provides essential Flow framework knowledge in ~600 lines instead of reading the entire file. Read this first, then use the Section Index to jump to specific sections only when needed. > **NEW in Multi-File Architecture**: Flow now uses separate files (`DASHBOARD.md`, `PLAN.md`, `phase-N/task-N.md`) instead of a single monolithic `PLAN.md`. All commands follow a **dashboard-first** navigation pattern. --- ## Multi-File Structure Overview Flow uses a **multi-file architecture** where work is split across focused files: ``` .flow/ ├── DASHBOARD.md # ⭐ USER'S MAIN WORKSPACE (single source of truth for progress) ├── PLAN.md # 📖 Static context (overview, architecture, scope) ├── BACKLOG.md # 📦 Deferred/future tasks ├── ARCHIVE.md # 🗄️ Completed work (created by /flow-plan-split) ├── phase-1/ # 👤 USER'S WORK FILES │ ├── task-1.md # 📝 Task with iterations, brainstorming, implementation │ ├── task-2.md │ └── task-3.md ├── phase-2/ # 👤 USER'S WORK FILES │ ├── task-1.md │ └── task-2.md └── framework/ # 🤖 AI REFERENCE FILES (read-only for user) ├── DEVELOPMENT_FRAMEWORK.md # 🎓 Complete methodology guide └── examples/ # 📚 Example files for AI to learn from ├── DASHBOARD.md ├── PLAN.md ├── phase-1/ │ └── task-1.md └── phase-2/ └── task-3.md ``` ### File Purposes **👤 USER'S FILES** (What you work in): **DASHBOARD.md** (⭐ Most Important - Single Source of Truth): - User spends most time here - Shows current work pointer (Phase/Task/Iteration) - Displays progress overview with ALL phases/tasks/iterations - Key decisions needing user input - **This is the ONLY place progress is tracked** - no duplication **PLAN.md** (Static Context - Rarely Changes): - Like CLAUDE.md but for this specific feature/project - Purpose, Goals (text only, no checklists), Scope (V1 only) - Architecture overview - DO/DON'T guidelines - Minimal and focused - no assumptions about future work **phase-N/task-N.md** (Work Files - All Tasks Have Iterations): - Contains task overview and dependencies - **All tasks have iterations** (no standalone tasks) - Each iteration has: Pre-tasks (optional) → Brainstorming (optional) → Action Items - One Action Items section per iteration - Brainstorming subjects produce "Resolution Items" → consolidated into Action Items **BACKLOG.md** (Future Work): - Tasks moved out of active plan - Deferred features - V2/V3 items (if user explicitly wants to track them) **ARCHIVE.md** (Completed Work): - Created by `/flow-plan-split` - Archives all completed tasks - Task files become references: "See ARCHIVE.md" **🤖 AI REFERENCE FILES** (Read-only, for AI agents): **framework/DEVELOPMENT_FRAMEWORK.md** (This File): - Complete Flow methodology - Templates, patterns, best practices - AI reads this to understand how Flow works **framework/examples/** (Example Project): - Real example of Flow in use (payment gateway project) - AI learns patterns from these examples - Shows DASHBOARD.md, PLAN.md, and task file formats --- ## Core Hierarchy ``` PHASE → TASK → ITERATION → BRAINSTORM → IMPLEMENTATION → COMPLETE ``` **Structure**: - **PHASE**: High-level milestone (e.g., "Core Implementation", "Testing") - Lives in: DASHBOARD.md (overview) + `phase-N/` directory - **TASK**: Feature/component to build (e.g., "Database Schema", "API Endpoints") - Lives in: `phase-N/task-N.md` file - **ITERATION**: Incremental buildout (e.g., "V1: Basic validation", "V2: Advanced rules") - Lives in: Inside task file (`phase-N/task-N.md`) - **BRAINSTORM**: Design before code (subjects → decisions → action items) - Lives in: Inside iteration section of task file - **IMPLEMENTATION**: Execute action items from brainstorming - Lives in: Inside iteration section of task file **Golden Rule**: Brainstorm → Pre-Tasks → Implementation (never skip brainstorming for complex work) --- ## Dashboard-First Navigation Pattern **ALL commands follow this pattern**: ``` 1. Read DASHBOARD.md (source of truth) 2. Extract current context: - Phase: Phase N - Task: Task M (in phase-N/ directory) - Iteration: Iteration K 3. Navigate to task file: phase-N/task-M.md 4. Perform operation (read/edit task file) 5. Update DASHBOARD.md with new state ``` **Example: `/flow-implement-start`**: ``` 1. Read DASHBOARD.md → Current: Phase 2, Task 3, Iteration 2 2. Construct path: phase-2/task-3.md 3. Read phase-2/task-3.md → Find Iteration 2 section 4. Add Implementation subsection 5. Update DASHBOARD.md: - Change Iteration 2 status: ⏳ → 🚧 - Update "Current Work" pointer ``` **Why Dashboard-First?** - Single source of truth for project state - User always knows where they are - Commands don't need to search multiple files - Consistent navigation across all commands **Key Insight**: DASHBOARD.md is like an index - it tells you WHERE to find detailed work (which task file, which iteration). --- ## Status Markers | Marker | Meaning | When to Use | |--------|---------|-------------| | ✅ | COMPLETE | Finished and verified (frozen, skip re-verification) | | ⏳ | PENDING | Not started yet | | 🚧 | IN PROGRESS | Currently working on this | | 🎨 | READY | Brainstorming done, ready to implement | | ❌ | CANCELLED | Decided against (must document WHY) | | 🔮 | DEFERRED | Moved to V2/V3/later (must document WHY + WHERE - usually moved to BACKLOG.md) | | 🎯 | ACTIVE | Current focus (optional, used in DASHBOARD.md) | **Rules**: - Every Phase/Task/Iteration/Subject MUST have a status marker - ✅ COMPLETE items are verified & frozen (skip re-verification) - ❌ CANCELLED and 🔮 DEFERRED must document reason - Status appears in BOTH: - DASHBOARD.md (for overview) - Task file header (phase-N/task-M.md) **Status Lifecycle**: ``` ⏳ PENDING → 🚧 IN PROGRESS → ✅ COMPLETE ↓ 🎨 READY (for iterations with brainstorming) ``` --- ## Task Structure Rules **The Golden Rule**: **ALL tasks have iterations** - this provides consistent structure and enables iterative development. ### Task with Iterations (The Only Pattern) **File**: `phase-N/task-N.md` ```markdown # Task 3: Implement Payment Gateway **Status**: 🚧 IN PROGRESS **Phase**: [Phase 2 - Core Implementation](../DASHBOARD.md#phase-2-core-implementation) **Purpose**: Integrate Stripe API for payment processing --- ## Task Overview Build production-ready payment gateway integration. **Why This Task**: Current system has no payment processing capability. **Dependencies**: - Requires: Task 1 (Database Layer) - Blocks: Task 4 (Subscription System) --- ## Iterations ### ✅ Iteration 1: API Setup **Goal**: Configure Stripe SDK and credentials **Status**: ✅ COMPLETE [Brainstorming → Action Items → Implementation sections below] --- ### 🚧 Iteration 2: Payment Processing **Goal**: Implement charge creation and webhooks **Status**: 🚧 IN PROGRESS [Currently brainstorming...] ``` **Why iterations-only**: - Consistent structure across all tasks - Enables human-in-loop iteration (plan → brainstorm → implement → complete) - Clear progress tracking (iteration status) - Simple tasks just have 1-2 iterations with action items - Complex tasks have multiple iterations with brainstorming **Structure per iteration**: 1. **Pre-Implementation Tasks** (optional) - Quick fixes before starting 2. **Brainstorming Session** (optional) - Design decisions → Resolution Items 3. **Action Items** (required) - ONE list per iteration, consolidated from brainstorming or direct 4. **Implementation** - Track work, files modified, discoveries --- ## Subject Resolution Types When brainstorming (inside task file), every resolved subject falls into ONE of these types: | Type | Name | When | Action | Example | |------|------|------|--------|---------| | **A** | Pre-Implementation Task | Small code changes needed BEFORE iteration | Create pre-task (< 30 min work) | Fix interface, rename file, update enum | | **B** | Immediate Documentation | Architectural decision, no code yet | Update PLAN.md Architecture section NOW | Design pattern choice, API contract | | **C** | Auto-Resolved | Answered by another subject's decision | Mark as resolved by Subject N | Cascade decisions | | **D** | Iteration Action Items | Substantial feature work that IS the iteration | Create "Resolution Items" list in subject | Build API endpoint, implement validator | **Decision Flow**: 1. Does subject require code changes? - **NO** → Type B (Documentation) or Type C (Auto-resolved) - **YES** → Continue to #2 2. Is it small quick task (< 30 min)? - **YES** → Type A (Pre-task) - **NO** → Type D (Resolution Items → Action Items) **Where They Live**: - Type B decisions → Update `PLAN.md` Architecture section immediately - Type A pre-tasks → Pre-Implementation Tasks section (before brainstorming complete) - Type D Resolution Items → Listed in subject, then `/flow-brainstorm-review` consolidates them into iteration's Action Items section **Key Insight**: Brainstorming creates "Resolution Items" per subject. The `/flow-brainstorm-review` command consolidates all Resolution Items → single Action Items list per iteration. --- ## Common Patterns Quick Reference ### Creating a New Project ```bash # Option 1: From scratch /flow-blueprint # Option 2: Convert existing docs /flow-migrate # Option 3: Convert old single-file PLAN.md /flow-plan-update ``` **Result**: Creates DASHBOARD.md, PLAN.md, phase-1/ directory with initial task files --- ### Starting Work on a Phase ```bash /flow-phase-add "Phase 2: Core Implementation" /flow-phase-start ``` **Files Created/Updated**: - `phase-2/` directory created - DASHBOARD.md updated with new phase section --- ### Adding a Task ```bash /flow-task-add "API Integration" ``` **Files Created/Updated**: - `phase-N/task-M.md` created (N = current phase, M = next task number) - DASHBOARD.md updated with new task entry --- ### Working on an Iteration ```bash # 1. Add iteration to current task /flow-iteration-add "Error Handling" # 2. Start brainstorming /flow-brainstorm-start # 3. Resolve subjects one by one /flow-next-subject # [Discuss subject, choose Type A/B/C/D, document decision] # 4. After all subjects resolved, review /flow-brainstorm-review # [AI suggests iterations/pre-tasks based on decisions] # 5. Complete any pre-tasks, then close brainstorming /flow-brainstorm-complete # 6. Start implementation /flow-implement-start # 7. Do the work... # 8. Complete implementation /flow-implement-complete ``` **Files Updated**: - Current `phase-N/task-M.md` (brainstorming, implementation sections added) - DASHBOARD.md (status updates throughout) - Possibly PLAN.md (if Type B decisions made) --- ### Checking Status ```bash /flow-status ``` **Result**: Reads DASHBOARD.md, shows formatted current state - Current work pointer - Progress overview **This is the REFERENCE MODEL command** - simple dashboard read, no complex logic needed. --- ### Finding Next Work ```bash /flow-next ``` **Logic**: 1. Read DASHBOARD.md 2. Check current iteration status 3. Suggest appropriate next command based on state --- ## Brainstorming Workflow Pattern **Context**: Happens inside `phase-N/task-M.md` file, within an iteration section. ### Structure in Task File ```markdown ### 🚧 Iteration 2: Error Handling **Goal**: Implement comprehensive error handling **Status**: 🚧 IN PROGRESS (Brainstorming) --- #### Brainstorming Session - Error Handling Strategy **Focus**: Design retry logic, error recovery patterns **Subjects to Discuss**: 1. ⏳ Retry Strategy 2. ⏳ Circuit Breaker Pattern 3. ⏳ Error Logging **Resolved Subjects**: --- ##### ✅ Subject 1: Retry Strategy **Decision**: Use exponential backoff with 3 retries **Resolution Type**: D (Iteration Action Items) **Rationale**: Balances reliability with user experience **Action Items**: - [ ] Implement RetryPolicy class - [ ] Add exponential backoff logic - [ ] Configure max retry count --- ##### ✅ Subject 2: Circuit Breaker Pattern **Decision**: Skip circuit breaker for V1, defer to V2 **Resolution Type**: B (Documentation) **Rationale**: V1 scope is tight, circuit breaker adds complexity **Documentation Update**: Added to PLAN.md V2 scope ``` ### Workflow Commands 1. **Start**: `/flow-brainstorm-start` - Adds brainstorming section to current iteration - Creates "Subjects to Discuss" list 2. **Resolve**: `/flow-next-subject` - Picks next ⏳ subject - Discuss with user - Document decision + choose Type A/B/C/D - Add action items if needed 3. **Review**: `/flow-brainstorm-review` (CRITICAL STEP!) - After all subjects resolved - AI analyzes all decisions - Suggests if more iterations needed - Identifies pre-implementation tasks - **Always suggest this BEFORE /flow-brainstorm-complete** 4. **Complete**: `/flow-brainstorm-complete` - Marks brainstorming ✅ COMPLETE - Changes iteration status to 🎨 READY - Only call AFTER completing pre-tasks --- ## Pre-Implementation Tasks Pattern **Context**: Discovered during brainstorming (Type A subjects). Must be completed BEFORE starting iteration implementation. ### Structure in Task File ```markdown ### 🚧 Iteration 2: Error Handling [... Brainstorming section above ...] --- #### Pre-Implementation Tasks These tasks MUST be completed BEFORE starting main implementation of this iteration. ##### ⏳ Pre-Task 1: Refactor Legacy Error Handler **Why Blocking**: Current ErrorHandler doesn't support async retry logic **Scope** (< 30 min): - Update ErrorHandler.ts to support async - Add retryAsync() method - Update 3 existing call sites **Files**: - src/utils/ErrorHandler.ts - src/services/BillingService.ts - tests/utils/ErrorHandler.test.ts **Test**: Run existing tests to ensure no regressions --- ##### ✅ Pre-Task 2: Update Type Definitions **Completed**: 2025-01-15 **Changes Made**: - Added ErrorType enum - Updated function signatures - All tests passing ``` ### Workflow 1. During brainstorming, identify Type A subjects (small < 30 min tasks) 2. `/flow-brainstorm-review` creates pre-implementation tasks section 3. Complete all pre-tasks (mark each ✅ with completion date) 4. Only then call `/flow-brainstorm-complete` 5. Then call `/flow-implement-start` **Why This Matters**: Pre-tasks unblock the main implementation. Doing them early prevents getting stuck mid-iteration. --- ## Section Index (Use Read Tool with Offset/Limit) **How to Use**: When you need deep details, use `Read(file_path, offset=X, limit=Y)` to read ONLY the specific section. ### Quick Reference Sections (You Just Read These!) - Lines 1-600: This Quick Reference (current section) ### Core Framework Sections - Lines 601-850: **Framework Philosophy & Principles** - Domain-Driven Design approach - Agile iterative philosophy - When to use Flow - Lines 851-1100: **Multi-File Architecture Deep Dive** - File responsibilities in detail - Cross-file references - Directory structure rules - File naming conventions - Lines 1101-1550: **Task Structure Rules (Complete Guide)** - Iterations-only architecture - When to split tasks - Task size guidelines - Nested iteration patterns - **Markdown heading structure rules** (5-level hierarchy for perfect folding) - Lines 1401-1700: **Brainstorming Pattern (Complete Guide)** - Full brainstorming workflow - Subject resolution types deep dive - Pre-implementation task patterns - Bugs discovered pattern - Lines 1701-1900: **Implementation Pattern (Complete Guide)** - Implementation structure - Notes and discoveries - Verification checklist - When to mark complete - Lines 1901-2100: **Status Management** - Status marker lifecycle - State transitions - Common pitfalls - Recovery from incorrect states - Lines 2101-2600: **File Templates** - DASHBOARD.md template (complete) - PLAN.md template (complete) - task-N.md template (complete) - Copy-paste ready templates - Lines 2601-2900: **Command Patterns** - Dashboard-first navigation (detailed) - Structure creation pattern - Full traversal pattern - Cross-file search pattern - Lines 2901-3200: **Complete Workflow Examples** - Full feature implementation walkthrough - File updates at each step - Real-world example with payment gateway - Lines 3201-3500: **Backlog Management** - BACKLOG.md structure - Moving tasks to backlog - Pulling tasks back - Archiving with /flow-plan-split - Lines 3501-3800: **Best Practices & Pitfalls** - Common mistakes - How to recover - Performance tips - Multi-developer workflows --- **End of Quick Reference** - Continue reading below for complete framework documentation → # Framework Philosophy & Principles ## What is Flow? Flow is a **specification-driven iterative development methodology** that combines: - **Domain-Driven Design** principles (understand before building) - **Agile philosophy** (iterative shipping, adapt to feedback) - **Progressive disclosure** (V1 → V2 → V3, defer complexity) ### Core Metaphor: Building a Human Body **Skeleton** (Phase 1) → **Veins** (Phase 2) → **Flesh** (Phase 3) → **Fibers** (Phase 4) - **Skeleton**: Basic structure and foundation - Minimal working version - Core data models - Basic happy path - **Veins**: Core data flow and connections - Main feature workflows - Critical integration points - Error handling basics - **Flesh**: Incremental complexity - Additional features - Edge cases - Performance optimization - **Fibers**: Refinement and optimization - Polish and UX improvements - Advanced edge cases - Production hardening ### Multi-File Architecture Philosophy **Problem**: Monolithic `PLAN.md` files grow to 500-5000+ lines, becoming: - Hard to navigate - Slow to load/edit - Git merge nightmares - Context overload for AI **Solution**: Split into focused files: - **DASHBOARD.md**: User's active workspace (what's happening NOW) - **PLAN.md**: Static context (WHY we're building this, HOW it fits together) - **phase-N/task-N.md**: Detailed work files (what's IN each task) - **BACKLOG.md**: Future work (what's DEFERRED) **Benefits**: - Smaller files = faster to read/edit - Each file has single responsibility - Git conflicts are localized - AI can focus on relevant file only - User knows where to look for information ### When to Use Flow **✅ Use Flow For**: - Complex features requiring design decisions - Multi-phase projects (> 2 weeks) - Features with unclear requirements (need exploration) - Team projects (shared context needed) - Features requiring iterative refinement **❌ Don't Use Flow For**: - Simple bug fixes (< 1 hour) - Trivial features (< 5 steps) - Well-defined copy-paste implementations - One-off scripts ### Key Principles #### 1. Plan-Before-Code **Never start coding without understanding the problem domain.** - Brainstorming is NOT optional for complex work - Document decisions and rationale - Identify pre-implementation tasks early - Update architecture documentation (PLAN.md) for major decisions #### 2. Context Preservation **The plan files ARE the memory of the project.** - DASHBOARD.md: Current state (always up-to-date) - PLAN.md: Static context (reference docs) - Task files: Complete work history per task - CHANGELOG.md: Historical decisions - Everything is documented, nothing is forgotten #### 3. Iterative Refinement **Ship V1, then V2, then V3 - don't try to build perfect V1.** - V1: Minimum viable (skeleton + veins) - V2: Enhancements (flesh) - V3: Optimization (fibers) - Defer complexity to later versions #### 4. Progressive Disclosure **Focus only on what's needed NOW.** - Each iteration is focused and shippable - Don't design V3 during V1 brainstorming - Document V2/V3 ideas in PLAN.md or BACKLOG.md - Revisit deferred decisions when actually needed #### 5. State Preservation **Status markers track progress across sessions.** - ✅ COMPLETE: Frozen, verified, skip re-verification - 🚧 IN PROGRESS: Currently active work - ⏳ PENDING: Not started yet - 🎨 READY: Brainstorming done, ready to code - Status in both DASHBOARD.md (overview) and task files (details) #### 6. Dashboard-First Navigation **DASHBOARD.md is the single source of truth for "where are we?"** - All commands read DASHBOARD.md first - Dashboard points to current task file - Task file contains detailed work - Consistent navigation pattern across all commands --- # Multi-File Architecture Deep Dive ## File Responsibilities ### DASHBOARD.md (Progress Tracking) **Purpose**: User's main workspace - shows current work and overall progress **Sections**: 1. **Current Work** - Pointer to active Phase/Task/Iteration 2. **Progress Overview** - All phases with task completion status 3. **Key Decisions** - Outstanding decisions needing user input 4. **Success Criteria** - Definition of done for phases 5. **Related Resources** - Links to docs, examples **Update Frequency**: Every command that changes state **User Interaction**: User reads this constantly to understand where they are **Example Structure**: ```markdown # Project Dashboard **Last Updated**: 2025-01-15 14:30 ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: [Iteration 2 - Error Handling](phase-2/task-3.md#iteration-2-error-handling) 🚧 ## 📊 Progress Overview ### Phase 1: Foundation ✅ COMPLETE - ✅ Task 1: Project Setup (3/3 iterations) - ✅ Task 2: Core Models (2/2 iterations) ### Phase 2: Core Implementation 🚧 IN PROGRESS (2/5 tasks) - ✅ Task 1: Database Layer (2/2 iterations) - ✅ Task 2: Business Logic (3/3 iterations) - 🚧 Task 3: API Integration (1/4 iterations) ← CURRENT - ⏳ Task 4: Authentication - ⏳ Task 5: Caching Layer ## 💡 Key Decisions **Decision Needed**: Should Skills be included in flow.sh or distributed separately? - Option A: Include in flow.sh (150KB → 180KB) - Users get Skills automatically, easier onboarding - Option B: Separate distribution (skills.zip) - Keeps flow.sh lean, users opt-in to Skills - **Recommendation**: Option A - Skills are lightweight (~30KB total), automatic deployment enhances AI experience **Decision Needed**: Which Skills to create first? - Option A: Start with 3 core Skills (navigator, planner, implementer) - MVP approach, faster testing - Option B: Create all 6 Skills upfront - Complete experience from day 1, but longer Phase 2 - **Recommendation**: Option A - Iterate on core 3, add remaining 3 based on real usage feedback **Resolved**: - **2025-10-30**: Skills Complement Commands - Skills = model-invoked (AI decides when), Commands = user-invoked (human triggers explicitly). This maintains human-in-loop philosophy. - **2025-10-30**: Human Still Drives - Skills give AI *awareness* of Flow patterns, not *authority* to make architectural decisions. Descriptions emphasize "when user wants..." patterns. --- ## 🎯 Success Criteria **Phase 1 Complete When**: - `.claude/skills/` directory structure exists - Skill templates documented in framework/ - build-standalone.sh embeds Skills in flow.sh - Skills deploy correctly to test project **Phase 2 Complete When**: - 6 Core Skills created with SKILL.md files - Each Skill has clear description triggering appropriate context - Skills reference framework patterns correctly - Skills tested individually **Phase 3 Complete When**: - Skills activate based on user requests (not manual invocation) - Real-world workflow test completed (plan → implement → complete) - Documentation updated (README, new SKILLS.md guide) - Example Skills added to framework/examples/ --- ## 📚 Related Resources - **Agent Skills Documentation**: https://docs.claude.com/en/docs/claude-code/skills - **Flow Framework**: framework/DEVELOPMENT_FRAMEWORK.md - **Slash Commands**: framework/SLASH_COMMANDS.md - **Build System**: build-standalone.sh (deployment logic) ``` ### PLAN.md (Static Context) **Purpose**: Like CLAUDE.md but for this specific feature/project **Sections**: 1. **Overview** - Purpose, Goals, Scope (V1/V2/V3) 2. **Architecture** - System design, components, data flow 3. **Testing Strategy** - How to test this feature 4. **Development Phases** - High-level phase descriptions (NOT detailed tasks) **Update Frequency**: Rarely (only when architecture changes or Type B brainstorming decisions) **User Interaction**: User reads at start of project, refers back occasionally **Key Insight**: This is the "WHY" and "HOW" documentation - it explains the big picture **Example Structure**: ```markdown # Payment Gateway Integration - Development Plan > **📍 Current Progress**: See [DASHBOARD.md](DASHBOARD.md) > **🎯 Purpose**: Integrate Stripe payment processing **Created**: 2025-01-10 **Version**: V1 ## Overview ### Purpose Build production-ready payment gateway integration supporting credit cards and subscriptions. ### Goals - [ ] Process credit card payments via Stripe API - [ ] Handle webhook events for async notifications - [ ] Implement retry logic for failed payments ### Scope **V1 (Included)**: - Credit card payment processing - Basic subscription support - Webhook handler - Retry logic (3 attempts) **V2 (Future)**: - ACH/bank transfer support - Multi-currency - Saved payment methods ## Architecture ### System Design **Components**: - `PaymentService` - Core payment orchestration - `StripeClient` - API wrapper with retry logic - `WebhookHandler` - Event processing - `PaymentRepository` - Database persistence ### Data Flow [Diagram or description] ## Testing Strategy **Methodology**: Simulation-based per-service testing **Location**: `scripts/` directory **Naming**: `{service}.scripts.ts` ## Development Phases ### Phase 1: Foundation Setup project structure and dependencies ### Phase 2: Core Implementation Build payment processing functionality ### Phase 3: Testing & Hardening Comprehensive testing and edge cases ``` ### phase-N/task-N.md (Work Files) **Purpose**: Container for all work related to a specific task **Sections**: 1. **Task Header** - Status, Phase link, Purpose 2. **Task Overview** - Description, dependencies, why this task 3. **Iterations** - All tasks have iterations (1+ iterations per task) 4. **Task Notes** - Discoveries, decisions, references **Update Frequency**: Constantly during work on this task **User Interaction**: User works in this file during active development **Key Insight**: This is the "WHAT" and "HOW SPECIFICALLY" - all the detailed work **Example Structure** (Task with Iterations): ```markdown # Task 3: API Integration **Status**: 🚧 IN PROGRESS **Phase**: [Phase 2 - Core Implementation](../DASHBOARD.md#phase-2-core-implementation) **Purpose**: Integrate with Stripe REST API --- ## Task Overview Build robust Stripe API client with error handling and retry logic. **Why This Task**: Need payment processing capability **Dependencies**: - Requires: Task 1 (Database Layer) - Blocks: Task 4 (Authentication) --- ## Iterations ### ✅ Iteration 1: REST Client Setup **Goal**: Create Stripe API client wrapper **Status**: ✅ COMPLETE [Brainstorming, Implementation sections below] --- ### 🚧 Iteration 2: Error Handling **Goal**: Implement error handling **Status**: 🚧 IN PROGRESS [Currently working on this iteration] --- ## Task Notes **Discoveries**: - Stripe SDK handles connection pooling automatically **Decisions**: - Using Stripe Node SDK v12.x **References**: - Stripe API Docs: https://stripe.com/docs/api ``` ### BACKLOG.md (Future Work) **Purpose**: Storage for deferred tasks and V2/V3 features **Sections**: 1. **Backlog Dashboard** - Summary of backlog items 2. **Backlog Items** - Deferred tasks with reasoning **Update Frequency**: When moving tasks out of active plan or adding future work **Example Structure**: ```markdown # Project Backlog ## 📋 Backlog Dashboard **Total Items**: 8 **V2 Features**: 5 **V3 Features**: 2 **Deferred Bugs**: 1 ## Backlog Items ### ⏳ Task: Multi-Currency Support **Originally Planned**: Phase 2, Task 6 **Deferred To**: V2 **Reasoning**: V1 scope focuses on USD only, multi-currency adds significant complexity **Estimated Effort**: 2 weeks **Dependencies**: Core payment processing complete ``` ### CHANGELOG.md (History) **Purpose**: Historical record of completed work **Example**: ```markdown # Changelog ## [V1.2.0] - 2025-01-15 ### Added - Retry logic for failed payments - Webhook signature validation ### Fixed - Race condition in payment processing ## [V1.1.0] - 2025-01-10 ### Added - Basic payment processing - Stripe API integration ``` ### ARCHIVE.md (Completed Work) **Purpose**: Created by `/flow-plan-split` - archives completed tasks **Structure**: Flat list of completed tasks with all iterations **Effect**: Original task files become references: ```markdown # Task 1: Project Setup **Status**: ✅ COMPLETE (Archived) See [ARCHIVE.md](../ARCHIVE.md#task-1-project-setup) for complete details. ``` ## Cross-File References ### Linking Between Files **Dashboard → Task File**: ```markdown - **Task**: [Task 3 - API Integration](phase-2/task-3.md) ``` **Task File → Dashboard**: ```markdown **Phase**: [Phase 2 - Core Implementation](../DASHBOARD.md#phase-2-core-implementation) ``` **Task File → PLAN.md**: ```markdown See [PLAN.md Architecture section](../PLAN.md#architecture) for system design ``` **PLAN.md → Backlog**: ```markdown Multi-currency support deferred to V2 (see [BACKLOG.md](BACKLOG.md)) ``` ### Reference Patterns **Current Work Pointer** (in DASHBOARD.md): ```markdown ## 📍 Current Work - **Phase**: Phase 2 - Core Implementation - **Task**: Task 3 - API Integration - **Iteration**: Iteration 2 - Error Handling - **File**: [phase-2/task-3.md](phase-2/task-3.md#iteration-2-error-handling) ``` This pointer is the SOURCE OF TRUTH for "where are we right now?" ## Directory Structure Rules ### Phase Directories **Naming**: `phase-N/` where N is the phase number (1, 2, 3, ...) **Created**: When `/flow-phase-add` is run **Contains**: Task files for that phase ``` phase-1/ ├── task-1.md ├── task-2.md └── task-3.md ``` ### Task File Naming **Format**: `task-N.md` where N is the task number within the phase **Numbering**: Sequential within each phase (task-1, task-2, task-3, ...) **Name in Content**: Task file contains descriptive name in header **Example**: - File: `phase-2/task-3.md` - Header: `# Task 3: API Integration` ### File Naming Conventions **DO**: - ✅ Use `phase-N/` for phase directories - ✅ Use `task-N.md` for task files - ✅ Keep all Flow files in `.flow/` directory - ✅ Use lowercase for filenames **DON'T**: - ❌ Don't put task name in filename (`task-3-api-integration.md`) - ❌ Don't nest deeper than `phase-N/task-N.md` - ❌ Don't create subdirectories under phase directories # Task Structure Rules (Complete Guide) ## The Golden Rule **ALL Tasks Have Iterations** This provides consistent structure and enables human-in-loop iterative development. ## Why Iterations-Only? - **Consistent structure** - Every task follows same pattern, easier to navigate - **Human-in-loop** - Enables plan → brainstorm → implement → complete cycle - **Progress tracking** - Clear iteration status shows where you are - **Flexibility** - Simple tasks have 1-2 iterations, complex tasks have many - **No special cases** - One pattern to learn and follow ## Task Pattern (The Only Pattern) **File**: `phase-N/task-N.md` ### Complete Example ```markdown # Task 3: API Integration **Status**: 🚧 IN PROGRESS **Phase**: [Phase 2 - Core Implementation](../DASHBOARD.md#phase-2-core-implementation) **Purpose**: Integrate with Stripe REST API for payment processing --- ## Task Overview Build robust Stripe API client with error handling, retry logic, and webhooks. **Why This Task**: Core payment functionality depends on reliable API integration. **Dependencies**: - **Requires**: Task 1 (Database Layer) - need PaymentRepository - **Requires**: Task 2 (Business Logic) - need PaymentService interface - **Blocks**: Task 4 (Authentication) - auth tokens stored via this API **Estimated Complexity**: High (3-4 iterations expected) --- ## Iterations ### ✅ Iteration 1: REST Client Setup **Goal**: Create Stripe API client wrapper with authentication **Status**: ✅ COMPLETE (2025-01-12) --- #### Brainstorming Session - REST Client Architecture **Focus**: Design API client abstraction and authentication flow **Subjects to Discuss**: (All subjects resolved) **Resolved Subjects**: --- ##### ✅ Subject 1: Client Architecture Pattern **Decision**: Use singleton pattern with lazy initialization **Resolution Type**: D (Iteration Action Items) **Rationale**: - Stripe SDK maintains connection pool internally - Multiple instances would create redundant connections - Lazy init delays credential validation until first use **Resolution Items**: - Create `StripeClient` singleton class - Implement lazy initialization in constructor - Add credential validation on first API call --- ##### ✅ Subject 2: Authentication Flow **Decision**: Use API key from environment variable with validation **Resolution Type**: D (Iteration Action Items) **Rationale**: - Follows Stripe best practices - Supports different keys per environment - Fails fast if key missing or invalid **Resolution Items**: - Load `STRIPE_API_KEY` from env - Validate key format at startup - Throw clear error if key missing --- #### Action Items (Consolidated from Resolution Items above by `/flow-brainstorm-review`) - [x] Create `StripeClient` singleton class - [x] Implement lazy initialization in constructor - [x] Add credential validation on first API call - [x] Load `STRIPE_API_KEY` from env - [x] Validate key format at startup - [x] Throw clear error if key missing --- #### Implementation - Iteration 1: REST Client Setup **Status**: ✅ COMPLETE (2025-01-12) **Implementation Notes**: - Created `src/payment/StripeClient.ts` with singleton pattern - Implemented environment-based key loading - Added validation for API key format (starts with `sk_`) - Discovered bug in existing error handling (see Pre-Implementation Tasks in Iteration 2) **Files Modified**: - `src/payment/StripeClient.ts` - Created (142 lines) - `src/config/env.ts` - Added STRIPE_API_KEY validation - `scripts/payment.scripts.ts` - Created test file **Verification**: - ✅ All tests passing in payment.scripts.ts - ✅ API key validation working correctly - ✅ Singleton pattern verified --- ### 🚧 Iteration 2: Error Handling **Goal**: Implement comprehensive error handling and retry logic **Status**: 🚧 IN PROGRESS (Brainstorming) --- #### Pre-Implementation Tasks ##### ⏳ Pre-Task 1: Refactor Legacy Error Handler **Why Blocking**: Current ErrorHandler doesn't support async retry logic **Scope** (< 30 min): - Update ErrorHandler.ts to support async - Add retryAsync() method - Update 3 existing call sites **Files**: - src/utils/ErrorHandler.ts - src/services/BillingService.ts - tests/utils/ErrorHandler.test.ts --- #### Brainstorming Session - Error Handling Strategy **Focus**: Design retry logic, error recovery patterns **Subjects to Discuss**: 1. ⏳ Retry Strategy 2. ⏳ Circuit Breaker Pattern 3. ⏳ Error Logging **Resolved Subjects**: (To be filled during brainstorming) --- ### ⏳ Iteration 3: Retry Logic **Goal**: Add exponential backoff retry for transient failures **Status**: ⏳ PENDING --- ### ⏳ Iteration 4: Integration Tests **Goal**: Comprehensive test coverage with Stripe API simulation **Status**: ⏳ PENDING --- ## Task Notes **Discoveries**: - Stripe SDK already implements connection pooling (no need for custom) - Error codes changed in Stripe API v2023-10-16 (updated error taxonomy) **Decisions**: - Using Stripe Node SDK v12.x (latest stable) - Not implementing custom connection pool (SDK handles it) **References**: - Stripe API Docs: https://stripe.com/docs/api - Existing billing: `src/legacy/billing.ts` (PayPal integration pattern) - Similar webhook: `src/webhooks/shipment.ts` (signature validation example) ``` ### Completion Criteria Task is ✅ COMPLETE when: - ALL iterations are ✅ COMPLETE - Task Notes updated with discoveries - All dependencies satisfied ## Exception: Pre-Implementation Tasks **Only exception to "no direct action items" rule**: Pre-implementation tasks are discovered during brainstorming (Type A subjects) and must be completed BEFORE iteration implementation starts. **Structure**: ``` Task ├── Iteration N │ ├── Pre-Implementation Tasks ← EXCEPTION: Action items at iteration level │ ├── Brainstorming Session │ └── Implementation ``` **Why Allowed**: These are blocking tasks that unblock the iteration. They're scoped to < 30 min and must be done before `/flow-implement-start`. ## When to Split a Task ### Task Too Large? **Signals**: - More than 5 iterations planned - Iterations span multiple unrelated concerns - Task takes > 4 weeks - Task description is vague ("Implement everything...") **Solution**: Split into multiple tasks **Example**: ``` Before: - Task: Payment System (10 iterations) After: - Task 1: Payment Processing (4 iterations) - Task 2: Webhook Handling (3 iterations) - Task 3: Payment Analytics (3 iterations) ``` ### Task Too Small? **Signals**: - Only 1 iteration with 2-3 action items - No brainstorming needed - Can complete in < 1 hour **Solution**: Use Single Iteration with Direct Action Items **Example**: ``` Task: Add Logging - Iteration 1: Logging Implementation - Action Items (no brainstorming): - Add logger configuration - Update main entry points - Add log rotation ``` ## Nested Iteration Pattern **Question**: Can iterations have sub-iterations? **Answer**: No. Keep structure flat. **Why**: Two levels (Task → Iteration) is enough. If you need more nesting, split the task. **If You Feel You Need More Nesting**: 1. You probably need multiple tasks instead 2. Or your brainstorming subjects should become separate iterations --- ## Markdown Heading Structure Rules **Purpose**: Flow task files use a consistent 5-level heading hierarchy that enables perfect folding in Markdown previewers (VSCode, GitHub, etc.). This structure is **mandatory** for all task files. ### The 5-Level Hierarchy ``` Level 1: # Task N: [Name] ← Task title (fold entire file) Level 2: ## Task Overview, ## Iterations, ## Task Notes ← Major sections (fold section) Level 3: ### Iteration N: [Name] ← Individual iteration (fold iteration) Level 4: #### Pre-Implementation Tasks ← Iteration subsections (fold subsection) #### Brainstorming Session #### Action Items #### Implementation Level 5: ##### Subject N: [Name] ← Individual subjects/pre-tasks (fold item) ##### Pre-Task N: [Name] ``` ### Visual Folding Hierarchy ``` # Task 3: API Integration [Level 1 - Fold entire task] ├── ## Task Overview [Level 2 - Fold section] ├── ## Iterations [Level 2 - Fold section] │ ├── ### ✅ Iteration 1: REST Client Setup [Level 3 - Fold iteration] │ │ ├── #### Pre-Implementation Tasks [Level 4 - Fold subsection] │ │ │ ├── ##### ✅ Pre-Task 1: Update ErrorHandler [Level 5 - Fold item] │ │ │ └── ##### ⏳ Pre-Task 2: Fix Type Definitions [Level 5 - Fold item] │ │ ├── #### Brainstorming Session - REST Client [Level 4 - Fold subsection] │ │ │ ├── ##### ✅ Subject 1: Client Pattern [Level 5 - Fold item] │ │ │ ├── ##### ✅ Subject 2: Authentication [Level 5 - Fold item] │ │ │ └── ##### ✅ Subject 3: Timeouts [Level 5 - Fold item] │ │ ├── #### Action Items [Level 4 - Fold subsection] │ │ └── #### Implementation - Iteration 1 [Level 4 - Fold subsection] │ ├── ### 🚧 Iteration 2: Error Handling [Level 3 - Fold iteration] │ │ ├── #### Pre-Implementation Tasks [Level 4 - Fold subsection] │ │ ├── #### Brainstorming Session - Error Handling [Level 4 - Fold subsection] │ │ ├── #### Action Items [Level 4 - Fold subsection] │ │ └── #### Implementation - Iteration 2 [Level 4 - Fold subsection] │ └── ### ⏳ Iteration 3: Retry Logic [Level 3 - Fold iteration] └── ## Task Notes [Level 2 - Fold section] ``` ### Golden Rules **Rule 1: Never Skip Levels** - ✅ CORRECT: Go 1 → 2 → 3 → 4 → 5 sequentially - ❌ WRONG: Skip from 1 → 3 or 2 → 5 **Rule 2: Consistent Subsections** All four subsections within an iteration MUST be level 4: - `#### Pre-Implementation Tasks` (if needed) - `#### Brainstorming Session - [Topic]` (if needed) - `#### Action Items` (required) - `#### Implementation - Iteration N: [Name]` (after `/flow-implement-start`) **Rule 3: Subjects and Pre-Tasks are Level 5** Individual items within subsections MUST be level 5: - `##### ✅ Subject 1: [Name]` - `##### ⏳ Pre-Task 1: [Name]` **Rule 4: Status Markers in Heading Text** Include status emoji in heading for visual scanning: - `### ✅ Iteration 1: REST Client Setup` - `##### 🚧 Subject 2: Error Taxonomy` ### DO / DON'T Examples **✅ DO - Correct Hierarchy**: ```markdown ## Iterations ← Level 2 ### ✅ Iteration 1: Setup ← Level 3 (one level deeper) #### Brainstorming Session ← Level 4 (one level deeper) ##### ✅ Subject 1: Architecture ← Level 5 (one level deeper) ``` **❌ DON'T - Skipped Levels**: ```markdown ## Iterations ← Level 2 ### ✅ Iteration 1: Setup ← Level 3 #### Brainstorming Session ← Level 4 ###### Subject 1: Architecture ← Level 6 (WRONG - skipped level 5!) ``` **❌ DON'T - Inconsistent Subsection Levels**: ```markdown ### Iteration 1: Setup ### Brainstorming Session ← WRONG - should be level 4 (####) #### Subject 1 ← WRONG - should be level 5 (#####) ``` **❌ DON'T - Content Sections with Headings Inside Subjects**: ```markdown ##### Subject 1: Error Handling **Decision**: Use exponential backoff **Resolution Type**: D ###### Resolution Items ← WRONG - no level 6 allowed ``` **✅ DO - Use Bold Text, Not Headings**: ```markdown ##### Subject 1: Error Handling **Decision**: Use exponential backoff **Resolution Type**: D (Iteration Action Items) **Resolution Items**: ← Bold text, not heading - Create RetryPolicy class - Implement backoff algorithm ``` ### Why This Matters **For Users**: - Clean folding in VSCode/GitHub - fold any section with one click - Easy navigation - jump between iterations/subjects - Visual hierarchy - clear parent-child relationships - Better readability - consistent structure across all tasks **For AI**: - Parsing consistency - AI can reliably extract sections - Template adherence - AI generates correctly structured files - Section identification - AI knows exactly where to add content - Command execution - Slash commands can navigate predictably ### Validation When creating or updating task files, verify: 1. Each heading is exactly one level deeper than its parent 2. All iteration subsections use level 4 (`####`) 3. All subjects/pre-tasks use level 5 (`#####`) 4. No heading uses level 6 (`######`) or deeper 5. Status markers included in heading text where applicable --- # Brainstorming Pattern (Complete Guide) ## What is Brainstorming? **Brainstorming** is the design-before-code phase where you: 1. Identify questions/decisions (subjects) 2. Discuss each subject 3. Document decisions 4. Generate action items 5. Identify pre-implementation work **Location**: Inside task file, within iteration section **Mandatory For**: Complex iterations requiring design decisions ## Brainstorming Structure ### Complete Brainstorming Section ```markdown #### Brainstorming Session - [Topic] **Focus**: [What we're designing/deciding] **Subjects to Discuss**: 1. ⏳ [Subject name] 2. ⏳ [Subject name] 3. ⏳ [Subject name] **Resolved Subjects**: --- ##### ✅ Subject 1: [Name] **Decision**: [Your decision] **Resolution Type**: A / B / C / D **Rationale**: [Why this decision] **Action Items** (if Type A or D): - [ ] Item 1 - [ ] Item 2 **Documentation Update** (if Type B): [What was updated in PLAN.md] --- ##### ✅ Subject 2: [Name] [... same structure ...] ``` ## Subject Resolution Types (Deep Dive) ### Type A: Pre-Implementation Task **When**: Small code change needed BEFORE iteration starts **Criteria**: - Required for iteration (blocking) - Small scope (< 30 min) - Can be done independently - Examples: Fix interface, rename file, update enum, fix bug **Action**: 1. Document decision 2. Create action items 3. Add to "Pre-Implementation Tasks" section 4. Complete BEFORE `/flow-brainstorm-complete` **Example**: ```markdown ##### ✅ Subject 3: Type Definition Updates **Decision**: Need to update PaymentStatus enum to include new states **Resolution Type**: A (Pre-Implementation Task) **Rationale**: Current enum missing "pending_retry" and "failed_permanent" states needed for retry logic **Action Items**: - [ ] Update PaymentStatus enum in types.ts - [ ] Update 4 switch statements to handle new states - [ ] Add tests for new states **Note**: Must complete before implementing retry logic ``` ### Type B: Immediate Documentation **When**: Architectural decision that affects system design **Criteria**: - No code changes yet - Updates PLAN.md Architecture section - Examples: Design pattern choice, API contract, data model **Action**: 1. Document decision 2. Update PLAN.md Architecture section NOW 3. Reference update in subject **Example**: ```markdown ##### ✅ Subject 1: Error Recovery Strategy **Decision**: Implement retry with exponential backoff, no circuit breaker for V1 **Resolution Type**: B (Documentation) **Rationale**: - Exponential backoff handles transient failures well - Circuit breaker adds complexity, defer to V2 - Stripe API has good rate limiting, low risk of cascade failures **Documentation Update**: Updated PLAN.md Architecture section with retry strategy diagram and V2 scope for circuit breaker ``` ### Type C: Auto-Resolved **When**: Subject answered by another subject's decision **Criteria**: - No independent decision needed - Cascade from another subject - Examples: Implementation detail determined by architecture choice **Action**: 1. Note which subject resolved this 2. No additional action items **Example**: ```markdown ##### ✅ Subject 4: Retry Delay Calculation **Decision**: Use exponential backoff as decided in Subject 1 **Resolution Type**: C (Auto-Resolved by Subject 1) **Rationale**: Subject 1 already decided on exponential backoff strategy, this subject is implementation detail ``` ### Type D: Iteration Action Items **When**: Substantial feature work that IS the iteration **Criteria**: - Main implementation work - Takes significant time (> 30 min) - Examples: Build API endpoint, implement validator, create service **Action**: 1. Document decision 2. Create action items 3. These become implementation action items **Example**: ```markdown ##### ✅ Subject 2: Retry Implementation **Decision**: Implement RetryPolicy class with configurable backoff strategy **Resolution Type**: D (Iteration Action Items) **Rationale**: - Separate class for testability - Configurable for different API endpoints - Can swap strategies (exponential, linear, fixed) **Action Items**: - [ ] Create RetryPolicy class - [ ] Implement exponential backoff algorithm - [ ] Add configuration for max retries, base delay - [ ] Integrate with StripeClient - [ ] Add tests for retry scenarios ``` ## Brainstorming Workflow Commands ### 1. `/flow-brainstorm-start` **When**: Starting brainstorming for current iteration **Effect**: - Adds brainstorming section to current iteration - Prompts user for subjects to discuss - Creates "Subjects to Discuss" list **Example**: ``` User: /flow-brainstorm-start AI: Let's start brainstorming for Iteration 2: Error Handling. What subjects should we discuss? (e.g., "Retry strategy, Error logging, Circuit breaker") User: Retry strategy, Error taxonomy, Logging format, Integration with existing error handler AI: Added 4 subjects to brainstorming session in phase-2/task-3.md ``` ### 2. `/flow-next-subject` **When**: Ready to discuss next subject **Effect**: - Finds next ⏳ PENDING subject - Discusses with user - Documents decision - User/AI chooses Type A/B/C/D - Creates action items if needed - Marks subject ✅ COMPLETE **Example**: ``` User: /flow-next-subject AI: Let's discuss Subject 1: Retry Strategy [Discussion happens...] AI: Decision: Use exponential backoff with 3 retries Is this: A) Pre-implementation task (< 30 min, blocking) B) Documentation update (update PLAN.md Architecture) C) Auto-resolved by another subject D) Main iteration work (implementation action items) User: D AI: What are the action items? User: Create RetryPolicy class, implement backoff algorithm, integrate with client, add tests AI: Documented. Subject 1 marked complete. 3 subjects remaining. ``` ### 3. `/flow-brainstorm-review` (CRITICAL!) **When**: After ALL subjects resolved, BEFORE `/flow-brainstorm-complete` **Why Critical**: - AI reviews all decisions holistically - Suggests if more iterations needed - Identifies pre-implementation tasks - Catches missing subjects **Effect**: - AI reads all resolved subjects - Suggests additional iterations if decisions reveal more work - Creates "Pre-Implementation Tasks" section if Type A subjects found - Confirms readiness to close brainstorming **Example**: ``` User: /flow-brainstorm-review AI: Reviewing all 4 resolved subjects... Summary: - Subject 1: Retry strategy (Type D) → Main iteration work - Subject 2: Error taxonomy (Type B) → Updated PLAN.md - Subject 3: Logging format (Type D) → Main iteration work - Subject 4: Integration with error handler (Type A) → Pre-implementation task Analysis: Based on the decisions, I recommend: 1. Pre-Implementation Task Identified: - Subject 4 requires updating ErrorHandler.ts before implementing retry logic - Estimated: 20 minutes - Action: Update ErrorHandler to support async operations 2. Current Iteration Scope Confirmed: - Implementing RetryPolicy and logging is appropriate for this iteration - Estimated: 3-4 hours of work 3. No Additional Iterations Needed: - All error handling concerns addressed - Circuit breaker deferred to V2 Next Steps: 1. Complete pre-implementation task (update ErrorHandler.ts) 2. Run /flow-brainstorm-complete 3. Run /flow-implement-start Ready to proceed? ``` ### 4. `/flow-brainstorm-complete` **When**: After completing ALL pre-implementation tasks **Effect**: - Marks brainstorming ✅ COMPLETE - Changes iteration status to 🎨 READY - Updates DASHBOARD.md **Example**: ``` User: /flow-brainstorm-complete AI: Verifying pre-implementation tasks... ✅ Pre-Task 1: Update ErrorHandler.ts - COMPLETE Brainstorming complete! Iteration 2 is now 🎨 READY. Next: /flow-implement-start to begin coding. ``` ## Pre-Implementation Tasks Pattern ### Structure ```markdown #### Pre-Implementation Tasks These tasks MUST be completed BEFORE starting main implementation of this iteration. ##### ⏳ Pre-Task 1: [Name] **Why Blocking**: [Explanation of why this blocks implementation] **Scope** (< 30 min): - [What needs to be done] - [Specific changes] **Files**: - [List of files to modify] **Test**: [How to verify it's done] --- ##### ✅ Pre-Task 2: [Name] **Completed**: [Date] **Changes Made**: - [What was actually done] - [Any deviations from plan] ``` ### Workflow 1. During brainstorming, Type A subjects are identified 2. `/flow-brainstorm-review` creates "Pre-Implementation Tasks" section 3. User completes each pre-task (or AI helps) 4. Mark each pre-task ✅ with completion date 5. Only after ALL pre-tasks done → `/flow-brainstorm-complete` ### Why This Pattern Exists **Problem**: During brainstorming, you discover small blocking issues: - Interface signature is wrong - Enum is missing a value - Legacy code doesn't support new pattern - Type definitions need update **Without Pre-Tasks**: - Start implementation - Hit blocker - Stop to fix blocker - Lose context - Take longer overall **With Pre-Tasks**: - Identify blockers upfront during brainstorming - Fix them while context is fresh - Start implementation with clean path - No interruptions ## Bugs Discovered Pattern **Use Case**: During brainstorming, you analyze reference implementations and find bugs **Pattern**: ```markdown #### Bugs Discovered in Reference Implementation ##### Bug 1: Race Condition in PaymentService **Location**: `src/services/PaymentService.ts:145` **Problem**: ```typescript // Current code (buggy) async processPayment(amount: number) { const status = await this.checkStatus(); // Race condition: status can change between check and update await this.updatePayment(status); } ``` **Fix**: ```typescript // Fixed code async processPayment(amount: number) { await this.db.transaction(async (tx) => { const status = await this.checkStatus(tx); await this.updatePayment(status, tx); }); } ``` **Impact**: Could cause duplicate charges in concurrent requests **Action**: Add to Pre-Implementation Tasks ``` **Why Document This**: - Shows thorough analysis - Prevents reintroducing same bugs - Helps team learn from reference code - Documents why certain patterns are used # Implementation Pattern (Complete Guide) ## What is Implementation? **Implementation** is the coding phase where you execute action items from brainstorming. **Location**: Inside task file, within iteration section, after brainstorming **Prerequisite**: Brainstorming must be ✅ COMPLETE (status 🎨 READY) ## Implementation Structure ```markdown #### Implementation - Iteration [N]: [Name] **Status**: 🚧 IN PROGRESS **Action Items**: See resolved subjects above **Implementation Notes**: [Document discoveries, decisions, challenges during work] **Files Modified**: - [file1.ts] - [what changed] - [file2.ts] - [what changed] **Verification**: - ✅ [verification step 1] - ✅ [verification step 2] ``` ## Implementation Workflow ### 1. `/flow-implement-start` **Prerequisites**: - Brainstorming ✅ COMPLETE - All pre-implementation tasks ✅ COMPLETE - Iteration status is 🎨 READY **Effect**: - Adds "Implementation" section to current iteration - Changes iteration status: 🎨 READY → 🚧 IN PROGRESS - Updates DASHBOARD.md ### 2. Do the Work **During Implementation**: - Work through action items from resolved subjects - Document discoveries in "Implementation Notes" - Track files modified - Note any deviations from plan **Good Implementation Notes**: ```markdown **Implementation Notes**: - Discovered Stripe SDK v12 deprecated `charges.create()`, using `paymentIntents.create()` instead - Added StripeErrorMapper class to convert SDK errors to domain errors (not in original plan, but needed) - Performance: API calls taking 200-300ms, added caching layer (will document in Architecture) - Bug found: Existing PaymentRepository missing transaction support, added in separate commit ``` ### 3. `/flow-implement-complete` **Prerequisites**: - All action items done - Code works (tests pass) - Implementation notes updated **Effect**: - Marks iteration ✅ COMPLETE - Updates DASHBOARD.md - Moves to next iteration or completes task ## Verification Checklist Before marking iteration complete, verify: **Code Quality**: - [ ] All action items implemented - [ ] Code follows project style guide - [ ] No commented-out code or TODOs left behind - [ ] Error handling in place **Testing**: - [ ] Unit tests written and passing - [ ] Integration tests if needed - [ ] Manual testing done - [ ] Edge cases covered **Documentation**: - [ ] Implementation notes updated - [ ] Files modified list complete - [ ] Any architecture changes documented in PLAN.md - [ ] Code comments for complex logic **Integration**: - [ ] Works with existing code - [ ] No breaking changes (or documented if intentional) - [ ] Dependencies satisfied - [ ] Performance acceptable ## When to Mark Complete **✅ Mark Complete When**: - All verification checklist items done - You would be comfortable shipping this - Another developer could understand what was done - No blocking issues remain **❌ Don't Mark Complete When**: - Tests are failing - Code is partially implemented - "TODO: finish this later" comments exist - Blocking bugs discovered but not fixed --- # Status Management ## Status Marker Lifecycle ### Phase Lifecycle ``` ⏳ PENDING (created) ↓ /flow-phase-start ↓ 🚧 IN PROGRESS (working on tasks) ↓ /flow-phase-complete (all tasks done) ↓ ✅ COMPLETE ``` **Alternative Endings**: - ❌ CANCELLED (decided not to do this phase) - 🔮 DEFERRED (moved to V2/V3, added to BACKLOG.md) ### Task Lifecycle (with Iterations) ``` ⏳ PENDING (created) ↓ /flow-task-start ↓ 🚧 IN PROGRESS (working on iterations) ↓ /flow-task-complete (all iterations done) ↓ ✅ COMPLETE ``` ### Iteration Lifecycle ``` ⏳ PENDING (created) ↓ /flow-brainstorm-start ↓ 🚧 IN PROGRESS (brainstorming) ↓ /flow-brainstorm-complete (all subjects resolved, pre-tasks done) ↓ 🎨 READY (ready to implement) ↓ /flow-implement-start ↓ 🚧 IN PROGRESS (implementing) ↓ /flow-implement-complete (all action items done, verified) ↓ ✅ COMPLETE ``` **Simplified Path** (no brainstorming): ``` ⏳ PENDING ↓ /flow-implement-start (if no brainstorming needed) ↓ 🚧 IN PROGRESS ↓ /flow-implement-complete ↓ ✅ COMPLETE ``` ## State Transitions ### Valid Transitions **Phase**: - ⏳ → 🚧 (start) - 🚧 → ✅ (complete) - 🚧 → ❌ (cancel) - 🚧 → 🔮 (defer) - ⏳ → ❌ (cancel before starting) - ⏳ → 🔮 (defer before starting) **Task**: - ⏳ → 🚧 (start) - 🚧 → ✅ (complete) - 🚧 → ❌ (cancel) - 🚧 → 🔮 (defer) **Iteration**: - ⏳ → 🚧 (start brainstorming or implementing) - 🚧 → 🎨 (finish brainstorming) - 🎨 → 🚧 (start implementing) - 🚧 → ✅ (finish implementing) ### Invalid Transitions **Never Do This**: - ❌ ✅ → 🚧 (reopening completed work - create new iteration instead) - ❌ ⏳ → ✅ (skipping work - mark cancelled or remove if never needed) - ❌ 🎨 → ⏳ (moving backwards - if brainstorming wrong, add new iteration) ## Common Pitfalls ### Pitfall 1: Marking Complete Too Early **Problem**: ```markdown ### Iteration 2: Error Handling ✅ COMPLETE **Implementation Notes**: - Started implementing retry logic - TODO: finish exponential backoff - TODO: add tests ``` **Why Bad**: Work is not done, tests missing, TODOs present **Fix**: Keep status 🚧 IN PROGRESS until ALL work done ### Pitfall 2: Not Updating DASHBOARD.md **Problem**: Update task file status but forget DASHBOARD.md **Effect**: DASHBOARD.md shows wrong current work, user is confused **Fix**: Commands automatically update both files ### Pitfall 3: Skipping Brainstorming **Problem**: ```markdown ### Iteration 2: Complex Feature ⏳ [Immediately start implementing without design] ``` **Why Bad**: No decisions documented, will need refactoring later **Fix**: Always brainstorm for complex work, only skip for trivial iterations ### Pitfall 4: Mixing Status in DASHBOARD and Task File **Problem**: - DASHBOARD.md shows Iteration 2 🚧 IN PROGRESS - Task file shows Iteration 2 ✅ COMPLETE **Why Bad**: Source of truth is inconsistent **Fix**: `/flow-verify-plan` detects this, always update both together ## Recovery from Incorrect States ### Reopening Completed Work **Scenario**: Marked iteration complete, but found bugs/issues **Wrong Approach**: Change ✅ → 🚧 **Right Approach**: 1. Keep original iteration ✅ COMPLETE 2. Add new iteration: "Iteration N+1: Fix Issues from Iteration N" 3. Document what needs fixing **Why**: Preserves history, shows work progression ### Abandoned Work **Scenario**: Started iteration, decided not to finish **Options**: 1. **Cancel**: Mark ❌ CANCELLED with reason 2. **Defer**: Mark 🔮 DEFERRED, move to BACKLOG.md with reason 3. **Remove**: If truly never started, just delete iteration **Choose Cancel/Defer**: When some work was done or decision has value **Choose Remove**: When created by mistake, no work done ### Stuck in Brainstorming **Scenario**: Brainstorming taking too long, can't resolve subjects **Solution**: 1. Review resolved subjects 2. Identify if subject should be Type C (auto-resolved) 3. Consider if subject should move to separate iteration 4. If truly stuck, add subject as "Research spike" iteration --- # File Templates ## DASHBOARD.md Template ```markdown # [Project Name] - Dashboard **Last Updated**: [Date & Time] **Project**: [Brief one-liner] **Status**: [Overall status] **Version**: [V1/V2/V3] --- ## 📍 Current Work - **Phase**: [Phase N - Name](phase-N/) - **Task**: [Task M - Name](phase-N/task-M.md) - **Iteration**: [Iteration K - Name](phase-N/task-M.md#iteration-K) [Status Emoji] - **Focus**: [One sentence describing current work] --- ## 📊 Progress Overview ### Phase 1: [Name] [Status Emoji] **Goal**: [One sentence phase goal] **Status**: [Completion summary, e.g., "3/3 tasks complete"] **Tasks**: - [Status Emoji] **Task 1**: [Name] ([X/Y iterations]) - [Status Emoji] Iteration 1: [Name] - [Status Emoji] Iteration 2: [Name] - [Status Emoji] **Task 2**: [Name] ([X/Y iterations]) - [Status Emoji] Iteration 1: [Name] ### Phase 2: [Name] [Status Emoji] **Goal**: [One sentence phase goal] **Status**: [Completion summary] **Tasks**: - [Status Emoji] **Task 1**: [Name] ([X/Y iterations]) - [Status Emoji] Iteration 1: [Name] - 🚧 Iteration 2: [Name] ← **CURRENT** - ⏳ Iteration 3: [Name] --- ## 💡 Key Decisions **Decision Needed**: [Question for user] - Option A: [Choice] - [Rationale] - Option B: [Choice] - [Rationale] - **Recommendation**: [If AI has suggestion] **Resolved**: - **[Date]**: [Decision made] - [Brief rationale] ``` --- ## PLAN.md Template ```markdown # [Feature/Project Name] - Development Plan > **📖 Framework Guide**: See [DEVELOPMENT_FRAMEWORK.md](DEVELOPMENT_FRAMEWORK.md) for complete methodology > **📍 Current Progress**: See [DASHBOARD.md](DASHBOARD.md) for real-time status tracking > **🎯 Purpose**: [One sentence describing what this feature/project does] **Created**: [Date] **Version**: [V1/V2/V3] **Plan Location**: `.flow/` (managed by Flow framework) --- ## Overview ### Purpose [2-3 paragraphs explaining WHY this feature exists and WHAT problem it solves] ### Goals [Describe what success looks like - text format, NOT checklists] **Primary Goals**: - [Measurable goal 1] - [Measurable goal 2] - [Measurable goal 3] **Success Criteria**: - [How we know this is successful] - [Performance targets, if applicable] - [User experience goals] ### Scope **V1 Scope** (Current Session): - [Feature 1] - [Feature 2] - [Feature 3] - [Constraint/limitation] **Note**: V2/V3/Out-of-Scope sections only included if user explicitly requests them. Default to V1-only scope for minimal planning overhead. --- ## Architecture ### System Context [High-level description of how this feature fits into the system - describe WHAT exists, NOT prescriptive current-vs-desired with line numbers] **Components**: - **[ComponentName]**: [Responsibility] - **[ComponentName]**: [Responsibility] **Key Dependencies**: - [Internal service/module]: [What we need from it] - [External library/API]: [Why we need it, version if relevant] **Reference Implementations** (if relevant): - [Existing code to learn from]: [File path or description] - [Similar feature]: [What to reuse/avoid] --- ## DO / DON'T Guidelines **✅ DO**: - [Best practice for this project] - [Quality standard to maintain] - [Pattern to follow] **❌ DO NOT**: - [Anti-pattern to avoid] - [Common mistake to prevent] - [Constraint to respect] --- ## Notes & Learnings **Design Decisions**: - [Date]: [Decision made and rationale] **References**: - [External doc]: [URL] - [Internal doc]: [Path] ``` --- ## task-N.md Template (With Iterations) ```markdown # Task [N]: [Task Name] **Status**: ⏳ PENDING **Phase**: [Phase M - Name](../DASHBOARD.md#phase-M-name) **Purpose**: [One sentence - what this task accomplishes] --- ## Task Overview [2-3 paragraphs describing this task in detail] **Why This Task**: [Explanation of why this task is necessary] **Dependencies**: - **Requires**: [Task name/number] - [What we need from it] - **Blocks**: [Task name/number] - [What depends on this] **Estimated Complexity**: [Low/Medium/High] ([X iterations expected]) --- ## Iterations ### ⏳ Iteration 1: [Name] **Goal**: [One sentence - what this iteration achieves] **Status**: ⏳ PENDING --- #### Brainstorming Session - [Iteration Name] (Optional - design decisions will be documented here if needed) **Focus**: [What we're designing - TBD] **Subjects to Discuss**: - (Add subjects with /flow-brainstorm-subject) **Resolved Subjects**: - (Filled during brainstorming) --- #### Action Items - [ ] [TBD - Define during brainstorming or add directly] --- ### ⏳ Iteration 2: [Name] **Goal**: [One sentence - what this iteration achieves] **Status**: ⏳ PENDING --- #### Brainstorming Session - [Iteration Name] (Optional - design decisions will be documented here if needed) **Focus**: [What we're designing - TBD] **Subjects to Discuss**: - (Add subjects with /flow-brainstorm-subject) **Resolved Subjects**: - (Filled during brainstorming) --- #### Action Items - [ ] [TBD - Define during brainstorming or add directly] --- ## Task Notes **Discoveries**: - [Things learned while working on this task] **Decisions**: - [Task-specific decisions made] **References**: - [Relevant code]: [Path] - [Documentation]: [URL] ``` --- ## Complete Task File Template (All Heading Levels) **Purpose**: This template shows the complete task file structure with all 5 heading levels explicitly labeled. Use this as a reference when creating or updating task files. ```markdown # Task 3: API Integration ← LEVEL 1: Task title **Status**: 🚧 IN PROGRESS **Phase**: [Phase 2 - Core Implementation](../DASHBOARD.md#phase-2-core-implementation) **Purpose**: Integrate with Stripe REST API for payment processing --- ## Task Overview ← LEVEL 2: Major section Build a robust Stripe API client with error handling, retry logic, and integration tests. **Why This Task**: Core payment functionality depends on reliable API integration. **Dependencies**: - **Requires**: Task 1 (Database Layer) - need PaymentRepository - **Blocks**: Task 4 (Webhook Handler) - webhook processing depends on API client **Estimated Complexity**: High (4 iterations expected) --- ## Iterations ← LEVEL 2: Major section ### ✅ Iteration 1: REST Client Setup ← LEVEL 3: Iteration **Goal**: Create Stripe API client wrapper with authentication **Status**: ✅ COMPLETE (2025-01-12) --- #### Pre-Implementation Tasks ← LEVEL 4: Iteration subsection (Optional - only if Type A subjects identified during brainstorming) These tasks MUST be completed BEFORE starting main implementation of this iteration. --- ##### ✅ Pre-Task 1: Refactor Legacy ErrorHandler ← LEVEL 5: Individual pre-task **Completed**: 2025-01-14 **Why Blocking**: Current ErrorHandler doesn't support async retry logic **Scope** (< 30 min): - Update ErrorHandler.ts to support async - Add retryAsync() method - Update 3 existing call sites **Files**: - src/utils/ErrorHandler.ts - src/services/BillingService.ts - tests/utils/ErrorHandler.test.ts **Test**: Run existing test suite to ensure no regressions **Changes Made**: - Added `retryAsync()` method - All tests passing - No breaking changes --- ##### ⏳ Pre-Task 2: Update Type Definitions ← LEVEL 5: Individual pre-task **Why Blocking**: Need new error types for error handling **Scope** (< 30 min): - Add ErrorType enum - Update function signatures **Files**: - src/types/errors.ts **Test**: TypeScript compilation succeeds --- #### Brainstorming Session - REST Client Architecture ← LEVEL 4: Iteration subsection (Optional - only for complex iterations requiring design decisions) **Focus**: Design API client abstraction and authentication flow **Subjects to Discuss**: (All subjects resolved) **Resolved Subjects**: --- ##### ✅ Subject 1: Client Architecture Pattern ← LEVEL 5: Individual subject **Decision**: Use singleton pattern with lazy initialization **Resolution Type**: D (Iteration Action Items) **Rationale**: - Stripe SDK maintains connection pool internally - Multiple instances would create redundant connections - Lazy initialization delays credential validation until first use **Resolution Items**: - Create `StripeClient` singleton class - Implement lazy initialization in constructor - Add credential validation on first API call - Export singleton instance for import across codebase --- ##### ✅ Subject 2: Authentication Flow ← LEVEL 5: Individual subject **Decision**: Use API key from environment variable with startup validation **Resolution Type**: D (Iteration Action Items) **Rationale**: - Stripe best practices recommend environment-based configuration - Supports different keys per environment (dev/staging/prod) - Validation at startup prevents runtime errors **Resolution Items**: - Load `STRIPE_API_KEY` from environment variables - Validate key format at startup (must start with `sk_test_` or `sk_live_`) - Throw descriptive error if key is missing or invalid - Log masked key on startup for debugging --- ##### ✅ Subject 3: API Timeout Configuration ← LEVEL 5: Individual subject **Decision**: Set 30-second timeout for API calls, configurable via environment **Resolution Type**: D (Iteration Action Items) **Rationale**: - Stripe recommends 30s timeout for payment operations - Prevents indefinite hanging on network issues - Configurable for different deployment scenarios **Resolution Items**: - Configure default timeout of 30 seconds - Make timeout configurable via `STRIPE_API_TIMEOUT_MS` env var - Add timeout handling in API call wrapper - Log timeout events for monitoring --- #### Action Items ← LEVEL 4: Iteration subsection (Required - ONE list per iteration) Consolidated from Resolution Items above by `/flow-brainstorm-review` - [x] Create `StripeClient` singleton class - [x] Implement lazy initialization in constructor - [x] Add credential validation on first API call - [x] Export singleton instance for import across codebase - [x] Load `STRIPE_API_KEY` from environment variables - [x] Validate key format at startup (must start with `sk_test_` or `sk_live_`) - [x] Throw descriptive error if key is missing or invalid - [x] Log masked key on startup for debugging - [x] Configure default timeout of 30 seconds - [x] Make timeout configurable via `STRIPE_API_TIMEOUT_MS` env var - [x] Add timeout handling in API call wrapper - [x] Log timeout events for monitoring --- #### Implementation - Iteration 1: REST Client Setup ← LEVEL 4: Iteration subsection (Added by `/flow-implement-start`, updated during work) **Status**: ✅ COMPLETE (2025-01-12) **Implementation Notes**: - Created `src/integrations/stripe/StripeClient.ts` with singleton pattern - Implemented lazy initialization - Stripe SDK initialized on first `getInstance()` call - Added comprehensive key validation (format check + test API call) - Discovered: Stripe SDK v12 changed API - using `paymentIntents` instead of deprecated `charges` - Performance: Singleton initialization takes ~50ms (acceptable for lazy init) **Files Modified**: - `src/integrations/stripe/StripeClient.ts` - Created new file (187 lines) - `src/config/env.ts` - Added STRIPE_API_KEY and STRIPE_API_TIMEOUT_MS validation - `src/integrations/stripe/index.ts` - Barrel export for clean imports - `scripts/stripe-client.scripts.ts` - Created test file **Verification**: - ✅ All tests passing in stripe-client.scripts.ts - ✅ API key validation working correctly (rejects invalid keys) - ✅ Singleton pattern verified (same instance returned) - ✅ Timeout configuration working - ✅ Connection to Stripe test API successful --- ### 🚧 Iteration 2: Error Handling ← LEVEL 3: Iteration **Goal**: Implement comprehensive error handling and error taxonomy **Status**: 🚧 IN PROGRESS (Implementing) --- (Pre-Implementation Tasks, Brainstorming Session, Action Items, Implementation sections follow same structure as Iteration 1) --- ### ⏳ Iteration 3: Advanced Retry Logic ← LEVEL 3: Iteration **Goal**: Add jitter to exponential backoff and retry budget pattern **Status**: ⏳ PENDING --- ## Task Notes ← LEVEL 2: Major section **Discoveries**: - Stripe SDK already implements connection pooling (no need for custom) - Stripe SDK v12 uses `paymentIntents` API instead of deprecated `charges` - Error codes changed in Stripe API v2023-10-16 **Decisions**: - Using Stripe Node SDK v12.18.0 (latest stable) - NOT implementing custom connection pool (SDK handles it) - NOT implementing circuit breaker for V1 (defer to V2) **Performance**: - Stripe API calls average 200-300ms response time - Singleton initialization overhead: ~50ms (one-time cost) **References**: - Stripe API Docs: https://stripe.com/docs/api - Existing PayPal integration: `src/legacy/billing.ts` ``` --- ## Heading Level Reference (Quick Lookup) When creating or editing task files, use this quick reference: | Level | Markdown | Usage | Example | |-------|----------|-------|---------| | **1** | `#` | Task title (once per file) | `# Task 3: API Integration` | | **2** | `##` | Major sections (3-4 per file) | `## Task Overview`, `## Iterations`, `## Task Notes` | | **3** | `###` | Individual iterations (multiple per task) | `### ✅ Iteration 1: REST Client Setup` | | **4** | `####` | Iteration subsections (4 types) | `#### Pre-Implementation Tasks`, `#### Brainstorming Session`, `#### Action Items`, `#### Implementation` | | **5** | `#####` | Individual items (subjects/pre-tasks) | `##### ✅ Subject 1: Architecture`, `##### ⏳ Pre-Task 1: Fix Types` | **Critical Rule**: Never use level 6 (`######`) or deeper. If you need more nesting, restructure with additional iterations instead. --- # Command Patterns ## Dashboard-First Navigation Pattern (Detailed) **Used By**: 16 commands (brainstorming, implementation, state management) ### Pattern Steps ``` 1. Read DASHBOARD.md 2. Extract current context from "📍 Current Work" section: - Phase number (e.g., "Phase 2") - Task number (e.g., "Task 3") - Iteration number (e.g., "Iteration 2") 3. Construct task file path: phase-{N}/task-{M}.md 4. Read task file 5. Locate relevant section (e.g., Iteration K) 6. Perform operation (read/edit) 7. Update DASHBOARD.md with new state ``` ### Example Implementation **Command**: `/flow-implement-start` ``` Step 1: Read DASHBOARD.md → Extract: Phase 2, Task 3, Iteration 2 Step 2: Construct path → phase-2/task-3.md Step 3: Read phase-2/task-3.md → Find "### Iteration 2: Error Handling" Step 4: Check prerequisites → Brainstorming status: ✅ COMPLETE → Iteration status: 🎨 READY Step 5: Add Implementation section → Insert "#### Implementation - Iteration 2: Error Handling" → Add structure (Status, Action Items, Implementation Notes, etc.) Step 6: Update DASHBOARD.md → Change "Iteration 2" status: 🎨 READY → 🚧 IN PROGRESS → Update "Last Updated" timestamp → Update "Current Work" section if needed Step 7: Notify user → "Started implementation of Iteration 2. See phase-2/task-3.md for details." ``` ### Commands Using This Pattern - `/flow-brainstorm-start` - `/flow-brainstorm-subject` - `/flow-next-subject` - `/flow-brainstorm-review` - `/flow-brainstorm-complete` - `/flow-implement-start` - `/flow-implement-complete` - `/flow-iteration-add` - `/flow-task-start` - `/flow-task-complete` - `/flow-next` - `/flow-next-iteration` --- ## Structure Creation Pattern **Used By**: 4 commands (blueprint, phase-add, task-add, migrate) ### Pattern Steps ``` 1. Read DASHBOARD.md (or create if missing for blueprint) 2. Determine what to create: - New phase directory? - New task file? - Initial project structure? 3. Create directory/file with template content 4. Update DASHBOARD.md to include new structure 5. Notify user with file paths created ``` ### Example: `/flow-task-add "API Integration"` ``` Step 1: Read DASHBOARD.md → Current phase: Phase 2 Step 2: Determine next task number → Read phase-2/ directory → Find existing files: task-1.md, task-2.md → Next task number: 3 Step 3: Create phase-2/task-3.md → Use "Task with Iterations" template → Fill in: Task name, Phase link, Status ⏳ Step 4: Update DASHBOARD.md → Add to Phase 2 section: "- ⏳ **Task 3**: API Integration" Step 5: Notify user → "Created phase-2/task-3.md. Use /flow-task-start to begin work." ``` --- ## Full Traversal Pattern **Used By**: 4 commands (status, summarize, verify-plan, plan-split) ### Pattern Steps ``` 1. Read DASHBOARD.md 2. Extract all phases from "Progress Overview" section 3. For each phase: a. Read phase directory (phase-N/) b. List all task files (task-*.md) c. Read each task file d. Extract relevant information (status, iterations, completion) 4. Aggregate information 5. Generate report or perform validation 6. Return result to user ``` ### Example: `/flow-summarize` ``` Step 1: Read DASHBOARD.md → Find phases: Phase 1, Phase 2, Phase 3 Step 2: For Phase 1: → Read phase-1/ directory → Files: task-1.md, task-2.md, task-3.md → Read each file, extract: - Task name - Status - Iteration count - Key decisions from brainstorming Step 3: For Phase 2: → (repeat same process) Step 4: For Phase 3: → (repeat same process) Step 5: Generate summary → Format output: # Project Summary ## Phase 1: Foundation ✅ COMPLETE - Task 1: Project Setup (3 iterations) ✅ - Key decisions: Singleton pattern, env-based config - Task 2: Core Models (2 iterations) ✅ - Key decisions: Entity validation, repository pattern ## Phase 2: Core Implementation 🚧 IN PROGRESS ... Step 6: Return summary to user ``` --- ## Cross-File Search Pattern **Used By**: 4 commands (backlog-add, backlog-pull, next-iteration, rollback) ### Pattern Steps ``` 1. Read DASHBOARD.md (understand scope) 2. Determine search criteria: - Looking for next ⏳ iteration? - Finding task by number? - Searching for specific status? 3. Use Grep or Read to search across multiple task files 4. Collect matches 5. Perform operation (move to backlog, update status, etc.) 6. Update DASHBOARD.md if needed 7. Return result ``` ### Example: `/flow-next-iteration` ``` Step 1: Read DASHBOARD.md → Current: Phase 2, Task 3, Iteration 2 (in progress) Step 2: Determine next iteration to work on → Check current task file first (phase-2/task-3.md) → Look for next ⏳ iteration after current one Step 3: Read phase-2/task-3.md → Find iterations: - Iteration 1: ✅ COMPLETE - Iteration 2: 🚧 IN PROGRESS (current) - Iteration 3: ⏳ PENDING ← FOUND - Iteration 4: ⏳ PENDING Step 4: If found in current task → Return "Iteration 3: Retry Logic" → Show goal and status Step 5: If not found in current task → Look at next task in current phase → Then next phase if needed Step 6: Return result → "Next iteration: Iteration 3 - Retry Logic (phase-2/task-3.md)" ``` --- # Complete Workflow Examples ## Example 1: Payment Gateway Integration (Full Feature) ### Project Setup ```bash # Create new project /flow-blueprint AI: Please provide project details: - Feature name? - Purpose? - High-level phases? User: Payment Gateway Integration Integrate Stripe for credit card payments Phases: Foundation, Core Implementation, Testing AI: Created: - DASHBOARD.md - PLAN.md - phase-1/ (Foundation) - phase-1/task-1.md (Project Setup) ``` **Files Created**: - `.flow/DASHBOARD.md` - Progress tracking - `.flow/PLAN.md` - Overview, architecture, testing strategy - `.flow/phase-1/` - First phase directory - `.flow/phase-1/task-1.md` - Initial task --- ### Working Through Phase 1 ```bash # Start first phase /flow-phase-start # Add tasks to Phase 1 /flow-task-add "Project Setup" /flow-task-add "Core Models" # Start first task /flow-task-start # Add iteration to Task 1 /flow-iteration-add "Repository Structure" # Start brainstorming /flow-brainstorm-start AI: What subjects should we discuss for Repository Structure? User: Directory layout, Configuration setup, Dependency management AI: Added 3 subjects to brainstorming. Use /flow-next-subject to begin. # Resolve subjects /flow-next-subject AI: Let's discuss Subject 1: Directory Layout What structure should we use? User: Standard src/ structure with feature-based organization AI: Is this: A) Pre-implementation task B) Documentation update C) Auto-resolved D) Main iteration work User: D AI: Action items? User: Create src/payment/ directory, Add index files, Setup barrel exports AI: Subject 1 resolved. 2 subjects remaining. /flow-next-subject [... continue resolving subjects ...] # After all subjects resolved /flow-brainstorm-review AI: Reviewing all 3 subjects... - Subject 1: Directory layout (Type D) - Subject 2: Config setup (Type D) - Subject 3: Dependencies (Type A - Pre-task) Pre-implementation task identified: - Update package.json with Stripe SDK Ready to proceed? User: Yes # Complete pre-task [Install Stripe SDK] # Complete brainstorming /flow-brainstorm-complete AI: Brainstorming complete. Iteration 1 is now 🎨 READY. Use /flow-implement-start to begin coding. # Start implementation /flow-implement-start # Do the work [Create directory structure, setup config, etc.] # Complete implementation /flow-implement-complete AI: Iteration 1 complete! ✅ Next: Use /flow-iteration-add for Iteration 2, or /flow-task-complete if task is done. ``` **Files Updated During This Workflow**: 1. **DASHBOARD.md**: - Phase 1 status: ⏳ → 🚧 - Task 1 status: ⏳ → 🚧 → ✅ - Current work pointer updated throughout - Progress percentages updated 2. **phase-1/task-1.md**: - Task status: ⏳ → 🚧 - Iteration 1 added - Brainstorming section filled - Implementation notes added - Status: 🚧 → ✅ --- ### Moving to Phase 2 ```bash # Complete Phase 1 /flow-phase-complete AI: Phase 1 complete! ✅ Ready to start Phase 2? # Add Phase 2 /flow-phase-add "Core Implementation" # Start Phase 2 /flow-phase-start # Add tasks /flow-task-add "API Integration" /flow-task-add "Webhook Handler" /flow-task-add "Error Handling" # Work through tasks [... repeat similar workflow as Phase 1 ...] ``` --- ## Example 2: Simple Task with Single Iteration ```bash # Add simple task /flow-task-add "Update Documentation" AI: Created phase-2/task-4.md Task created with iterations structure. Since this is simple documentation work, you can: - Add one iteration with direct action items (skip brainstorming) - Start, implement, and complete quickly # Add single iteration /flow-iteration-add "Documentation Updates" AI: Added Iteration 1 to Task 4. For simple work, you can skip brainstorming and add action items directly. User: Add these action items: - Update README - Fix typos - Add examples AI: Added 3 action items to Iteration 1. Use /flow-implement-start to begin. # Start implementation /flow-implement-start # Do the work [Update docs] # Complete implementation /flow-implement-complete AI: Iteration 1 complete! ✅ Task 4 has 1/1 iterations complete. Use /flow-task-complete to mark task done. /flow-task-complete AI: Task 4 complete! ✅ Moving to next task... ``` **Note**: Simple tasks use one iteration with direct action items - no brainstorming required. --- ## Example 3: Deferring Work to Backlog ```bash # During Phase 2, decide to defer a task /flow-backlog-add 5 "Multi-currency support adds too much complexity for V1" AI: Moved Task 5 to BACKLOG.md with reason. Updated DASHBOARD.md to reflect removal. # Later, pull it back /flow-backlog-pull 5 AI: Pulled Task 5 from backlog. Added to end of Phase 2. Updated DASHBOARD.md. ``` --- ## Example 4: Archiving Completed Work ```bash # After completing Phase 1 and Phase 2 /flow-plan-split AI: Archiving completed work... - Phase 1: 3 tasks archived - Phase 2: Task 1-2 archived (completed only) Created ARCHIVE.md with all completed task details. Updated task files to reference archive: - phase-1/task-1.md → "See ARCHIVE.md" - phase-1/task-2.md → "See ARCHIVE.md" - phase-2/task-1.md → "See ARCHIVE.md" - phase-2/task-2.md → "See ARCHIVE.md" DASHBOARD.md now shows only active work. ``` --- # Backlog Management ## BACKLOG.md Structure ```markdown # Project Backlog **Last Updated**: [Date] --- ## 📋 Backlog Dashboard **Total Items**: [N] **By Version**: - V2 Features: [N] - V3 Features: [N] - Technical Debt: [N] - Deferred Tasks: [N] **By Priority**: - High: [N] - Medium: [N] - Low: [N] --- ## Backlog Items ### High Priority #### ⏳ Task: Multi-Currency Support **Originally Planned**: Phase 2, Task 6 **Deferred To**: V2 **Priority**: High **Reasoning**: V1 scope focuses on USD only. Multi-currency requires: - Exchange rate API integration - Currency conversion logic - Multi-currency display in UI - Testing across currencies This adds 2-3 weeks and is not critical for V1 launch. **Estimated Effort**: 2-3 weeks **Dependencies**: Core payment processing complete (Phase 2, Task 1-3) **When to Pull Back**: - After V1 launch - When international customers become priority - When we have exchange rate API access --- #### ⏳ Task: Advanced Retry Logic with Circuit Breaker **Originally Planned**: Phase 2, Task 3, Iteration 3 **Deferred To**: V2 **Priority**: High **Reasoning**: Basic retry logic (3 attempts, exponential backoff) is sufficient for V1. Circuit breaker pattern adds value but requires: - State management for circuit status - Monitoring and alerting integration - Configuration management - Additional testing **Estimated Effort**: 1 week **Dependencies**: Basic retry logic (Phase 2, Task 3, Iteration 2) --- ### Medium Priority #### ⏳ Feature: Saved Payment Methods **Deferred To**: V2 **Priority**: Medium **Reasoning**: V1 focuses on one-time payments. Saved payment methods require: - Secure token storage - Card management UI - PCI compliance review - Additional security testing **Estimated Effort**: 2 weeks **Dependencies**: Payment processing complete, Security audit done --- ### Low Priority #### ⏳ Technical Debt: Refactor PaymentService **Deferred To**: V3 **Priority**: Low **Reasoning**: Current PaymentService works but has some code duplication. Not urgent, can refactor after V2 when we understand all use cases better. **Estimated Effort**: 3-4 days **Dependencies**: None --- ## Removed from Backlog ### Task: ACH Payment Support **Originally**: V2 Feature **Removed**: 2025-01-20 **Reason**: Business decision - focus on credit cards only for foreseeable future ``` --- ## Backlog Commands ### `/flow-backlog-add [task-number] "[reason]"` **Purpose**: Move task from active plan to backlog **Usage**: ```bash # Move single task /flow-backlog-add 6 "Multi-currency adds too much complexity for V1, deferring to V2" # Move range of tasks /flow-backlog-add 6-8 "These features are V2 scope" ``` **Effect**: 1. Reads DASHBOARD.md, finds Phase/Task info 2. Reads task file (phase-N/task-M.md) 3. Copies task details to BACKLOG.md with reason 4. Marks task as 🔮 DEFERRED in DASHBOARD.md 5. Updates task file status to 🔮 DEFERRED with reference to BACKLOG.md **Task File After**: ```markdown # Task 6: Multi-Currency Support **Status**: 🔮 DEFERRED **Deferred To**: V2 **Reason**: Too complex for V1 scope See [BACKLOG.md](../BACKLOG.md#task-multi-currency-support) for details and reasoning. ``` --- ### `/flow-backlog-view` **Purpose**: Show backlog contents **Usage**: ```bash /flow-backlog-view ``` **Output**: ``` Backlog Summary: - Total items: 8 - V2 features: 5 - V3 features: 2 - Technical debt: 1 High Priority (3 items): 1. Multi-Currency Support (V2) 2. Advanced Retry Logic (V2) 3. Saved Payment Methods (V2) Medium Priority (3 items): ... See BACKLOG.md for full details. ``` --- ### `/flow-backlog-pull [task-number] [position]"` **Purpose**: Pull task from backlog back into active plan **Usage**: ```bash # Pull task, add to end of current phase /flow-backlog-pull 6 # Pull task, insert after specific task /flow-backlog-pull 6 "after task 3" # Pull task, insert at beginning of phase /flow-backlog-pull 6 "at start" ``` **Effect**: 1. Reads BACKLOG.md, finds task details 2. Determines current phase from DASHBOARD.md 3. Creates new task file in phase directory 4. Assigns next available task number 5. Updates DASHBOARD.md with new task 6. Removes from BACKLOG.md (or marks as pulled) **Example**: ```bash /flow-backlog-pull 6 AI: Pulled "Multi-Currency Support" from backlog. Created phase-2/task-6.md Updated DASHBOARD.md Task is now ⏳ PENDING in Phase 2. Use /flow-task-start when ready to begin. ``` --- ## When to Use Backlog ### Use Backlog For: **V2/V3 Features**: - Features planned but not in current version scope - Enhancements discovered during V1 development - Nice-to-have features that aren't MVP **Deferred Tasks**: - Tasks started but decided against mid-development - Tasks that turned out more complex than expected - Tasks blocked by external dependencies (waiting for API access, etc.) **Technical Debt**: - Refactoring opportunities identified - Code improvements that aren't urgent - Performance optimizations that can wait **Scope Creep Prevention**: - Features requested during development that expand scope - "Wouldn't it be cool if..." ideas - Gold-plating attempts ### Don't Use Backlog For: **Cancelled Work**: - Use ❌ CANCELLED status in task file instead - Document reason directly in task **Bugs**: - Bugs should be fixed, not backlogged - Exception: Non-critical bugs in V2 features can be backlogged with V2 **Core MVP Features**: - If it's truly needed for V1, keep it in active plan - Descope properly rather than backlog everything --- # Best Practices & Pitfalls ## Best Practices ### 1. Always Brainstorm for Complex Work **✅ DO**: ```markdown ### Iteration 2: Error Handling ⏳ [Brainstorming section] [Pre-implementation tasks] [Implementation section] ``` **❌ DON'T**: ```markdown ### Iteration 2: Error Handling ⏳ [Start implementing without design] ``` **Why**: Brainstorming surfaces decisions early, prevents refactoring later. --- ### 2. Keep DASHBOARD.md Up-to-Date **✅ DO**: - Update DASHBOARD.md every time status changes - Use commands that automatically update both files - Run `/flow-status` regularly to verify state **❌ DON'T**: - Update task file but forget DASHBOARD.md - Manually edit both files (error-prone) - Let DASHBOARD.md get stale **Why**: DASHBOARD.md is source of truth for current state. Stale dashboard confuses everyone. --- ### 3. Use Descriptive Commit Messages **✅ DO**: ```bash git commit -m "Complete Iteration 2: Error Handling - Implemented RetryPolicy with exponential backoff - Added error taxonomy mapping - Fixed legacy ErrorHandler async support - All tests passing Updated: phase-2/task-3.md, DASHBOARD.md" ``` **❌ DON'T**: ```bash git commit -m "updates" ``` **Why**: Commit history tells story of feature development. --- ### 4. Document Discoveries Immediately **✅ DO**: ```markdown **Implementation Notes**: - Discovered Stripe SDK v12 deprecated charges API - Switched to PaymentIntents API (newer, more flexible) - Added StripeErrorMapper class (not in original plan) - Performance: API calls 200-300ms, added caching ``` **❌ DON'T**: ```markdown **Implementation Notes**: (empty) ``` **Why**: Discoveries are valuable context for future work and team members. --- ### 5. Break Down Large Tasks **✅ DO**: ``` Phase 2: Core Implementation - Task 1: Database Layer (3 iterations) - Task 2: Business Logic (4 iterations) - Task 3: API Integration (4 iterations) ``` **❌ DON'T**: ``` Phase 2: Core Implementation - Task 1: Everything (25 iterations) ``` **Why**: Smaller tasks are easier to reason about, track progress, and complete. --- ### 6. Use Pre-Implementation Tasks **✅ DO**: ```markdown #### Pre-Implementation Tasks ##### ⏳ Pre-Task 1: Fix Interface Signature **Why Blocking**: Current interface doesn't support async ... [Complete before /flow-brainstorm-complete] ``` **❌ DON'T**: ```markdown [Start implementation] [Hit blocker] [Stop to fix blocker] [Lose context] ``` **Why**: Unblock early while context is fresh. --- ### 7. Reference PLAN.md for Big Decisions **✅ DO**: - Update PLAN.md Architecture section for Type B decisions - Reference PLAN.md when explaining system design - Keep PLAN.md as single source of truth for architecture **❌ DON'T**: - Scatter architecture decisions across task files - Forget to document major design choices - Let PLAN.md get out of sync with reality --- ### 8. Use /flow-verify-plan Regularly **✅ DO**: ```bash /flow-verify-plan # Run this: - After bulk edits - When feeling lost - Before marking phase complete - After pulling from git ``` **Why**: Catches inconsistencies early before they cause confusion. --- ## Common Pitfalls ### Pitfall 1: Skipping /flow-brainstorm-review **Problem**: ```bash /flow-next-subject # Resolve all subjects /flow-brainstorm-complete # Skip review! ``` **Why Bad**: Miss identifying pre-implementation tasks, miss suggesting more iterations. **Fix**: ALWAYS run `/flow-brainstorm-review` after resolving all subjects, BEFORE `/flow-brainstorm-complete`. --- ### Pitfall 2: Marking Complete Too Early **Problem**: ```markdown ### Iteration 2: Error Handling ✅ COMPLETE **Implementation Notes**: - TODO: Add tests - TODO: Fix edge case ``` **Why Bad**: Work not actually done, TODOs present. **Fix**: Only mark ✅ COMPLETE when ALL work done, verified, and no TODOs remain. --- ### Pitfall 3: Not Reading DASHBOARD.md First **Problem**: ``` [AI tries to edit task file without reading DASHBOARD.md] [Edits wrong task/iteration] [Causes confusion] ``` **Why Bad**: Don't know current context, edit wrong places. **Fix**: ALWAYS read DASHBOARD.md first (dashboard-first pattern). --- ### Pitfall 4: Creating Too Many Small Tasks **Problem**: ``` Phase 2: Core Implementation - Task 1: Create class (1 action item) - Task 2: Add method (1 action item) - Task 3: Add another method (1 action item) [... 20 tiny tasks ...] ``` **Why Bad**: Overhead of task management exceeds value. **Fix**: Combine related small work into one task with multiple action items or iterations. --- ### Pitfall 5: Not Linking Files **Problem**: ```markdown # Task 3 in phase-2/task-3.md **Phase**: Phase 2 ``` **Why Bad**: No clickable link back to DASHBOARD.md, hard to navigate. **Fix**: Always use markdown links: ```markdown **Phase**: [Phase 2 - Core Implementation](../DASHBOARD.md#phase-2-core-implementation) ``` --- ### Pitfall 6: Forgetting to Update Examples **Problem**: Make changes to framework, forget to update example files. **Why Bad**: Users learn from outdated examples. **Fix**: After changing framework docs, update examples/ directory to match. --- ## Performance Tips ### For Large Projects **Problem**: 100+ tasks across 10 phases = slow to navigate **Solutions**: 1. **Use /flow-plan-split regularly**: - Archives completed work - Keeps active plan small - Old work still accessible in ARCHIVE.md 2. **Leverage DASHBOARD.md**: - Dashboard has jump links - Don't read all task files, just current one - Use Grep to search across files when needed 3. **Keep task files focused**: - One task per file - Don't let iterations grow too large - Split task if > 7-8 iterations --- ## Multi-Developer Workflows ### Git Merge Conflicts **Problem**: Multiple developers editing same files **With Multi-File Architecture**: - Conflicts localized to specific task files - DASHBOARD.md conflicts are small and obvious - Much better than monolithic PLAN.md merge conflicts **Best Practices**: 1. Each developer works on different tasks (different files) 2. Communicate before editing DASHBOARD.md 3. Pull frequently to stay in sync 4. Use `/flow-verify-plan` after merging --- ### Handoff Between Developers **Scenario**: Developer A starts task, Developer B finishes it **Process**: 1. Developer A updates DASHBOARD.md and task file with current state 2. Developer A commits and pushes 3. Developer B pulls, runs `/flow-status` to understand current state 4. Developer B reads current task file (DASHBOARD.md tells them which file) 5. Developer B continues work from current iteration **Key**: DASHBOARD.md + task files preserve complete context for handoff. --- ## Summary of Key Rules 1. **Dashboard-First**: Always read DASHBOARD.md first 2. **Iterations-Only**: All tasks have iterations (simple tasks use single iteration) 3. **Brainstorm Complex Work**: Don't skip brainstorming for complex iterations 4. **Pre-Tasks Before Implementation**: Complete all pre-tasks before `/flow-brainstorm-complete` 5. **Review Before Complete**: Always `/flow-brainstorm-review` before `/flow-brainstorm-complete` 6. **Document Everything**: Implementation notes, discoveries, decisions 7. **Update Both Files**: Commands update both DASHBOARD.md and task files 8. **Verify Regularly**: Use `/flow-verify-plan` to catch inconsistencies 9. **Archive When Large**: Use `/flow-plan-split` to keep active plan manageable 10. **Use Backlog**: Defer scope creep to BACKLOG.md, don't delete work --- **End of Complete Framework Documentation** For quick reference, see lines 1-600 (Quick Reference section). For specific sections, see Section Index (lines 543-614). FRAMEWORK_DATA_EOF } get_example_dashboard() { cat <<'EXAMPLE_DASHBOARD_EOF' # Payment Gateway Integration - Dashboard **Last Updated**: 2025-01-15 16:45 **Project**: Stripe payment processing integration with webhook support **Status**: Phase 2 in progress **Version**: V1 --- ## 📍 Current Work - **Phase**: [Phase 2 - Core Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: [Iteration 2 - Error Handling](phase-2/task-3.md#iteration-2-error-handling) 🚧 IN PROGRESS - **Focus**: Implementing comprehensive error handling with retry logic for Stripe API calls --- ## 📊 Progress Overview ### Phase 1: Foundation ✅ COMPLETE **Goal**: Establish project structure and core data models **Status**: 100% complete (5/5 iterations) **Tasks**: - ✅ **Task 1**: Project Setup (3/3 iterations) - ✅ Iteration 1: Repository Structure - ✅ Iteration 2: Dependencies & Configuration - ✅ Iteration 3: Development Environment - ✅ **Task 2**: Core Models (2/2 iterations) - ✅ Iteration 1: Entity Design - ✅ Iteration 2: Validation Logic ### Phase 2: Core Implementation 🚧 IN PROGRESS **Goal**: Build payment processing and webhook handling functionality **Status**: 40% complete (6/15 iterations) **Tasks**: - ✅ **Task 1**: Database Layer (2/2 iterations) - ✅ Iteration 1: Repository Pattern - ✅ Iteration 2: Transaction Support - ✅ **Task 2**: Business Logic (3/3 iterations) - ✅ Iteration 1: Payment Service Core - ✅ Iteration 2: State Management - ✅ Iteration 3: Validation Rules - 🚧 **Task 3**: API Integration (1/4 iterations) ← **CURRENT** - ✅ Iteration 1: REST Client Setup - 🚧 Iteration 2: Error Handling ← **ACTIVE** - ⏳ Iteration 3: Retry Logic - ⏳ Iteration 4: Integration Tests - ⏳ **Task 4**: Webhook Handler (0/3 iterations) - ⏳ Iteration 1: Signature Verification - ⏳ Iteration 2: Event Processing - ⏳ Iteration 3: Idempotency - ⏳ **Task 5**: Authentication (0/3 iterations) - ⏳ Iteration 1: Token Management - ⏳ Iteration 2: Security Middleware - ⏳ Iteration 3: Rate Limiting ### Phase 3: Testing & Hardening ⏳ PENDING **Goal**: Comprehensive testing and production readiness **Status**: Not started (0/8 iterations) **Tasks**: - ⏳ **Task 1**: Test Suite (0/3 iterations) - ⏳ Iteration 1: Unit Tests - ⏳ Iteration 2: Integration Tests - ⏳ Iteration 3: E2E Tests - ⏳ **Task 2**: Error Scenarios (0/2 iterations) - ⏳ Iteration 1: Edge Cases - ⏳ Iteration 2: Failure Recovery - ⏳ **Task 3**: Performance Testing (0/2 iterations) - ⏳ Iteration 1: Load Testing - ⏳ Iteration 2: Optimization - ⏳ **Task 4**: Documentation (0/1 iteration) - ⏳ Iteration 1: API Docs & Guides --- ## 📚 Framework Patterns Demonstrated This example project demonstrates Flow's **Resolution Items Pattern**: - **See**: [phase-2/task-3.md](phase-2/task-3.md) - Iteration 1 and 2 - **Pattern**: During brainstorming, each subject produces "Resolution Items" - **Consolidation**: `/flow-brainstorming-review` consolidates all Resolution Items into single Action Items list - **Benefit**: Prevents scattered action items, ensures brainstorming flows cleanly into implementation --- ## 💡 Key Decisions **Decision Needed**: Should we implement circuit breaker pattern for retry logic? - Option A: Add circuit breaker now - More resilient, but adds complexity - Option B: Defer to V2 - Ship V1 faster, add sophistication later - **Recommendation**: Option B - Basic retry (exponential backoff, 3 attempts) is sufficient for V1. Circuit breaker can wait. **Resolved**: - **2025-01-13**: Retry Strategy - Using exponential backoff with 3 retries max. Balances reliability with user experience. - **2025-01-14**: Error Taxonomy - Mapping Stripe errors to domain errors to decouple domain logic from Stripe SDK. - **2025-01-13**: Circuit Breaker Deferred to V2 - Adds complexity, not critical for V1 launch. EXAMPLE_DASHBOARD_EOF } get_example_plan() { cat <<'EXAMPLE_PLAN_EOF' # Payment Gateway Integration - Development Plan > **📖 Framework Guide**: See [DEVELOPMENT_FRAMEWORK.md](DEVELOPMENT_FRAMEWORK.md) for complete Flow methodology > **📍 Current Progress**: See [DASHBOARD.md](DASHBOARD.md) for real-time status tracking > **🎯 Purpose**: Integrate Stripe payment processing with credit card support and webhook handling **Created**: 2025-01-08 **Version**: V1 **Plan Location**: `.flow/` (managed by Flow framework) --- ## Overview ### Purpose Build a production-ready payment gateway integration that allows our platform to accept credit card payments through Stripe. The system must handle synchronous payment processing, asynchronous webhook notifications for payment events, and provide robust error handling with retry logic for transient failures. This integration is critical for monetization and must meet PCI compliance requirements while maintaining <2s response time for payment operations. ### Goals **Primary Goals**: - Process credit card payments via Stripe API with <2s response time - Handle webhook events for async payment state notifications (payment succeeded, failed, refunded) - Implement automatic retry logic for transient API failures (3 attempts, exponential backoff) - Maintain 99.9% payment processing success rate (excluding card declines) - Ensure PCI compliance through proper token handling (no raw card data stored) **Success Criteria**: - Payment processing works end-to-end in production - All webhook events handled correctly with idempotency - Error rate < 0.1% (excluding legitimate declines) - Test coverage > 85% for payment critical paths - Security audit passed for PCI compliance ### Scope **V1 Scope** (Current Session): - Credit card payment processing (charges API) - Basic subscription support (create, cancel) - Webhook handler for critical events: `payment_intent.succeeded`, `payment_intent.failed`, `charge.refunded` - Retry logic: 3 attempts with exponential backoff (1s, 2s, 4s) - Error handling: Map Stripe errors to domain errors - Basic authentication with API keys - USD currency only - Payment history storage in PostgreSQL --- ## Architecture ### System Context The payment gateway integration follows a layered architecture with clear separation of concerns: API Layer (request handling), Service Layer (business logic), Integration Layer (Stripe API wrapper), and Data Layer (persistence). **Components**: - **PaymentService**: Orchestrates payment processing flow (createPayment, processPayment, refundPayment) - **StripeClient**: Stripe API wrapper with retry logic and error mapping (singleton pattern) - **WebhookHandler**: Processes incoming Stripe webhook events with signature verification and idempotency - **PaymentRepository**: Payment data persistence with ACID transaction support - **ErrorMapper**: Translates Stripe errors to domain errors for decoupling **Key Dependencies**: - **Stripe Node SDK** (v12.18.0): Official API client with TypeScript support - **Existing Auth Service**: User authentication for protected endpoints - **PostgreSQL** (v14+): Database with transaction support for payment state **Reference Implementations**: - **Existing PayPal Integration** (`src/legacy/billing.ts`): Webhook signature validation pattern - **Shipment Webhook Handler** (`src/webhooks/shipment.ts`): Idempotency pattern using event IDs --- ## DO / DON'T Guidelines **✅ DO**: - Always validate webhook signatures before processing events (security critical) - Use transactions for all payment state changes (data integrity) - Map Stripe errors to domain errors immediately (decouple from provider) - Implement idempotency for webhook event processing (handle duplicate events) - Log all payment operations for audit trail (PCI compliance) - Use exponential backoff for retries (avoid thundering herd) **❌ DO NOT**: - Store raw card numbers in database (PCI violation - use tokens only) - Skip webhook signature verification (security risk) - Hard-code Stripe error codes in business logic (tight coupling) - Process duplicate webhook events (use event ID deduplication) - Return detailed error messages to client for declined cards (security) - Retry non-transient errors (e.g., card declined, invalid request) --- ## Notes & Learnings **Design Decisions**: - **2025-01-13**: Using exponential backoff with 3 retries max for API calls - balances reliability with user experience - **2025-01-14**: Mapping Stripe errors to domain errors - decouples domain logic from Stripe SDK, enables future provider switching - **2025-01-13**: Deferring circuit breaker pattern to V2 - basic retry is sufficient for V1, reduces complexity **References**: - [Stripe API Docs](https://stripe.com/docs/api): Official API reference - [Webhook Best Practices](https://stripe.com/docs/webhooks/best-practices): Security and idempotency patterns EXAMPLE_PLAN_EOF } get_example_task_standalone() { cat <<'EXAMPLE_TASK_STANDALONE_EOF' # Task 1: Project Setup **Status**: ✅ COMPLETE **Phase**: [Phase 1 - Foundation](../DASHBOARD.md#phase-1-foundation) **Purpose**: Set up project structure, dependencies, and development environment --- ## Task Overview Initialize the payment gateway project with proper directory structure, install required dependencies (Stripe SDK, testing frameworks), and configure the development environment for local development. **Why This Task**: Foundation must be solid before building payment features. Proper setup prevents technical debt and configuration issues later. **Dependencies**: None (first task in project) --- ## Iterations ### ✅ Iteration 1: Repository Structure **Goal**: Create src/ directory structure and initialize project configuration **Status**: ✅ COMPLETE --- #### Action Items - [x] Create directory structure (src/api, src/services, src/integrations, src/repositories) - [x] Initialize package.json with required dependencies - [x] Install Stripe SDK (stripe@12.18.0) - [x] Install TypeScript and configure tsconfig.json (strict mode) - [x] Create .env.example with required environment variables - [x] Write README.md with setup instructions --- #### Implementation - Iteration 1: Repository Structure **Status**: ✅ COMPLETE **Implementation Notes**: - Created feature-based directory structure (group by feature, not by type) - Pattern: src/{feature}/{api|service|repository}/ - Rationale: Easier to navigate, better encapsulation - Stripe SDK v12 uses ESM modules, required updating tsconfig.json moduleResolution - Needed to add `@types/node` for TypeScript type definitions - TypeScript strict mode enabled to catch type errors early **Files Modified**: - `package.json` - Dependencies and scripts - `tsconfig.json` - TypeScript configuration with strict mode - `.env.example` - Environment variable template - `README.md` - Setup and development instructions - Created `src/` directory structure **Verification**: - ✅ All dependencies installed successfully (no vulnerabilities) - ✅ TypeScript compiles without errors - ✅ Test connection to Stripe API successful (test mode) --- ### ✅ Iteration 2: Dependencies & Configuration **Goal**: Install testing frameworks and configure database **Status**: ✅ COMPLETE --- #### Action Items - [x] Install Jest and testing utilities - [x] Configure jest.config.js - [x] Set up database connection and migration framework - [x] Create initial schema migration for payments table - [x] Verify setup by running database migrations --- #### Implementation - Iteration 2: Dependencies & Configuration **Status**: ✅ COMPLETE **Implementation Notes**: - Jest for unit tests, custom simulation scripts for integration tests - Rationale: Jest for fast unit tests, simulation scripts for realistic E2E tests without hitting live API - PostgreSQL connection pooling requires max 10 connections for local dev - Database migrations run successfully on all environments (local, staging) **Files Modified**: - `jest.config.js` - Jest testing configuration - `src/database/connection.ts` - PostgreSQL connection pooling - `migrations/001_create_payments_table.sql` - Initial schema **Verification**: - ✅ Database migrations run successfully - ✅ Jest test runner configured and working - ✅ All team members able to set up locally --- ### ✅ Iteration 3: Development Environment **Goal**: Finalize local development setup and validate end-to-end **Status**: ✅ COMPLETE --- #### Action Items - [x] Create npm scripts for development workflow (dev, build, test, migrate) - [x] Set up hot-reload for local development - [x] Add linting and formatting (ESLint, Prettier) - [x] Validate entire setup with smoke test - [x] Document common development tasks in README --- #### Implementation - Iteration 3: Development Environment **Status**: ✅ COMPLETE **Implementation Notes**: - Added npm scripts: `npm run dev`, `npm run build`, `npm test`, `npm run migrate` - Hot-reload working with nodemon for fast iteration - ESLint + Prettier configured with team coding standards - Smoke test validates Stripe connection, database connection, and TypeScript compilation **Files Modified**: - `package.json` - Added development scripts - `.eslintrc.js` - ESLint configuration - `.prettierrc` - Prettier configuration - `scripts/smoke-test.ts` - Smoke test for local setup validation - `README.md` - Updated with development workflow instructions **Verification**: - ✅ `npm run dev` starts server with hot-reload - ✅ `npm test` runs all tests successfully - ✅ `npm run migrate` applies database migrations - ✅ Smoke test passes (Stripe + DB + TypeScript all working) - ✅ All team members successfully completed setup --- ## Task Notes **Key Decisions**: - Feature-based directory structure chosen over layer-based structure for better encapsulation - TypeScript strict mode enabled despite slight learning curve - better type safety worth it - Jest + simulation scripts hybrid approach for testing - fast unit tests + realistic integration tests **References**: - [Stripe Node SDK](https://github.com/stripe/stripe-node): Official SDK documentation - [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html): Configuration guide EXAMPLE_TASK_STANDALONE_EOF } get_example_task_iterations() { cat <<'EXAMPLE_TASK_ITERATIONS_EOF' # Task 3: API Integration **Status**: 🚧 IN PROGRESS **Phase**: [Phase 2 - Core Implementation](../DASHBOARD.md#phase-2-core-implementation) **Purpose**: Integrate with Stripe REST API for payment processing --- ## Task Overview Build a robust Stripe API client with error handling, retry logic for transient failures, and comprehensive integration tests. This is the core integration layer that all payment operations depend on. **Why This Task**: Payment processing requires reliable communication with Stripe API. Without proper error handling and retry logic, transient network issues or API hiccups would cause payment failures and poor user experience. **Dependencies**: - **Requires**: Task 1 (Database Layer) - need PaymentRepository for state persistence - **Requires**: Task 2 (Business Logic) - need PaymentService interface definitions - **Blocks**: Task 4 (Webhook Handler) - webhook processing depends on API client - **Blocks**: Task 5 (Authentication) - auth tokens stored via API calls **Estimated Complexity**: High (4 iterations expected) **Risk Level**: High - Core payment functionality depends on this --- ## Iterations ### ✅ Iteration 1: REST Client Setup **Goal**: Create Stripe API client wrapper with authentication and configuration **Status**: ✅ COMPLETE (2025-01-12) --- #### Brainstorming Session - REST Client Architecture **Focus**: Design API client abstraction layer and authentication flow **Subjects to Discuss**: (All subjects resolved) **Resolved Subjects**: --- ##### ✅ Subject 1: Client Architecture Pattern **Decision**: Use singleton pattern with lazy initialization **Resolution Type**: D (Iteration Action Items) **Rationale**: - Stripe SDK maintains connection pool internally - Multiple client instances would create redundant connections and waste resources - Lazy initialization delays credential validation until first use (fast app startup) - Singleton ensures consistent configuration across the application **Resolution Items**: - Create `StripeClient` singleton class in src/integrations/stripe/ - Implement lazy initialization in constructor (init on first API call) - Add credential validation on first API call (fail fast if misconfigured) - Export singleton instance for import across codebase --- ##### ✅ Subject 2: Authentication Flow **Decision**: Use API key from environment variable with startup validation **Resolution Type**: D (Iteration Action Items) **Rationale**: - Stripe best practices recommend environment-based configuration - Supports different keys per environment (dev/staging/prod) - Validation at startup prevents runtime errors from missing/invalid keys - Fails fast with clear error message if key is missing or malformed **Resolution Items**: - Load `STRIPE_API_KEY` from environment variables - Validate key format at startup (must start with `sk_test_` or `sk_live_`) - Throw descriptive error if key is missing or invalid - Log masked key on startup for debugging (sk_***...last4chars) --- ##### ✅ Subject 3: API Timeout Configuration **Decision**: Set 30-second timeout for API calls, configurable via environment **Resolution Type**: D (Iteration Action Items) **Rationale**: - Stripe recommends 30s timeout for payment operations - Prevents indefinite hanging on network issues - Configurable via environment for different deployment scenarios - Balance between reliability (long enough for legit slow requests) and responsiveness (not too long) **Resolution Items**: - Configure default timeout of 30 seconds - Make timeout configurable via `STRIPE_API_TIMEOUT_MS` env var - Add timeout handling in API call wrapper - Log timeout events for monitoring --- #### Action Items (Consolidated from Resolution Items above by `/flow-brainstorming-review`) - [x] Create `StripeClient` singleton class in src/integrations/stripe/ - [x] Implement lazy initialization in constructor (init on first API call) - [x] Add credential validation on first API call (fail fast if misconfigured) - [x] Export singleton instance for import across codebase - [x] Load `STRIPE_API_KEY` from environment variables - [x] Validate key format at startup (must start with `sk_test_` or `sk_live_`) - [x] Throw descriptive error if key is missing or invalid - [x] Log masked key on startup for debugging (sk_***...last4chars) - [x] Configure default timeout of 30 seconds - [x] Make timeout configurable via `STRIPE_API_TIMEOUT_MS` env var - [x] Add timeout handling in API call wrapper - [x] Log timeout events for monitoring --- #### Implementation - Iteration 1: REST Client Setup **Status**: ✅ COMPLETE (2025-01-12) **Implementation Notes**: - Created `src/integrations/stripe/StripeClient.ts` with singleton pattern - Implemented lazy initialization - Stripe SDK initialized on first `getInstance()` call - Added comprehensive key validation (format check + test API call) - Discovered: Stripe SDK v12 changed API - using `paymentIntents` instead of deprecated `charges` - Added utility method `maskApiKey()` for safe logging - Performance: Singleton initialization takes ~50ms (acceptable for lazy init) **Files Modified**: - `src/integrations/stripe/StripeClient.ts` - Created new file (187 lines) - `src/config/env.ts` - Added STRIPE_API_KEY and STRIPE_API_TIMEOUT_MS validation - `src/integrations/stripe/index.ts` - Barrel export for clean imports - `scripts/stripe-client.scripts.ts` - Created test file with connection verification **Verification**: - ✅ All tests passing in stripe-client.scripts.ts - ✅ API key validation working correctly (rejects invalid keys) - ✅ Singleton pattern verified (same instance returned on multiple calls) - ✅ Timeout configuration working (tested with slow network simulation) - ✅ Connection to Stripe test API successful - ✅ Code review completed by team **Bugs Discovered**: None in current scope, but found issue in existing ErrorHandler (see Pre-Implementation Tasks in Iteration 2) --- ### 🚧 Iteration 2: Error Handling **Goal**: Implement comprehensive error handling and error taxonomy mapping **Status**: 🚧 IN PROGRESS (Implementing) --- #### Pre-Implementation Tasks These tasks MUST be completed BEFORE starting main implementation of this iteration. --- ##### ✅ Pre-Task 1: Refactor Legacy ErrorHandler **Completed**: 2025-01-14 **Why Blocking**: Current ErrorHandler class doesn't support async retry logic needed for Stripe API calls **Scope** (< 30 min): - Update ErrorHandler.ts to support async error handlers - Add `retryAsync()` method - Update 3 existing call sites to use new async pattern **Files**: - `src/utils/ErrorHandler.ts` - Add async support - `src/services/BillingService.ts` - Update to use retryAsync() - `src/services/PaymentService.ts` - Update to use retryAsync() - `tests/utils/ErrorHandler.test.ts` - Add async tests **Test**: Run existing test suite to ensure no regressions **Changes Made**: - Added `retryAsync(fn: () => Promise, options)` method to ErrorHandler - Updated ErrorHandler to handle Promise-based operations - Migrated BillingService and PaymentService to use retryAsync() - All existing tests pass + 5 new async tests added - No breaking changes to existing sync error handling --- #### Brainstorming Session - Error Handling Strategy **Focus**: Design error taxonomy, retry logic, and error recovery patterns **Subjects to Discuss**: (All subjects resolved) **Resolved Subjects**: --- ##### ✅ Subject 1: Error Taxonomy **Decision**: Map Stripe errors to domain-specific error types using ErrorMapper class **Resolution Type**: D (Iteration Action Items) **Rationale**: - Decouples domain logic from Stripe SDK (enables future provider switching) - Provides consistent error handling across application - Enables easier testing with mocked errors - Business logic doesn't need to know about Stripe-specific error codes **Error Categories**: - `PaymentDeclinedError` - Card declined (insufficient funds, incorrect details, etc.) - `PaymentAuthenticationError` - 3D Secure or authentication required - `PaymentProcessingError` - Stripe API or network error (retryable) - `PaymentConfigurationError` - API key or configuration issue (not retryable) - `PaymentValidationError` - Invalid request parameters (not retryable) **Resolution Items**: - Create `ErrorMapper` class in src/integrations/stripe/ - Define domain error types in src/errors/ - Map all Stripe error codes to domain errors - Add tests for error mapping (all Stripe error codes covered) --- ##### ✅ Subject 2: Retry Strategy **Decision**: Implement exponential backoff with 3 retries for transient errors only **Resolution Type**: D (Iteration Action Items) **Rationale**: - Exponential backoff prevents overwhelming Stripe API during issues - 3 retries balances reliability (handle transient failures) with user experience (don't wait too long) - Retry delays: 1s, 2s, 4s (total 7s max additional wait) - Only retry transient errors (network issues, 5xx responses), not permanent errors (4xx client errors) **Retry Decision Logic**: - Retry: Network timeout, Stripe 500/502/503/504, rate limit (429) - Don't retry: Card declined (402), invalid request (400), authentication errors (401) **Resolution Items**: - Create `RetryPolicy` class with exponential backoff algorithm - Implement retry logic in StripeClient wrapper - Add configuration for max retries (default 3, configurable via env) - Add configuration for base delay (default 1000ms, configurable via env) - Log retry attempts with attempt number and delay - Add tests for retry scenarios (success after N retries, exhausted retries) --- ##### ✅ Subject 3: Error Logging **Decision**: Log all errors with structured logging including request context and retry attempts **Resolution Type**: D (Iteration Action Items) **Rationale**: - Structured logs enable better monitoring and debugging - Request context (payment ID, user ID, amount) helps trace issues - Retry attempt numbers help understand system behavior under failures - Sensitive data (API keys, card numbers) must be redacted **Log Format**: ```typescript { level: 'error', message: 'Stripe API call failed', paymentId: 'pay_123', userId: 'user_456', stripeErrorCode: 'card_declined', retryAttempt: 2, timestamp: '2025-01-15T14:30:00Z' } ``` **Resolution Items**: - Add structured logging to StripeClient - Log all API errors with full context - Redact sensitive data before logging - Add retry attempt number to logs - Integrate with existing logging infrastructure --- ##### ✅ Subject 4: Circuit Breaker Pattern **Decision**: Skip circuit breaker for V1, defer to V2 **Resolution Type**: B (Documentation) **Rationale**: - Circuit breaker adds complexity (state management, monitoring, configuration) - Stripe API has robust rate limiting and rarely has prolonged outages - Our expected V1 volume (<100 requests/min) is low risk for cascade failures - Retry logic with exponential backoff provides sufficient resilience for V1 - Can add circuit breaker in V2 when we have production metrics to tune thresholds **Documentation Update**: Added circuit breaker to PLAN.md V2 scope with reasoning and implementation notes --- #### Action Items (Consolidated from Resolution Items above by `/flow-brainstorming-review`) - [x] Create `ErrorMapper` class in src/integrations/stripe/ - [x] Define domain error types in src/errors/ - [x] Map all Stripe error codes to domain errors - [x] Add tests for error mapping (all Stripe error codes covered) - [x] Create `RetryPolicy` class with exponential backoff algorithm - [x] Implement retry logic in StripeClient wrapper - [x] Add configuration for max retries (default 3, configurable via env) - [x] Add configuration for base delay (default 1000ms, configurable via env) - [x] Log retry attempts with attempt number and delay - [x] Add tests for retry scenarios (success after N retries, exhausted retries) - [x] Add structured logging to StripeClient - [x] Log all API errors with full context - [x] Redact sensitive data before logging - [x] Add retry attempt number to logs - [x] Integrate with existing logging infrastructure --- #### Implementation - Iteration 2: Error Handling **Status**: 🚧 IN PROGRESS (2025-01-15) **Implementation Notes**: - Created `src/integrations/stripe/ErrorMapper.ts` (98 lines) - Comprehensive mapping of all Stripe error codes - Includes error code reference documentation - Created `src/integrations/stripe/RetryPolicy.ts` (76 lines) - Exponential backoff algorithm implementation - Configurable via STRIPE_MAX_RETRIES and STRIPE_RETRY_BASE_DELAY_MS env vars - Updated `src/integrations/stripe/StripeClient.ts` to use ErrorMapper and RetryPolicy - All API calls wrapped with retry logic - Errors mapped before thrown to service layer - Created `src/errors/payment/` directory with domain error classes - PaymentDeclinedError - PaymentProcessingError - PaymentConfigurationError - PaymentValidationError - PaymentAuthenticationError - Added structured logging to all error paths - Using existing logger with additional context fields - Sensitive data redaction working correctly - Discovered: Stripe SDK throws different error types for network vs API errors, needed special handling **Files Modified**: - `src/integrations/stripe/StripeClient.ts` - Added error handling and retry (220 lines now, +33) - `src/integrations/stripe/ErrorMapper.ts` - Created (98 lines) - `src/integrations/stripe/RetryPolicy.ts` - Created (76 lines) - `src/errors/payment/PaymentDeclinedError.ts` - Created (18 lines) - `src/errors/payment/PaymentProcessingError.ts` - Created (18 lines) - `src/errors/payment/PaymentConfigurationError.ts` - Created (18 lines) - `src/errors/payment/PaymentValidationError.ts` - Created (18 lines) - `src/errors/payment/PaymentAuthenticationError.ts` - Created (18 lines) - `src/errors/payment/index.ts` - Barrel export (8 lines) - `scripts/error-handling.scripts.ts` - Created test file (156 lines) - Tests all error mapping scenarios - Tests retry logic with simulated failures - Tests exhausted retry scenarios **Verification** (In Progress): - ✅ Error mapping tests passing (all Stripe error codes covered) - ✅ Retry logic tests passing (success after retries, exhausted retries) - ✅ Exponential backoff working correctly (measured actual delays) - ✅ Structured logging working (verified log format) - ✅ Sensitive data redaction working - [ ] Integration test with real Stripe test API (in progress) - [ ] Team code review (scheduled for 2025-01-16) **Next Steps**: 1. Complete integration test with Stripe test API 2. Get code review approval 3. Mark iteration complete 4. Move to Iteration 3 --- ### ⏳ Iteration 3: Advanced Retry Logic **Goal**: Add jitter to exponential backoff and implement retry budget pattern **Status**: ⏳ PENDING **Note**: This iteration will be planned after Iteration 2 is complete. Initial thoughts: - Add jitter to prevent thundering herd problem - Implement retry budget to prevent excessive retries across all requests - May defer some advanced features to V2 based on Iteration 2 outcomes --- ### ⏳ Iteration 4: Integration Tests **Goal**: Comprehensive test coverage with Stripe API simulation **Status**: ⏳ PENDING **Note**: This iteration focuses on end-to-end integration testing: - Simulate all Stripe API responses (success, errors, timeouts) - Test retry logic with controlled network conditions - Verify error mapping for all error codes - Performance testing (measure API call latency with retries) --- ## Task Notes **Discoveries**: - Stripe SDK already implements connection pooling internally (no need for custom pool) - Stripe SDK v12 uses `paymentIntents` API instead of deprecated `charges` API - Error codes changed in Stripe API v2023-10-16 (updated error taxonomy accordingly) - Stripe webhooks can deliver out of order (must handle idempotently in Task 4) - Network timeouts throw different error type than API errors (needed special handling) **Decisions**: - Using Stripe Node SDK v12.18.0 (latest stable) - NOT implementing custom connection pool (Stripe SDK handles it better) - NOT implementing circuit breaker for V1 (defer to V2) - Using exponential backoff over fixed delay (more efficient) - Retry 3 times max (balance between reliability and user experience) **Performance**: - Stripe API calls average 200-300ms response time - With 3 retries and exponential backoff, worst case is ~7s additional wait - Total max time for payment call: 30s timeout + 7s retry delay = 37s (acceptable) - Singleton initialization overhead: ~50ms (one-time cost) **References**: - Stripe API Docs: https://stripe.com/docs/api - Stripe Error Codes: https://stripe.com/docs/error-codes - Stripe Best Practices: https://stripe.com/docs/api/errors/handling - Existing PayPal integration: `src/legacy/billing.ts` (learned webhook validation pattern) - Similar retry logic: `src/utils/HttpClient.ts` (reused exponential backoff algorithm) **Team Feedback**: - Code review from @alice (2025-01-12): Suggested adding timeout configuration - added ✅ - Code review from @bob (2025-01-14): Requested more comprehensive error tests - added ✅ - Architecture review (2025-01-13): Approved singleton pattern and retry strategy ✅ EXAMPLE_TASK_ITERATIONS_EOF } get_skills_guide() { cat <<'SKILLS_GUIDE_EOF' # Flow Framework Skills Guide Complete guide for creating effective Agent Skills for the Flow framework. ## Table of Contents 1. [Overview](#overview) 2. [Writing Effective Descriptions](#writing-effective-descriptions) 3. [When to Use allowed-tools](#when-to-use-allowed-tools) 4. [Single-File vs Multi-File Decision](#single-file-vs-multi-file-decision) 5. [Testing Skill Activation](#testing-skill-activation) 6. [Common Pitfalls](#common-pitfalls) 7. [Troubleshooting](#troubleshooting) --- ## Overview Agent Skills are **model-invoked** capabilities - Claude autonomously decides when to use them based on your request and the Skill's description. This differs from slash commands which are **user-invoked** (you explicitly type `/command`). **Key Principle**: Skills provide awareness and context, not authority. They help Claude understand Flow patterns while keeping the human as the driver. --- ## Writing Effective Descriptions The `description` field (max 1024 characters) is **critical** for Skill discovery. It must include: ### Formula 1. **What the Skill does** (capability) 2. **When to use it** (specific trigger phrases users would say) 3. **What it provides** (outcome/guidance) ### Good Example ```yaml description: Navigate Flow framework's multi-file architecture (DASHBOARD.md, PLAN.md, phase-N/task-M.md). Use when user asks "where am I", "what's next", "show status", "current work", or wants to understand project structure. Provides dashboard-first navigation guidance. ``` **Why it works**: - ✅ Describes capability: "Navigate multi-file architecture" - ✅ Lists specific triggers: "where am I", "what's next", "show status" - ✅ States outcome: "dashboard-first navigation guidance" - ✅ Within 1024 char limit ### Bad Example ```yaml description: Helps with navigation ``` **Why it fails**: - ❌ Vague: "Helps with" is too general - ❌ No triggers: Claude won't know when to activate - ❌ No outcome: What does it provide? ### Trigger Phrase Best Practices **Include natural language users would actually say**: - ✅ "what should I work on next?" - ✅ "let's implement this" - ✅ "review the plan" - ❌ "navigate_flow_structure" (too technical) - ❌ "use skill" (too meta) **Cover variations**: - "What's next?" / "What should I do next?" / "Where am I?" - "Let's code" / "Time to implement" / "Start building" - "Check the plan" / "Review status" / "Verify completion" --- ## When to Use allowed-tools The `allowed-tools` field restricts which tools Claude can use when a Skill is active. ### When to Restrict (Read-Only Skills) **Use `allowed-tools: Read, Grep, Glob` for**: - **Navigation Skills**: Only read files, don't modify - **Review Skills**: Inspect code/plans without changes - **Status Skills**: Check state without altering it **Example**: ```yaml --- name: flow-navigator description: Navigate Flow framework's multi-file architecture... allowed-tools: Read, Grep, Glob --- ``` **Benefits**: - Prevents accidental modifications - Faster (no permission prompts for read operations) - Clear intent (inspection only) ### When NOT to Restrict (Implementation Skills) **Omit `allowed-tools` for**: - **Planning Skills**: Need to create/modify files - **Implementation Skills**: Need full tool access - **Documentation Skills**: Need write access **Example**: ```yaml --- name: flow-implementer description: Guide implementation workflow... # No allowed-tools - needs write access --- ``` --- ## Single-File vs Multi-File Decision Use this decision tree: ### Use Single-File Template (`_TEMPLATE/`) **When**: - ✅ Skill fits in < 200 lines - ✅ No supporting documentation needed - ✅ Instructions are straightforward - ✅ Few examples needed **Examples**: flow-navigator, flow-reviewer (read-only, simple workflows) ### Use Multi-File Template (`_TEMPLATE-MULTI/`) **When**: - ✅ Skill requires > 200 lines - ✅ Detailed reference documentation needed - ✅ Multiple complex examples - ✅ Templates or scripts to include **Examples**: flow-planner (many templates), flow-architect (extensive guidance) ### Progressive Disclosure Pattern Multi-file Skills use **progressive disclosure** - Claude only loads supporting files when needed: ```markdown # SKILL.md (always loaded) Quick start instructions here. For details, see [REFERENCE.md](REFERENCE.md). # Loaded only if user needs details ## Examples See [EXAMPLES.md](EXAMPLES.md) for scenarios. # Loaded only for examples ``` **Benefits**: - Keeps context manageable - Fast initial activation - Deep dive available when needed --- ## Testing Skill Activation After creating a Skill, test that it activates correctly: ### Step 1: Deploy Skill ```bash # Build and deploy ./build-standalone.sh ./flow.sh ``` ### Step 2: Test Trigger Phrases Use **exact trigger phrases from description**: ``` # For flow-navigator User: "What should I work on next?" Expected: Skill activates, reads DASHBOARD.md, provides navigation # For flow-planner User: "Let's add a new task" Expected: Skill activates, suggests /flow-task-add, shows task structure # For flow-implementer User: "Time to implement" Expected: Skill activates, checks brainstorming, uses /flow-implement-start ``` ### Step 3: Verify Activation **Signs Skill activated correctly**: - Claude references Skill content in response - Appropriate guidance provided - Correct tools used (respecting allowed-tools if set) **Signs Skill did NOT activate**: - Generic response without Skill context - Wrong workflow suggested - No mention of Flow patterns ### Step 4: Refine Description If Skill doesn't activate: 1. Add more trigger phrase variations to description 2. Make description more specific 3. Ensure trigger phrases match how users actually talk 4. Test again --- ## Common Pitfalls ### 1. Vague Descriptions **Problem**: `description: "For working with Flow"` **Solution**: Be specific about what, when, and how ### 2. Missing Trigger Phrases **Problem**: Description doesn't include phrases users would say **Solution**: Add natural language triggers: "Use when user asks '...'" ### 3. Description Too Long **Problem**: 2000 character description (exceeds 1024 limit) **Solution**: Be concise, move details to SKILL.md body ### 4. Wrong allowed-tools Setting **Problem**: Read-only Skill without allowed-tools restriction **Solution**: Add `allowed-tools: Read, Grep, Glob` for inspection-only Skills ### 5. Duplicate Functionality **Problem**: Skill overlaps with existing slash command **Solution**: Skills complement commands, don't replace them. Skill = awareness, command = execution ### 6. Too Broad Scope **Problem**: One Skill trying to do everything **Solution**: Keep Skills focused on one capability, compose multiple Skills ### 7. Testing with Wrong Phrases **Problem**: Testing with phrases not in description **Solution**: Test with exact trigger phrases from description field --- ## Troubleshooting ### Skill Doesn't Activate **Check**: 1. Description includes specific trigger phrases 2. Description under 1024 characters 3. YAML syntax valid (opening/closing `---`) 4. Name format: lowercase, hyphens only, max 64 chars 5. Skill file deployed to `.claude/skills/flow-*/SKILL.md` **Test**: ```bash # Verify Skill exists ls ~/.claude/skills/flow-navigator/SKILL.md # or ls .claude/skills/flow-navigator/SKILL.md # Check description cat .claude/skills/flow-navigator/SKILL.md | head -10 ``` ### Skill Activates at Wrong Time **Problem**: Skill triggers when it shouldn't **Solution**: Make description more specific: - Add context about when NOT to use - Narrow trigger phrases - Add distinguishing terms ### Multiple Skills Conflict **Problem**: Two Skills activate simultaneously or wrong one activates **Solution**: Differentiate descriptions: - Use distinct trigger terms - Add specific context (e.g., "for navigation" vs "for implementation") - Reference different user intents ### allowed-tools Not Working **Problem**: Skill still asks for write permissions despite `allowed-tools: Read, Grep, Glob` **Check**: 1. YAML syntax correct (comma-separated tools) 2. Tool names match exactly: Read, Grep, Glob (capitalized) 3. Skill redeployed after changes --- ## Validation Checklist Before deploying a new Skill: - [ ] **Name**: Lowercase, hyphens only, max 64 chars - [ ] **Description**: Max 1024 chars, includes what/when/outcome - [ ] **Trigger phrases**: Specific natural language phrases included - [ ] **allowed-tools**: Set for read-only Skills - [ ] **Instructions**: Clear step-by-step guidance - [ ] **Examples**: At least one concrete example - [ ] **Testing**: Skill activates with trigger phrases - [ ] **No conflicts**: Doesn't overlap with other Skills - [ ] **Focused scope**: One capability, not too broad --- ## Examples from Flow Skills ### flow-navigator (Read-Only) ```yaml name: flow-navigator description: Navigate Flow framework's multi-file architecture (DASHBOARD.md, PLAN.md, phase-N/task-M.md). Use when user asks "where am I", "what's next", "show status", "current work", or wants to understand project structure. Provides dashboard-first navigation guidance. Read-only access. allowed-tools: Read, Grep, Glob ``` ### flow-implementer (Full Access) ```yaml name: flow-implementer description: Guide implementation workflow using Flow framework. Use when user says "implement", "let's code", "start building", "time to write code", or is ready to execute action items. Enforces pre-implementation gate (brainstorming must be complete), guides use of /flow-implement-start and /flow-implement-complete commands, tracks action item completion. # No allowed-tools - needs write access ``` ### flow-reviewer (Read-Only) ```yaml name: flow-reviewer description: Review code and plan consistency using Flow framework. Use when user says "review", "verify", "check", "validate", or asks "is this complete". Validates status markers match actual state, checks for phantom tasks, ensures brainstorming complete before implementation. Read-only inspection using Read, Grep, Glob tools. allowed-tools: Read, Grep, Glob ``` --- ## References - **Agent Skills Documentation**: https://docs.claude.com/en/docs/claude-code/skills - **Agent Skills Best Practices**: https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices - **Flow Framework**: framework/DEVELOPMENT_FRAMEWORK.md - **Skills Templates**: framework/skills/_TEMPLATE/ and framework/skills/_TEMPLATE-MULTI/ SKILLS_GUIDE_EOF } # Skill extraction functions (8 workflow stage-based skills) # 1. flow-initializer (NEW) get_skill_flow_initializer() { cat <<'SKILL_FLOW_INITIALIZER_EOF' --- name: flow-initializer description: Initialize Flow projects from scratch, migrate existing docs, or update old structures. Use when user says "start flow", "initialize", "migrate to flow", "set up flow project". --- # Flow Initializer Help users initialize new Flow projects, migrate existing documentation to Flow format, or update old Flow structures to current framework patterns. This is the entry point for getting started with Flow. ## When to Use This Skill Activate when the user wants project initialization: - "Start a new Flow project" - "Set up Flow framework" - "Initialize Flow in my project" - "Migrate my TODO/PLAN to Flow" - "Convert my docs to Flow format" - "Create Flow structure" - "Bootstrap Flow" - "Update my old Flow plan" - "My plan structure is outdated" ## Initialization Philosophy **Three Paths to Flow**: 1. **Blueprint** - Create new project from scratch 2. **Migrate** - Convert existing docs (PRD, TODO, PLAN) to Flow 3. **Update** - Modernize old Flow structures to current patterns **Multi-File Architecture**: Flow uses: - `DASHBOARD.md` - Progress tracking (single source of truth) - `PLAN.md` - Static context (overview, architecture, scope) - `phase-N/task-M.md` - Work files with iterations ## Path 1: Blueprint (New Project) ### When to Use User wants to create a brand new Flow project from scratch. ### Input Validation **Step 1: Check for content** - Reject if empty or whitespace only **Step 2: Detect blueprint mode** **Mode A: SUGGEST Structure** (AI designs) - Trigger: NO explicit structure markers - Examples: "websocket server", "user auth system" - Behavior: Ask questions, generate suggested structure **Mode B: CREATE Explicit Structure** (User designed) - Trigger: Contains numbered lists, "Phase N:", "Task N:", or bullets - Behavior: Parse structure, show dry-run preview, get approval **Step 3: Semantic check** (Mode A only) - If too vague, ask for clarification **Step 4: Dry-run preview** (Mode B only) - Show what will be created, get approval ### Blueprint Workflow **Mode A: SUGGEST Structure** 1. Gather requirements (ask about goals, phases, tasks) 2. Generate suggested structure 3. Get user approval before creating files **Mode B: CREATE Explicit Structure** 1. Parse user's structure (phases, tasks, iterations, V1/V2 splits) 2. Show dry-run preview 3. Get user approval ### Files to Create Use these template files for complete structures: - [DASHBOARD_TEMPLATE.md](DASHBOARD_TEMPLATE.md) - Progress tracking structure - [PLAN_TEMPLATE.md](PLAN_TEMPLATE.md) - Static context structure - [TASK_TEMPLATES.md](TASK_TEMPLATES.md) - Task file structures (standalone, iterations, brainstorming) - [OTHER_TEMPLATES.md](OTHER_TEMPLATES.md) - BACKLOG and CHANGELOG templates (optional) ### Creation Process 1. Check `.flow/` doesn't exist (unless user confirms overwrite) 2. Create directory structure: `.flow/` and `.flow/phase-1/` 3. Write DASHBOARD.md, PLAN.md, phase-1/task-1.md using templates 4. Confirm success with summary ## Path 2: Migrate (Convert Existing Docs) ### When to Use User has existing documentation (PRD.md, TODO.md, PLAN.md, etc.) and wants to convert to Flow format. ### Discovery Phase 1. Check if user provided path in request 2. Otherwise search project root for common files: `PRD.md`, `PLAN.md`, `TODO.md`, `DEVELOPMENT.md`, `ROADMAP.md`, `TASKS.md` 3. If multiple found, ask which to migrate 4. If none found, offer to create new project instead ### Analysis Phase **Detect structure type**: - **STRUCTURED** (Path A): Has phases/tasks/iterations or similar hierarchy - **FLAT_LIST** (Path B): Simple todo list or numbered items - **UNSTRUCTURED** (Path C): Free-form notes, ideas, design docs **Extract key information**: Project context, completed work, current position, remaining work, architecture, V1/V2 splits, deferred/cancelled items ### Backup Phase Create timestamped backup before migration: `[original].pre-flow-backup-$(date +%Y-%m-%d-%H%M%S)` ### Migration Patterns See [MIGRATION_PATTERNS.md](MIGRATION_PATTERNS.md) for detailed conversion patterns for each structure type: **Path A: STRUCTURED** - Map phases→phase-N/, tasks→task-M.md, preserve status markers, extract sections to DASHBOARD/PLAN **Path B: FLAT_LIST** - Group into phases (ask if unclear), convert items to tasks, detect status from markers **Path C: UNSTRUCTURED** - Show preview, offer options: extract & suggest structure, create basic plan, or start fresh ### Post-Migration Report what was created with summary of phases, tasks, current position, and next steps ## Path 3: Update (Modernize Old Flow Structure) ### When to Use User has an existing Flow structure that's outdated and needs updating to current framework patterns. ### Detection **Read current structure**: Read DASHBOARD.md, PLAN.md, list phase directories, sample 2-3 task files **Identify what needs updating**: - Missing sections in DASHBOARD.md (📍 Current Work, 📊 Progress Overview) - Missing sections in PLAN.md (Architecture, Testing Strategy) - Outdated status markers - Incorrect task structure (action items + iterations in same task) - Missing CHANGELOG.md or BACKLOG.md ### Backup Phase Create timestamped backup in `.flow/backup-[timestamp]/` before making changes ### Update Process **DASHBOARD.md updates**: Ensure required sections exist, update timestamps and pointers **PLAN.md updates**: Ensure Overview/Architecture/Testing sections exist, remove detailed tasks (move to task files) **Task Files updates**: Ensure Task Overview and Iterations sections exist, convert standalone tasks to iteration format, fix status markers **Missing Files**: Create CHANGELOG.md and/or BACKLOG.md if needed ### Report Changes Show summary of what was updated in each file and guide user to next steps ## Validation Gates **Before creating**: Check `.flow/` doesn't exist (unless overwrite confirmed), verify minimum viable content **Before migrating**: Verify source docs exist, confirm backup created **After creation/migration/update**: Verify DASHBOARD.md and PLAN.md exist with required sections, at least one phase directory exists, current work pointer is valid ## Examples ### Example 1: New Project from Scratch (Mode A: AI Suggests Structure) ``` User: "Set up Flow for my WebSocket chat app" AI Process: 1. Detect Mode A (no explicit structure) 2. Ask: "What are the main phases? For example: Backend setup, WebSocket integration, Frontend, Testing" 3. User: "Backend, then frontend" 4. Generate suggested structure with 2 phases 5. Get approval, create files Files Created: - .flow/DASHBOARD.md (current: Phase 1, Task 1) - .flow/PLAN.md (Purpose: WebSocket chat, Architecture: [TBD]) - .flow/phase-1/task-1.md (Backend setup) - .flow/phase-2/task-1.md (Frontend) ``` ### Example 2: Migrating TODO.md to Flow ``` User: "Migrate my TODO.md to Flow" AI Process: 1. Read TODO.md 2. Detect structure type: FLAT_LIST (12 tasks) 3. Create backup: TODO.md.pre-flow-backup-[timestamp] 4. Group tasks: Phase 1 (Foundation, 4 tasks), Phase 2 (Features, 5 tasks), Phase 3 (Polish, 3 tasks) 5. Ask approval, migrate Files Created: - .flow/DASHBOARD.md (shows Phase 2, Task 2 in progress) - .flow/PLAN.md (Purpose extracted, Architecture [TBD]) - .flow/phase-1/ (3 tasks complete, 1 pending) - .flow/phase-2/ (2 in progress, 3 pending) - .flow/phase-3/ (3 pending) ``` ### Example 3: Updating Old Flow Single-File Plan ``` User: "Update my plan structure" AI Process: 1. Read existing .flow/DASHBOARD.md and PLAN.md 2. Detect outdated patterns: missing sections, wrong task structure 3. Create backup: .flow/backup-[timestamp]/ 4. Update DASHBOARD.md: Add "📍 Current Work" section 5. Update PLAN.md: Add Testing Strategy, move tasks to files 6. Update task files: Convert 2 standalone tasks to iteration format Report: ✅ Updated to current patterns - DASHBOARD.md: Added Current Work section - PLAN.md: Added Testing Strategy - Tasks: Converted 2 to iteration format ``` ## Interaction with Other Flow Skills **After Initialization**: - flow-planner adds new phases/tasks/iterations - flow-designer fills in Architecture during brainstorming - flow-builder executes iterations - flow-navigator shows current status ## Key Reminders **Before**: Understand which path, validate input/detect sources, get user approval for structure **During**: Create backups (migrate/update), follow multi-file architecture, use correct status markers (✅ ⏳ 🚧), mark [TBD] for unknowns **After**: Verify files created, report summary, guide user to next steps ## References - **Multi-File Architecture**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 82-169 - **File Templates**: - [DASHBOARD_TEMPLATE.md](DASHBOARD_TEMPLATE.md) - Complete DASHBOARD.md structure - [PLAN_TEMPLATE.md](PLAN_TEMPLATE.md) - Complete PLAN.md structure - [TASK_TEMPLATES.md](TASK_TEMPLATES.md) - Task file structures - [OTHER_TEMPLATES.md](OTHER_TEMPLATES.md) - BACKLOG and CHANGELOG - **Migration Patterns**: [MIGRATION_PATTERNS.md](MIGRATION_PATTERNS.md) - Conversion strategies for different doc types - **Status Markers**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1872-1968 - **Task Structure Rules**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 238-566 SKILL_FLOW_INITIALIZER_EOF } get_skill_flow_initializer_dashboard_template() { cat <<'SKILL_FLOW_INITIALIZER_DASHBOARD_EOF' # DASHBOARD.md Template Complete template for DASHBOARD.md used during project initialization. ## Template Structure ```markdown # [PROJECT_NAME] - Dashboard **Last Updated**: [TIMESTAMP] **Project**: [ONE_LINE_DESCRIPTION] **Status**: [CURRENT_PHASE_STATUS] **Version**: V1 --- ## 📍 Current Work - **Phase**: [Phase N - PHASE_NAME](phase-N/) - **Task**: [Task M - TASK_NAME](phase-N/task-M.md) - **Status**: [STATUS_EMOJI] [STATUS_TEXT] - **Next**: [NEXT_ACTION_GUIDANCE] --- ## 📊 Progress Overview ### Phase 1: [PHASE_NAME] [STATUS_EMOJI] [STATUS] **Goal**: [PHASE_GOAL] **Status**: [PHASE_STATUS_DESCRIPTION] **Tasks**: - [STATUS_EMOJI] **Task 1**: [TASK_NAME] ([COMPLETED_ITERATIONS]/[TOTAL_ITERATIONS] iterations) - [BRIEF_TASK_DESCRIPTION] - [STATUS_EMOJI] **Task 2**: [TASK_NAME] ([COMPLETED_ITERATIONS]/[TOTAL_ITERATIONS] iterations) - [BRIEF_TASK_DESCRIPTION] ### Phase 2: [PHASE_NAME] [STATUS_EMOJI] [STATUS] **Goal**: [PHASE_GOAL] **Status**: [PHASE_STATUS_DESCRIPTION] **Tasks**: - [STATUS_EMOJI] **Task 1**: [TASK_NAME] ([COMPLETED_ITERATIONS]/[TOTAL_ITERATIONS] iterations) - [BRIEF_TASK_DESCRIPTION] --- ## 📈 Completion Status **Overall Progress**: [PERCENTAGE]% ### By Phase - Phase 1: [PERCENTAGE]% ([COMPLETED]/[TOTAL] tasks) - Phase 2: [PERCENTAGE]% ([COMPLETED]/[TOTAL] tasks) ### By Status - ✅ Complete: [COUNT] tasks ([PERCENTAGE]%) - 🚧 In Progress: [COUNT] tasks ([PERCENTAGE]%) - ⏳ Pending: [COUNT] tasks ([PERCENTAGE]%) --- ## 💡 Key Decisions [ARCHITECTURAL_DECISIONS_IF_ANY] **Decision Needed**: [QUESTION] - Option A: [OPTION_A_DESCRIPTION] - Option B: [OPTION_B_DESCRIPTION] - **Recommendation**: [RECOMMENDATION_WITH_REASONING] **Resolved**: - **[DATE]**: [DECISION_TITLE] - [DECISION_SUMMARY] --- ## 🎯 Success Criteria **Phase 1 Complete When**: - [CRITERION_1] - [CRITERION_2] - [CRITERION_3] **Phase 2 Complete When**: - [CRITERION_1] - [CRITERION_2] --- ## 📚 Related Resources - **Flow Framework**: .flow/framework/DEVELOPMENT_FRAMEWORK.md - **Slash Commands**: .flow/framework/SLASH_COMMANDS.md - **[EXTERNAL_RESOURCE]**: [URL] ``` ## Placeholders Explained | Placeholder | Example Value | Notes | |------------|---------------|-------| | `[PROJECT_NAME]` | "WebSocket Chat App" | From user input | | `[TIMESTAMP]` | "2025-11-02T14:30:00" | ISO format | | `[ONE_LINE_DESCRIPTION]` | "Real-time chat with Socket.IO" | Brief summary | | `[CURRENT_PHASE_STATUS]` | "Phase 1 in progress" | Current state | | `[PHASE_NAME]` | "Foundation", "Core Features" | From user input | | `[STATUS_EMOJI]` | ✅ or 🚧 or ⏳ | Based on actual status | | `[STATUS]` | "COMPLETE", "IN PROGRESS", "PENDING" | Text status | | `[PHASE_GOAL]` | "Establish basic server infrastructure" | Why this phase exists | | `[TASK_NAME]` | "Set up Express server" | Specific task | | `[COMPLETED_ITERATIONS]` | "2" | Number done | | `[TOTAL_ITERATIONS]` | "4" | Total planned | | `[PERCENTAGE]` | "67" | Calculated percentage | | `[NEXT_ACTION_GUIDANCE]` | "Use flow-planner to begin Task 1" | What to do next | ## Usage Notes **MUST fill** (required): - `[PROJECT_NAME]` - `[TIMESTAMP]` - `[PHASE_NAME]` for Phase 1 - `[TASK_NAME]` for Task 1 **SHOULD fill** (if available): - `[PHASE_GOAL]` for each phase - `[TASK_OVERVIEW]` for each task **CAN defer** (use in Progress Overview): - Key Decisions (if no decisions yet) - Multiple phases (if starting with one) - Completion Status percentages (calculate after setup) ## Example: Filled DASHBOARD.md for New Project **User Input**: "Create Flow project for WebSocket chat app with 2 phases: 1. Backend (server + database), 2. Frontend (React UI)" **Filled Template**: ```markdown # WebSocket Chat App - Dashboard **Last Updated**: 2025-11-02T14:30:00 **Project**: Real-time chat application with WebSocket support **Status**: Phase 1 in progress **Version**: V1 --- ## 📍 Current Work - **Phase**: [Phase 1 - Backend](phase-1/) - **Task**: [Task 1 - Server Setup](phase-1/task-1.md) - **Status**: ⏳ PENDING - Ready to start - **Next**: Use flow-planner to begin Task 1 --- ## 📊 Progress Overview ### Phase 1: Backend ⏳ PENDING **Goal**: Establish server infrastructure and database **Status**: Not started **Tasks**: - ⏳ **Task 1**: Server Setup (0/2 iterations) - Create Express server with WebSocket support - ⏳ **Task 2**: Database Integration (0/2 iterations) - Set up PostgreSQL and schema ### Phase 2: Frontend ⏳ PENDING **Goal**: Build user interface for chat **Status**: Not started (blocked by Phase 1) **Tasks**: - ⏳ **Task 1**: React UI (0/3 iterations) - Create chat interface components --- ## 🎯 Success Criteria **Phase 1 Complete When**: - WebSocket server accepting connections - Database storing messages - Basic API endpoints working **Phase 2 Complete When**: - Chat UI renders messages - Users can send/receive messages in real-time - Message history loads from database --- ## 📚 Related Resources - **Flow Framework**: .flow/framework/DEVELOPMENT_FRAMEWORK.md - **Slash Commands**: .flow/framework/SLASH_COMMANDS.md ``` SKILL_FLOW_INITIALIZER_DASHBOARD_EOF } get_skill_flow_initializer_migration_patterns() { cat <<'SKILL_FLOW_INITIALIZER_MIGRATION_EOF' # Migration Patterns Detailed patterns for converting various documentation formats to Flow's multi-file structure. ## Pattern 1: PRD → Flow ### Source Format (PRD.md) ```markdown # Product Requirements Document ## Overview Build a real-time chat application... ## Goals - Enable real-time messaging - Support multiple users - Persist chat history ## Requirements ### Phase 1: Backend - [ ] Set up Express server - [ ] Configure WebSocket - [x] Database schema ### Phase 2: Frontend - [ ] Chat UI - [ ] User authentication ## Technical Design Using Node.js with Socket.IO... ## Out of Scope - Voice calls (V2) - File sharing (V2) ``` ### Conversion Strategy **Extract sections**: - Overview → PLAN.md Purpose - Goals → PLAN.md Goals (remove checkboxes, keep text only) - Requirements → Phase directories + task files - Technical Design → PLAN.md Architecture - Out of Scope → PLAN.md Scope (V2 section) **Map structure**: - "Phase 1: Backend" → `.flow/phase-1/` - Tasks under Phase 1 → `phase-1/task-1.md`, `phase-1/task-2.md`, etc. - `[x]` marker → ✅ COMPLETE status - `[ ]` marker → ⏳ PENDING status **Result**: ``` .flow/ ├── DASHBOARD.md (shows Phase 1, Task 3 in progress) ├── PLAN.md (Purpose, Goals, Architecture, Scope with V2) ├── phase-1/ │ ├── task-1.md (Set up Express server - COMPLETE) │ ├── task-2.md (Configure WebSocket - PENDING) │ └── task-3.md (Database schema - COMPLETE) └── phase-2/ ├── task-1.md (Chat UI - PENDING) └── task-2.md (User authentication - PENDING) ``` ## Pattern 2: TODO.md → Flow ### Source Format (TODO.md) ```markdown # TODO ## Done - [x] Create project structure - [x] Set up TypeScript config ## In Progress - [>] Implement API client - [x] Basic HTTP methods - [ ] Error handling - [ ] Retry logic ## Pending - [ ] Add tests - [ ] Write documentation - [ ] Deploy to production ## Later - [ ] Add caching - [ ] Implement rate limiting ``` ### Conversion Strategy **Group into phases** (ask user if unclear): ``` Phase 1: Foundation (Done items) Phase 2: Core Implementation (In Progress items) Phase 3: Finalization (Pending items) ``` **Convert "In Progress" item with sub-items** → Task with iterations: ```markdown # Task 1: Implement API Client ## Iterations ### ✅ Iteration 1: Basic HTTP methods **Status**: ✅ COMPLETE ### 🚧 Iteration 2: Error handling **Status**: 🚧 IN PROGRESS ### ⏳ Iteration 3: Retry logic **Status**: ⏳ PENDING ``` **"Later" items** → BACKLOG.md **Result**: ``` .flow/ ├── DASHBOARD.md (shows Phase 2, Task 1, Iteration 2 in progress) ├── PLAN.md (minimal - fill [TBD] for Purpose/Architecture) ├── BACKLOG.md (caching, rate limiting) ├── phase-1/ │ ├── task-1.md (Project structure - COMPLETE) │ └── task-2.md (TypeScript config - COMPLETE) ├── phase-2/ │ └── task-1.md (API client with 3 iterations, iteration 2 in progress) └── phase-3/ ├── task-1.md (Tests - PENDING) ├── task-2.md (Documentation - PENDING) └── task-3.md (Deploy - PENDING) ``` ## Pattern 3: Flat PLAN.md → Flow ### Source Format (Single-File PLAN.md) ```markdown # Project Plan Purpose: Build chat app ## Phase 1 - Task 1: Server setup [DONE] - Task 2: WebSocket integration [IN PROGRESS] - Iteration 1: Basic connection [DONE] - Iteration 2: Room support [WIP] - Iteration 3: Error handling [TODO] ## Phase 2 - Task 1: Frontend - Task 2: Testing V2: Video calls, file sharing ``` ### Conversion Strategy **Split single file into multi-file**: - Static content → PLAN.md - Progress tracking → DASHBOARD.md - Tasks → phase-N/task-M.md files **Preserve hierarchy**: - Phase 1 → `phase-1/` - Task 1 → `phase-1/task-1.md` - Iterations stay within task file **Map status markers**: - [DONE] → ✅ COMPLETE - [IN PROGRESS], [WIP] → 🚧 IN PROGRESS - [TODO], no marker → ⏳ PENDING **Result**: ``` .flow/ ├── DASHBOARD.md (current: Phase 1, Task 2, Iteration 2) ├── PLAN.md (Purpose, Scope V1/V2) ├── phase-1/ │ ├── task-1.md (Server setup - COMPLETE) │ └── task-2.md (WebSocket integration - IN PROGRESS with 3 iterations) └── phase-2/ ├── task-1.md (Frontend - PENDING) └── task-2.md (Testing - PENDING) ``` ## Pattern 4: Unstructured Notes → Flow ### Source Format (DEVELOPMENT.md) ```markdown # Development Notes I want to build a chat app with real-time messaging. Key features: - Multiple users can chat - Messages persist in database - Use Socket.IO for real-time Architecture ideas: - Node.js backend - React frontend - PostgreSQL database Need to figure out: - Authentication strategy - Scaling approach - Testing plan ``` ### Conversion Strategy **Show preview and ask**: ``` "I found unstructured notes. I can: A) Extract key points and suggest this structure: - Phase 1: Backend (Node.js + Socket.IO + PostgreSQL) - Phase 2: Frontend (React + real-time integration) - Phase 3: Production (auth + scaling + testing) B) Create a basic single-phase plan with 5 tasks C) Let's start fresh with blueprint instead Which approach?" ``` **If option A** (extract and structure): - Features → Task names - Architecture ideas → PLAN.md Architecture section (mark as [TBD] if incomplete) - "Need to figure out" → Brainstorming subjects or [TBD] markers **If option B** (basic plan): - Create Phase 1 with tasks based on main points - Mark most fields as [TBD] **If option C** (start fresh): - Switch to blueprint path (get structured input from user) **Result (Option A)**: ``` .flow/ ├── DASHBOARD.md (Phase 1, Task 1 ready to start) ├── PLAN.md (Purpose: real-time chat, Architecture: Node.js + React + PostgreSQL) ├── phase-1/ │ ├── task-1.md (Backend API - Node.js + Socket.IO) │ └── task-2.md (Database - PostgreSQL setup) ├── phase-2/ │ ├── task-1.md (Frontend - React UI) │ └── task-2.md (Real-time integration) └── phase-3/ ├── task-1.md (Authentication - [TBD strategy]) ├── task-2.md (Scaling - [TBD approach]) └── task-3.md (Testing - [TBD plan]) ``` ## Pattern 5: Multi-File Project with Scattered Docs → Flow ### Source Format (Multiple Files) ``` project/ ├── README.md (overview, goals) ├── ARCHITECTURE.md (technical design) ├── TODO.md (task list) └── ROADMAP.md (phases, timeline) ``` ### Conversion Strategy **Discover all relevant files**: ``` Found multiple doc files: 1. README.md (overview, goals) 2. ARCHITECTURE.md (technical design) 3. TODO.md (12 tasks) 4. ROADMAP.md (3 phases) Which should I use as primary source? (number or 'combine all') ``` **If "combine all"**: - README.md Overview → PLAN.md Purpose - README.md Goals → PLAN.md Goals - ARCHITECTURE.md → PLAN.md Architecture - TODO.md → Task files - ROADMAP.md → Phase structure **Result**: ``` .flow/ ├── DASHBOARD.md (synthesized from TODO + ROADMAP) ├── PLAN.md (Purpose from README, Architecture from ARCHITECTURE.md) ├── phase-1/ (from ROADMAP Phase 1) ├── phase-2/ (from ROADMAP Phase 2) └── phase-3/ (from ROADMAP Phase 3) ``` ## Status Marker Conversion Reference ### Common Markers in Existing Docs | Source Marker | Flow Status | Flow Emoji | |--------------|-------------|------------| | `[x]`, `✓`, `✅` | COMPLETE | ✅ | | `[>]`, `WIP`, `IN PROGRESS`, `DOING` | IN PROGRESS | 🚧 | | `[ ]`, `TODO`, `PENDING` | PENDING | ⏳ | | `READY`, `READY TO START` | READY | 🎨 | | `CANCELLED`, `ABANDONED`, `DROPPED` | CANCELLED | ❌ | | `DEFERRED`, `LATER`, `V2`, `FUTURE` | Move to BACKLOG or PLAN.md V2 | 🔮 | ### Ambiguous Markers **If unclear, ask user**: ``` "Found marker '[~]' on 3 tasks. Should this be: A) ⏳ PENDING (not started) B) 🚧 IN PROGRESS (working on it) C) Something else?" ``` ## Section Mapping Reference ### Source Document → Flow Files | Source Section | Flow Destination | Notes | |---------------|------------------|-------| | Overview, Summary, Purpose | PLAN.md Purpose | First section | | Goals, Objectives | PLAN.md Goals | Remove checkboxes | | Scope, V1, V2 | PLAN.md Scope | Split into V1/V2 | | Architecture, Design, Technical | PLAN.md Architecture | Technical details | | Testing, QA | PLAN.md Testing Strategy | How to verify | | Phases, Milestones | DASHBOARD.md Progress | + phase-N/ directories | | Tasks, Action Items | phase-N/task-M.md | Individual files | | Current Work, Status | DASHBOARD.md Current Work | Pointer to current position | | Later, Backlog, Deferred | BACKLOG.md | Optional file | | History, Changelog | CHANGELOG.md | Optional file | ## Common Migration Issues ### Issue 1: Deeply Nested Tasks **Problem**: Source has 4+ levels of nesting ``` - Phase 1 - Feature A - Component A1 - Function A1a - Test A1a1 ``` **Solution**: Flatten to Flow's 3-level hierarchy (Phase → Task → Iteration) ``` Phase 1 ├── Task 1: Feature A Component A1 (with iterations) │ ├── Iteration 1: Implement Function A1a │ └── Iteration 2: Add Tests ``` **Ask user if unclear**: "I see deep nesting. Should I flatten to 3 levels or group differently?" ### Issue 2: Mixed Status Indicators **Problem**: Source uses inconsistent status markers ``` - [x] Task A - DONE: Task B - ✅ Task C - Task D (complete) ``` **Solution**: Normalize to Flow's status markers (✅ 🚧 ⏳) - All completed → ✅ COMPLETE - Report normalization: "Normalized 4 different 'complete' markers to ✅ COMPLETE" ### Issue 3: Unclear Current Position **Problem**: Source doesn't clearly indicate where work stopped ``` - Task A (done) - Task B (done) - Task C - Task D ``` **Solution**: Ask user ``` "I see Tasks A-B are complete. Which task is current: A) Task C (next in sequence) B) Task D (different priority) C) Still on Task B (not actually complete) D) No current task (plan only)" ``` ### Issue 4: Scope Creep in Single Section **Problem**: Source has 50+ tasks in flat list with no structure **Solution**: Propose grouping ``` "Found 52 tasks in flat list. I suggest grouping into phases: Phase 1: Foundation (Tasks 1-12) - Setup and core infrastructure Phase 2: Features (Tasks 13-38) - Main functionality Phase 3: Polish (Tasks 39-52) - Testing, docs, deployment Or should I ask you to define phases differently?" ``` ## Validation Checklist After migration, verify: - [ ] DASHBOARD.md exists with "📍 Current Work" section - [ ] PLAN.md exists with Purpose, Scope, Architecture sections - [ ] At least one phase directory exists (phase-1/) - [ ] At least one task file exists (phase-1/task-1.md) - [ ] Current work pointer is valid (points to existing phase/task/iteration) - [ ] All status markers are Flow format (✅ 🚧 ⏳) - [ ] Completed tasks show ✅ COMPLETE - [ ] In-progress tasks show 🚧 IN PROGRESS - [ ] No orphaned tasks (all tasks belong to a phase) - [ ] Backup of source file created - [ ] V2 items captured (in PLAN.md Scope or BACKLOG.md) ## Migration Report Template After successful migration, report: ``` ✅ Migration complete! **Source**: [original file/files] **Backup**: [backup location] **Created**: - DASHBOARD.md - Current work: Phase [N], Task [M], Iteration [I] - Total progress: [X]% complete - PLAN.md - Purpose: [extracted/[TBD]] - Architecture: [extracted/[TBD]] - Scope V1: [extracted] - Scope V2: [N items deferred] - [N] phase directories - [M] task files - BACKLOG.md ([X] deferred items) **Status Summary**: - ✅ [N] tasks complete - 🚧 [M] tasks in progress - ⏳ [K] tasks pending **Next Steps**: 1. Review DASHBOARD.md for accuracy 2. Fill in [TBD] markers in PLAN.md if needed 3. Use `/flow-task-start` to continue current work Questions? Use `/flow-status` to see your position. ``` SKILL_FLOW_INITIALIZER_MIGRATION_EOF } get_skill_flow_initializer_other_templates() { cat <<'SKILL_FLOW_INITIALIZER_OTHER_EOF' # Other Templates Templates for optional Flow files: BACKLOG.md and CHANGELOG.md ## BACKLOG.md Template Use for tracking deferred work (V2 features, future enhancements, nice-to-haves). ```markdown # Backlog **Purpose**: Track deferred work (V2 features, future enhancements, nice-to-haves) --- ## V2 Features ### [FEATURE_NAME] **Why Deferred**: [REASON_FOR_V2] **Description**: [WHAT_THIS_FEATURE_DOES] **Dependencies**: [WHAT_NEEDS_TO_EXIST_FIRST] **Estimated Effort**: [SMALL/MEDIUM/LARGE] --- ### [FEATURE_NAME] **Why Deferred**: [REASON_FOR_V2] **Description**: [WHAT_THIS_FEATURE_DOES] **Dependencies**: [WHAT_NEEDS_TO_EXIST_FIRST] **Estimated Effort**: [SMALL/MEDIUM/LARGE] --- ## Future Enhancements - [ENHANCEMENT_1] - [BRIEF_DESCRIPTION] - [ENHANCEMENT_2] - [BRIEF_DESCRIPTION] - [ENHANCEMENT_3] - [BRIEF_DESCRIPTION] --- ## Ideas (Unvalidated) - [IDEA_1] - [WHY_INTERESTING] - [IDEA_2] - [WHY_INTERESTING] - [IDEA_3] - [WHY_INTERESTING] ``` ## CHANGELOG.md Template Use for tracking project history and notable changes. ```markdown # Changelog All notable changes to this project will be documented in this file. --- ## [Unreleased] ### Added - [NEW_FEATURE] ### Changed - [MODIFICATION_TO_EXISTING] ### Fixed - [BUG_FIX] --- ## [1.0.0] - [DATE] ### Added - Initial project structure - [FEATURE_1] - [FEATURE_2] ### Phase 1 Complete - [MILESTONE_ACHIEVEMENT] --- ## Notes - Follow [Keep a Changelog](https://keepachangelog.com/) format - Version numbers follow [Semantic Versioning](https://semver.org/) ``` ## Usage Notes ### When to Create BACKLOG.md **Always create** if: - User mentions "V2", "later", "future" features - Migration source has "deferred" or "future" sections - User explicitly separates V1 and V2 scope **Don't create** if: - No V2 features mentioned - User focused only on immediate work - Can add later when V2 features emerge ### When to Create CHANGELOG.md **Always create** if: - Migrating from existing project (capture history) - User mentions versioning strategy - Project is production-ready or has releases **Don't create** if: - Brand new project (no history yet) - User prefers Git history only - Can add later when first milestone reached ### Populating BACKLOG.md During Migration **Extract from source documentation**: - Look for sections titled "V2", "Future", "Later", "Backlog" - Look for items marked "deferred", "future", "nice-to-have" - Look for items in comments like "// TODO: later" or "# Future:" **Categorize into sections**: - **V2 Features**: Well-defined features explicitly deferred - **Future Enhancements**: Ideas with some detail but not fully scoped - **Ideas (Unvalidated)**: Raw ideas that need validation ### Populating CHANGELOG.md During Migration **Extract from source documentation**: - Look for sections titled "History", "Changelog", "Releases", "Versions" - Extract completed milestones from progress sections - Note major architectural decisions made **Structure entries**: - Use semantic versioning (1.0.0, 1.1.0, etc.) - Group by type: Added, Changed, Fixed, Removed - Include dates when available ## Examples ### Example: BACKLOG.md for Chat App ```markdown # Backlog **Purpose**: Track deferred work (V2 features, future enhancements, nice-to-haves) --- ## V2 Features ### Group Chat Rooms **Why Deferred**: V1 focuses on 1-to-1 messaging; group chat requires additional complexity **Description**: Allow multiple users to join named chat rooms and communicate **Dependencies**: V1 messaging system must be stable and performant **Estimated Effort**: LARGE (requires room management, permissions, scaling considerations) --- ### File Sharing **Why Deferred**: V1 focuses on text messaging only **Description**: Allow users to share files (images, documents) in conversations **Dependencies**: V1 messaging + storage solution + CDN **Estimated Effort**: MEDIUM (file upload, storage, retrieval, preview) --- ## Future Enhancements - Voice/video calling - WebRTC integration for audio/video chat - Message reactions - Emoji reactions to messages (like Slack) - Message threading - Reply to specific messages with threads - Search functionality - Full-text search across message history --- ## Ideas (Unvalidated) - AI-powered message translation - Translate messages between languages in real-time - Disappearing messages - Self-destructing messages after set time - End-to-end encryption - Encrypted messaging for privacy ``` ### Example: CHANGELOG.md After Migration ```markdown # Changelog All notable changes to this project will be documented in this file. --- ## [Unreleased] ### In Progress - Migrating to Flow framework for better project structure --- ## [0.3.0] - 2025-10-15 ### Added - Real-time message delivery with Socket.IO - Online/offline status indicators - Message history persistence to PostgreSQL ### Changed - Switched from polling to WebSocket for better performance ### Fixed - Race condition in message ordering - Connection drops on mobile networks ### Phase 2 Complete - Backend and frontend communication established - Users can send/receive messages in real-time --- ## [0.2.0] - 2025-09-01 ### Added - Basic Express server setup - PostgreSQL database schema - JWT authentication ### Phase 1 Complete - Backend infrastructure established --- ## [0.1.0] - 2025-08-15 ### Added - Initial project structure - Development environment setup - Basic routing and middleware --- ## Notes - Follow [Keep a Changelog](https://keepachangelog.com/) format - Version numbers follow [Semantic Versioning](https://semver.org/) ``` SKILL_FLOW_INITIALIZER_OTHER_EOF } get_skill_flow_initializer_plan_template() { cat <<'SKILL_FLOW_INITIALIZER_PLAN_EOF' # PLAN.md Template Complete template for PLAN.md used during project initialization. ## Template Structure ```markdown # [PROJECT_NAME] **Flow Framework Reference**: This project uses [Flow framework](https://github.com/liadgoren/flow) - a human-in-loop development methodology combining Domain-Driven Design with Agile philosophy. --- ## Overview ### Purpose [WHY_THIS_PROJECT_EXISTS] ### Goals [HIGH_LEVEL_OUTCOMES_NOT_CHECKLISTS] Examples: - Achieve [specific outcome] - Enable [capability] - Deliver [value] ### Scope **V1 (Current)**: [CORE_FEATURES_FOR_FIRST_VERSION] Examples: - Basic [feature] - Essential [capability] - Minimal [component] **V2 (Future)**: [DEFERRED_FEATURES] Examples: - Advanced [feature] - Enhanced [capability] - Optional [component] --- ## Architecture ### System Design [HIGH_LEVEL_ARCHITECTURE] **Components**: - **[COMPONENT_NAME]**: [RESPONSIBILITY] - **[COMPONENT_NAME]**: [RESPONSIBILITY] **Data Flow**: [HOW_DATA_MOVES_THROUGH_SYSTEM] ### Key Technologies - **[TECHNOLOGY_1]**: [WHY_CHOSEN] - **[TECHNOLOGY_2]**: [WHY_CHOSEN] ### DO / DON'T Guidelines **DO**: - [BEST_PRACTICE_1] - [BEST_PRACTICE_2] - [BEST_PRACTICE_3] **DON'T**: - [ANTI_PATTERN_1] - [ANTI_PATTERN_2] - [ANTI_PATTERN_3] --- ## Testing Strategy ### Approach [OVERALL_TESTING_PHILOSOPHY] ### Test Types - **Unit Tests**: [WHAT_TO_UNIT_TEST] - **Integration Tests**: [WHAT_TO_INTEGRATION_TEST] - **E2E Tests**: [WHAT_TO_E2E_TEST] ### Coverage Goals - Minimum [PERCENTAGE]% code coverage - All [CRITICAL_PATHS] must have tests --- ## Development Phases ### Phase 1: [PHASE_NAME] **Goal**: [PHASE_GOAL] **Key Deliverables**: - [DELIVERABLE_1] - [DELIVERABLE_2] ### Phase 2: [PHASE_NAME] **Goal**: [PHASE_GOAL] **Key Deliverables**: - [DELIVERABLE_1] - [DELIVERABLE_2] ### Phase 3: [PHASE_NAME] **Goal**: [PHASE_GOAL] **Key Deliverables**: - [DELIVERABLE_1] - [DELIVERABLE_2] --- ## Notes [ADDITIONAL_CONTEXT_IF_NEEDED] ``` ## Placeholders Explained | Placeholder | Example Value | Notes | |------------|---------------|-------| | `[PROJECT_NAME]` | "WebSocket Chat App" | From user input | | `[WHY_THIS_PROJECT_EXISTS]` | "Enable real-time communication between users in a web browser" | Purpose statement | | `[HIGH_LEVEL_OUTCOMES_NOT_CHECKLISTS]` | "Achieve sub-100ms message latency" | Goals (no checkboxes!) | | `[CORE_FEATURES_FOR_FIRST_VERSION]` | "1-to-1 messaging, online status, message history" | V1 scope | | `[DEFERRED_FEATURES]` | "Group chats, file sharing, voice calls" | V2 scope | | `[COMPONENT_NAME]` | "WebSocket Server", "Message Queue" | Architecture components | | `[TECHNOLOGY_1]` | "Socket.IO" | Tech stack | | `[WHY_CHOSEN]` | "Real-time bidirectional communication" | Justification | | `[BEST_PRACTICE_1]` | "Use connection pooling for database" | DO guideline | | `[ANTI_PATTERN_1]` | "Don't store messages in server memory" | DON'T guideline | | `[OVERALL_TESTING_PHILOSOPHY]` | "Test-driven development for business logic" | Testing approach | | `[PHASE_GOAL]` | "Establish working real-time connection" | Why this phase | | `[DELIVERABLE_1]` | "WebSocket server accepting connections" | Phase output | ## Usage Notes **Use [TBD] for unknown values** - Don't guess, mark as "to be determined" **Sections that can be [TBD] initially**: - Architecture > System Design (will be designed during brainstorming) - Architecture > DO/DON'T Guidelines (will emerge during development) - Testing Strategy (can be defined in Phase 1) **Sections that should be filled from user input**: - Purpose (extract from project description) - Goals (extract from user's stated objectives) - Scope V1 (core features mentioned) - Scope V2 (if user mentions "later" or "future" features) - Key Technologies (if user specifies tech stack) ## Example: Filled PLAN.md **User Input**: "WebSocket chat with Node.js and React" ```markdown # WebSocket Chat App **Flow Framework Reference**: This project uses [Flow framework](https://github.com/liadgoren/flow) - a human-in-loop development methodology combining Domain-Driven Design with Agile philosophy. --- ## Overview ### Purpose Enable real-time communication between users through a web-based chat interface. ### Goals - Achieve sub-100ms message delivery latency - Support concurrent users without performance degradation - Provide persistent message history ### Scope **V1 (Current)**: - 1-to-1 messaging - Online/offline status indicators - Message history persistence - Basic authentication **V2 (Future)**: - Group chat rooms - File sharing - Voice/video calls - Message reactions --- ## Architecture ### System Design [TBD - Will be documented during brainstorming] ### Key Technologies - **Node.js**: Server runtime for JavaScript backend - **Socket.IO**: Real-time bidirectional event-based communication - **React**: Frontend UI library for component-based interface - **PostgreSQL**: [TBD - if mentioned, otherwise fill during design] ### DO / DON'T Guidelines **DO**: - [TBD - Will be defined during development] **DON'T**: - [TBD - Will be defined during development] --- ## Testing Strategy [TBD - Will be defined in Phase 1] --- ## Development Phases ### Phase 1: Backend **Goal**: Establish server infrastructure and real-time communication ### Phase 2: Frontend **Goal**: Build user interface and client-side connection --- ## Notes [None yet] ``` SKILL_FLOW_INITIALIZER_PLAN_EOF } get_skill_flow_initializer_task_templates() { cat <<'SKILL_FLOW_INITIALIZER_TASK_EOF' # Task File Templates Templates for task files with different structures: standalone tasks, tasks with iterations, and tasks with brainstorming. ## Task Template (Standalone Task) Use this template for simple tasks without iterations (rare in Flow - most tasks should have iterations). ```markdown # Task [N]: [TASK_NAME] **Status**: [STATUS_EMOJI] [STATUS] --- ## Task Overview **Purpose**: [WHY_THIS_TASK_EXISTS] **Dependencies**: [DEPENDENCY_LIST_OR_NONE] --- ## Action Items - [ ] [ACTION_ITEM_1] - [ ] [ACTION_ITEM_2] - [ ] [ACTION_ITEM_3] - [ ] [ACTION_ITEM_4] --- ## Verification **Success Criteria**: - [ ] [VERIFICATION_POINT_1] - [ ] [VERIFICATION_POINT_2] **Test Plan**: - [HOW_TO_TEST_THIS_TASK] --- ## Notes [ADDITIONAL_CONTEXT_DESIGN_DECISIONS_OR_DISCOVERIES] ``` ## Task Template (Task with Iterations) Use this template for most tasks - iterations allow breaking work into manageable chunks. ```markdown # Task [N]: [TASK_NAME] **Status**: [STATUS_EMOJI] [STATUS] --- ## Task Overview **Purpose**: [WHY_THIS_TASK_EXISTS] **Dependencies**: [DEPENDENCY_LIST_OR_NONE] **Design Notes**: [KEY_ARCHITECTURAL_CONSIDERATIONS] --- ## Iterations ### [STATUS_EMOJI] Iteration 1: [ITERATION_NAME] **Goal**: [WHAT_THIS_ITERATION_ACHIEVES] **Status**: [STATUS_EMOJI] [STATUS] ([DATE_IF_COMPLETE]) #### Action Items - [ ] [ACTION_ITEM_1] - [ ] [ACTION_ITEM_2] - [ ] [ACTION_ITEM_3] #### Implementation [IMPLEMENTATION_NOTES_OR_BLANK_IF_NOT_STARTED] #### Verification - [ ] [VERIFICATION_POINT_1] - [ ] [VERIFICATION_POINT_2] --- ### [STATUS_EMOJI] Iteration 2: [ITERATION_NAME] **Goal**: [WHAT_THIS_ITERATION_ACHIEVES] **Status**: [STATUS_EMOJI] [STATUS] #### Action Items - [ ] [ACTION_ITEM_1] - [ ] [ACTION_ITEM_2] - [ ] [ACTION_ITEM_3] #### Verification - [ ] [VERIFICATION_POINT_1] - [ ] [VERIFICATION_POINT_2] --- ### [STATUS_EMOJI] Iteration 3: [ITERATION_NAME] **Goal**: [WHAT_THIS_ITERATION_ACHIEVES] **Status**: [STATUS_EMOJI] [STATUS] #### Action Items - [ ] [ACTION_ITEM_1] - [ ] [ACTION_ITEM_2] - [ ] [ACTION_ITEM_3] #### Verification - [ ] [VERIFICATION_POINT_1] - [ ] [VERIFICATION_POINT_2] --- ## Notes [ADDITIONAL_CONTEXT_DISCOVERIES_OR_CHANGES] ``` ## Task Template (Task with Brainstorming) Use this template for complex tasks requiring design decisions before implementation. ```markdown # Task [N]: [TASK_NAME] **Status**: [STATUS_EMOJI] [STATUS] --- ## Task Overview **Purpose**: [WHY_THIS_TASK_EXISTS] **Dependencies**: [DEPENDENCY_LIST_OR_NONE] --- ## Iterations ### [STATUS_EMOJI] Iteration 1: [ITERATION_NAME] **Goal**: [WHAT_THIS_ITERATION_ACHIEVES] **Status**: [STATUS_EMOJI] [STATUS] --- #### Brainstorming **Status**: [STATUS_EMOJI] [STATUS] ([DATE_IF_COMPLETE]) **Subjects to Discuss**: 1. [STATUS_EMOJI] [SUBJECT_NAME] - [QUESTION_OR_DECISION_NEEDED] 2. [STATUS_EMOJI] [SUBJECT_NAME] - [QUESTION_OR_DECISION_NEEDED] 3. [STATUS_EMOJI] [SUBJECT_NAME] - [QUESTION_OR_DECISION_NEEDED] --- ##### Subject 1: [SUBJECT_NAME] **Status**: [STATUS_EMOJI] [STATUS] ([DATE_IF_RESOLVED]) **Question**: [WHAT_NEEDS_TO_BE_DECIDED] **Options**: - **Option A**: [DESCRIPTION] - Pros: [PROS], Cons: [CONS] - **Option B**: [DESCRIPTION] - Pros: [PROS], Cons: [CONS] **Decision**: [CHOSEN_OPTION_AND_REASONING] **Resolution Type**: [A/B/C/D] **Action Items** (if Type A or D): - [ ] [ACTION_ITEM_1] - [ ] [ACTION_ITEM_2] --- ##### Subject 2: [SUBJECT_NAME] **Status**: [STATUS_EMOJI] [STATUS] **Question**: [WHAT_NEEDS_TO_BE_DECIDED] [REPEAT_STRUCTURE_AS_SUBJECT_1] --- #### Pre-Implementation Tasks **Status**: [STATUS_EMOJI] [STATUS] These must be completed BEFORE starting main implementation: - [ ] [PRE_TASK_1_FROM_BRAINSTORMING_TYPE_A] - [ ] [PRE_TASK_2_FROM_BRAINSTORMING_TYPE_A] --- #### Implementation **Status**: [STATUS_EMOJI] [STATUS] **Files Modified**: - [FILE_PATH_1] - [FILE_PATH_2] **Changes Made**: [DESCRIPTION_OF_IMPLEMENTATION] #### Action Items - [ ] [ACTION_ITEM_1_FROM_BRAINSTORMING_TYPE_D] - [ ] [ACTION_ITEM_2_FROM_BRAINSTORMING_TYPE_D] - [ ] [ACTION_ITEM_3_FROM_BRAINSTORMING_TYPE_D] #### Verification - [ ] [VERIFICATION_POINT_1] - [ ] [VERIFICATION_POINT_2] --- ## Notes [ADDITIONAL_CONTEXT] ``` ## Usage Guidelines ### When to Use Each Template **Standalone Task** (rare): - Simple, atomic tasks with no natural breakdown - One-step operations (e.g., "Deploy to production", "Create Git repository") - Administrative tasks **Task with Iterations** (most common): - Complex work that can be broken into steps - Feature implementation with multiple phases - Tasks requiring incremental progress **Task with Brainstorming** (for complex/uncertain work): - New features requiring design decisions - Tasks with multiple implementation approaches - Work involving architectural choices - Cases where requirements need clarification ### Status Marker Reference | Status | Emoji | When to Use | |--------|-------|-------------| | COMPLETE | ✅ | Work finished and verified | | IN PROGRESS | 🚧 | Currently working on this | | PENDING | ⏳ | Not started yet | | READY | 🎨 | Ready to implement (brainstorming complete) | | CANCELLED | ❌ | Work abandoned | | DEFERRED | 🔮 | Moved to future version | ### Template Selection Logic ``` IF task is simple AND atomic: → Use Standalone Task template ELSE IF task is well-defined AND can be broken into steps: → Use Task with Iterations template ELSE IF task needs design decisions OR has uncertainties: → Use Task with Brainstorming template ``` ## Example: Choosing the Right Template **Scenario 1**: "Set up CI/CD pipeline" - **Complexity**: Medium - **Breakdown**: Multiple steps (configure, test, deploy) - **Design needed**: No (well-understood process) - **→ Use**: Task with Iterations (3 iterations: configure, test, deploy) **Scenario 2**: "Add real-time chat feature" - **Complexity**: High - **Breakdown**: Multiple components - **Design needed**: Yes (WebSocket vs polling, state management, etc.) - **→ Use**: Task with Brainstorming (design decisions first, then iterations) **Scenario 3**: "Create Git repository" - **Complexity**: Low - **Breakdown**: Single atomic step - **Design needed**: No - **→ Use**: Standalone Task (just create repo, no iterations) SKILL_FLOW_INITIALIZER_TASK_EOF } # 2. flow-navigator (KEEP - no changes) get_skill_flow_navigator() { cat <<'SKILL_FLOW_NAVIGATOR_EOF' --- name: flow-navigator description: Navigate Flow projects with dashboard-first pattern. Use when user asks about status, current work, what's next, or project progress. Read-only skill. allowed-tools: Read, Grep, Glob --- # Flow Navigator Navigate Flow framework projects using the dashboard-first pattern. This Skill helps you understand project structure, locate current work, and guide users through their Flow workflow. ## When to Use This Skill Activate when the user asks questions like: - "Where am I in the project?" - "What should I work on next?" - "Show me the current status" - "What's left to do?" - "Where are we in the plan?" - "What's the progress?" ## Dashboard-First Navigation Pattern **Golden Rule**: Always start with DASHBOARD.md before diving into details. ### Step 1: Read DASHBOARD.md Start here for every navigation request: ``` Read .flow/DASHBOARD.md ``` The dashboard contains: - **Current Work** section → Shows active phase/task/iteration - **Progress Overview** section → Shows all phases with status markers - **Key Decisions** section → Important architectural choices - **Success Criteria** section → What "done" looks like ### Step 2: Parse Current Work Extract the active work location: ```markdown ## 📍 Current Work - **Phase**: [Phase 2 - Implementation](phase-2/) - **Task**: [Task 3 - API Integration](phase-2/task-3.md) - **Iteration**: [Iteration 2 - Error Handling] 🚧 IMPLEMENTING ``` This tells you: - Current phase number and name - Current task number and file path - Current iteration status ### Step 3: Read Task File (Only When Needed) **When to read task files**: - User asks for specific details about current task - User wants to see action items or implementation notes - User needs to understand iteration goals **When to stay at dashboard level**: - User only wants high-level status - User asks "what's next" (dashboard shows this) - Quick progress checks **Pattern**: ``` Read .flow/phase-N/task-M.md ``` ### Step 4: Use Status Markers Understand progress through markers: - ✅ **COMPLETE** - Work finished and verified - 🚧 **IN PROGRESS** - Currently being worked on - ⏳ **PENDING** - Not started yet - 🎨 **READY** - Brainstorming complete, ready to implement - ❌ **CANCELLED** - Decided not to do this - 🔮 **FUTURE** - Deferred to later version ## Common Navigation Patterns ### Pattern 1: "What should I do next?" 1. Read DASHBOARD.md 2. Check "Current Work" section 3. If iteration is 🚧 IMPLEMENTING: "Continue working on [iteration name]" 4. If no active work: Check next ⏳ PENDING task/iteration ### Pattern 2: "Where are we in the plan?" 1. Read DASHBOARD.md 2. Count completed vs total tasks/iterations 3. Report: "Phase X in progress, Y/Z tasks complete" 4. Highlight current focus from "Current Work" ### Pattern 3: "Show me the current status" 1. Read DASHBOARD.md 2. Report from "Current Work" section 3. Show active iteration with status marker 4. List immediate next steps ### Pattern 4: "What's left to do?" 1. Read DASHBOARD.md "Progress Overview" 2. Count ⏳ PENDING items across all phases 3. Provide breakdown: "X tasks, Y iterations remaining" 4. Optionally list high-level task names ## Multi-File Architecture Flow projects use this structure: ``` .flow/ ├── DASHBOARD.md # Start here - high-level view ├── PLAN.md # Architecture, scope, decisions ├── phase-1/ │ ├── task-1.md # Detailed task breakdown │ ├── task-2.md │ └── task-3.md ├── phase-2/ │ └── task-1.md └── phase-3/ └── task-1.md ``` **Navigation hierarchy**: 1. DASHBOARD.md → Overview, current work, progress 2. PLAN.md → Architecture decisions, scope boundaries 3. phase-N/task-M.md → Detailed iterations, action items, implementation notes ## Read-Only Philosophy **This Skill is for navigation, not modification.** ✅ **DO**: - Read files to understand structure - Parse status markers - Report progress to user - Suggest next steps ❌ **DON'T**: - Modify DASHBOARD.md or task files - Update status markers - Add/remove tasks - Make architectural changes **When user wants changes**: Guide them to appropriate actions: - To start working on a task: Help them understand what task to begin - To begin iteration implementation: Verify they're ready (brainstorming complete) - To mark iteration done: Verify all work is complete first - Read-only skill: Cannot modify files, only show status and suggest next steps ## Examples ### Example 1: Quick Status Check ``` User: "What's next?" Response: 1. Read .flow/DASHBOARD.md 2. Parse "Current Work" section 3. Report: "You're on Phase 2, Task 3, Iteration 2 (Error Handling) 🚧 IN PROGRESS. Current focus: Implementing retry logic with exponential backoff. Next step: Complete this iteration, then move to Iteration 3 (Logging)." ``` ### Example 2: Progress Overview ``` User: "Show me where we are in the plan" Response: 1. Read .flow/DASHBOARD.md 2. Count completion: - Phase 1: ✅ COMPLETE (3/3 tasks) - Phase 2: 🚧 IN PROGRESS (1/4 tasks complete) - Phase 3: ⏳ PENDING 3. Report: "Phase 2 in progress. Completed 4 of 10 total iterations. Currently implementing: Task 3, Iteration 2 (Error Handling) Remaining work: 2 iterations in current task, then 3 more tasks in Phase 2, plus Phase 3." ``` ### Example 3: Lost User ``` User: "I'm confused, where am I?" Response: 1. Read .flow/DASHBOARD.md 2. Show clear location: "You're in the **Flow Framework Agent Skills** project. 📍 Current Location: - Phase: Phase 2 - Core Skills Implementation - Task: Task 1 - flow-navigator Skill - Iteration: Iteration 1 - SKILL.md creation 🚧 IMPLEMENTING What you're doing: Creating the navigation Skill file with dashboard-first instructions. Files you're working in: framework/skills/flow-navigator/SKILL.md" ``` ## Best Practices 1. **Always read DASHBOARD.md first** - Never skip straight to task files 2. **Respect status markers** - They're the source of truth for progress 3. **Stay high-level by default** - Only dive into details when asked 4. **Use exact marker symbols** - Don't paraphrase (✅ not "done", 🚧 not "working") 5. **Reference file paths** - Help user understand multi-file structure 6. **Suggest next actions** - Guide user on what to do next based on context ## References - **Dashboard-first approach**: Read DASHBOARD.md to understand current position - **Status markers**: DEVELOPMENT_FRAMEWORK.md lines 1872-1968 - **Multi-file architecture**: DEVELOPMENT_FRAMEWORK.md lines 105-179 - **Quick Reference Guide**: DEVELOPMENT_FRAMEWORK.md lines 1-353 SKILL_FLOW_NAVIGATOR_EOF } # 3. flow-planner (KEEP - no changes) get_skill_flow_planner() { cat <<'SKILL_FLOW_PLANNER_EOF' --- name: flow-planner description: Plan phases, tasks, and iterations. Use when structuring new work, adding features, or organizing development plans. --- # Flow Planner Help users plan and structure new work using Flow framework. Guide task structure decisions (standalone vs iterations) and suggest brainstorming for complex features. ## When to Use This Skill Activate when the user wants to add new work: - "Add a new task" - "Plan this feature" - "Create iterations for..." - "Break this down into steps" - "How should we structure this?" - "Add this to the plan" ## Planning Philosophy **Flow's Core Principle**: Plan before code. Structure work hierarchically (phases → tasks → iterations) with clear boundaries. **Key Decision**: Every task is EITHER: - **Standalone** - Direct action items, no iterations - **Task with Iterations** - No direct action items, ONLY iterations **NEVER mix both** - This is the Golden Rule. ## Task Structure Decision Tree ``` User wants to add work ↓ Is it complex/multi-step? ↓ YES → Task with Iterations Break into 3-5 iterations Each iteration = milestone ↓ NO → Standalone Task Direct action items Complete in one go ``` ## When to Suggest Brainstorming **Always suggest brainstorming for**: - Complex features with multiple approaches - Architectural decisions needed - Integration with external systems - Performance-critical features - Database schema changes - API contract design - Security-sensitive features **Skip brainstorming for**: - Simple additions (new file, basic function) - Well-defined tasks (clear requirements) - Repetitive work (similar to previous tasks) - Bug fixes with obvious solutions ## Brainstorming Subject Resolution Types When users DO need brainstorming, help them understand how subjects get resolved: ### Type A: Pre-Implementation Task **When**: Small blocking code change needed BEFORE iteration starts **Criteria**: Required for iteration (blocking), small scope (< 30 min), can be done independently **Examples**: Fix interface, rename file, update enum, fix bug **What happens**: Action items go into "Pre-Implementation Tasks" section, must complete BEFORE main implementation ### Type B: Immediate Documentation **When**: Architectural decision that affects system design **Criteria**: No code changes yet, updates PLAN.md Architecture section NOW **Examples**: Design pattern choice, API contract, data model **What happens**: AI updates PLAN.md immediately during brainstorming ### Type C: Auto-Resolved **When**: Subject answered by another subject's decision **Criteria**: No independent decision needed, cascade from another subject **What happens**: No action items, just note which subject resolved this ### Type D: Iteration Action Items **When**: Substantial feature work that IS the iteration **Criteria**: Main implementation work, takes significant time (> 30 min) **Examples**: Build API endpoint, implement validator, create service **What happens**: These action items become the iteration's implementation action items ## Complexity Indicators ### Simple Task (No Brainstorming) **Indicators**: Single file change, clear requirements, no integration points, < 1 hour, similar to previous work **Examples**: "Add validation function", "Fix typo", "Export function", "Add logging" **Guidance**: "This looks straightforward - standalone task with direct action items. No brainstorming needed." ### Complex Task (Needs Brainstorming) **Indicators**: Multiple approaches possible, affects architecture, integration needed, > 4 hours, user unsure **Examples**: "Add authentication", "Integrate Stripe", "Implement caching", "Design database" **Guidance**: "This is complex - I recommend brainstorming first. Let's discuss: [list 3-5 subjects]." ### Borderline Task (Ask User) **Indicators**: Moderate complexity (2-4 hours), some design decisions, user hasn't expressed preference **Examples**: "Add error handling to API", "Refactor data layer", "Implement search" **Guidance**: "This could go either way. We could brainstorm first, or jump into iterations if you have a clear vision. Which do you prefer?" ## Step-by-Step Planning Workflow ### Step 1: Understand the Request Ask clarifying questions: - "What's the goal of this feature?" - "Are there any constraints or requirements?" - "Does this build on existing work?" ### Step 2: Determine Complexity **Simple** → Standalone task **Complex** → Task with iterations **Uncertain** → Suggest brainstorming first ### Step 3: Propose Structure Present options to user: ``` I suggest structuring this as: **Option A: Standalone Task** - "Add Feature X" - Direct action items - Single completion - Estimated: 1-2 hours **Option B: Task with 3 Iterations** - Iteration 1: Basic implementation - Iteration 2: Add advanced features - Iteration 3: Polish and optimize - Estimated: 4-6 hours Which approach fits better? ``` ### Step 4: Create the Structure Read DASHBOARD.md to find current phase and task count, then create appropriate files: **For new phase**: Create `.flow/phase-N/` directory, update DASHBOARD.md with new phase entry **For new task**: Create `.flow/phase-N/task-M.md`, add to DASHBOARD.md progress overview **For new iteration**: Add iteration section to existing task file Use templates from [TEMPLATES.md](TEMPLATES.md) for proper structure. ### Step 5: Add Context Help user fill in: - **Purpose**: Why this task exists - **Dependencies**: What it requires/blocks - **Design Notes**: Key considerations - **Action Items**: Concrete steps (standalone) or iteration goals (with iterations) ## Starting Work (Phase/Task) ### Starting a Phase When user wants to begin work on a phase: 1. Read DASHBOARD.md to find the phase 2. Verify phase status is ⏳ PENDING (not already 🚧 IN PROGRESS) 3. Update DASHBOARD.md: - Change phase status from ⏳ PENDING to 🚧 IN PROGRESS - Update "Current Work" section to point to this phase 4. Report to user: "Phase N: [Name] is now in progress. Starting with Task 1." ### Starting a Task When user wants to begin work on a task: 1. Read DASHBOARD.md to find the task 2. Verify task status is ⏳ PENDING (not already 🚧 IN PROGRESS) 3. Update task file: - Change `**Status**: ⏳ PENDING` to `**Status**: 🚧 IN PROGRESS` 4. Update DASHBOARD.md: - Change task status marker from ⏳ to 🚧 - Update "Current Work" section to point to this task 5. Report to user: "Task N: [Name] is now in progress. [Guidance on first step]" ## Next Action Suggestions When user asks "what's next" or "what should I work on": ### If Nothing In Progress Read DASHBOARD.md to find next ⏳ PENDING item: - If current phase has pending tasks → "Start Task N: [Name]" - If current phase complete → "Start Phase N+1: [Name]" - If project complete → "All work complete! 🎉" ### If Work In Progress Read current work context: - If task has pending iterations → "Continue with Iteration N" - If iteration needs planning → "Add iterations to break down the work" - If unclear → "What aspect would you like to work on next?" ## Task Structure Patterns See [TEMPLATES.md](TEMPLATES.md) for complete templates: - **Standalone Task**: Direct action items, no iterations - **Task with Iterations**: Skeleton → Veins → Flesh pattern - **Task with Brainstorming**: Design decisions first, then implementation ## Best Practices 1. **Always clarify complexity** - Don't assume, ask user 2. **Suggest iterations for complex work** - Better to break down than have massive tasks 3. **Propose brainstorming when uncertain** - Design first, implement second 4. **Use Flow's metaphor** - Skeleton → Veins → Flesh 5. **Keep iterations focused** - Each should have clear goal and completion criteria ## Task Structure Golden Rules **DO**: - ✅ Standalone task with action items - ✅ Task with iterations (no direct action items) - ✅ Each iteration has specific goal - ✅ Iterations build on each other **DON'T**: - ❌ Mix action items and iterations in same task - ❌ Create task with only 1 iteration (make it standalone) - ❌ Make iterations too large (break down further) - ❌ Skip brainstorming for complex features ## Iteration Sizing Guidelines **Good Iteration Size**: - Completable in 1-2 hours - Clear completion criteria - Testable milestone - Adds incremental value **Too Large** (split into multiple iterations): - "Implement entire feature" - "Build and test everything" - No clear milestone **Too Small** (combine or make standalone): - "Add one line of code" - "Rename a variable" - Trivial changes ## Examples ### Example 1: User Asks to Add Feature ``` User: "I want to add real-time notifications" AI Process: 1. Assess complexity: Complex feature (WebSocket, multiple components) 2. Suggest structure: Task with 3 iterations 3. Propose brainstorming: Technology choice, message format, persistence 4. Create task file with iteration structure Structure Created: **Task: Real-Time Notifications** (3 iterations) **Iteration 1: Skeleton - WebSocket Connection** - Goal: Establish basic WebSocket connection - Set up WebSocket server, implement client connection, basic keepalive **Iteration 2: Veins - Notification System** - Goal: Core notification sending/receiving - Design message format, server-side broadcast, client-side handlers **Iteration 3: Flesh - UI & Polish** - Goal: User-facing notification display - Create UI component, add history, implement dismiss/mark-read Before Starting: Suggest brainstorming: WebSocket library choice (ws, socket.io, native)? Notification types? Persistence strategy? ``` ### Example 2: User Asks to Fix Bug ``` User: "The search filter isn't working correctly" AI Process: 1. Assess complexity: Simple bug fix (focused scope) 2. Suggest structure: Standalone task 3. Skip brainstorming: Clear requirements 4. Create task file with action items Task Created: **Task: Fix Search Filter Bug** **Action Items**: - [ ] Reproduce bug with test case - [ ] Debug filter logic - [ ] Identify root cause (likely query building) - [ ] Implement fix - [ ] Add unit test for this scenario - [ ] Verify fix resolves issue Estimated: 1-2 hours ``` ### Example 3: Guiding Brainstorming Subject Resolution ``` User: "Let's brainstorm the retry logic for API calls" AI Response: Great! Let me suggest subjects to discuss: Subjects: 1. Retry Strategy - Exponential backoff vs fixed delay? 2. Error Classification - Which errors trigger retry? 3. Max Retry Attempts - How many before giving up? 4. Existing Error Handler - Need to update ErrorHandler.ts for async? 5. Timeout Configuration - Per-request vs total operation? I'll help categorize each decision by resolution type (A/B/C/D). --- [After discussing Subject 4...] User: "We need to update ErrorHandler.ts to support async operations" AI Response: This is Type A (Pre-Implementation Task): ✅ Blocking? YES - Can't implement retry without async support ✅ Small? YES - Estimated 20-30 minutes ✅ Independent? YES - Self-contained change Resolution Type: A Action Items (Pre-Implementation): - [ ] Update ErrorHandler.ts to support async operations - [ ] Add retryAsync() method - [ ] Update 3 existing call sites - [ ] Add tests for async error handling Must complete BEFORE running implementation. --- [After discussing Subject 1...] User: "Let's use exponential backoff with base delay of 1 second" AI Response: This is Type D (Iteration Action Items): ✅ Substantial work? YES - Core feature implementation ✅ Takes > 30 min? YES - Estimated 2-3 hours ✅ Main iteration work? YES - This IS what we're building Resolution Type: D Action Items (Implementation): - [ ] Create RetryPolicy class - [ ] Implement exponential backoff algorithm (base: 1s, max: 32s) - [ ] Add configuration for max retries (default: 3) - [ ] Integrate with API client - [ ] Add tests for retry scenarios These become the iteration's implementation action items. ``` ## Files Read/Write **READ**: - `.flow/DASHBOARD.md` - Find current phase, count tasks, check structure - `.flow/phase-N/task-M.md` - Existing tasks (when adding iterations) **WRITE**: - `.flow/phase-N/` - Create new phase directories - `.flow/phase-N/task-M.md` - Create new task files, add iterations - `.flow/DASHBOARD.md` - Add tasks/phases to progress overview, update status ## Validation Gates - Before adding phase: Verify previous phase has at least one task - Before adding task: Verify phase directory exists - Before starting task/phase: Verify not already IN PROGRESS - Before adding iteration: Verify task file exists ## References - **Task Structure Rules**: [TEMPLATES.md](TEMPLATES.md) - Complete templates for all task types - **Framework Reference**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 238-566 (Task structure) - **Brainstorming Pattern**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1167-1797 SKILL_FLOW_PLANNER_EOF } get_skill_flow_planner_templates() { cat <<'SKILL_FLOW_PLANNER_TEMPLATES_EOF' # Flow Planning Templates Ready-to-use templates for creating phases, tasks, and iterations using Flow framework. Copy and customize these structures for your planning needs. ## Template 1: Standalone Task Use when: Simple, focused work that doesn't need breaking down ```markdown # Task [N]: [Task Name] **Status**: ⏳ PENDING **Phase**: [Phase [N] - [Phase Name]](../DASHBOARD.md#phase-[n]-[phase-name]) **Purpose**: [Brief description of what this task accomplishes] ## Overview [1-2 paragraphs explaining the task's context, why it's needed, and how it fits into the larger project] ## Action Items - [ ] [Concrete action step 1] - [ ] [Concrete action step 2] - [ ] [Concrete action step 3] - [ ] [Concrete action step 4] - [ ] [Concrete action step 5] ## Notes **Key Considerations**: - [Important point to remember] - [Trade-off or constraint] - [Dependency or prerequisite] **References**: - [Link to related documentation] - [Link to relevant framework section] ``` ### Example: Standalone Task ```markdown # Task 3: Add Request Logging **Status**: ⏳ PENDING **Phase**: [Phase 2 - Core Features](../DASHBOARD.md#phase-2-core-features) **Purpose**: Add structured logging for all HTTP requests to aid debugging ## Overview Currently, the application doesn't log HTTP requests, making it difficult to debug issues in production. This task adds middleware to log all incoming requests with relevant metadata (method, path, duration, status code). ## Action Items - [ ] Create logging middleware function - [ ] Add request ID generation - [ ] Log request start (method, path, headers) - [ ] Log request completion (status, duration) - [ ] Add middleware to express app - [ ] Test logging output format - [ ] Update documentation ## Notes **Key Considerations**: - Use structured logging (JSON format) - Don't log sensitive data (passwords, tokens) - Include correlation IDs for request tracing **References**: - Express middleware docs - Winston logging library ``` --- ## Template 2: Task with Iterations Use when: Complex, multi-step work that needs progressive refinement ```markdown # Task [N]: [Task Name] **Status**: ⏳ PENDING **Phase**: [Phase [N] - [Phase Name]](../DASHBOARD.md#phase-[n]-[phase-name]) **Purpose**: [Brief description of what this task accomplishes] ## Overview [1-2 paragraphs explaining the task's context, complexity, and why it's broken into iterations] ## Iterations ### ⏳ Iteration 1: [Skeleton] - [Minimal version] **Goal**: [What minimal functionality this iteration delivers] **Status**: ⏳ PENDING #### Action Items - [ ] [Core action 1] - [ ] [Core action 2] - [ ] [Core action 3] ### ⏳ Iteration 2: [Veins] - [Core functionality] **Goal**: [What essential features this iteration adds] **Status**: ⏳ PENDING #### Action Items - [ ] [Essential feature 1] - [ ] [Essential feature 2] - [ ] [Essential feature 3] ### ⏳ Iteration 3: [Flesh] - [Polish and edge cases] **Goal**: [What production-ready features this iteration completes] **Status**: ⏳ PENDING #### Action Items - [ ] [Polish item 1] - [ ] [Edge case handling 1] - [ ] [Final touches 1] ## Notes **Task Structure**: - This task follows Flow's iterative pattern: Skeleton → Veins → Flesh - Each iteration is independently testable and adds value - No direct action items in task - only in iterations **Dependencies**: - [Prerequisite work that must be complete] - [Related tasks that affect this one] **References**: - [Link to related documentation] - [Link to framework patterns] ``` ### Example: Task with Iterations ```markdown # Task 2: User Authentication System **Status**: ⏳ PENDING **Phase**: [Phase 1 - Foundation](../DASHBOARD.md#phase-1-foundation) **Purpose**: Implement secure user authentication with JWT tokens ## Overview The application needs a complete authentication system supporting user registration, login, logout, and token-based session management. This is complex enough to warrant iterative development, building from basic login to full production-ready auth. ## Iterations ### ⏳ Iteration 1: Skeleton - Basic Login/Logout **Goal**: Minimal working login/logout with password hashing **Status**: ⏳ PENDING #### Action Items - [ ] Create User model with password field - [ ] Implement password hashing (bcrypt) - [ ] Create POST /login endpoint - [ ] Create POST /logout endpoint - [ ] Add basic session storage - [ ] Test login/logout flow ### ⏳ Iteration 2: Veins - JWT Tokens & Auth Middleware **Goal**: Secure token-based authentication for protected routes **Status**: ⏳ PENDING #### Action Items - [ ] Generate JWT tokens on login - [ ] Create auth middleware to verify tokens - [ ] Add token to response headers - [ ] Implement token refresh logic - [ ] Add protected route examples - [ ] Test token validation ### ⏳ Iteration 3: Flesh - Registration & Password Reset **Goal**: Complete auth system with all user flows **Status**: ⏳ PENDING #### Action Items - [ ] Create POST /register endpoint - [ ] Add email verification flow - [ ] Implement forgot-password endpoint - [ ] Create password reset token system - [ ] Add rate limiting to auth endpoints - [ ] Test complete user lifecycle ## Notes **Task Structure**: - Skeleton: Get basic auth working - Veins: Add security and token management - Flesh: Polish with registration and recovery flows **Dependencies**: - Database schema must be set up - Email service configured (for Iteration 3) **References**: - JWT library: jsonwebtoken - DEVELOPMENT_FRAMEWORK.md lines 567-613 ``` --- ## Template 3: Individual Iteration Use when: Adding a new iteration to an existing task ```markdown ### ⏳ Iteration [N]: [Iteration Name] **Goal**: [Clear, specific goal this iteration achieves] **Status**: ⏳ PENDING #### Action Items - [ ] [Action step 1] - [ ] [Action step 2] - [ ] [Action step 3] - [ ] [Action step 4] - [ ] [Action step 5] #### Design Notes **Approach**: [Brief explanation of the implementation approach] **Key Decisions**: - [Important decision 1 and rationale] - [Important decision 2 and rationale] **Testing**: [How to verify this iteration works] ``` ### Example: Individual Iteration ```markdown ### ⏳ Iteration 4: Add Redis Caching **Goal**: Reduce database load by caching frequently accessed data **Status**: ⏳ PENDING #### Action Items - [ ] Set up Redis client connection - [ ] Identify cacheable queries (user profiles, product listings) - [ ] Implement cache-aside pattern - [ ] Add cache invalidation on updates - [ ] Set appropriate TTLs for different data types - [ ] Add cache hit/miss metrics - [ ] Test cache behavior under load #### Design Notes **Approach**: Use cache-aside pattern where application checks cache first, then falls back to database. Invalidate cache entries on write operations. **Key Decisions**: - TTL: 5 minutes for user profiles, 1 hour for product listings - Cache key format: `{resource}:{id}` (e.g., `user:123`) - Invalidation: Delete on update, let expire on delete **Testing**: - Verify cache hits reduce DB queries - Confirm stale data doesn't persist after updates - Load test with Redis enabled vs disabled ``` --- ## Template 4: Task with Brainstorming Use when: Complex decisions need discussion before implementation ```markdown # Task [N]: [Task Name] **Status**: ⏳ PENDING **Phase**: [Phase [N] - [Phase Name]](../DASHBOARD.md#phase-[n]-[phase-name]) **Purpose**: [Brief description] ## Overview [Explanation of task and why it needs design discussion] ## Iterations ### ⏳ Iteration 1: Design [Core System] **Goal**: Make key architectural decisions **Status**: ⏳ PENDING #### Brainstorming Session **Subjects to Discuss**: 1. ⏳ **[Subject 1]** - [Key question to decide] 2. ⏳ **[Subject 2]** - [Trade-off to evaluate] 3. ⏳ **[Subject 3]** - [Approach to determine] **Resolved Subjects**: [Will be filled during `/flow-brainstorm-start`] ### ⏳ Iteration 2: Implement [Core] **Goal**: Build based on design decisions **Status**: ⏳ PENDING #### Action Items - [ ] [Implementation step 1] - [ ] [Implementation step 2] - [ ] [Implementation step 3] ### ⏳ Iteration 3: [Additional Features] **Goal**: [Next increment] **Status**: ⏳ PENDING ## Notes **Why Brainstorming First**: - [Reason brainstorming is valuable] - [What decisions need discussion] ``` ### Example: Task with Brainstorming ```markdown # Task 1: Database Schema Design **Status**: ⏳ PENDING **Phase**: [Phase 1 - Foundation](../DASHBOARD.md#phase-1-foundation) **Purpose**: Design normalized database schema supporting all product requirements ## Overview The database schema is foundational - poor choices here create technical debt. We need to discuss relationships, indexing strategy, and migration approach before implementation. ## Iterations ### ⏳ Iteration 1: Design Schema Structure **Goal**: Finalize table structure, relationships, and indexing **Status**: ⏳ PENDING #### Brainstorming Session **Subjects to Discuss**: 1. ⏳ **User-Product Relationship** - One-to-many or many-to-many with junction table? 2. ⏳ **Indexing Strategy** - Which columns to index? Composite indexes needed? 3. ⏳ **Soft Deletes** - Use soft deletes (deleted_at) or hard deletes? 4. ⏳ **Timestamps** - What audit fields (created_at, updated_at, created_by)? 5. ⏳ **Migration Approach** - How to handle schema changes in production? **Resolved Subjects**: [Will be filled during brainstorming] ### ⏳ Iteration 2: Create Initial Migration **Goal**: Implement decided schema in SQL migration **Status**: ⏳ PENDING #### Action Items - [ ] Write SQL migration file - [ ] Create database models (ORM) - [ ] Add indexes per brainstorming decisions - [ ] Test migration up/down - [ ] Seed test data ### ⏳ Iteration 3: Add Constraints and Triggers **Goal**: Production-ready schema with validation **Status**: ⏳ PENDING #### Action Items - [ ] Add foreign key constraints - [ ] Create database triggers for audit fields - [ ] Add check constraints for data validation - [ ] Test constraint enforcement - [ ] Document schema design ## Notes **Why Brainstorming First**: - Schema changes are expensive once production data exists - Trade-offs between normalization and performance need discussion - Team alignment on conventions (soft deletes, audit fields) needed upfront ``` --- ## Template 5: Phase Structure Use when: Adding a new phase to the project ```markdown # Phase [N]: [Phase Name] **Goal**: [High-level goal this phase accomplishes] **Status**: ⏳ PENDING **Complexity**: [Simple / Medium / Complex] ## Overview [2-3 paragraphs explaining: - What this phase delivers - Why it's a distinct phase - How it relates to previous/next phases] ## Tasks 1. **Task 1**: [Task Name] - [Brief description] 2. **Task 2**: [Task Name] - [Brief description] 3. **Task 3**: [Task Name] - [Brief description] ## Success Criteria This phase is complete when: - [ ] [Measurable outcome 1] - [ ] [Measurable outcome 2] - [ ] [Measurable outcome 3] ## Dependencies **Requires** (must be done first): - [Prerequisite phase or work] **Blocks** (waiting on this): - [Dependent phases or work] ## Notes **Estimated Duration**: [Time estimate] **Risk Level**: [Low / Medium / High] **Key Challenges**: [Anticipated difficulties] ``` --- ## Usage Guidelines ### When to Use Each Template **Standalone Task**: - Bug fixes - Simple feature additions - Documentation updates - Configuration changes - Estimated < 2 hours **Task with Iterations**: - Complex features - System integrations - Architecture changes - New modules/services - Estimated > 2 hours **Task with Brainstorming**: - Architectural decisions - Multiple valid approaches - Performance-critical features - External integrations - Trade-offs need discussion ### Customization Tips 1. **Adjust iteration count** - Use 2-5 iterations based on complexity 2. **Add sections as needed** - Testing Strategy, Performance Notes, Security Considerations 3. **Reference framework docs** - Link to relevant DEVELOPMENT_FRAMEWORK.md sections 4. **Include examples** - Add code snippets or diagrams when helpful 5. **Keep action items atomic** - Each checkbox is a clear, completable step ### Common Mistakes to Avoid ❌ **DON'T**: Mix standalone and iteration patterns in same task ✅ **DO**: Choose one structure and stick with it ❌ **DON'T**: Create task with only 1 iteration ✅ **DO**: Make it standalone if there's only one phase ❌ **DON'T**: Have action items both in task AND in iterations ✅ **DO**: Action items only in iterations (for task-with-iterations pattern) ❌ **DON'T**: Make iterations too small (< 30 min) or too large (> 1 day) ✅ **DO**: Size iterations to 1-3 hours of focused work ## References - **Task Structure Rules**: DEVELOPMENT_FRAMEWORK.md lines 238-566 - **Brainstorming Patterns**: DEVELOPMENT_FRAMEWORK.md lines 1167-1797 - **Complete Workflow**: DEVELOPMENT_FRAMEWORK.md lines 614-940 - **Status Markers Guide**: DEVELOPMENT_FRAMEWORK.md lines 1872-1968 SKILL_FLOW_PLANNER_TEMPLATES_EOF } # 4. flow-designer (NEW - replaces flow-architect) get_skill_flow_designer() { cat <<'SKILL_FLOW_DESIGNER_EOF' --- name: flow-designer description: Design features through brainstorming and make architectural decisions. Use when user wants to brainstorm, design approach, make architecture choices, or update PLAN.md. --- # Flow Designer Help users design features through structured brainstorming sessions and make architectural decisions that shape the project. ## When to Use This Skill Activate when the user wants to design or brainstorm: - "Let's brainstorm this" - "Design the approach" - "How should we architect this?" - "What's the best way to implement this?" - "Should we use [technology]?" - "Update architecture documentation" - "Add a DO/DON'T rule" ## Design Philosophy **Flow's Core Principle**: Design before implementation. Use structured brainstorming to explore options, make decisions, and document rationale before writing code. **Brainstorming Structure**: - **Subjects**: Questions or decisions to resolve - **Resolution Types**: How each subject gets resolved (A/B/C/D) - **Outcomes**: Pre-tasks (Type A), documentation (Type B), or action items (Type D) ## Brainstorming Workflow ### Step 1: Start Brainstorming When user wants to brainstorm an iteration: 1. Read DASHBOARD.md to find current iteration 2. Read task file to check if brainstorming section exists 3. If doesn't exist, create: ```markdown #### Brainstorming **Status**: 🚧 IN PROGRESS **Subjects to Discuss**: 1. ⏳ [Subject Name] - [Question or decision] 2. ⏳ [Subject Name] - [Question or decision] ``` 4. Prompt user for initial subjects if not provided 5. Add subjects as ⏳ PENDING items ### Step 2: Add Subjects When user wants to add a new subject: 1. Find brainstorming section in current iteration 2. Add to "Subjects to Discuss" list: ```markdown N. ⏳ Subject Name - Description ``` 3. Keep list organized (unresolved at top) ### Step 3: Discuss and Resolve Subjects When user asks "what's next subject" or wants to discuss: 1. Find next ⏳ PENDING or 🚧 IN PROGRESS subject 2. Display subject for discussion 3. After user discusses, help determine resolution type (see [RESOLUTION_TYPES.md](RESOLUTION_TYPES.md)) 4. Create subject section with resolution: ```markdown ##### Subject N: [Name] **Status**: ✅ RESOLVED (2025-MM-DD) **Question**: [What needed to be decided] **Decision**: [What was decided and why] **Resolution Type**: [A/B/C/D] **Action Items** (if Type A or D): - [ ] [Item 1] - [ ] [Item 2] ``` 5. Update subject status in list: ⏳ → ✅ 6. If Type B, update PLAN.md immediately (see [PLAN_UPDATES.md](PLAN_UPDATES.md)) ### Step 4: Review Brainstorming When user asks "review brainstorming" or wants to check progress: 1. List all ✅ RESOLVED subjects 2. Show resolution types breakdown: - Type A subjects → Pre-Implementation Tasks - Type B subjects → PLAN.md updates (already done) - Type C subjects → Auto-resolved - Type D subjects → Main action items 3. Calculate: Resolved vs Total subjects 4. Suggest completing if all resolved ### Step 5: Complete Brainstorming When user says "complete brainstorming" or ready to finish: 1. **Verify**: All subjects have ✅ RESOLVED status 2. **Collect Type A subjects** → Create "Pre-Implementation Tasks" section: ```markdown #### Pre-Implementation Tasks **Status**: ⏳ PENDING These must be completed BEFORE starting main implementation: - [ ] [Pre-task from Subject N] - [ ] [Pre-task from Subject M] ``` 3. **Collect Type D subjects** → Add to iteration's "Action Items": ```markdown #### Action Items - [ ] [Main work from Subject X] - [ ] [Main work from Subject Y] ``` 4. **Update brainstorming status**: `**Status**: ✅ COMPLETE (2025-MM-DD)` 5. **Set iteration status**: - If pre-tasks exist: `**Status**: ⏳ PENDING` (must do pre-tasks first) - If no pre-tasks: `**Status**: 🎨 READY` (ready to implement) 6. Report to user what's next ## Subject Resolution Types See [RESOLUTION_TYPES.md](RESOLUTION_TYPES.md) for detailed explanation. Quick reference: ### Type A: Pre-Implementation Task **When**: Small blocking code change needed BEFORE iteration starts **Criteria**: - Required for iteration (blocking) - Small scope (< 30 min) - Can be done independently **Examples**: Fix interface, rename file, update enum **Outcome**: Goes into "Pre-Implementation Tasks" section, must complete before main work ### Type B: Immediate Documentation **When**: Architectural decision affecting system design **Criteria**: - No code changes yet - Updates PLAN.md Architecture section NOW - High-level design decision **Examples**: Design pattern choice, API contract, data model **Outcome**: Update PLAN.md immediately during brainstorming (see [PLAN_UPDATES.md](PLAN_UPDATES.md)) ### Type C: Auto-Resolved **When**: Subject answered by another subject's decision **Criteria**: - No independent decision needed - Cascade from another subject **Examples**: Implementation detail determined by architecture choice **Outcome**: No action items, just note which subject resolved this ### Type D: Iteration Action Items **When**: Substantial feature work that IS the iteration **Criteria**: - Main implementation work - Takes significant time (> 30 min) **Examples**: Build API endpoint, implement validator, create service **Outcome**: These become the iteration's implementation action items ## Architecture Decision Making When brainstorming reveals architectural decisions (Type B), update PLAN.md: ### When to Update PLAN.md **Always update for**: - Technology choices (libraries, frameworks, tools) - Design patterns adopted - System architecture changes - API contracts or interfaces - Data model decisions - DO/DON'T guidelines that emerge **Don't update for**: - Implementation details (those go in task notes) - Temporary decisions (those stay in brainstorming) - Personal preferences (only team-wide guidelines) ### How to Update PLAN.md See [PLAN_UPDATES.md](PLAN_UPDATES.md) for detailed patterns. Quick guide: **Architecture Section Update**: ```markdown ### [Component/Feature Name] **Decision**: [What was decided] **Rationale**: [Why this approach] **Trade-offs**: - **Chosen**: [Approach X] because [reason] - **Not chosen**: [Approach Y] because [reason] ``` **DO/DON'T Guidelines**: ```markdown **DO**: - [Guideline from experience] **DON'T**: - [Anti-pattern to avoid] ``` ## Subject Discussion Guidance ### Asking the Right Questions Help users explore decisions: - "What are the options?" - "What are the trade-offs?" - "What are the constraints?" - "What's the impact if we choose wrong?" - "Is this decision reversible?" ### Recommending Resolution Types **Recommend Type A if**: - User says "we need to fix [X] first" - Small blocking change mentioned - Quick prerequisite work identified **Recommend Type B if**: - Major architectural decision - Technology choice discussion - System-wide pattern emerging - User asks "how should we architect" **Recommend Type C if**: - Subject is consequence of another decision - No independent choice to make - Answer is implied by previous subjects **Recommend Type D if**: - Main feature work described - Core implementation discussed - User describes "what we're building" ## Examples ### Example 1: Complete Brainstorming Session ``` User: "Let's brainstorm the retry logic for API calls" AI Process: 1. Find current iteration in task file 2. Create brainstorming section with status 🚧 IN PROGRESS 3. Suggest initial subjects: - Retry Strategy (exponential backoff vs fixed delay) - Error Classification (which errors retry) - Max Retry Attempts (how many before giving up) - Existing Error Handler (need async support) - Timeout Configuration (per-request vs total) User provides input, AI adds subjects to list as ⏳ PENDING --- User: "What's the next subject?" AI Response: Subject 1: Retry Strategy Let's discuss - what are the options? - Exponential backoff (1s, 2s, 4s, 8s...) - Fixed delay (1s between each retry) - Linear backoff (1s, 2s, 3s, 4s...) Which approach fits your needs? User: "Exponential backoff with base delay 1 second" AI Response: This is Type D (Iteration Action Items) - the main feature work. Creating resolution: **Resolution Type**: D **Action Items**: - [ ] Create RetryPolicy class - [ ] Implement exponential backoff algorithm (base: 1s, max: 32s) - [ ] Add configuration for max retries (default: 3) - [ ] Integrate with API client - [ ] Add tests for retry scenarios Marked Subject 1 as ✅ RESOLVED. Next subject? --- User: "Subject about error handler needing async support" AI Response: Subject 4: Existing Error Handler - Need Async Support This sounds like a blocking prerequisite. Let me confirm: ✅ Is it blocking? YES - can't implement retry without async ✅ Is it small? YES - estimated 20-30 minutes ✅ Can be done independently? YES This is Type A (Pre-Implementation Task). **Resolution Type**: A **Action Items**: - [ ] Update ErrorHandler.ts to support async operations - [ ] Add retryAsync() method - [ ] Update 3 existing call sites - [ ] Add tests for async error handling This will go into "Pre-Implementation Tasks" - must complete BEFORE main implementation. --- After all subjects resolved... User: "Complete brainstorming" AI Process: 1. Verify all 5 subjects ✅ RESOLVED 2. Collect Type A subjects: - Subject 4 action items → Pre-Implementation Tasks section 3. Collect Type D subjects: - Subject 1, 2, 3, 5 action items → Iteration Action Items 4. Mark brainstorming ✅ COMPLETE (2025-10-20) 5. Set iteration status: ⏳ PENDING (pre-tasks exist) AI Response: ✅ Brainstorming complete! **Pre-Implementation Tasks** (4 items): Must complete these BEFORE starting main implementation. **Iteration Action Items** (12 items): Main retry logic implementation. **Next Steps**: 1. Complete pre-implementation tasks first 2. Then run implementation on this iteration Iteration is now ⏳ PENDING (will be 🎨 READY after pre-tasks done). ``` ### Example 2: Architecture Decision (Type B) ``` User: "Should we use REST or GraphQL for our API?" AI Response: This is a major architectural decision. Let's brainstorm: **Subject**: API Technology Choice **Options**: - REST: Simple, well-understood, stateless - GraphQL: Flexible queries, reduces over-fetching What are your requirements? (data complexity, client needs, team experience) User: "Team knows REST well, simple CRUD operations, mobile app needs specific fields" AI Response: Based on your context: - Team experience: REST ✅ - Use case: CRUD operations fit REST - Mobile optimization: Could benefit from GraphQL, but REST + field selection achievable **Recommendation**: REST with field selection query params This is Type B (Immediate Documentation) - architectural decision. **Resolution Type**: B I'm updating PLAN.md Architecture section now: **PLAN.md Update**: ```markdown ### API Architecture **Decision**: RESTful API with field selection via query parameters **Rationale**: - Team has strong REST experience (faster development) - CRUD operations map naturally to REST resources - Field selection (`?fields=name,email`) addresses mobile bandwidth concerns - Simpler stack (no GraphQL server/client overhead) **Trade-offs**: - **Chosen**: REST + field selection - Pros: Simpler, team-ready, adequate for needs - Cons: Less flexible than GraphQL for complex queries - **Not chosen**: GraphQL - Pros: Perfect field selection, great for evolving requirements - Cons: Learning curve, additional infrastructure **DO**: - Use field selection query params for bandwidth optimization - Follow RESTful resource naming conventions - Version API endpoints (/v1/users) **DON'T**: - Return full objects when mobile clients need subsets - Create custom endpoint for every use case (use field selection) ``` ✅ PLAN.md updated. Subject marked ✅ RESOLVED. ``` ### Example 3: Auto-Resolved Subject (Type C) ``` User: "What about the retry delay calculation?" AI Response: Subject 5: Retry Delay Calculation Looking at previous decisions... This was answered by Subject 1 (Retry Strategy): - You chose exponential backoff with base 1s - Formula: delay = base_delay * (2 ^ attempt_number) - Max delay: 32s **Resolution Type**: C (Auto-Resolved by Subject 1) No additional action needed - implementation in Subject 1 covers this. Subject marked ✅ RESOLVED. ``` ## Files Read/Write **READ**: - `.flow/DASHBOARD.md` - Find current work (which iteration to brainstorm) - `.flow/phase-N/task-M.md` - Current iteration, existing brainstorming - `.flow/PLAN.md` - Current architecture, DO/DON'T guidelines **WRITE**: - `.flow/phase-N/task-M.md` - Add/update brainstorming section, subjects, resolutions - `.flow/PLAN.md` - Update Architecture section, DO/DON'T guidelines, Technology Choices ## Validation Gates - Before starting: Verify iteration exists in task file - Before completing: Verify all subjects have ✅ RESOLVED status - Before marking iteration READY: Verify no pending pre-tasks (or mark PENDING if pre-tasks exist) - After Type B resolution: Verify PLAN.md updated correctly ## References - **Subject Resolution Types**: [RESOLUTION_TYPES.md](RESOLUTION_TYPES.md) - Detailed guide on A/B/C/D types - **PLAN.md Updates**: [PLAN_UPDATES.md](PLAN_UPDATES.md) - How to update architecture documentation - **Brainstorming Pattern**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1167-1797 - **Framework Reference**: .flow/framework/DEVELOPMENT_FRAMEWORK.md lines 1-353 SKILL_FLOW_DESIGNER_EOF } get_skill_flow_designer_resolution_types() { cat <<'SKILL_FLOW_DESIGNER_RESOLUTION_EOF' # Subject Resolution Types Deep dive on the four types of brainstorming subject resolutions (A/B/C/D). ## Overview When brainstorming, each subject must be resolved with one of four types. The type determines what happens next with the decision. | Type | Name | Outcome | Timing | |------|------|---------|--------| | A | Pre-Implementation Task | Small blocking work BEFORE iteration | Done before main implementation | | B | Immediate Documentation | Update PLAN.md NOW | Done during brainstorming | | C | Auto-Resolved | No action (answered by another subject) | Already resolved | | D | Iteration Action Items | Main feature work | Done during implementation | ## Type A: Pre-Implementation Task ### Definition Small blocking code changes that must be done BEFORE the iteration's main implementation can start. ### Criteria (All 3 must be true) ✅ **Required for iteration** (blocking) - Cannot start main work without this - Main implementation depends on this being done ✅ **Small scope** (< 30 min) - Quick change, not a full feature - Typically affects 1-3 files ✅ **Can be done independently** - Self-contained change - Doesn't require the full iteration context ### Examples **Example 1: Type Definition Update** ```markdown Subject: Payment Status Enum **Question**: Need to add new payment states for retry logic? **Decision**: Add PENDING_RETRY and FAILED_PERMANENT to PaymentStatus enum **Resolution Type**: A (Pre-Implementation Task) **Why Type A**: - ✅ Blocking: Retry logic needs these states to function - ✅ Small: 5-minute change (update enum, 4 switch statements) - ✅ Independent: Can update enum without retry implementation **Action Items**: - [ ] Update PaymentStatus enum in types.ts - [ ] Add PENDING_RETRY and FAILED_PERMANENT - [ ] Update 4 switch statements to handle new states - [ ] Add tests for new states ``` **Example 2: Interface Fix** ```markdown Subject: API Client Interface **Question**: Current APIClient doesn't support async retry callbacks? **Decision**: Add async callback support to APIClient interface **Resolution Type**: A (Pre-Implementation Task) **Why Type A**: - ✅ Blocking: Retry logic requires async callback support - ✅ Small: 15-minute change (update interface, 2 implementations) - ✅ Independent: Interface change doesn't require retry implementation **Action Items**: - [ ] Update APIClient interface with async callback support - [ ] Update HttpClient implementation - [ ] Update MockClient implementation for tests ``` ### What Goes into Pre-Implementation Tasks Section ```markdown #### Pre-Implementation Tasks **Status**: ⏳ PENDING These must be completed BEFORE starting main implementation: - [ ] Update PaymentStatus enum (Subject 2) - [ ] Add async callback support to APIClient (Subject 4) - [ ] Rename ErrorHandler to AsyncErrorHandler (Subject 7) **Estimated Time**: 30-45 minutes total ``` ### Workflow 1. During brainstorming, identify Type A subjects 2. When brainstorming completes, collect all Type A action items 3. Create "Pre-Implementation Tasks" section 4. Mark iteration status: ⏳ PENDING 5. Complete ALL pre-tasks 6. Mark pre-tasks section: ✅ COMPLETE 7. Update iteration status: 🎨 READY 8. THEN start main implementation ## Type B: Immediate Documentation ### Definition Architectural decisions that shape the system design. These get documented in PLAN.md IMMEDIATELY during brainstorming, not during implementation. ### Criteria (Any 2 or more) ✅ **System-wide impact** - Affects multiple features or components - Sets precedent for future work ✅ **Technology choice** - Picking libraries, frameworks, tools - Choosing between approaches (REST vs GraphQL) ✅ **Design pattern adoption** - Architectural pattern (MVC, Event-Driven, etc.) - Code organization approach ✅ **High-level abstraction** - API contracts, interfaces - Data models, database schema - System boundaries ### Examples **Example 1: Technology Choice** ```markdown Subject: Retry Library vs Custom Implementation **Question**: Use existing retry library or build custom? **Decision**: Build custom RetryPolicy class **Rationale**: - Existing libraries (retry, async-retry) too generic - Need tight integration with error classification - Want exponential backoff with custom jitter - Library overhead not justified for our simple needs **Resolution Type**: B (Immediate Documentation) **PLAN.md Update** (done NOW): ```markdown ### Retry Mechanism **Decision**: Custom RetryPolicy class (not external library) **Rationale**: - Tight integration with error classification system - Custom exponential backoff with jitter - Simpler than adding library dependency for basic needs **Trade-offs**: - **Chosen**: Custom implementation - Pros: Full control, simple, no dependencies - Cons: We maintain the code - **Not chosen**: retry library - Pros: Battle-tested, feature-rich - Cons: Generic (not tailored to our needs), overhead **DO**: - Use exponential backoff for transient errors - Add jitter to prevent thundering herd - Make retry config injectable for testing **DON'T**: - Retry on permanent failures (4xx errors except 429) - Retry infinitely (max 3 attempts) - Block other requests while retrying ``` ``` **Example 2: Data Model Decision** ```markdown Subject: User Session Storage **Question**: Store sessions in memory, Redis, or database? **Decision**: Redis for session storage **Rationale**: - Need fast session lookups (< 10ms) - Sessions expire (TTL built into Redis) - Horizontal scaling requires shared state - Database too slow for every request **Resolution Type**: B (Immediate Documentation) **PLAN.md Update** (done NOW): ```markdown ### Session Management **Decision**: Redis for session storage with 7-day TTL **Rationale**: - Sub-10ms lookups required for performance - Built-in TTL matches session expiry needs - Shared state enables horizontal scaling - Database (500ms avg) too slow for per-request lookups **Trade-offs**: - **Chosen**: Redis - Pros: Fast, TTL support, scalable - Cons: Additional infrastructure, volatile - **Not chosen**: Database - Pros: Durable, existing infrastructure - Cons: Too slow (500ms vs 5ms) - **Not chosen**: In-memory - Pros: Fastest, simple - Cons: Can't scale horizontally, lost on restart **DO**: - Set 7-day TTL on sessions - Use Redis cluster for high availability - Implement session refresh on activity **DON'T**: - Store sensitive data (only session tokens) - Use for permanent data (use database) - Assume sessions persist forever ``` ``` ### What to Update in PLAN.md See [PLAN_UPDATES.md](PLAN_UPDATES.md) for detailed templates. Key sections: 1. **Architecture Section** - Add decision with rationale 2. **DO/DON'T Guidelines** - Add patterns learned 3. **Technology Choices** - Document why chosen/not chosen 4. **Testing Strategy** - If testing approach decided ### Workflow 1. During brainstorming, user makes architectural decision 2. Identify as Type B (architectural impact) 3. **Immediately** read PLAN.md 4. Update appropriate section with decision + rationale 5. Mark subject ✅ RESOLVED (with PLAN.md reference) 6. Continue with next subject **Key**: Type B happens DURING brainstorming, not later! ## Type C: Auto-Resolved ### Definition Subjects that are answered by another subject's decision. No independent decision needed - the answer is implied. ### Criteria ✅ **No independent decision** - Answer determined by previous subject - Consequence of another choice ✅ **Cascade relationship** - "If we chose X, then Y must be Z" - Implementation detail flowing from architecture choice ### Examples **Example 1: Implementation Detail** ```markdown Subject 1: Retry Strategy (Type D) **Decision**: Exponential backoff starting at 1 second --- Subject 5: Retry Delay Calculation (Type C) **Question**: How to calculate delay between retries? **Decision**: Use exponential formula from Subject 1 **Resolution Type**: C (Auto-Resolved by Subject 1) **Explanation**: Subject 1 decided exponential backoff with base 1s. Formula: `delay = 1s * (2 ^ attempt_number)` Max delay: 32s (after 5 attempts: 1s, 2s, 4s, 8s, 16s, 32s) No additional decision needed - implementation covered by Subject 1. ``` **Example 2: Consequential Choice** ```markdown Subject 2: Session Storage = Redis (Type B) **Decision**: Use Redis for session storage --- Subject 8: Session Serialization Format (Type C) **Question**: How to serialize session data? **Decision**: JSON (standard for Redis) **Resolution Type**: C (Auto-Resolved by Subject 2) **Explanation**: Subject 2 chose Redis for sessions. Redis stores strings, JSON is standard practice. No decision needed - follow Redis conventions. ``` ### What Happens ```markdown ##### Subject 5: Retry Delay Calculation **Status**: ✅ RESOLVED (Auto-Resolved by Subject 1) **Decision**: Exponential backoff formula from Subject 1 **Resolution Type**: C **No Action Items** (implementation covered by Subject 1) ``` ### Workflow 1. User asks about something that was already decided 2. AI recognizes cascade from previous subject 3. Mark as Type C and reference which subject resolved it 4. No action items needed 5. Move to next subject ## Type D: Iteration Action Items ### Definition The main feature work - substantial implementation that IS the iteration's purpose. This is the "meat" of what you're building. ### Criteria (Any 2 or more) ✅ **Substantial scope** (> 30 min, typically hours) - Core feature implementation - Multiple components affected ✅ **Main iteration goal** - This IS what the iteration is about - Central to the feature being built ✅ **Implementation-focused** - Actual coding work - Building the feature ### Examples **Example 1: Core Feature** ```markdown Subject: Retry Logic Implementation **Question**: How to implement the retry mechanism? **Decision**: Create RetryPolicy class with exponential backoff and error classification **Resolution Type**: D (Iteration Action Items) **Why Type D**: - ✅ Substantial: 3-4 hours of implementation - ✅ Main goal: This IS what "Add Retry Logic" iteration is about - ✅ Implementation: Core coding work **Action Items**: - [ ] Create RetryPolicy class with config (max attempts, base delay) - [ ] Implement exponential backoff algorithm with jitter - [ ] Integrate with ErrorClassifier to determine retryable errors - [ ] Add retry() method that wraps async operations - [ ] Implement circuit breaker pattern for repeated failures - [ ] Add RetryMetrics for monitoring (attempts, successes, failures) - [ ] Write unit tests for retry scenarios (success after N attempts, max retries exceeded) - [ ] Write integration tests with real API calls - [ ] Add logging for retry attempts and outcomes - [ ] Update API client to use RetryPolicy ``` **Example 2: Feature Implementation** ```markdown Subject: Webhook Delivery System **Question**: How to implement reliable webhook delivery? **Decision**: Queue-based delivery with retry and dead-letter queue **Resolution Type**: D (Iteration Action Items) **Why Type D**: - ✅ Substantial: Full feature, 6-8 hours - ✅ Main goal: Iteration is "Webhook Delivery" - ✅ Implementation: Complete system to build **Action Items**: - [ ] Create WebhookQueue class using BullMQ - [ ] Implement WebhookDelivery service with HTTP client - [ ] Add retry logic (3 attempts with exponential backoff) - [ ] Create dead-letter queue for failed deliveries - [ ] Add webhook signature generation (HMAC-SHA256) - [ ] Implement webhook event types (user.created, payment.succeeded, etc.) - [ ] Add webhook delivery status tracking (pending, delivered, failed) - [ ] Create admin API to view delivery status and retry manually - [ ] Write tests for delivery, retries, and failures - [ ] Add monitoring and alerts for delivery rate ``` ### What Goes into Iteration Action Items Section ```markdown #### Action Items - [ ] Create RetryPolicy class with config (Subject 1) - [ ] Implement exponential backoff algorithm (Subject 1) - [ ] Integrate with ErrorClassifier (Subject 1, Subject 3) - [ ] Add retry() method wrapping async operations (Subject 1) - [ ] Add RetryMetrics for monitoring (Subject 6) - [ ] Write unit tests for retry scenarios (Subject 1) - [ ] Write integration tests with real API (Subject 1) - [ ] Update API client to use RetryPolicy (Subject 1) ``` ### Workflow 1. During brainstorming, identify main feature work as Type D 2. When brainstorming completes, collect all Type D action items 3. Add to iteration's "Action Items" section 4. These become the implementation checklist 5. Execute during `/flow-implement-start` 6. Check off as completed 7. Verify all done before `/flow-implement-complete` ## Decision Flow chart ``` Is this a small blocking change needed first? ↓ YES → Type A (Pre-Implementation Task) ↓ NO ↓ Is this an architectural decision affecting system design? ↓ YES → Type B (Immediate Documentation) ↓ NO ↓ Is this already answered by another subject? ↓ YES → Type C (Auto-Resolved) ↓ NO ↓ Is this substantial implementation work (main goal)? ↓ YES → Type D (Iteration Action Items) ``` ## Common Mistakes ### ❌ Mistake 1: Confusing A and D **Wrong**: Marking "Update ErrorHandler" as Type D because it involves coding **Right**: It's Type A (small, blocking, independent prerequisite) **How to tell**: Ask "Is this blocking main work?" + "Can I do this in < 30 min?" ### ❌ Mistake 2: Not Using Type B **Wrong**: Keeping architectural decisions only in brainstorming notes **Right**: Document in PLAN.md immediately (Type B) **How to tell**: Ask "Will future developers need to know this?" + "Does it affect system design?" ### ❌ Mistake 3: Everything as Type D **Wrong**: Making every subject Type D with action items **Right**: Use A/B/C when appropriate **How to tell**: Not everything is main implementation work. Look for prerequisites (A), architecture (B), and cascades (C). ## Summary Table | Type | When | Outcome | Example | |------|------|---------|---------| | **A** | Small blocking prerequisite | Pre-Implementation Tasks section | Update enum before using it | | **B** | Architectural decision | PLAN.md updated immediately | Choose Redis for sessions | | **C** | Answered by another subject | No action (reference other subject) | Formula determined by strategy choice | | **D** | Main feature work | Iteration Action Items section | Build retry policy class | ## Examples in Context See SKILL.md Examples section for complete brainstorming sessions showing all four types in action. SKILL_FLOW_DESIGNER_RESOLUTION_EOF } get_skill_flow_designer_plan_updates() { cat <<'SKILL_FLOW_DESIGNER_PLAN_EOF' # PLAN.md Update Patterns This document provides best practices and patterns for updating PLAN.md during brainstorming sessions using Flow framework projects. Use this as a reference when documenting architectural decisions, DO/DON'T guidelines, technology choices, and scope boundaries. > **Note**: This is a Level 3 resource for the flow-architect Skill. See [SKILL.md](SKILL.md) for core architectural guidance. ## Table of Contents 1. [When to Update PLAN.md](#when-to-update-planmd) 2. [Architecture vs Scope](#architecture-vs-scope) 3. [DO/DON'T Guideline Examples](#dodont-guideline-examples) 4. [Technology Choice Documentation](#technology-choice-documentation) 5. [Keeping PLAN.md Focused](#keeping-planmd-focused) ## When to Update PLAN.md ### During Brainstorming (Type B Subjects) **Type B subjects** are resolved by updating PLAN.md documentation: - Architectural decisions finalized - Design patterns chosen - Technology/library selection complete - Scope boundaries clarified - DO/DON'T pattern discovered **Workflow**: 1. Discuss options during brainstorming 2. User makes final decision 3. Update PLAN.md with decision + rationale 4. Mark brainstorming subject as ✅ RESOLVED (Type B) **Example Subject**: ```markdown ### Subject 3: Choose Error Mapping Strategy **Status**: ✅ RESOLVED (Type B - Documentation) **Question**: How should we map Stripe errors to domain errors? **Decision**: Use dedicated ErrorMapper class with error code lookup table **Rationale**: - Centralizes error mapping logic - Easy to extend with new error codes - Testable in isolation - Keeps StripeClient focused **PLAN.md Updated**: - Added ErrorMapper to Architecture section (Component list) - Added "DO: Use ErrorMapper for all Stripe errors" guideline ``` ### Not During Implementation **DON'T update PLAN.md during implementation** for: - Bug fixes (document in iteration notes) - Implementation details (document in code comments) - Completed work (document in task files) - Discovered issues (document in implementation notes) **Exception**: If implementation reveals a pattern that should be followed consistently, note it for future brainstorming session to add to DO/DON'T guidelines. ## Architecture vs Scope ### Architecture Section: HOW the system works **Use Architecture section for**: - System structure (components, modules, layers) - Component responsibilities and boundaries - Data flow between components - Integration points (external services, APIs) - Design patterns being used - Key technical constraints **Example - Architecture Section**: ```markdown ## Architecture ### Component Structure **Core Modules**: - **PaymentProcessor** (Orchestrator) - Coordinates payment workflow - Handles transaction lifecycle - Delegates to specialized components - **StripeClient** (Integration Adapter) - Wraps Stripe SDK - Applies retry policy to all API calls - Maps Stripe responses to domain models - **ErrorMapper** (Error Translation) - Classifies errors (transient vs permanent) - Maps Stripe error codes to domain errors - Provides user-friendly error messages - **RetryPolicy** (Resilience) - Configurable exponential backoff - Jitter to prevent thundering herd - Different policies for different error types ### Data Flow ``` User Request ↓ PaymentProcessor.process() ↓ StripeClient.createCharge() → [RetryPolicy wraps call] ↓ Stripe API ↓ (success) Return Charge ID ↓ (failure - transient) RetryPolicy → exponential backoff → retry ↓ (failure - permanent) ErrorMapper → domain error → return to user ``` ### Integration Points **External Services**: - Stripe API v2024-10 (payment processing) - Rate limit: 100 req/sec - Retry-after header respected - Webhook for async updates **Database**: - Transaction log (PostgreSQL) - Payment attempts (for audit) - Retry history (for analytics) ``` ### Scope Section: WHAT is included **Use Scope section for**: - Features included in V1 - Features deferred to V2/V3 - Explicit exclusions - Business constraints - Performance requirements - Platform limitations **Example - Scope Section**: ```markdown ## Scope ### V1 - MVP (Current Release) **In Scope**: - Credit card payments (Visa, Mastercard, Amex) - Basic retry for transient failures - Error classification (permanent vs transient) - Transaction logging for audit - Synchronous payment flow **Out of Scope** (defer to V2): - Refund processing: Not needed for launch - Subscription billing: Future business model - Multi-currency support: US market only for V1 - Webhook processing: Will add with async flow - Saved payment methods: V2 feature **Constraints**: - Stripe API v2024-10 required - TypeScript 5.x (project standard) - Response time < 3 seconds (includes retries) - Must handle 100 payments/sec **Platform Limitations**: - Stripe test mode: 100 req/hour (not a production issue) - No 3D Secure in V1 (adds complexity, defer to V2) ``` ### Quick Decision Tree ``` Need to document decision ↓ Does it explain HOW the system is structured? ↓ YES → Architecture section - Components - Data flow - Patterns - Integration points ↓ NO → Does it define WHAT is included/excluded? ↓ YES → Scope section - V1 features - V2 deferred - Constraints - Limitations ``` ## DO/DON'T Guideline Examples ### Example 1: API Integration Pattern ```markdown ### DO: Use RetryPolicy for all external API calls **Rationale**: External APIs have transient failures (network issues, rate limits, temporary unavailability). Retry logic with exponential backoff provides resilience without user-facing errors. **Pattern**: ```typescript // Good: Wrapped with retry policy const result = await retryPolicy.execute(async () => { return await externalApi.call(params); }); ``` **Anti-pattern**: ```typescript // Bad: Direct call without retry const result = await externalApi.call(params); // Fails on transient errors ``` **When to Apply**: - All calls to Stripe API - All calls to third-party services - Any network request that can fail transiently **Exceptions**: - Internal service calls (use different error handling) - Database queries (use transaction retry instead) ``` ### Example 2: Error Handling Constraint ```markdown ### DON'T: Retry permanent failures **Rationale**: Permanent failures (invalid input, insufficient funds, authorization denied) will never succeed no matter how many times you retry. Retrying wastes resources and delays error feedback to users. **Impact**: - User waits longer for error message - Unnecessary load on payment provider - Risk of hitting rate limits - Wasted compute resources **How to Identify Permanent Failures**: ```typescript // Use ErrorMapper to classify const error = errorMapper.map(stripeError); if (error.type === 'permanent') { // Don't retry - return error immediately throw error; } if (error.type === 'transient') { // Safe to retry await retryPolicy.execute(() => operation()); } ``` **Permanent Error Codes** (Stripe): - `card_declined` - Card issuer rejected - `insufficient_funds` - Not enough money - `invalid_card` - Card details invalid - `expired_card` - Card past expiration ``` ### Example 3: Configuration Management ```markdown ### DO: Make retry policies configurable per environment **Rationale**: Different environments have different performance characteristics and requirements. Test environments need faster retries for quick feedback. Production needs conservative retries to handle real failures. **Configuration**: ```typescript // config/retry.ts export const retryConfig = { development: { maxRetries: 2, baseDelay: 100, // 100ms maxDelay: 1000, // 1 second }, test: { maxRetries: 1, baseDelay: 10, // 10ms (fast tests) maxDelay: 100, }, production: { maxRetries: 5, baseDelay: 1000, // 1 second maxDelay: 32000, // 32 seconds }, }; ``` **Usage**: ```typescript const policy = new RetryPolicy(retryConfig[process.env.NODE_ENV]); ``` ``` ### Example 4: Testing Pattern ```markdown ### DO: Test error scenarios with mocks **Rationale**: External API failures are hard to reproduce in tests. Use mocks to simulate transient failures, permanent failures, and edge cases consistently. **Pattern**: ```typescript describe('PaymentProcessor with retries', () => { it('should retry on transient failure', async () => { // Mock: fail twice, then succeed const mockStripe = jest.fn() .mockRejectedValueOnce(new TransientError('rate_limit')) .mockRejectedValueOnce(new TransientError('network_error')) .mockResolvedValueOnce({ id: 'ch_123', status: 'succeeded' }); const result = await processor.process(payment); expect(mockStripe).toHaveBeenCalledTimes(3); // 2 retries + success expect(result.status).toBe('succeeded'); }); it('should not retry on permanent failure', async () => { const mockStripe = jest.fn() .mockRejectedValueOnce(new PermanentError('card_declined')); await expect(processor.process(payment)).rejects.toThrow('card_declined'); expect(mockStripe).toHaveBeenCalledTimes(1); // No retries }); }); ``` ``` ## Technology Choice Documentation ### Template ```markdown ### [Component/Feature]: [Technology/Pattern] **Decision**: Using [specific technology] for [purpose] **Rationale**: - [Reason 1: primary benefit] - [Reason 2: fits project needs] - [Reason 3: team familiarity / community support] **Alternatives Considered**: - [Alternative 1]: [Why not chosen - specific reason] - [Alternative 2]: [Why not chosen - specific reason] **Trade-offs**: - ✅ Pros: - [Advantage 1] - [Advantage 2] - ❌ Cons: - [Disadvantage 1] - [Disadvantage 2] - ⚖️ Acceptable for V1: [Why trade-offs are acceptable] **Migration Path** (if relevant): - V1: [Current approach] - V2: [Future improvement if needed] ``` ### Example 1: Library Selection ```markdown ### Retry Logic: Custom Implementation **Decision**: Building custom RetryPolicy class instead of using generic retry library **Rationale**: - Need Stripe-specific error classification (transient vs permanent) - Stripe SDK v12 doesn't expose retry configuration - Want exponential backoff with jitter (not all libraries support this) - Need different policies for different error types **Alternatives Considered**: - **async-retry**: Generic library, but doesn't understand Stripe errors - Would need wrapper anyway for error classification - Adds dependency for limited benefit - **Stripe SDK built-in**: Not customizable in v12 - No access to retry timing - Can't distinguish transient from permanent - Would need to wait for v13 (6+ months) **Trade-offs**: - ✅ Pros: - Full control over retry behavior - Stripe-aware error handling - Testable in isolation - Zero external dependencies - ❌ Cons: - More code to maintain (~75 lines) - Need to implement backoff algorithm ourselves - Testing async timing can be tricky - ⚖️ Acceptable for V1: - Retry logic is isolated in single class - Well-tested with mocks (time-injection pattern) - Can swap for library later if needed (interface stays same) **Migration Path**: - V1: Custom RetryPolicy class - V2: Monitor if Stripe SDK v13+ adds customizable retry - V3: Consider migrating to SDK if it meets needs ``` ### Example 2: Design Pattern ```markdown ### Error Handling: Strategy Pattern **Decision**: Using Strategy pattern for error classification **Rationale**: - Different error types need different handling strategies - Easy to add new error types without modifying existing code - Testable strategies in isolation - Clear separation of concerns **Implementation**: ```typescript interface ErrorStrategy { canHandle(error: StripeError): boolean; handle(error: StripeError): DomainError; } class TransientErrorStrategy implements ErrorStrategy { canHandle(error: StripeError): boolean { return ['rate_limit', 'network_error'].includes(error.code); } handle(error: StripeError): DomainError { return new TransientError(error.message, { retryable: true }); } } class PermanentErrorStrategy implements ErrorStrategy { canHandle(error: StripeError): boolean { return ['card_declined', 'insufficient_funds'].includes(error.code); } handle(error: StripeError): DomainError { return new PermanentError(error.message, { retryable: false }); } } ``` **Alternatives Considered**: - **Simple if/else chain**: Harder to test, grows complex with more error types - **Error code mapping table**: Less flexible, can't handle complex logic **Trade-offs**: - ✅ Pros: Extensible, testable, clean - ❌ Cons: More classes (4 strategies + manager) - ⚖️ Acceptable: Error handling is core feature, worth the structure ``` ## Keeping PLAN.md Focused ### What TO Include **Architecture Section**: - ✅ High-level component structure - ✅ Data flow diagrams (text-based) - ✅ Integration points with external systems - ✅ Key design patterns being used - ✅ Technical constraints affecting design **DO/DON'T Guidelines**: - ✅ Patterns discovered from real experience - ✅ Anti-patterns that caused problems - ✅ Platform-specific constraints - ✅ Examples with code snippets **Technology Choices**: - ✅ Major library/framework selections - ✅ Design pattern choices - ✅ Rationale and trade-offs **Scope**: - ✅ V1 feature list - ✅ Explicitly deferred features (V2/V3) - ✅ Performance requirements - ✅ Platform constraints ### What NOT to Include **Avoid in Architecture**: - ❌ Implementation details (specific line numbers) - ❌ Completed work (belongs in task files) - ❌ Bug fixes (belongs in iteration notes) - ❌ Todos and action items (belongs in task files) - ❌ Speculation about V2 features (keep focused on V1) **Avoid in DO/DON'T**: - ❌ Obvious best practices ("write tests", "use version control") - ❌ One-off decisions that aren't patterns - ❌ Personal preferences without rationale - ❌ Guidelines without examples **Avoid in Scope**: - ❌ Detailed implementation plans (belongs in tasks) - ❌ Tentative "maybe" features (defer or commit) - ❌ Features without user value justification ### Red Flags (PLAN.md Getting Too Large) **Warning signs**: - PLAN.md over 300 lines (probably too detailed) - Architecture section listing every file - DO/DON'T with 20+ guidelines (too many patterns) - Scope including V2/V3/V4 features **How to slim down**: 1. Move implementation details to code comments 2. Move completed work to task files or ARCHIVE.md 3. Consolidate similar guidelines 4. Focus scope on V1 only, defer V2/V3 discussion ### Example: Too Detailed vs Just Right **❌ Too Detailed** (avoid): ```markdown ## Architecture ### File Structure - src/ - payment/ - PaymentProcessor.ts (145 lines) - process() method (lines 23-67) - validate() method (lines 69-89) - log() method (lines 91-103) - StripeClient.ts (213 lines) - createCharge() (lines 45-98) ... ``` **✅ Just Right**: ```markdown ## Architecture ### Component Structure **PaymentProcessor** (Orchestrator): - Validates payment requests - Coordinates Stripe API calls - Logs transactions **StripeClient** (Integration): - Wraps Stripe SDK - Applies retry policy - Maps errors to domain model ``` ## Summary **Key Principles**: 1. Update PLAN.md during brainstorming (Type B subjects) 2. Distinguish Architecture (HOW) from Scope (WHAT) 3. DO/DON'T guidelines need rationale + examples 4. Document technology choices with trade-offs 5. Keep PLAN.md focused on V1, high-level decisions **When in doubt**: - Ask: "Is this a pattern others should follow?" → DO/DON'T - Ask: "Does this explain system structure?" → Architecture - Ask: "Does this define what's included?" → Scope - Ask: "Is this implementation detail?" → Code comments / task file SKILL_FLOW_DESIGNER_PLAN_EOF } # 5. flow-builder (REFACTOR - renamed from flow-implementer) get_skill_flow_builder() { cat <<'SKILL_FLOW_BUILDER_EOF' --- name: flow-builder description: Execute implementation work with gate checks and verification. Use when user wants to code, build features, implement iterations, or execute action items. Enforces gates, guides workflow, tracks progress. --- # Flow Builder Execute implementation work following Flow framework patterns. This skill guides the build phase: verify readiness → start implementation → execute action items → verify completion → mark complete. ## When to Use This Skill Activate when the user wants to start coding: - "Let's implement this" - "Start coding" - "Build the feature" - "Time to write code" - "Ready to implement" - "Execute the action items" - "Begin implementation" ## Implementation Philosophy **Flow's Core Principle**: Design before code. Implementation happens AFTER brainstorming is complete (if needed) and pre-implementation tasks are done. **Key Gates**: - **Pre-Implementation Gate**: Brainstorming must be ✅ COMPLETE (if iteration had brainstorming) - **Pre-Tasks Gate**: All pre-implementation tasks must be ✅ COMPLETE - **Verification Gate**: All action items done, tests passing, ready for next work **Implementation Pattern**: Start → Execute → Verify → Complete ## Pre-Implementation Gate Check Before starting ANY implementation, verify readiness: ### Check 1: Brainstorming Status (if applicable) ``` IF iteration has brainstorming section: IF brainstorming status ≠ ✅ COMPLETE: ❌ BLOCK implementation SUGGEST: "Brainstorming must be completed first. Use `/flow-next-subject` to continue brainstorming." ELSE: ✅ PASS gate ELSE: ✅ PASS gate (no brainstorming needed) ``` ### Check 2: Pre-Implementation Tasks (if applicable) ``` IF iteration has "Pre-Implementation Tasks" section: IF any pre-task status ≠ ✅ COMPLETE: ❌ BLOCK implementation LIST incomplete pre-tasks SUGGEST: "Complete pre-tasks first, then use `/flow-implement-start`" ELSE: ✅ PASS gate ELSE: ✅ PASS gate (no pre-tasks) ``` ### Check 3: Iteration Status ``` IF iteration status = 🚧 IN PROGRESS: ✅ PASS (already implementing) IF iteration status = 🎨 READY or ⏳ PENDING: SUGGEST: "Use `/flow-implement-start` to begin implementation" ``` ## Implementation Workflow ### Step 1: Start Implementation **Command**: `/flow-implement-start` **What it does**: - Marks iteration 🚧 IN PROGRESS - Creates "Implementation" section in task file - Updates DASHBOARD.md current work **When to suggest**: User is ready to code and gates passed ### Step 2: Execute Action Items **Sequential Execution**: 1. Read action items from iteration (or brainstorming Type D subjects) 2. Execute each action item in order 3. Check off items as completed: `- [x] Action item` 4. Document progress in "Implementation Notes" **Parallel Execution** (when safe): - If action items are independent (no dependencies) - Example: Creating multiple unrelated files - Still check off sequentially for tracking **Handling Blockers**: ``` IF encounter blocker during implementation: DOCUMENT blocker in Implementation Notes ASSESS severity: - Minor (< 15 min fix): Handle and continue - Major (> 15 min, out of scope): STOP and notify user - Blocking (cannot proceed): Mark iteration ❌ BLOCKED, notify user ``` ### Step 3: Verify Completion Before marking iteration complete, verify: **Verification Checklist**: - [ ] All action items checked off (✅) - [ ] Code compiles/runs without errors - [ ] Tests passing (if applicable) - [ ] Files modified documented - [ ] Implementation notes updated - [ ] No unresolved blockers **Testing Strategy** (from PLAN.md): - Follow Testing Strategy section in PLAN.md - Run tests according to project conventions - Document test results in Implementation Notes ### Step 4: Complete Implementation **Command**: `/flow-implement-complete` **What it does**: - Marks iteration ✅ COMPLETE - Updates completion date - Updates DASHBOARD.md progress - Advances to next iteration **When to suggest**: All verification criteria met ## Implementation Slash Commands ### `/flow-implement-start` **Use when**: Starting implementation for current iteration **Prerequisites**: - Brainstorming ✅ COMPLETE (if applicable) - Pre-tasks ✅ COMPLETE (if applicable) - Iteration status = 🎨 READY or ⏳ PENDING **Effect**: - Changes iteration status to 🚧 IN PROGRESS - Creates implementation section in task file - Updates DASHBOARD.md ### `/flow-implement-complete` **Use when**: All action items done and verified **Prerequisites**: - All action items checked off - Verification criteria met - No unresolved blockers **Effect**: - Marks iteration ✅ COMPLETE - Updates completion date - Advances to next iteration or task ## Action Item Execution Patterns ### Pattern 1: Sequential Implementation **Use when**: Action items depend on each other ```markdown Action Items: - [x] Create database schema - [x] Implement data access layer (depends on schema) - [x] Add service layer (depends on DAL) - [x] Create API endpoints (depends on service) ``` **Approach**: 1. Complete item 1 2. Verify item 1 works 3. Move to item 2 4. Repeat until all done ### Pattern 2: Parallel Implementation **Use when**: Action items are independent ```markdown Action Items: - [ ] Create logger utility - [ ] Create validator utility - [ ] Create formatter utility ``` **Approach**: 1. Create all three files 2. Verify each works independently 3. Check off all items ### Pattern 3: Incremental Verification **Use when**: Complex implementation with multiple steps ```markdown Action Items: - [x] Implement basic authentication (VERIFY: can login) - [x] Add JWT token generation (VERIFY: tokens valid) - [x] Add token refresh (VERIFY: refresh works) - [x] Add logout (VERIFY: tokens invalidated) ``` **Approach**: 1. Complete one action item 2. Test/verify immediately 3. Document verification in notes 4. Move to next item ## Pre-Implementation Tasks Pattern ### What Are Pre-Implementation Tasks? Small blocking tasks (< 30 min) that must be completed BEFORE main iteration work starts. **Examples**: - Refactor interface to support new pattern - Update enum with missing values - Fix bug in legacy code - Rename file to match convention ### When to Complete Pre-Tasks ``` IF iteration has "Pre-Implementation Tasks" section: FOR EACH pre-task: Complete pre-task Mark ✅ COMPLETE with date Document changes in pre-task section ONLY AFTER ALL PRE-TASKS DONE: Run /flow-implement-start for main iteration ``` ### Pre-Task Structure ```markdown #### Pre-Implementation Tasks ##### ⏳ Pre-Task 1: Update ErrorHandler to support async **Why Blocking**: Retry logic requires async error handling **Scope** (< 30 min): - Update ErrorHandler.ts with async support - Add retryAsync() method - Update 3 call sites **Files**: - src/utils/ErrorHandler.ts --- ##### ✅ Pre-Task 1: Update ErrorHandler to support async **Completed**: 2025-10-30 **Changes Made**: - Added async support to ErrorHandler class - Implemented retryAsync() method with exponential backoff - Updated call sites in BillingService, PaymentService, OrderService - Added unit tests for async error handling **Files Modified**: - src/utils/ErrorHandler.ts (+42 lines) - tests/utils/ErrorHandler.test.ts (+28 lines) ``` ## Verification Best Practices ### What to Verify **Code Quality**: - [ ] No syntax errors - [ ] No linting errors - [ ] Follows project conventions - [ ] Code is readable and well-structured **Functionality**: - [ ] Feature works as intended - [ ] Edge cases handled - [ ] Error handling implemented - [ ] No regressions introduced **Testing**: - [ ] Unit tests pass - [ ] Integration tests pass (if applicable) - [ ] Manual testing done (if no automated tests) **Documentation**: - [ ] Implementation notes updated - [ ] Files modified list complete - [ ] Verification results documented ### When to Mark ❌ BLOCKED Mark iteration ❌ BLOCKED when: - External dependency not available - Blocker requires > 1 hour to resolve - Need user decision before proceeding - Technical limitation discovered **Blocked Pattern**: ```markdown ### ❌ Iteration 2: Error Handling **Status**: ❌ BLOCKED **Blocker**: Stripe SDK doesn't support custom retry logic in v12 **Options**: A) Downgrade to Stripe SDK v11 (supports custom retry) B) Wait for v13 release (eta 2 weeks) C) Implement wrapper around SDK calls **Waiting for**: User decision on approach ``` ## Detailed Verification Guidance For comprehensive guidance on verification, testing patterns, completion criteria, bug documentation, and decision-making, see **[VERIFICATION.md](VERIFICATION.md)**. That resource includes: - **Testing Patterns**: Unit testing, integration testing, manual testing checklists, and TDD patterns with complete code examples - **What "Done" Looks Like**: 6 detailed completion criteria with examples - **When to Document Bugs and Issues**: Bug documentation templates, severity levels, and fix-immediately vs defer guidance - **Deciding: ❌ BLOCKED vs Continue**: Decision flowchart, 8 scenarios with examples, and real-world case studies ## Scope Boundary Rules ### When You Discover New Work During implementation, if you discover issues NOT in current action items: 1. **STOP** - Don't make assumptions 2. **ASSESS** - Categorize the issue: - Syntax error in file you're editing? Fix and document - Missing functionality? Discuss with user - New feature idea? Defer to future iteration - Blocking bug? Propose pre-implementation task 3. **NOTIFY** user with structured options: - **Option A**: Create pre-implementation task (< 30 min, blocking) - **Option B**: Add as new brainstorming subject (design needed) - **Option C**: Handle immediately (if user approves) - **Option D**: Defer to separate iteration (after current work) 4. **AWAIT** user decision before proceeding ### Example: Scope Boundary Alert ``` ⚠️ SCOPE BOUNDARY ALERT During implementation of Iteration 2 (Error Handling), discovered: **Issue**: PaymentService.ts uses deprecated error format that conflicts with new retry logic **Impact**: Cannot complete current action item without addressing this **Options**: A) Create pre-implementation task (estimated 20 min): - Update PaymentService error format - Update 2 call sites - Add to Pre-Implementation Tasks section B) Add as brainstorming subject: - Need to design error format standard across all services - Affects more than just PaymentService C) Handle immediately: - Fix PaymentService.ts now as part of current work - Document change in Implementation Notes D) Defer to separate iteration: - Work around issue for now - Create new iteration for error format standardization Which approach would you prefer? ``` ## Common Implementation Patterns ### Pattern: Feature Implementation ``` User: "Let's implement the authentication system" AI Response: I'll help you implement the authentication system. Let me check readiness: ✅ Brainstorming Session - COMPLETE (4 subjects resolved) ✅ Pre-Implementation Tasks - COMPLETE (updated User model) ✅ Iteration Status - 🎨 READY Ready to implement! Use `/flow-implement-start` to begin. Action items from brainstorming: 1. Create AuthService class 2. Implement login/logout methods 3. Add JWT token generation 4. Integrate with API endpoints 5. Add authentication middleware Estimated time: 3-4 hours Should I start implementation? ``` ### Pattern: Handling Blockers ``` User: "Start implementing the payment integration" AI Response: I'll help you implement payment integration. Let me check readiness: ❌ Pre-Implementation Tasks - INCOMPLETE Found 2 incomplete pre-tasks: 1. ⏳ Pre-Task 1: Refactor PaymentConfig interface 2. ⏳ Pre-Task 2: Update environment variables These tasks must be completed before main implementation. Should I help you complete them now? ``` ### Pattern: Verification Before Completion ``` User: "Are we done with this iteration?" AI Response: Let me verify completion criteria: ✅ All action items checked off (5/5) ✅ Code compiles without errors ✅ Tests passing (unit: 12/12, integration: 3/3) ✅ Files modified documented (4 files) ✅ Implementation notes updated ✅ No unresolved blockers Verification complete! All criteria met. Use `/flow-implement-complete` to mark this iteration done and move to the next one. ``` ### Pattern: Incremental Progress ``` User: "How's the implementation going?" AI Response: Implementation progress for Iteration 2: Error Handling Completed (3/5): - [x] Create RetryPolicy class - [x] Implement exponential backoff algorithm - [x] Add configuration for max retries In Progress (1/5): - [ ] Integrate with StripeClient ← CURRENT (60% done) Pending (1/5): - [ ] Add tests for retry scenarios Estimated completion: 1 hour Working on integrating RetryPolicy with StripeClient.ts. Will move to tests next. ``` ## Examples ### Example 1: Starting Implementation After Brainstorming ``` User: "Let's start building the retry logic" AI Process: 1. Read current iteration from task file 2. Check brainstorming status: ✅ COMPLETE (4 subjects resolved) 3. Check pre-tasks: ✅ COMPLETE (updated ErrorHandler.ts) 4. Verify iteration status: 🎨 READY AI Response: "Ready to start implementation! All gates passed: ✅ Brainstorming complete (4 subjects resolved) ✅ Pre-tasks complete (ErrorHandler updated) ✅ Iteration status: READY Action items from brainstorming (Type D): - [ ] Create RetryPolicy class - [ ] Implement exponential backoff algorithm - [ ] Add configuration for max retries - [ ] Integrate with StripeClient - [ ] Add tests for retry scenarios Use `/flow-implement-start` to begin, then I'll execute these action items." ``` ### Example 2: Handling Incomplete Pre-Tasks ``` User: "Start implementing the payment flow" AI Process: 1. Read current iteration from task file 2. Check brainstorming: ✅ COMPLETE 3. Check pre-tasks: Found 2 incomplete pre-tasks AI Response: "Cannot start implementation yet. Pre-tasks must be completed first: ❌ Pre-Implementation Tasks - INCOMPLETE Blocking tasks: 1. ⏳ Pre-Task 1: Update PaymentStatus enum - Add PENDING_RETRY and FAILED_PERMANENT states 2. ⏳ Pre-Task 2: Refactor PaymentService.process() - Extract validation logic to separate method These must be done BEFORE main implementation. Should I complete these pre-tasks now?" User: "Yes, complete them" AI Process: 1. Complete Pre-Task 1 (update enum, update switch statements) 2. Mark Pre-Task 1 ✅ COMPLETE with date and changes 3. Complete Pre-Task 2 (extract validation method) 4. Mark Pre-Task 2 ✅ COMPLETE with date and changes 5. Verify all pre-tasks done AI Response: "All pre-tasks completed: ✅ Pre-Task 1: PaymentStatus enum updated (4 files modified) ✅ Pre-Task 2: Validation logic extracted (2 files modified) Now ready for main implementation. Use `/flow-implement-start` to begin." ``` ### Example 3: Verification Before Marking Complete ``` User: "I think we're done with this iteration" AI Process: 1. Read current iteration action items 2. Check completion status 3. Verify each completion criterion AI Response: "Let me verify completion criteria: ✅ Action Items (5/5): - [x] Create RetryPolicy class - [x] Implement exponential backoff algorithm - [x] Add configuration for max retries - [x] Integrate with StripeClient - [x] Add tests for retry scenarios ✅ Code Quality: - No syntax errors - Linting passed - Follows project conventions ✅ Tests: - Unit tests: 8/8 passing - Integration tests: 2/2 passing ✅ Documentation: - Files modified documented (4 files) - Implementation notes updated All verification criteria met! Use `/flow-implement-complete` to mark this iteration complete." ``` ### Example 4: Scope Boundary During Implementation ``` User: [AI is implementing action items] AI Process: 1. Working on "Integrate RetryPolicy with StripeClient" 2. Discovers PaymentService.ts uses deprecated error format 3. Realizes this is out of scope AI Response: "⚠️ SCOPE BOUNDARY ALERT While integrating RetryPolicy with StripeClient, I discovered: **Issue**: PaymentService.ts uses deprecated error format that conflicts with new retry logic **Impact**: Current action item can continue, but this will cause issues when we add retry to PaymentService later **Options**: A) Create pre-implementation task for NEXT iteration: - Estimated: 20-30 minutes - Update PaymentService error format - Update 3 call sites B) Add as new brainstorming subject: - Design error format standard across all services - Affects PaymentService, BillingService, OrderService C) Handle immediately (expand current scope): - Fix PaymentService.ts now - Document as scope expansion D) Defer to separate iteration: - Work around for now (document workaround) - Create new task for error format standardization I recommend Option A (pre-task for next iteration) as it's small and blocking for future work. Which approach would you prefer?" ``` ## Interaction with Other Flow Skills **Design Stage** (flow-designer Skill): - `/flow-brainstorm-start` - Design decisions - `/flow-brainstorm-complete` - Generate action items **Build Stage** (This Skill): - `/flow-implement-start` - Begin work ← YOU ARE HERE - `/flow-implement-complete` - Finish iteration ← YOU ARE HERE **Navigation Stage** (flow-navigator Skill): - `/flow-status` - Check progress - `/flow-next` - What to do next ## References - **Implementation Pattern**: DEVELOPMENT_FRAMEWORK.md lines 1798-1836 - **Status Markers**: DEVELOPMENT_FRAMEWORK.md lines 1872-1968 - **Brainstorming Pattern**: DEVELOPMENT_FRAMEWORK.md lines 1167-1797 - **Pre-Implementation Tasks**: DEVELOPMENT_FRAMEWORK.md lines 1683-1723 - **Scope Boundary Rules**: DEVELOPMENT_FRAMEWORK.md lines 339-540 ## Implementation Gate Checklist Before implementing, verify ALL gates passed: ``` [ ] Brainstorming complete (if applicable) [ ] Pre-implementation tasks complete (if applicable) [ ] Current iteration status = 🎨 READY or ⏳ PENDING [ ] User confirmed ready to implement ``` If ALL checked → Use `/flow-implement-start` If ANY unchecked → Address blockers first ## Completion Checklist Before marking complete, verify ALL criteria met: ``` [ ] All action items checked off [ ] Code compiles/runs [ ] Tests passing [ ] Files modified documented [ ] Implementation notes updated [ ] No unresolved blockers [ ] Verification completed ``` If ALL checked → Use `/flow-implement-complete` If ANY unchecked → Continue implementation SKILL_FLOW_BUILDER_EOF } get_skill_flow_builder_patterns() { cat <<'SKILL_FLOW_BUILDER_PATTERNS_EOF' # Implementation Patterns This document provides detailed patterns for handling pre-implementation tasks and executing action items using Flow framework. ## Table of Contents 1. [Pre-Implementation Tasks Pattern](#pre-implementation-tasks-pattern) 2. [Action Item Execution Best Practices](#action-item-execution-best-practices) 3. [Sequential vs Parallel Execution](#sequential-vs-parallel-execution) 4. [Breaking Down Large Action Items](#breaking-down-large-action-items) 5. [Common Implementation Scenarios](#common-implementation-scenarios) --- ## Pre-Implementation Tasks Pattern ### What Are Pre-Implementation Tasks? **Pre-implementation tasks** are small, blocking pieces of work (< 30 min) that must be completed BEFORE starting the main iteration implementation. **Key Characteristics**: - **Small scope**: Can be completed in < 30 minutes - **Blocking**: Main iteration cannot start without them - **Independent**: Can be done separately from main work - **Discovered during brainstorming**: Identified when resolving Type A subjects ### When to Create Pre-Implementation Tasks Create pre-implementation tasks when you discover during brainstorming: **Code Structure Issues**: - Interface signature doesn't support new pattern - Enum missing required values - Type definitions need updates - File naming doesn't match conventions **Legacy Code Issues**: - Old code doesn't support async operations - Error handling pattern incompatible - Deprecated API being used - Missing error states **Refactoring Needs**: - Duplicate code needs extraction - Hard-coded values need configuration - Tight coupling needs decoupling - Missing abstraction layer **Bug Fixes**: - Race condition in existing code - Memory leak in utility function - Off-by-one error in loop - Missing null checks ### Pre-Implementation Task Structure #### Template ```markdown #### Pre-Implementation Tasks These tasks MUST be completed BEFORE starting main implementation of this iteration. ##### ⏳ Pre-Task 1: [Name] **Why Blocking**: [Explanation of why this blocks implementation] **Scope** (< 30 min): - [Specific change 1] - [Specific change 2] - [Specific change 3] **Files**: - [File path 1] - [File path 2] **Test**: [How to verify it's done] --- ##### ✅ Pre-Task 1: [Name] **Completed**: [Date] **Changes Made**: - [What was actually done] - [Any deviations from plan] **Files Modified**: - [File path 1] ([+/-] X lines) - [File path 2] ([+/-] Y lines) **Verification**: - [How it was tested] ``` ### Example 1: Interface Update **Before (Planning)**: ```markdown ##### ⏳ Pre-Task 1: Update PaymentProcessor interface **Why Blocking**: Current interface doesn't support async retry logic needed for main implementation **Scope** (< 30 min): - Add `retryPolicy?: RetryPolicy` parameter to ProcessPaymentOptions - Update 3 implementations (StripeProcessor, PayPalProcessor, MockProcessor) - Update type definitions file **Files**: - src/types/payment.ts - src/processors/StripeProcessor.ts - src/processors/PayPalProcessor.ts - src/processors/MockProcessor.ts **Test**: TypeScript compiles without errors, all processors accept new parameter ``` **After (Completed)**: ```markdown ##### ✅ Pre-Task 1: Update PaymentProcessor interface **Completed**: 2025-10-30 **Changes Made**: - Added `retryPolicy?: RetryPolicy` to ProcessPaymentOptions interface - Updated all 3 processor implementations with optional parameter - Added JSDoc comments explaining retry policy usage - Discovered MockProcessor was missing error handling - fixed that too **Files Modified**: - src/types/payment.ts (+8 lines) - src/processors/StripeProcessor.ts (+12 lines) - src/processors/PayPalProcessor.ts (+10 lines) - src/processors/MockProcessor.ts (+15 lines, +8 for error handling fix) **Verification**: - TypeScript compiles cleanly - All unit tests passing - Mock tests verify optional parameter behavior ``` ### Example 2: Enum Update **Before (Planning)**: ```markdown ##### ⏳ Pre-Task 2: Add missing payment states to enum **Why Blocking**: Retry logic needs "pending_retry" and "failed_permanent" states **Scope** (< 15 min): - Add two new states to PaymentStatus enum - Update 4 switch statements to handle new states - Update state transition documentation **Files**: - src/types/payment.ts - src/services/PaymentService.ts - src/services/RetryService.ts - docs/payment-states.md **Test**: No switch statement exhaustiveness errors, docs updated ``` **After (Completed)**: ```markdown ##### ✅ Pre-Task 2: Add missing payment states to enum **Completed**: 2025-10-30 **Changes Made**: - Added `PENDING_RETRY` and `FAILED_PERMANENT` to PaymentStatus enum - Updated 4 switch statements with proper handling - Added state transition diagram to docs - Also added `CANCELLED_BY_USER` state (discovered during implementation) **Files Modified**: - src/types/payment.ts (+3 states) - src/services/PaymentService.ts (+8 lines) - src/services/RetryService.ts (+6 lines) - docs/payment-states.md (+state diagram) **Verification**: - TypeScript exhaustiveness checks pass - All switch statements handle new states - State diagram reviewed and accurate ``` ### Example 3: Legacy Code Refactor **Before (Planning)**: ```markdown ##### ⏳ Pre-Task 3: Update ErrorHandler to support async operations **Why Blocking**: Current ErrorHandler is synchronous, retry logic requires async **Scope** (< 30 min): - Add `handleAsync()` method to ErrorHandler class - Implement async error recovery pattern - Update 3 existing call sites to use async version - Keep sync version for backwards compatibility **Files**: - src/utils/ErrorHandler.ts - src/services/BillingService.ts - src/services/PaymentService.ts - src/services/OrderService.ts **Test**: All services use async handler, no regressions in error handling ``` **After (Completed)**: ```markdown ##### ✅ Pre-Task 3: Update ErrorHandler to support async operations **Completed**: 2025-10-30 **Changes Made**: - Added `handleAsync()` method with Promise-based error recovery - Implemented exponential backoff helper function - Updated all 3 call sites to async pattern - Kept sync `handle()` method for backwards compatibility - Added comprehensive unit tests for async error handling **Files Modified**: - src/utils/ErrorHandler.ts (+65 lines) - tests/utils/ErrorHandler.test.ts (+42 lines) - src/services/BillingService.ts (+8 lines) - src/services/PaymentService.ts (+12 lines) - src/services/OrderService.ts (+6 lines) **Verification**: - All unit tests passing (12 new tests) - Integration tests with services passing - No regressions in existing error handling - Async pattern verified with multiple retry scenarios ``` ### Pre-Implementation Task Workflow ``` 1. During brainstorming, identify Type A subjects ↓ 2. /flow-brainstorm-review creates Pre-Implementation Tasks section ↓ 3. Complete each pre-task sequentially ↓ 4. Mark each ✅ COMPLETE with date and details ↓ 5. Verify all pre-tasks done ↓ 6. ONLY THEN run /flow-implement-start for main iteration ``` --- ## Action Item Execution Best Practices ### General Principles **1. Read Before Execute** - Read ALL action items before starting - Understand dependencies between items - Identify which can be parallel vs sequential **2. Check Off Immediately** - Mark item `[x]` as soon as completed - Don't batch multiple completions - Provides clear progress tracking **3. Document as You Go** - Update Implementation Notes with discoveries - Note any deviations from plan - Document workarounds or alternative approaches **4. Verify Incrementally** - Test after each action item (if possible) - Don't wait until end to verify everything - Catch issues early while context is fresh ### Action Item Checklist Format **Good Action Items** (specific, measurable): ```markdown - [ ] Create `src/payment/RetryPolicy.ts` class - [ ] Implement exponential backoff algorithm (base: 1s, max: 32s) - [ ] Add configuration for max retries (default: 3) - [ ] Integrate RetryPolicy with StripeClient.processPayment() - [ ] Add unit tests for retry scenarios (success, failure, timeout) ``` **Poor Action Items** (vague, unmeasurable): ```markdown - [ ] Handle retries - [ ] Make it work - [ ] Add tests - [ ] Fix issues ``` ### Execution Order Strategies #### Strategy 1: Dependency Order Execute items based on what depends on what. **Example**: ```markdown 1. [x] Create RetryPolicy class (nothing depends on this yet) 2. [x] Implement backoff algorithm (depends on class existing) 3. [x] Add configuration (depends on algorithm structure) 4. [x] Integrate with client (depends on all above) 5. [x] Add tests (depends on everything working) ``` #### Strategy 2: Risk Order Do risky/uncertain items first to catch blockers early. **Example**: ```markdown 1. [x] Research Stripe API rate limits (uncertain, might change approach) 2. [x] Implement retry logic (core feature, most risk) 3. [x] Add configuration (low risk, straightforward) 4. [x] Add logging (low risk, enhancement) 5. [x] Add tests (low risk, verification) ``` #### Strategy 3: Value Order Deliver most valuable functionality first. **Example**: ```markdown 1. [x] Implement basic payment processing (core value) 2. [x] Add error handling (high value, prevents crashes) 3. [x] Integrate with database (high value, persistence) 4. [x] Add logging (medium value, debugging) 5. [x] Add rate limiting (low value, optimization) ``` ### Handling Blockers **When you encounter a blocker**: 1. **Document the blocker immediately**: ```markdown **Implementation Notes**: - Created RetryPolicy class - Implemented backoff algorithm - **BLOCKER**: Stripe SDK v12 doesn't support custom retry hooks - Cannot complete action item 4 (integrate with client) - Options: downgrade to v11, wait for v13, implement wrapper - Needs user decision ``` 2. **Notify user with options**: ``` ⚠️ BLOCKER ENCOUNTERED Action Item: "Integrate RetryPolicy with StripeClient" Issue: Stripe SDK v12 doesn't expose retry hooks for custom logic Options: A) Downgrade to Stripe SDK v11 (supports custom retry, but older) B) Wait for SDK v13 release (has retry hooks, ETA 2 weeks) C) Implement wrapper around SDK calls (adds complexity) D) Mark iteration ❌ BLOCKED and move to different work Which approach should we take? ``` 3. **Wait for user decision** before proceeding ### Parallel Action Items **Safe for parallel execution**: - Independent files - Different modules - No shared state - Can verify independently **Example**: ```markdown Action Items (can do in parallel): - [ ] Create `logger.ts` utility - [ ] Create `validator.ts` utility - [ ] Create `formatter.ts` utility - [ ] Create `parser.ts` utility All four can be created simultaneously. ``` **NOT safe for parallel**: - One depends on another - Shared file/state - Must be tested together **Example**: ```markdown Action Items (MUST be sequential): - [ ] Create database schema - [ ] Create data access layer (needs schema) - [ ] Create service layer (needs DAL) - [ ] Create API endpoints (needs service) These have dependencies - do in order. ``` --- ## Sequential vs Parallel Execution ### Sequential Execution Pattern **When to use**: Action items have dependencies **Pattern**: ``` Item 1 → Item 2 → Item 3 → Item 4 ``` **Example: Building API Endpoint** ```markdown #### Action Items (Sequential) - [x] Define API request/response types ↓ (next item needs types) - [x] Implement validation logic ↓ (next item needs validation) - [x] Create service method ↓ (next item needs service) - [x] Create API endpoint handler ↓ (next item needs endpoint) - [x] Add integration tests **Why Sequential**: Each item builds on the previous one. ``` **Execution Strategy**: 1. Complete item 1 fully 2. Verify item 1 works 3. Move to item 2 4. Repeat until all done ### Parallel Execution Pattern **When to use**: Action items are independent **Pattern**: ``` ┌─ Item 1 ├─ Item 2 ├─ Item 3 └─ Item 4 ``` **Example: Creating Utility Functions** ```markdown #### Action Items (Parallel) - [x] Create logger utility - [x] Create validator utility - [x] Create formatter utility - [x] Create error handler utility **Why Parallel**: None depend on each other, all are standalone utilities. ``` **Execution Strategy**: 1. Create all files at once 2. Implement all functions 3. Verify each independently 4. Check off all items ### Hybrid Execution Pattern **When to use**: Mix of dependent and independent items **Pattern**: ``` Item 1 → ┌─ Item 2a ├─ Item 2b → Item 3 └─ Item 2c ``` **Example: Feature with Multiple Components** ```markdown #### Action Items (Hybrid) - [x] Create base authentication interface ↓ ┌─ [x] Implement JWT auth provider (uses interface) ├─ [x] Implement OAuth provider (uses interface) └─ [x] Implement API key provider (uses interface) ↓ - [x] Create auth middleware (uses all providers) - [x] Add tests for all auth methods **Why Hybrid**: Interface must exist first, then providers can be built in parallel, then middleware needs all providers. ``` **Execution Strategy**: 1. Complete item 1 (interface) 2. Complete items 2a, 2b, 2c in parallel 3. Complete item 3 (middleware) 4. Complete item 4 (tests) ### Decision Tree: Sequential or Parallel? ``` Does Item B need Item A's output? ↓ YES → Sequential (A → B) ↓ NO → Check for shared resources ↓ Same file/state? ↓ YES → Sequential (safer) ↓ NO → Parallel (A + B) ``` --- ## Breaking Down Large Action Items ### When to Break Down **Signs an action item is too large**: - Estimated > 2 hours - Involves multiple files - Multiple sub-steps needed - Unclear how to complete - High risk of failure **Example of Too-Large Item**: ```markdown - [ ] Implement payment system ``` This is too vague and large. Break it down! ### Breakdown Strategies #### Strategy 1: By Component Break into logical components/modules. **Before**: ```markdown - [ ] Implement payment system ``` **After**: ```markdown - [ ] Create PaymentProcessor interface - [ ] Implement StripeProcessor class - [ ] Implement PayPalProcessor class - [ ] Create PaymentService to coordinate processors - [ ] Add payment validation logic - [ ] Add error handling and retry - [ ] Add tests for all processors ``` #### Strategy 2: By Layer Break into architectural layers. **Before**: ```markdown - [ ] Add user authentication ``` **After**: ```markdown - [ ] Database: Create users table with auth fields - [ ] Data Layer: Create UserRepository with auth methods - [ ] Service Layer: Create AuthService with login/logout - [ ] API Layer: Create /login and /logout endpoints - [ ] Middleware: Add authentication middleware - [ ] Tests: Add auth integration tests ``` #### Strategy 3: By Phase Break into implementation phases (skeleton → veins → flesh). **Before**: ```markdown - [ ] Build search feature ``` **After**: ```markdown Skeleton (basic functionality): - [ ] Create search API endpoint that returns hardcoded results - [ ] Add search input in UI - [ ] Wire UI to API Veins (core functionality): - [ ] Implement database search query - [ ] Add pagination to results - [ ] Add sorting options Flesh (polish): - [ ] Add search filters (date, type, status) - [ ] Add search highlighting - [ ] Add search suggestions - [ ] Optimize query performance ``` #### Strategy 4: By File Break into file-level changes. **Before**: ```markdown - [ ] Refactor error handling ``` **After**: ```markdown - [ ] Update ErrorHandler.ts with new error types - [ ] Update PaymentService.ts error handling - [ ] Update OrderService.ts error handling - [ ] Update BillingService.ts error handling - [ ] Update error handling tests - [ ] Update error documentation ``` ### Breakdown Examples #### Example 1: API Integration **Too Large**: ```markdown - [ ] Integrate with Stripe API ``` **Properly Broken Down**: ```markdown - [ ] Create StripeClient class with API key configuration - [ ] Implement createPayment() method - [ ] Implement getPayment() method - [ ] Implement refundPayment() method - [ ] Add error mapping (Stripe errors → our errors) - [ ] Add retry logic for transient failures - [ ] Add webhook signature validation - [ ] Add unit tests with mocked Stripe API - [ ] Add integration tests with Stripe test mode ``` #### Example 2: Database Schema **Too Large**: ```markdown - [ ] Design and implement database schema ``` **Properly Broken Down**: ```markdown - [ ] Create users table with fields and constraints - [ ] Create payments table with foreign keys - [ ] Create orders table with relationships - [ ] Add indexes on frequently queried fields - [ ] Create migration script for schema - [ ] Add seed data for development - [ ] Test schema with sample queries - [ ] Document schema in ER diagram ``` #### Example 3: Refactoring **Too Large**: ```markdown - [ ] Refactor legacy payment code ``` **Properly Broken Down**: ```markdown - [ ] Extract payment processing into separate class - [ ] Replace hard-coded values with configuration - [ ] Convert callbacks to async/await - [ ] Add proper error handling - [ ] Replace any types with proper interfaces - [ ] Update tests to match new structure - [ ] Verify no regressions with integration tests - [ ] Update documentation ``` --- ## Common Implementation Scenarios ### Scenario 1: Creating New Feature **Context**: Building a new feature from scratch **Recommended Pattern**: Sequential with verification ```markdown #### Action Items - [x] Design and document API contract → Verification: API spec reviewed and approved - [x] Create database schema and migration → Verification: Migration runs cleanly, schema correct - [x] Implement data access layer → Verification: Unit tests for DAL passing - [x] Implement service layer → Verification: Service tests passing - [x] Create API endpoints → Verification: Integration tests passing - [x] Add error handling → Verification: Error cases tested and working - [x] Add logging and monitoring → Verification: Logs visible, metrics tracked - [x] Write documentation → Verification: Docs accurate and complete ``` ### Scenario 2: Bug Fix **Context**: Fixing a specific bug **Recommended Pattern**: Diagnose → Fix → Verify ```markdown #### Action Items - [x] Reproduce bug with test case → Verification: Test fails, reproducing bug - [x] Debug and identify root cause → Verification: Root cause documented - [x] Implement fix → Verification: Test now passes - [x] Add regression test → Verification: New test prevents bug from returning - [x] Verify fix doesn't break anything else → Verification: All tests still passing ``` ### Scenario 3: Refactoring **Context**: Improving existing code structure **Recommended Pattern**: Incremental with safety checks ```markdown #### Action Items - [x] Add comprehensive tests for current behavior → Verification: Tests passing, covering all cases - [x] Extract method/class/module → Verification: Tests still passing - [x] Update call sites to use new code → Verification: Tests still passing - [x] Remove old code → Verification: Tests still passing - [x] Clean up and optimize → Verification: Tests still passing, code cleaner ``` ### Scenario 4: Integration **Context**: Integrating with external system **Recommended Pattern**: Mock → Real → Error handling ```markdown #### Action Items - [x] Create client interface and types → Verification: Interface matches external API - [x] Implement client with mock responses → Verification: Mock client works, tests passing - [x] Replace mock with real API calls → Verification: Integration test with real API succeeds - [x] Add error handling and retry logic → Verification: Error cases handled gracefully - [x] Add rate limiting and timeouts → Verification: Rate limits respected, timeouts working ``` ### Scenario 5: Performance Optimization **Context**: Improving performance of existing feature **Recommended Pattern**: Measure → Optimize → Verify ```markdown #### Action Items - [x] Add performance benchmarks → Verification: Baseline performance measured - [x] Profile and identify bottlenecks → Verification: Bottlenecks documented - [x] Implement optimization (e.g., caching) → Verification: Benchmarks show improvement - [x] Verify functionality unchanged → Verification: All tests still passing - [x] Document performance characteristics → Verification: Docs updated with new benchmarks ``` --- ## Best Practices Summary **Pre-Implementation Tasks**: - ✅ Keep scope < 30 minutes - ✅ Complete ALL before starting main work - ✅ Document why each is blocking - ✅ Mark completed with date and details **Action Items**: - ✅ Make items specific and measurable - ✅ Check off immediately after completion - ✅ Execute in logical order (dependencies first) - ✅ Verify incrementally, not just at end - ✅ Document blockers and deviations **Breaking Down Large Items**: - ✅ If > 2 hours, break it down - ✅ Use component, layer, phase, or file breakdown - ✅ Ensure sub-items are still specific - ✅ Maintain logical grouping **Sequential vs Parallel**: - ✅ Sequential when items depend on each other - ✅ Parallel when items are independent - ✅ Hybrid when mix of both - ✅ When in doubt, go sequential (safer) **Common Scenarios**: - ✅ New feature: Sequential with verification - ✅ Bug fix: Diagnose → Fix → Verify - ✅ Refactoring: Incremental with safety checks - ✅ Integration: Mock → Real → Error handling - ✅ Optimization: Measure → Optimize → Verify SKILL_FLOW_BUILDER_PATTERNS_EOF } get_skill_flow_builder_verification() { cat <<'SKILL_FLOW_BUILDER_VERIFICATION_EOF' # Implementation Verification Guide This document provides detailed verification patterns, completion criteria, and decision-making guidance for implementation work using Flow framework. Reference this guide when you need detailed examples and templates for verifying your work. > **Note**: This is a Level 3 resource for the flow-implementer Skill. See [SKILL.md](SKILL.md) for core implementation workflow. ## Table of Contents 1. [Testing Patterns](#testing-patterns) 2. [What "Done" Looks Like](#what-done-looks-like) 3. [When to Document Bugs and Issues](#when-to-document-bugs-and-issues) 4. [Deciding: ❌ BLOCKED vs Continue](#deciding--blocked-vs-continue) --- ## Testing Patterns ### Unit Testing Pattern **When**: Testing individual functions/methods in isolation **Example Structure**: ```typescript describe('RetryPolicy', () => { describe('calculateDelay', () => { it('should return base delay for first retry', () => { const policy = new RetryPolicy({ baseDelay: 1000, maxRetries: 3 }); expect(policy.calculateDelay(1)).toBe(1000); }); it('should apply exponential backoff', () => { const policy = new RetryPolicy({ baseDelay: 1000, maxRetries: 3 }); expect(policy.calculateDelay(2)).toBe(2000); expect(policy.calculateDelay(3)).toBe(4000); }); it('should cap at max delay', () => { const policy = new RetryPolicy({ baseDelay: 1000, maxDelay: 5000 }); expect(policy.calculateDelay(10)).toBe(5000); }); }); }); ``` **What to Test**: - Happy path (expected inputs → expected outputs) - Edge cases (empty, null, undefined, boundary values) - Error cases (invalid inputs → proper errors) - State changes (method calls affect object state correctly) ### Integration Testing Pattern **When**: Testing multiple components working together **Example Structure**: ```typescript describe('Payment Integration', () => { it('should process payment with retry on transient failure', async () => { // Setup: Create real instances (or test doubles) const stripe = new StripeClient(testApiKey); const processor = new PaymentProcessor(stripe); // Mock Stripe to fail once, then succeed jest.spyOn(stripe, 'createCharge') .mockRejectedValueOnce(new TransientError('rate_limit')) .mockResolvedValueOnce({ id: 'ch_123', status: 'succeeded' }); // Execute: Run the full flow const result = await processor.process({ amount: 1000, currency: 'usd', retryPolicy: { maxRetries: 3 } }); // Verify: Check end-to-end behavior expect(result.status).toBe('succeeded'); expect(stripe.createCharge).toHaveBeenCalledTimes(2); // Failed once, succeeded second time }); }); ``` **What to Test**: - Component interactions (A calls B correctly) - Data flow (data transforms correctly through layers) - Error propagation (errors bubble up properly) - Side effects (database writes, API calls, file I/O) ### Manual Testing Checklist **When**: No automated tests exist or testing UI/UX **Checklist Template**: ```markdown **Manual Testing - [Feature Name]** **Setup**: - [ ] Environment: [development/staging] - [ ] Test data: [describe test data used] - [ ] Prerequisites: [any setup needed] **Test Cases**: 1. Happy Path: - [ ] Action: [what you did] - [ ] Expected: [what should happen] - [ ] Actual: [what actually happened] - [ ] Result: ✅ PASS / ❌ FAIL 2. Edge Case: - [ ] Action: [what you did] - [ ] Expected: [what should happen] - [ ] Actual: [what actually happened] - [ ] Result: ✅ PASS / ❌ FAIL **Issues Found**: - [Bug 1 description + severity] - [Bug 2 description + severity] **Verified**: [Date] by [Name] ``` ### Test-Driven Development (TDD) Pattern **When**: Complex logic where tests help design **Flow**: ``` 1. RED: Write failing test ↓ 2. GREEN: Write minimal code to pass ↓ 3. REFACTOR: Improve code while keeping tests green ↓ Repeat ``` **Example Iteration**: ```typescript // Step 1: RED - Write failing test test('should calculate exponential backoff', () => { const delay = calculateBackoff(2, 1000); expect(delay).toBe(2000); }); // Run test → FAILS (function doesn't exist) // Step 2: GREEN - Minimal implementation function calculateBackoff(attempt: number, baseDelay: number): number { return attempt * baseDelay; } // Run test → PASSES // Step 3: REFACTOR - Improve implementation function calculateBackoff(attempt: number, baseDelay: number): number { return Math.pow(2, attempt - 1) * baseDelay; } // Run test → STILL PASSES (for attempt=2: 2^1 * 1000 = 2000) // Step 4: Add more tests to drive better design test('should handle attempt=1', () => { expect(calculateBackoff(1, 1000)).toBe(1000); // 2^0 * 1000 }); ``` --- ## What "Done" Looks Like ### Iteration Completion Criteria An iteration is **truly done** when ALL of the following are true: #### 1. All Action Items Completed ```markdown ✅ Correct: - [x] Create RetryPolicy class - [x] Implement backoff algorithm - [x] Add configuration - [x] Integrate with client - [x] Add tests ❌ Incorrect: - [x] Create RetryPolicy class - [x] Implement backoff algorithm - [ ] Add configuration ← NOT DONE - [x] Integrate with client - [x] Add tests ``` #### 2. Code Works Correctly **Verification Methods** (choose based on project): - Unit tests passing (all green) - Integration tests passing - Manual testing completed with checklist - Code review approved - No compiler/linter errors **Example**: ```bash ✅ All tests passing: PASS src/payment/RetryPolicy.test.ts PASS src/payment/StripeClient.test.ts PASS integration/payment.integration.test.ts Test Suites: 3 passed, 3 total Tests: 24 passed, 24 total ``` #### 3. No Unresolved Blockers **Resolved Blocker Example**: ```markdown **Implementation Notes**: - Created RetryPolicy class - **Blocker Encountered**: Stripe SDK v12 doesn't support custom retry - **Resolution**: Implemented wrapper pattern around SDK calls - **Impact**: Added StripeClientWrapper.ts (86 lines) - Integrated wrapper with payment processor ``` **Unresolved Blocker Example** (iteration NOT done): ```markdown **Implementation Notes**: - Created RetryPolicy class - **Blocker Encountered**: Stripe SDK v12 doesn't support custom retry - **Status**: ❌ WAITING FOR USER DECISION - **Options Presented**: Downgrade to v11, wait for v13, or implement wrapper - **Action**: Cannot proceed until user chooses approach ``` #### 4. Implementation Notes Updated **Complete Notes Example**: ```markdown **Implementation Notes**: Created comprehensive retry logic for payment processing: **What Was Built**: - RetryPolicy class with configurable backoff (src/payment/RetryPolicy.ts, 124 lines) - Exponential backoff algorithm (base: 1s, max: 32s, jitter: 20%) - Error classification (transient vs permanent errors) - Integration with StripeClient via wrapper pattern **Design Decisions**: - Chose exponential backoff over linear (better for API rate limiting) - Added jitter to prevent thundering herd problem - Made policy injectable for easy testing **Challenges & Solutions**: - Challenge: Stripe SDK v12 doesn't support custom retry - Solution: Implemented StripeClientWrapper to intercept API calls - Challenge: Difficult to test retry timing - Solution: Made clock injectable via dependency injection **Deviations from Plan**: - Originally planned to use Stripe's built-in retry, but discovered it's not customizable - Added StripeClientWrapper.ts (not in original action items, but necessary) **Bugs Fixed**: - Fixed off-by-one error in backoff calculation (was 2^attempt, now 2^(attempt-1)) ``` #### 5. Files Modified Documented **Complete Documentation Example**: ```markdown **Files Modified**: - src/payment/RetryPolicy.ts (created, 124 lines) - src/payment/StripeClientWrapper.ts (created, 86 lines) - src/payment/StripeClient.ts (modified, +24 lines, -8 lines) - src/types/payment.ts (modified, +12 lines for retry types) - tests/payment/RetryPolicy.test.ts (created, 98 lines) - tests/payment/StripeClientWrapper.test.ts (created, 64 lines) - integration/payment.integration.test.ts (modified, +42 lines) ``` #### 6. Ready for Next Work **Verification Questions**: - Can the next iteration start immediately? YES / NO - Are there any dependencies that need resolving? YES / NO - Does anything need user decision before continuing? YES / NO **Example - Ready**: ```markdown ✅ READY FOR NEXT ITERATION Current Status: - Iteration 2 (Retry Logic) complete and verified - All tests passing - No blockers for Iteration 3 (Error Logging) - Can proceed immediately with /flow-implement-complete ``` **Example - NOT Ready**: ```markdown ❌ NOT READY - NEEDS USER DECISION Current Status: - Iteration 2 (Retry Logic) functionally complete - All tests passing - **Blocker for Iteration 3**: User needs to decide on logging library - Options: Winston, Pino, or custom logger - Cannot start Iteration 3 until decision made - Mark Iteration 2 complete, but address blocker before starting Iteration 3 ``` --- ## When to Document Bugs and Issues ### Bug Discovery During Implementation **When you discover bugs in EXISTING code** (not your changes): #### Document in Implementation Notes ```markdown **Implementation Notes**: Created payment retry logic. **Bugs Discovered in Existing Code**: ##### Bug 1: Race Condition in PaymentService **Location**: `src/services/PaymentService.ts:145-152` **Problem**: ```typescript // Current buggy code async processPayment(amount: number) { const status = await this.checkStatus(); // Race condition: status can change between check and update await this.updatePayment(status); } ``` **Impact**: Could cause duplicate charges in concurrent requests **Action Taken**: Documented here, created separate task for fix (not in scope of current iteration) **Recommendation**: High priority fix for next sprint ``` #### When to Fix Immediately vs Defer **Fix Immediately** (document in Implementation Notes): - Blocking bug in file you're currently modifying - Syntax error preventing compilation - Trivial fix (< 5 minutes) - Part of your current action items **Defer** (document and create task): - Bug in unrelated code - Requires significant refactoring - Needs design discussion - Out of scope for current iteration ### Issue Severity Levels **Critical** (Fix immediately or BLOCK iteration): - Causes data loss - Security vulnerability - System crash/unavailability - Blocking current work **High** (Document and create follow-up task): - Incorrect functionality - Performance degradation - Race condition/concurrency issue - Affects multiple users **Medium** (Document for backlog): - Edge case handling missing - Poor error messages - Minor performance issue - Affects few users **Low** (Document for future): - Code quality issue - Missing tests - Documentation gap - Nice-to-have improvement --- ## Deciding: ❌ BLOCKED vs Continue ### When to Mark ❌ BLOCKED Mark iteration **❌ BLOCKED** when you **CANNOT PROCEED** without external help: **Valid Blocking Scenarios**: 1. **External Dependency Unavailable**: ```markdown ❌ BLOCKED: Stripe API test environment down - Cannot run integration tests - Need API to be back up before proceeding - Estimated wait: 2-4 hours (according to status page) ``` 2. **Need User Decision**: ```markdown ❌ BLOCKED: Need architecture decision - Two viable approaches for retry logic: A) Client-side retry (simpler, less reliable) B) Server-side retry queue (complex, more reliable) - Cannot proceed without user choosing approach - Next action: Present options to user, await decision ``` 3. **Technical Limitation Discovered**: ```markdown ❌ BLOCKED: Library doesn't support required feature - Stripe SDK v12 doesn't expose retry hooks - Options: downgrade to v11, wait for v13, or implement wrapper - Estimated resolution time: > 2 hours (needs investigation) ``` 4. **Missing Information**: ```markdown ❌ BLOCKED: Missing API credentials - Need production Stripe API key to test - Cannot verify integration without real credentials - User must provide credentials ``` ### When to CONTINUE (Not Block) **DO NOT mark blocked** if you can work around or continue: **Continue Scenarios**: 1. **Minor Issue with Workaround**: ```markdown ✅ CONTINUING: Test flakiness found - Integration test occasionally fails (timing issue) - **Workaround**: Added retry logic to test itself - Can proceed with implementation - **Note**: Will fix flakiness in separate cleanup task ``` 2. **Discover Out-of-Scope Work**: ```markdown ✅ CONTINUING: Found refactoring opportunity - Noticed ErrorHandler could be refactored for better reuse - **Decision**: Out of scope for this iteration - **Action**: Documented for future refactoring task - Proceeding with current implementation using existing ErrorHandler ``` 3. **Can Complete Action Items Without Resolution**: ```markdown ✅ CONTINUING: Documentation incomplete - Found outdated API documentation - **Action**: Using source code as reference instead - Can complete implementation despite docs being stale - **Note**: Will update docs in separate task ``` 4. **Temporary Solution Acceptable**: ```markdown ✅ CONTINUING: Performance not optimal - Current retry logic takes 30s worst case (goal was 20s) - **Decision**: Acceptable for V1, will optimize in V2 - Can mark iteration complete with known limitation - **Note**: Documented in Implementation Notes for V2 improvement ``` ### Decision Flowchart ``` Encounter Issue ↓ Can I complete action items without resolving this? ↓ YES → CONTINUE ↓ Document issue in Implementation Notes Create follow-up task if needed Proceed with implementation ↓ NO → Assess Impact ↓ Is this a minor issue (< 30 min to resolve)? ↓ YES → FIX NOW ↓ Resolve issue Document in Implementation Notes Continue implementation ↓ NO → BLOCKED ↓ Mark iteration ❌ BLOCKED Document blocker clearly Present options to user Wait for decision/resolution ``` ### Example: Blocked vs Continue **Scenario**: Discovered Stripe API rate limiting during testing **Option 1: Mark BLOCKED** (if cannot proceed): ```markdown ❌ BLOCKED: Hit Stripe API rate limit **Issue**: Integration tests hitting Stripe API rate limit (100 requests/hour in test mode) **Impact**: Cannot run integration tests to verify implementation **Cannot Proceed Because**: - Tests are mandatory for completion - No way to verify retry logic works without testing against real API - Mock tests insufficient (need real API behavior) **Options**: A) Request higher rate limit from Stripe support (ETA: 1-2 days) B) Space out test runs (run tests every hour, very slow) C) Use more sophisticated mocking to reduce API calls **Waiting for**: User decision on approach ``` **Option 2: CONTINUE** (if can work around): ```markdown ✅ CONTINUING: Stripe API rate limit hit **Issue**: Integration tests hitting Stripe API rate limit (100 requests/hour in test mode) **Workaround**: Implemented smart test mocking - Created realistic mock responses based on Stripe API documentation - Validated mock responses against real API (used 10 of 100 requests) - Remaining integration tests use mocks - Will run full integration test suite during deployment (production has higher limits) **Impact**: Can proceed with confidence - Core logic tested with mocks - Sample verification with real API successful - Documented limitation for deployment testing **Next Steps**: Continue with implementation ``` SKILL_FLOW_BUILDER_VERIFICATION_EOF } # 6. flow-completer (NEW) get_skill_flow_completer() { cat <<'SKILL_FLOW_COMPLETER_EOF' --- name: flow-completer description: Mark tasks and phases complete after verification. Use when finishing tasks, closing phases, or marking work done. Ensures all work verified before completion. --- # Flow Completer Mark tasks and phases complete after verifying all work is done. This skill enforces completion gates to ensure nothing is forgotten before moving forward. ## When to Use This Skill Activate when the user wants to finish work: - "Finish this task" - "Mark task complete" - "Done with this task" - "Complete the task" - "Finish this phase" - "Mark phase complete" - "Done with this phase" - "Close the task" - "Close the phase" ## Completion Philosophy **Flow's Core Principle**: Verify before closing. Every completion requires verification that all work is done, tested, and documented. **Key Gates**: - **Task Completion Gate**: All iterations ✅ COMPLETE (or ❌ CANCELLED/🔮 DEFERRED) - **Phase Completion Gate**: All tasks ✅ COMPLETE (or ❌ CANCELLED) - **Documentation Gate**: All changes documented, notes updated **Completion Pattern**: Verify → Update Status → Advance Pointer → Report ## Task Completion Workflow ### Step 1: Read Task File Before marking task complete, read the task file to understand current state: **READ**: `.flow/phase-N/task-M.md` **Extract**: - Task name and status - All iterations (if task has iterations) - All action items (if standalone task) - Current work status ### Step 2: Verify Task Completion **Verification Checklist**: ``` IF task has iterations: FOR EACH iteration: IF status = ⏳ PENDING or 🚧 IN PROGRESS: ❌ FAIL: "Iteration N: [Name] is not complete" IF status = ❌ CANCELLED or 🔮 DEFERRED: ✅ PASS (acceptable, not blocking) IF status = ✅ COMPLETE: ✅ PASS IF ALL iterations are ✅/❌/🔮: ✅ PASS task verification ELSE IF standalone task: IF any action items unchecked `- [ ]`: ❌ FAIL: "X action items incomplete" IF all action items checked `- [x]`: ✅ PASS task verification ``` **Additional Checks**: - [ ] Implementation notes updated (if task had implementation) - [ ] Files modified documented - [ ] No unresolved blockers mentioned - [ ] Verification section filled out ### Step 3: Mark Task Complete If verification passes: 1. **Update task file**: ```markdown # Task N: Name **Status**: ✅ COMPLETE (2025-MM-DD) ``` 2. **Update DASHBOARD.md**: - Find task in "Progress Overview" - Change marker: `⏳ Task N: Name` → `✅ Task N: Name` - Update phase completion percentage - Advance "Current Work" pointer to next pending task 3. **Report to user**: ``` ✅ Task N: [Name] marked complete! Completed: - [X] iterations complete (or Y cancelled/deferred) - All action items verified - Documentation updated Next: [Next task or phase status] ``` ### Step 4: Handle Incomplete Work If verification fails: 1. **Report incomplete items**: ``` ❌ Cannot mark task complete. Incomplete work found: Iterations: - ⏳ Iteration 2: [Name] - Status: PENDING - 🚧 Iteration 3: [Name] - Status: IN PROGRESS OR Action Items: - [ ] 3 unchecked action items Complete these first, then use `/flow-task-complete` again. ``` 2. **Suggest actions**: - If iterations pending: "Use `/flow-next-iteration` to continue work" - If action items unchecked: "Complete remaining action items" - If user wants to defer: "Use `/flow-iteration-add` to mark iteration 🔮 DEFERRED" ## Phase Completion Workflow ### Step 1: List All Tasks in Phase **READ**: `.flow/phase-N/` directory **Extract**: - All task files in phase directory - Count total tasks - Determine status of each task ### Step 2: Verify Phase Completion **Verification Checklist**: ``` FOR EACH task in phase: IF task status = ⏳ PENDING or 🚧 IN PROGRESS: ❌ FAIL: "Task N: [Name] is not complete" IF task status = ❌ CANCELLED: ✅ PASS (acceptable, not blocking) IF task status = ✅ COMPLETE: ✅ PASS IF ALL tasks are ✅/❌: ✅ PASS phase verification ``` **Additional Checks**: - [ ] Phase goals achieved (check DASHBOARD.md phase description) - [ ] All deliverables complete - [ ] No pending work in any task ### Step 3: Mark Phase Complete If verification passes: 1. **Update DASHBOARD.md**: - Find phase in "Progress Overview" - Change header: `### Phase N: Name` → `### Phase N: Name ✅` - Update phase status line - Advance "Current Work" to next phase 2. **Report to user**: ``` ✅ Phase N: [Name] marked complete! Completed: - [X] tasks complete (Y cancelled) - All phase goals achieved Next Phase: Phase [N+1]: [Name] OR Project complete! 🎉 ``` ### Step 4: Handle Incomplete Work If verification fails: 1. **Report incomplete tasks**: ``` ❌ Cannot mark phase complete. Incomplete tasks found: Tasks: - ⏳ Task 2: [Name] - Status: PENDING - 🚧 Task 3: [Name] - Status: IN PROGRESS Complete these first, or cancel if scope changed. ``` 2. **Suggest actions**: - "Use `/flow-task-start` to continue Task N" - "Use `/flow-task-complete` to finish Task N" - If scope changed: "Consider marking Task N as ❌ CANCELLED" ## Completion Slash Commands ### `/flow-task-complete` **Use when**: All iterations/action items done for current task **Prerequisites**: - All iterations ✅ COMPLETE (or ❌/🔮) - All action items checked off (if standalone) - Documentation updated **Effect**: - Marks task ✅ COMPLETE with date - Updates DASHBOARD.md progress - Advances current work pointer ### `/flow-phase-complete` **Use when**: All tasks done in current phase **Prerequisites**: - All tasks ✅ COMPLETE (or ❌ CANCELLED) - Phase goals achieved **Effect**: - Marks phase ✅ COMPLETE - Updates DASHBOARD.md - Advances to next phase or project end ## Edge Cases ### Cancelled or Deferred Work **Cancelled Iterations** (❌): - Not blocking for task completion - Document why cancelled in iteration notes - Examples: Scope changed, not needed, replaced by better approach **Deferred Iterations** (🔮): - Not blocking for task completion - Document why deferred (V2, future version) - Examples: Nice-to-have, optimization, future enhancement **Cancelled Tasks** (❌): - Not blocking for phase completion - Document why cancelled in task notes - Examples: Duplicate work, scope change, no longer needed ### Partial Completion **Scenario**: Task has 5 iterations, 3 complete, 2 deferred ``` ✅ Iteration 1: Basic Implementation - COMPLETE ✅ Iteration 2: Core Features - COMPLETE ✅ Iteration 3: Testing - COMPLETE 🔮 Iteration 4: Advanced Features - DEFERRED (V2) 🔮 Iteration 5: Optimizations - DEFERRED (V2) ``` **Action**: Task can be marked complete! Deferred work doesn't block. **Report**: ``` ✅ Task can be marked complete! Completed: 3/5 iterations Deferred to V2: 2 iterations (documented) This is valid - deferred work doesn't block completion. ``` ### Blocked Work **Scenario**: Task has iteration marked ❌ BLOCKED ``` ✅ Iteration 1: Setup - COMPLETE ❌ Iteration 2: Implementation - BLOCKED (external dependency unavailable) ⏳ Iteration 3: Testing - PENDING ``` **Action**: Cannot mark task complete - blocked iteration needs resolution **Report**: ``` ❌ Cannot mark task complete. Found blocked work: Iteration 2: Implementation - ❌ BLOCKED Blocker: External dependency unavailable Resolution options: 1. Unblock iteration and complete it 2. Mark iteration ❌ CANCELLED if no longer needed 3. Mark iteration 🔮 DEFERRED if can be done later ``` ## Completion Verification Patterns ### Pattern 1: Task with All Iterations Complete ``` ✅ Iteration 1: Skeleton - COMPLETE (2025-10-15) ✅ Iteration 2: Veins - COMPLETE (2025-10-18) ✅ Iteration 3: Flesh - COMPLETE (2025-10-22) ``` **Verification**: ✅ PASS - All iterations complete **Action**: Mark task complete ### Pattern 2: Task with Mixed Status ``` ✅ Iteration 1: Basic Feature - COMPLETE (2025-10-15) ❌ Iteration 2: Advanced Feature - CANCELLED (scope change) 🔮 Iteration 3: Optimization - DEFERRED (V2) ``` **Verification**: ✅ PASS - No pending/in-progress iterations **Action**: Mark task complete (cancelled and deferred are acceptable) ### Pattern 3: Standalone Task ``` Action Items: - [x] Create component - [x] Add tests - [x] Update documentation - [x] Deploy to staging ``` **Verification**: ✅ PASS - All action items checked **Action**: Mark task complete ### Pattern 4: Phase with All Tasks Done ``` ### Phase 2: Core Features - ✅ Task 1: User Authentication - COMPLETE - ✅ Task 2: API Endpoints - COMPLETE - ❌ Task 3: Admin Dashboard - CANCELLED (out of V1 scope) - ✅ Task 4: Error Handling - COMPLETE ``` **Verification**: ✅ PASS - No pending/in-progress tasks **Action**: Mark phase complete ## Best Practices **DO**: - ✅ Verify ALL iterations/tasks before marking complete - ✅ Check documentation is updated - ✅ Update both task file AND DASHBOARD.md - ✅ Advance current work pointer after completion - ✅ Report summary of what was completed **DON'T**: - ❌ Skip verification checks - ❌ Mark incomplete work as complete - ❌ Forget to update DASHBOARD.md - ❌ Leave current work pointer on completed item - ❌ Ignore blocked or pending iterations ## Examples ### Example 1: Completing Task with All Iterations Done ``` User: "Mark this task complete" AI Process: 1. Read task file (task-2.md) 2. Find 3 iterations, all marked ✅ COMPLETE 3. Verify documentation updated 4. All checks pass AI Response: "✅ Task 2: API Integration marked complete! Verification Results: ✅ All 3 iterations complete: - Iteration 1: Basic Setup (2025-10-15) - Iteration 2: Error Handling (2025-10-18) - Iteration 3: Testing (2025-10-22) ✅ Implementation notes updated ✅ 12 files modified documented ✅ Tests passing Updated DASHBOARD.md - Phase 2 now 50% complete (2/4 tasks done) Next: Task 3: Database Integration (⏳ PENDING)" ``` ### Example 2: Cannot Complete - Found Incomplete Work ``` User: "Finish this task" AI Process: 1. Read task file (task-3.md) 2. Find 4 iterations: 2 complete, 1 in progress, 1 pending 3. Verification FAILS AI Response: "❌ Cannot mark task complete. Found incomplete work: Iterations Status: ✅ Iteration 1: Schema Design - COMPLETE ✅ Iteration 2: Migrations - COMPLETE 🚧 Iteration 3: Data Access Layer - IN PROGRESS (60% done) ⏳ Iteration 4: Testing - PENDING Complete Iteration 3 and 4 first, then use `/flow-task-complete`. Current action items for Iteration 3: - [x] Create User repository - [x] Create Post repository - [ ] Create Comment repository (← CURRENT) - [ ] Add transaction support - [ ] Add error handling" ``` ### Example 3: Completing Phase ``` User: "Mark Phase 2 complete" AI Process: 1. List all tasks in phase-2/ directory 2. Find 5 tasks: 4 complete, 1 cancelled 3. Verify phase goals achieved 4. All checks pass AI Response: "✅ Phase 2: Core Features marked complete! Verification Results: ✅ All tasks done: - Task 1: User Auth - COMPLETE - Task 2: API Endpoints - COMPLETE - Task 3: Data Layer - COMPLETE - Task 4: Error Handling - COMPLETE - Task 5: Admin Panel - CANCELLED (scope change, documented) ✅ Phase goals achieved: - User authentication working - API fully functional - Data persistence implemented - Error handling in place Phase 2 Duration: 3 weeks (Oct 1 - Oct 22) Updated DASHBOARD.md - Project now 66% complete (2/3 phases done) Next Phase: Phase 3: Testing & Polish (⏳ PENDING)" ``` ### Example 4: Completing Task with Deferred Work ``` User: "Complete this task" AI Process: 1. Read task file (task-4.md) 2. Find 5 iterations: 3 complete, 2 deferred to V2 3. Verification PASSES (deferred is acceptable) AI Response: "✅ Task 4: Performance Optimization can be marked complete! Verification Results: ✅ Core iterations complete (3/5): - Iteration 1: Identify Bottlenecks - COMPLETE - Iteration 2: Database Indexing - COMPLETE - Iteration 3: Caching Layer - COMPLETE 🔮 Deferred to V2 (2/5): - Iteration 4: Advanced Caching - DEFERRED (nice-to-have) - Iteration 5: Load Balancing - DEFERRED (premature optimization) This is valid! Deferred work doesn't block task completion. Updated task status to ✅ COMPLETE (2025-10-22) Phase 3 now 75% complete (3/4 tasks done) Next: Task 5: Documentation (⏳ PENDING)" ``` ## Interaction with Other Flow Skills **Build Stage** (flow-builder Skill): - `/flow-implement-complete` - Marks iteration complete - That feeds into this skill's task completion checks **Complete Stage** (This Skill): - `/flow-task-complete` - Mark task done ← YOU ARE HERE - `/flow-phase-complete` - Mark phase done ← YOU ARE HERE **Navigate Stage** (flow-navigator Skill): - `/flow-status` - Check what's left before completing - `/flow-next` - See next work after completing ## References - **Task Completion Pattern**: DEVELOPMENT_FRAMEWORK.md lines 1837-1871 - **Status Markers**: DEVELOPMENT_FRAMEWORK.md lines 1872-1968 - **Phase Management**: DEVELOPMENT_FRAMEWORK.md lines 170-237 ## Completion Gate Checklist ### Before Completing Task ``` [ ] All iterations ✅ COMPLETE (or ❌/🔮) [ ] OR all action items checked (standalone task) [ ] Implementation notes updated [ ] Files modified documented [ ] No unresolved blockers [ ] Verification section complete ``` If ALL checked → Use `/flow-task-complete` If ANY unchecked → Complete remaining work first ### Before Completing Phase ``` [ ] All tasks ✅ COMPLETE (or ❌ CANCELLED) [ ] Phase goals achieved [ ] All deliverables done [ ] No pending work in phase ``` If ALL checked → Use `/flow-phase-complete` If ANY unchecked → Complete remaining tasks first SKILL_FLOW_COMPLETER_EOF } # 7. flow-verifier (REFACTOR - renamed from flow-reviewer) get_skill_flow_verifier() { cat <<'SKILL_FLOW_VERIFIER_EOF' --- name: flow-verifier description: Verify plan consistency, generate summaries, maintain plan health. Use for review, verification, summaries, or plan maintenance. Mostly read-only with maintenance operations. allowed-tools: Read, Grep, Glob, Edit, Write --- # Flow Verifier Verify plan consistency, generate summaries, and maintain plan health. This skill combines read-only inspection (verify, review) with maintenance operations (summarize, compact, rollback). ## When to Use This Skill Activate when the user wants verification: - "Review the plan" - "Verify the status" - "Check if we're done" - "Is the implementation complete?" - "Validate the structure" - "Are there any issues?" - "Check for inconsistencies" - "Verify all tasks are tracked" ## Review Philosophy **Read-Only Inspection**: This Skill observes and reports, never modifies. **What We Check**: - Status markers match actual state - No phantom tasks (DASHBOARD promises what doesn't exist) - Brainstorming complete before implementation starts - Task structure follows Flow rules - Action items are all checked off when complete - File references are valid **Tools Available**: `Read`, `Grep`, `Glob` (read-only tools only) ## Review Checklist ### 1. Status Marker Consistency **Check**: Do status markers reflect actual state? **How to verify**: ```bash # Find all IN PROGRESS items grep -r "🚧 IN PROGRESS" .flow/ # Find all COMPLETE items grep -r "✅ COMPLETE" .flow/ # Find all PENDING items grep -r "⏳ PENDING" .flow/ ``` **Common issues**: - Task marked 🚧 IN PROGRESS but all iterations are ✅ COMPLETE - Iteration marked ⏳ PENDING but has implementation section - Multiple items marked 🚧 IN PROGRESS (should only be one active) **Example problem**: ```markdown ### 🚧 Iteration 2: Error Handling **Status**: ✅ COMPLETE (2025-10-30) ← MISMATCH! ``` **Report**: ``` ❌ Status Marker Mismatch - Iteration 2 header shows 🚧 IN PROGRESS - Implementation section shows ✅ COMPLETE - Action: Update header to match implementation status ``` ### 2. Phantom Task Detection **Check**: Does every task listed in DASHBOARD.md have a corresponding file? **How to verify**: ```bash # List all tasks mentioned in DASHBOARD grep "Task [0-9]" .flow/DASHBOARD.md # Check if task files exist ls .flow/phase-*/task-*.md ``` **Common issues**: - DASHBOARD lists "Task 5" but `.flow/phase-2/task-5.md` doesn't exist - Task file references non-existent iterations **Example problem**: ```markdown DASHBOARD.md: - 🚧 **Task 3**: API Integration (2/4 iterations) But: .flow/phase-2/task-3.md doesn't exist ``` **Report**: ``` ❌ Phantom Task Detected - DASHBOARD.md references Task 3: API Integration - File .flow/phase-2/task-3.md does not exist - Action: Create task file or remove from DASHBOARD ``` ### 3. Implementation Gate Verification **Check**: Is implementation starting before brainstorming is complete? **How to verify**: ```bash # Check if iteration has brainstorming grep -A 20 "## Brainstorming" task-file.md # Check brainstorming status grep "Brainstorming.*Status.*COMPLETE" task-file.md # Check if implementation started grep "## Implementation" task-file.md ``` **Gate Rule**: If iteration has brainstorming, it must be ✅ COMPLETE before implementation starts. **Example problem**: ```markdown ## Brainstorming **Status**: 🚧 IN PROGRESS ## Implementation **Status**: 🚧 IN PROGRESS ← GATE VIOLATION! ``` **Report**: ``` ❌ Implementation Gate Violation - Iteration 2 has brainstorming IN PROGRESS - Implementation section already started - Action: Complete brainstorming before implementing ``` ### 4. Task Structure Validation **Check**: Does task follow the Golden Rule (Standalone XOR Iterations)? **Golden Rule**: Tasks have EITHER: - Direct action items (standalone task) - OR iterations with action items in each iteration - NEVER both **How to verify**: ```bash # Check if task has direct action items grep -A 5 "## Action Items" task-file.md # Check if task has iterations grep "### " task-file.md | grep "Iteration" ``` **Example problem**: ```markdown # Task 3: API Integration ## Action Items - [ ] Create StripeClient - [ ] Add error handling ## Iterations ### Iteration 1: Setup ... ``` **Report**: ``` ❌ Task Structure Violation (Golden Rule) - Task 3 has both direct action items AND iterations - Golden Rule: Tasks must be EITHER standalone OR have iterations, never both - Action: Move action items into iterations or remove iterations ``` ### 5. Action Item Completion Check **Check**: Are all action items checked off when iteration is marked complete? **How to verify**: ```bash # Find iteration marked COMPLETE grep -B 2 "Status.*COMPLETE" task-file.md # Check for unchecked action items in that iteration grep -A 30 "### ✅ Iteration" task-file.md | grep "\[ \]" ``` **Example problem**: ```markdown ### ✅ Iteration 2: Error Handling **Status**: ✅ COMPLETE #### Action Items - [x] Create ErrorMapper - [ ] Add tests ← UNCHECKED! - [x] Integrate with client ``` **Report**: ``` ❌ Incomplete Action Items - Iteration 2 marked ✅ COMPLETE - But action item "Add tests" is unchecked - Action: Either complete the item or mark iteration as IN PROGRESS ``` ### 6. File Reference Validation **Check**: Do all file references point to existing files? **How to verify**: ```bash # Find file references in task files grep -r "\`.*\.ts\`" .flow/ | grep -v "example" # Check if referenced files exist ls path/to/file.ts ``` **Example problem**: ```markdown **Files Modified**: - src/payment/StripeClient.ts - src/payment/DoesNotExist.ts ← FILE DOESN'T EXIST! ``` **Report**: ``` ⚠️ Invalid File Reference - Iteration 2 references src/payment/DoesNotExist.ts - File does not exist in repository - Action: Verify file path or remove invalid reference ``` ## Status Markers Reference ### Valid Status Markers **Task/Iteration Status**: - ✅ `COMPLETE` - Work finished and verified - 🚧 `IN PROGRESS` - Currently working on this - ⏳ `PENDING` - Not started yet - 🎨 `READY` - Ready to implement (brainstorming complete) - ❌ `CANCELLED` - Work abandoned - 🔮 `DEFERRED` - Moved to future version **Phase Status**: - ✅ `COMPLETE` - All tasks in phase done - 🚧 `IN PROGRESS` - Currently working in this phase - ⏳ `PENDING` - Phase not started ### Status Marker Lifecycle **Iteration Lifecycle**: ``` ⏳ PENDING ↓ (brainstorming started) 🚧 IN PROGRESS (brainstorming) ↓ (brainstorming complete, ready to implement) 🎨 READY ↓ (/flow-implement-start) 🚧 IN PROGRESS (implementing) ↓ (/flow-implement-complete) ✅ COMPLETE ``` **Common Mistakes**: - ❌ Skipping 🎨 READY (going from brainstorming to implementation without marking ready) - ❌ Multiple items marked 🚧 IN PROGRESS (should only be one active) - ❌ Marking ✅ COMPLETE with unchecked action items - ❌ Using ⏳ PENDING after implementation started ## Common Review Patterns ### Pattern 1: Full Plan Review **When**: User asks "review the entire plan" **Steps**: 1. Read DASHBOARD.md to understand structure 2. For each phase: - Verify phase status matches task statuses - Check all tasks listed have files 3. For each task: - Verify task status matches iteration statuses - Check structure (standalone XOR iterations) 4. For each iteration: - Verify status marker consistency - Check action items if marked complete 5. Report all findings **Output format**: ```markdown ## Plan Review Results **Summary**: 15 items checked, 2 issues found ### ✅ Passing Checks (13) - All phase statuses consistent - No phantom tasks detected - Task structure valid - ... ### ❌ Issues Found (2) #### Issue 1: Status Marker Mismatch - **Location**: Phase 2, Task 3, Iteration 2 - **Problem**: Header shows 🚧 but implementation shows ✅ - **Action**: Update header to ✅ COMPLETE #### Issue 2: Unchecked Action Items - **Location**: Phase 2, Task 4, Iteration 1 - **Problem**: Iteration marked complete but 1 action item unchecked - **Action**: Complete action item or mark iteration IN PROGRESS ``` ### Pattern 2: Task-Specific Review **When**: User asks "review Task 3" **Steps**: 1. Read task file 2. Check task status consistency 3. Verify structure (standalone XOR iterations) 4. For each iteration: - Status marker consistency - Action item completion - Implementation gate (brainstorming before implementation) 5. Report findings ### Pattern 3: Status Audit **When**: User asks "check all status markers" **Steps**: 1. Grep for all status markers 2. For each marker: - Verify it's in valid lifecycle position - Check consistency with surrounding content 3. Check for multiple IN PROGRESS items (should be max 1) 4. Report findings ## Review Commands ### Check for Phantom Tasks ```bash # List tasks from DASHBOARD grep -E "Task [0-9]" .flow/DASHBOARD.md # List actual task files ls .flow/phase-*/task-*.md # Compare (manual check) ``` ### Find Incomplete Work ```bash # Find all IN PROGRESS items grep -r "🚧 IN PROGRESS" .flow/ # Find unchecked action items grep -r "\[ \]" .flow/phase-*/*.md ``` ### Verify Implementation Gates ```bash # Find iterations with brainstorming grep -r "## Brainstorming" .flow/phase-*/ # Check if brainstorming is complete grep -A 2 "## Brainstorming" .flow/phase-*/*.md | grep "Status" ``` ### Validate Task Structure ```bash # Check for direct action items in tasks grep -A 5 "## Action Items" .flow/phase-*/task-*.md # Check for iterations grep "### " .flow/phase-*/task-*.md | grep -i iteration ``` ## Summary Generation **Command**: `/flow-summarize` **Purpose**: Generate comprehensive summary of project status ### When to Summarize - Project milestone reached - Preparing status report - End of sprint/phase - Before stakeholder meeting - User asks "summarize the project" ### Summary Template ```markdown # Project Summary **Generated**: [DATE] **Project**: [PROJECT_NAME from PLAN.md] **Version**: [VERSION from PLAN.md] ## Overview **Goal**: [Project goal from PLAN.md] **Status**: [Overall status - % complete] **Current Work**: Phase [N], Task [M], Iteration [K] ## Phase Progress ### Phase 1: [Name] ✅ COMPLETE **Duration**: [Start date] - [End date] **Goal**: [Phase goal] **Completed Tasks**: [X/X] Key deliverables: - [Task 1: Name] - [Brief outcome] - [Task 2: Name] - [Brief outcome] ### Phase 2: [Name] 🚧 IN PROGRESS **Duration**: [Start date] - present **Goal**: [Phase goal] **Completed Tasks**: [X/Y] Completed: - [Task 1: Name] - [Brief outcome] In Progress: - [Task 2: Name] - [Current iteration] Pending: - [Task 3: Name] - [Purpose] ## Key Decisions [Extract from PLAN.md Key Decisions section] ## Next Steps 1. [Immediate next action] 2. [Upcoming milestone] 3. [Blockers if any] ``` ### Summary Generation Process 1. Read DASHBOARD.md for current status 2. Read all task files for completion details 3. Read PLAN.md for project context 4. Generate summary using template 5. Return formatted markdown ## Plan Maintenance ### Compact Operation **Command**: `/flow-compact` **Purpose**: Remove clutter from old completed work **When to Compact**: - DASHBOARD.md getting too large (>500 lines) - Many completed iterations with excessive notes - Old completed phases cluttering active plan **What Gets Compacted**: - Completed iterations older than 30 days: - Remove implementation notes (keep summary) - Remove detailed action items (keep count) - Keep completion date and key outcomes - Completed phases: - Collapse task details (keep titles and status) - Keep phase summary and goals achieved **What's Preserved**: - All status markers - Completion dates - Task/iteration names - Key outcomes - Current work (last 30 days) **Process**: 1. Create backup in `.flow/.backups/` 2. Identify items to compact 3. Remove excessive detail 4. Verify plan still valid 5. Report what was compacted ### Rollback Operation **Command**: `/flow-rollback` **Purpose**: Undo last change if something went wrong **When to Rollback**: - Accidental deletion of important content - Bad compact operation - Incorrect status updates - User regrets last change **Rollback Process**: 1. List available backups in `.flow/.backups/` 2. Show timestamp and change description 3. User selects backup to restore 4. Restore selected files 5. Report what was rolled back **Backup Strategy**: - Auto-backup before compact - Auto-backup before plan-split - Keep last 10 backups - Backups include timestamp and change type ## Interaction with Other Flow Skills **Planning Stage** (flow-planner Skill): - Planner creates structure - Verifier validates structure **Implementation Stage** (flow-builder Skill): - Builder executes work - Verifier checks completion **Design Stage** (flow-designer Skill): - Designer documents decisions - Verifier checks references are valid **Verify Stage** (This Skill): - Inspect plan consistency ← YOU ARE HERE - Generate summaries ← YOU ARE HERE - Maintain plan health ← YOU ARE HERE ## Reporting Guidelines ### Report Format **Use this structure for review findings**: ```markdown ## Review Results **Scope**: [What was reviewed] **Date**: [Review date] **Status**: [✅ All Clear | ⚠️ Issues Found] ### Summary - X checks performed - Y issues found - Z warnings ### ✅ Passing Checks - [List what's working correctly] ### ❌ Issues Found - [List problems discovered] ### ⚠️ Warnings - [List potential concerns] ### 📋 Recommendations - [Suggested actions to fix issues] ``` ### Severity Levels **❌ Critical**: Must fix before proceeding - Phantom tasks (DASHBOARD promises don't exist) - Implementation started before brainstorming complete - Task structure violates Golden Rule **⚠️ Warning**: Should fix soon - Status marker inconsistency (cosmetic) - Unchecked action items with work complete - Minor file reference issues **ℹ️ Info**: Nice to fix - Formatting inconsistencies - Missing optional documentation ## Examples ### Example 1: Full Plan Review ``` User: "Review the entire plan" AI Process: 1. Read DASHBOARD.md to understand structure (3 phases, 8 tasks total) 2. Check each phase for status consistency 3. Verify all task files exist 4. Check task structure (standalone XOR iterations) 5. Verify status markers match implementation 6. Check action item completion AI Response: "## Plan Review Results **Summary**: 15 checks performed, 2 issues found ### ✅ Passing Checks (13) - All phase statuses consistent with task statuses - No phantom tasks detected (all DASHBOARD tasks have files) - Task structure valid (no mixing of action items and iterations) - All completed iterations have checked action items - File references valid ### ❌ Issues Found (2) #### Issue 1: Status Marker Mismatch - **Location**: Phase 2, Task 3, Iteration 2 - **Problem**: Header shows 🚧 IN PROGRESS but status line shows ✅ COMPLETE (2025-10-30) - **Severity**: ⚠️ Warning (cosmetic issue) - **Action**: Update header to `### ✅ Iteration 2: Error Handling` #### Issue 2: Implementation Gate Violation - **Location**: Phase 2, Task 4, Iteration 1 - **Problem**: Brainstorming status is 🚧 IN PROGRESS but Implementation section exists - **Severity**: ❌ Critical (violates gate rule) - **Action**: Complete brainstorming before continuing implementation" ``` ### Example 2: Generating Summary ``` User: "Summarize the project status" AI Process: 1. Read DASHBOARD.md for current work and progress 2. Read PLAN.md for project context 3. Read all task files for completion details 4. Generate formatted summary AI Response: "# Project Summary **Generated**: 2025-11-02 **Project**: Flow Framework Agent Skills **Version**: 1.0.0 ## Overview **Goal**: Refactor 8 workflow stage-based agent skills from 28 slash commands **Status**: 57% complete (4/7 iterations in current task) **Current Work**: Phase 3, Task 4, Iteration 5 ## Phase Progress ### Phase 1: Foundation ✅ COMPLETE **Duration**: Oct 15 - Oct 22 **Goal**: Set up project structure **Completed Tasks**: 2/2 Key deliverables: - Task 1: Project Setup - Framework structure established - Task 2: Documentation - Architecture spec complete ### Phase 2: Initial Skills 🚧 IN PROGRESS **Duration**: Oct 23 - present **Goal**: Build core workflow skills **Completed Tasks**: 2/4 Completed: - Task 1: flow-initializer - Project initialization complete - Task 2: flow-planner - Planning workflows done In Progress: - Task 4: Stage-Based Skills - Building flow-designer + flow-builder (Iteration 5 of 7) Pending: - Task 5: Verification Skills - Not started ## Key Decisions - Progressive disclosure strategy: SKILL.md (400-500 lines) + supporting files - 8 workflow stage-based skills absorb all 28 commands - Dashboard-first navigation pattern throughout ## Next Steps 1. Complete Iteration 5 (flow-completer + flow-navigator) 2. Begin Iteration 6 (flow-verifier + flow-curator) 3. Final verification and integration testing" ``` ### Example 3: Compact Operation ``` User: "The DASHBOARD is getting too long, can you clean it up?" AI Process: 1. Read DASHBOARD.md (780 lines) 2. Identify completed items older than 30 days (Phase 1 completed Oct 22) 3. Create backup before compacting AI Response: "I'll compact old completed work to reduce clutter. **Before Compacting**: - Created backup: .flow/.backups/2025-11-02-143022-pre-compact.zip - Current DASHBOARD.md: 780 lines - Identified items to compact: Phase 1 (completed 11 days ago) **What Will Be Compacted**: - Phase 1, Task 1: Remove 45 lines of implementation notes (keep summary) - Phase 1, Task 2: Remove 38 lines of detailed action items (keep count) - Preserve all status markers and completion dates **After Compacting**: - New DASHBOARD.md: ~520 lines (33% reduction) - All important info preserved - Backup available for rollback if needed Proceed with compact operation?" ``` ### Example 4: Rollback Operation ``` User: "Oh no, I accidentally deleted important content. Can you undo that?" AI Process: 1. List backups in .flow/.backups/ 2. Show recent backups with timestamps AI Response: "Available backups: 1. 2025-11-02 14:30:22 - Pre-compact (DASHBOARD.md, 780 lines) 2. 2025-11-01 16:45:10 - Pre-plan-split (3 phase files archived) 3. 2025-10-31 09:20:15 - Manual backup (full project) Which backup would you like to restore? User: "Restore backup 1" AI Process: 1. Restore DASHBOARD.md from backup 1 2. Verify restored file 3. Report what was rolled back AI Response: "✅ Rollback complete! **Restored**: - .flow/DASHBOARD.md (from 2025-11-02 14:30:22 backup) - File size: 780 lines - All content restored to pre-compact state **What Changed**: - Phase 1 details restored (83 lines of implementation notes) - Detailed action items restored - Current file backed up to .flow/.backups/2025-11-02-145530-pre-rollback.zip (just in case) Your content is back!" ``` ## References - **Status Markers**: DEVELOPMENT_FRAMEWORK.md lines 1872-1968 - **Task Structure Rules**: DEVELOPMENT_FRAMEWORK.md lines 238-566 - **Implementation Gates**: DEVELOPMENT_FRAMEWORK.md lines 1798-1836 - **Slash Commands**: `/flow-verify-plan`, `/flow-summarize`, `/flow-compact`, `/flow-rollback` ## Key Reminders **Before reviewing**: - [ ] Understand what user wants reviewed (full plan, specific task, status audit) - [ ] Use read-only tools (Grep, Read, Glob) - [ ] Never modify files during review **During review**: - [ ] Check status marker consistency - [ ] Verify no phantom tasks - [ ] Validate implementation gates - [ ] Check task structure (Golden Rule) - [ ] Verify action item completion **After review**: - [ ] Report findings in structured format - [ ] Prioritize issues by severity - [ ] Suggest specific actions to fix - [ ] Don't modify files - let user or other Skills handle fixes SKILL_FLOW_VERIFIER_EOF } get_skill_flow_verifier_verify() { cat <<'SKILL_FLOW_VERIFIER_VERIFY_EOF' # Verification Scripts Quick reference for common Flow framework verification tasks using bash commands. > **Note**: This is a Level 3 resource for the flow-reviewer Skill. See [SKILL.md](SKILL.md) for complete review guidance. ## Status Consistency Checks ### Find All IN PROGRESS Items ```bash grep -r "🚧 IN PROGRESS" .flow/ ``` ### Count Active Work Items ```bash grep -r "🚧 IN PROGRESS" .flow/ | wc -l # Should be 1 (only one active item at a time) ``` ### Find Mismatched Status Markers ```bash # Find headers marked IN PROGRESS grep -B 2 "### 🚧" .flow/phase-*/*.md # Check if their implementation sections match grep -A 5 "Status.*COMPLETE" .flow/phase-*/*.md | grep "### 🚧" ``` ## Incomplete Work Detection ### Find Unchecked Action Items ```bash grep -r "\[ \]" .flow/phase-*/*.md ``` ### Find Iterations Marked Complete with Unchecked Items ```bash for file in .flow/phase-*/task-*.md; do if grep -q "### ✅.*Iteration" "$file"; then echo "Checking $file..." grep -A 50 "### ✅.*Iteration" "$file" | grep "\[ \]" && echo "❌ Found unchecked items in complete iteration" fi done ``` ## Phantom Task Detection ### List Tasks from DASHBOARD ```bash grep -E "Task [0-9]:" .flow/DASHBOARD.md | sed 's/.*Task /Task /' ``` ### List Actual Task Files ```bash ls .flow/phase-*/task-*.md | xargs -n 1 basename ``` ### Compare (Find Missing Files) ```bash # Extract task numbers from DASHBOARD dashboard_tasks=$(grep -oE "Task [0-9]+" .flow/DASHBOARD.md | sort -u) # Check each one exists for task in $dashboard_tasks; do task_num=$(echo $task | grep -oE "[0-9]+") if ! ls .flow/phase-*/task-${task_num}.md 2>/dev/null | grep -q .; then echo "❌ Phantom task: $task (file missing)" fi done ``` ## Implementation Gate Verification ### Check Brainstorming Status Before Implementation ```bash for file in .flow/phase-*/task-*.md; do if grep -q "## Brainstorming" "$file"; then brainstorm_status=$(grep -A 2 "## Brainstorming" "$file" | grep "Status" | head -1) impl_status=$(grep -A 2 "## Implementation" "$file" | grep "Status" | head -1 2>/dev/null) if echo "$impl_status" | grep -q "IN PROGRESS" && ! echo "$brainstorm_status" | grep -q "COMPLETE"; then echo "❌ Gate violation in $file" echo " Brainstorming: $brainstorm_status" echo " Implementation: $impl_status" fi fi done ``` ## Task Structure Validation ### Find Tasks with Both Standalone Items AND Iterations ```bash for file in .flow/phase-*/task-*.md; do has_items=$(grep -c "^## Action Items" "$file" 2>/dev/null || echo 0) has_iterations=$(grep -c "### .*Iteration" "$file" 2>/dev/null || echo 0) if [ "$has_items" -gt 0 ] && [ "$has_iterations" -gt 0 ]; then echo "❌ Golden Rule violation: $file has both standalone items AND iterations" fi done ``` ## Common Verification Workflows ### Full Plan Health Check ```bash #!/bin/bash echo "=== Flow Plan Health Check ===" echo echo "1. Checking for multiple IN PROGRESS items..." in_progress=$(grep -r "🚧 IN PROGRESS" .flow/ | wc -l) if [ "$in_progress" -gt 1 ]; then echo "⚠️ Found $in_progress IN PROGRESS items (should be max 1)" grep -r "🚧 IN PROGRESS" .flow/ else echo "✅ Only $in_progress IN PROGRESS item" fi echo echo "2. Checking for phantom tasks..." # (phantom task check from above) echo echo "3. Checking for unchecked items in complete iterations..." # (unchecked items check from above) echo echo "=== Health Check Complete ===" ``` ### Quick Status Audit ```bash echo "Task Status Summary:" echo "===================" echo "COMPLETE: $(grep -r "✅ COMPLETE" .flow/ | wc -l)" echo "IN PROGRESS: $(grep -r "🚧 IN PROGRESS" .flow/ | wc -l)" echo "PENDING: $(grep -r "⏳ PENDING" .flow/ | wc -l)" echo "READY: $(grep -r "🎨 READY" .flow/ | wc -l)" ``` ## Issue Reporting Template When verification finds issues, report them like this: ```markdown ## Verification Results **Date**: 2025-10-30 **Scope**: Full plan review ### Issues Found #### ❌ Issue 1: Multiple IN PROGRESS Items - **Details**: Found 3 items marked 🚧 IN PROGRESS - **Locations**: - Phase 2, Task 3, Iteration 2 - Phase 2, Task 4, Iteration 1 - Phase 3, Task 1, Iteration 1 - **Action**: Mark 2 as complete or pending, keep only 1 active #### ⚠️ Warning: Unchecked Action Items - **Details**: Iteration marked complete but has unchecked items - **Location**: Phase 2, Task 3, Iteration 2 - **Action**: Check off items or mark iteration IN PROGRESS ``` SKILL_FLOW_VERIFIER_VERIFY_EOF } # 8. flow-curator (NEW) get_skill_flow_curator() { cat <<'SKILL_FLOW_CURATOR_EOF' --- name: flow-curator description: Manage backlog and archive completed work. Use for backlog operations, archiving phases, or keeping active plan focused. Curates plan organization. --- # Flow Curator Manage backlog, archive completed work, and keep the active plan focused. This skill handles plan organization and hygiene through backlog management and archiving operations. ## When to Use This Skill Activate when the user wants plan organization: - "Move this to backlog" - "Add to backlog" - "Show backlog" - "View backlog" - "Pull from backlog" - "Bring back from backlog" - "Archive completed work" - "Archive this phase" - "Split the plan" - "Clean up completed tasks" ## Curation Philosophy **Keep Active Plan Focused**: Only show work that's relevant now. Defer future work to backlog, archive completed work to history. **Three Storage Areas**: - **Active Plan** (`.flow/phase-N/`): Current and near-future work - **Backlog** (`.flow/backlog/`): Deferred tasks (scope creep, future ideas, blocked work) - **Archive** (`.flow/archive/`): Completed phases (history, reference) ## Backlog Management ### When to Backlog **Move tasks to backlog when**: - Scope creep: "That's a good idea, but not for V1" - Blocked: "Can't work on this until X is done" - Priorities shifted: "Let's focus on Y first" - Future enhancement: "Nice-to-have, but not essential" - Too many active tasks: "Plan is getting cluttered" **DON'T backlog**: - Tasks already IN PROGRESS (complete or cancel them) - Tasks already COMPLETE (archive instead) - Core V1 features (adjust scope instead) ### Backlog Structure **Backlog task file** (`.flow/backlog/task-M.md`): ```markdown # Task M: [Name] **Original Phase**: Phase [N] **Backlogged**: [DATE] **Reason**: [Why deferred - scope creep, blocked, priority shift, etc.] **Status**: 🔮 BACKLOG --- ## Task Overview **Purpose**: [Why this task exists] **Dependencies**: [What it requires] --- ## Action Items / Iterations [Original task content preserved] --- ## Notes **When to Pull Back**: - [Condition that would make this task relevant again] - [Example: "When API v2 is stable", "After V1 launch", "If user feedback requests this"] ``` ### Backlog Operations #### Add to Backlog **Command**: `/flow-backlog-add` **Process**: 1. Verify task is ⏳ PENDING (not IN PROGRESS or COMPLETE) 2. Prompt: "Why are you backlogging this task?" (capture reason) 3. Move `phase-N/task-M.md` to `.flow/backlog/task-M.md` 4. Add metadata header (original phase, date, reason) 5. Update DASHBOARD.md: - Remove from phase progress overview - Add to "Backlog" section 6. Renumber remaining tasks in phase if needed 7. Report what was backlogged #### View Backlog **Command**: `/flow-backlog-view` **Process**: 1. List all files in `.flow/backlog/` 2. For each task, extract: - Task name - Original phase - Date backlogged - Reason 3. Sort by date backlogged (oldest first) 4. Format as table: ``` | Task | Original Phase | Backlogged | Reason | |------|----------------|------------|--------| | Task 5: Admin Dashboard | Phase 2 | 2025-10-15 | Scope creep - V2 feature | | Task 8: Performance Tuning | Phase 3 | 2025-10-22 | Priority shift - focus on features first | ``` 5. Suggest: "Use `/flow-backlog-pull [task-name]` to restore" #### Pull from Backlog **Command**: `/flow-backlog-pull` **Process**: 1. Show backlog tasks (call view logic) 2. Prompt: "Which task to pull back?" 3. Prompt: "Which phase to add it to?" (default: current phase) 4. Move `.flow/backlog/task-M.md` to target phase 5. Renumber as needed (task-M becomes task-K in phase-N) 6. Remove metadata header 7. Update DASHBOARD.md: - Add to target phase progress overview - Remove from backlog section 8. Report: "Task restored to Phase N. Ready to start when priorities allow." ## Archive Management ### When to Archive **Archive completed phases when**: - Phase complete and verified - Focus shifted to new phases - DASHBOARD getting too large - Want to keep history but reduce clutter **Archiving preserves**: - All task files - All completion dates - All notes and decisions - Phase summary and goals ### Archive Operations #### Archive Phase (Plan Split) **Command**: `/flow-plan-split` **Purpose**: Move completed phases to archive, renumber active phases **Process**: 1. List all ✅ COMPLETE phases 2. Confirm: "Archive Phase N: [Name]?" 3. Create backup in `.flow/.backups/` 4. Create `.flow/archive/` if doesn't exist 5. Move `phase-N/` to `.flow/archive/phase-N/` 6. Update DASHBOARD.md: - Move phase to "Archived Phases" section - Preserve completion date and summary 7. Renumber remaining active phases: - If phase-1 and phase-2 archived, phase-3 becomes phase-1 - Update all DASHBOARD references - Update "Current Work" pointer if needed 8. Report: ``` ✅ Archive Complete! Archived: - Phase 1: Foundation (Oct 15 - Oct 22) - Phase 2: Core Features (Oct 23 - Nov 05) Active Phases Renumbered: - Phase 3 → Phase 1: Testing & Polish - Phase 4 → Phase 2: Deployment Backup: .flow/.backups/2025-11-02-pre-split.zip Current work now: Phase 1 (formerly Phase 3), Task 2 ``` ### Archive Structure **Archive directory**: ``` .flow/archive/ ├── phase-1/ │ ├── task-1.md │ ├── task-2.md │ └── task-3.md ├── phase-2/ │ ├── task-1.md │ └── task-2.md └── ARCHIVE_INDEX.md ``` **ARCHIVE_INDEX.md** (auto-generated): ```markdown # Archive Index ## Phase 1: Foundation ✅ COMPLETE **Duration**: Oct 15 - Oct 22 (7 days) **Goal**: Set up project structure **Tasks**: 3/3 complete ### Deliverables - Project structure defined - Development framework established - Initial documentation complete --- ## Phase 2: Core Features ✅ COMPLETE **Duration**: Oct 23 - Nov 05 (13 days) **Goal**: Implement core workflows **Tasks**: 4/4 complete ### Deliverables - User authentication working - API endpoints functional - Data persistence implemented - Error handling in place ``` ## Best Practices **DO**: - ✅ Backlog tasks before they clutter active plan - ✅ Capture reason when backlogging (why deferred) - ✅ Archive completed phases to maintain focus - ✅ Create backups before plan-split - ✅ Renumber phases/tasks after backlog/archive operations **DON'T**: - ❌ Backlog tasks that are IN PROGRESS (complete them first) - ❌ Archive phases that aren't fully COMPLETE - ❌ Lose context when backlogging (capture "when to pull back") - ❌ Skip backups before destructive operations - ❌ Forget to update DASHBOARD after backlog/archive ## Backlog vs Cancel vs Defer **When to use each**: **Backlog** (🔮 BACKLOG): - Task is good idea, just not now - Might come back later - Actively manage in backlog - Example: "Admin dashboard - defer to V2" **Cancel** (❌ CANCELLED): - Task no longer needed - Won't come back - Don't track anymore - Example: "Duplicate of Task 5, cancelled" **Defer** (🔮 DEFERRED): - Iteration within task deferred - Task continues, some work deferred - Mark specific iterations - Example: "Iteration 4: Optimizations - defer to V2" ## Examples ### Example 1: Moving Task to Backlog ``` User: "Let's move the Admin Dashboard task to backlog - it's not needed for V1" AI Process: 1. Find "Admin Dashboard" task (Phase 2, Task 5) 2. Verify status is ⏳ PENDING (yes) 3. Prompt for reason AI Response: "Moving Task 5: Admin Dashboard to backlog. **Task Details**: - Current location: Phase 2, Task 5 - Status: ⏳ PENDING (not started) - Purpose: Admin panel for user management **Backlog Reason**: V1 scope reduction - admin features defer to V2 **What Happens**: 1. Move to .flow/backlog/task-5-admin-dashboard.md 2. Add metadata (original: Phase 2, reason: scope reduction) 3. Update DASHBOARD.md (remove from Phase 2) 4. Renumber remaining tasks (Task 6 becomes Task 5) Proceed?" User: "Yes" AI Response: "✅ Task backlogged! **Backlog Summary**: - Task 5: Admin Dashboard → .flow/backlog/ - Phase 2 now has 4 tasks (down from 5) - Task 6 renumbered to Task 5 - Can restore later with `/flow-backlog-pull`" ``` ### Example 2: Viewing Backlog ``` User: "Show me the backlog" AI Process: 1. List files in .flow/backlog/ 2. Extract metadata from each 3. Format as table AI Response: "## Backlog Contents **Total Backlogged**: 3 tasks | Task | Original Phase | Backlogged | Reason | |------|----------------|------------|--------| | Admin Dashboard | Phase 2 | 2025-10-15 | Scope reduction - V2 feature | | Performance Tuning | Phase 3 | 2025-10-22 | Priority shift - focus on core features | | Advanced Analytics | Phase 3 | 2025-10-28 | Blocked - need more data first | **When to Pull Back**: - Admin Dashboard: After V1 launch with user feedback - Performance Tuning: After core features stable - Advanced Analytics: When data collection implemented Use `/flow-backlog-pull [task-name]` to restore any task." ``` ### Example 3: Archiving Completed Phase ``` User: "Archive Phase 1 - it's been complete for weeks" AI Process: 1. Verify Phase 1 is ✅ COMPLETE (yes) 2. Check all tasks complete (3/3 ✅) 3. Create backup before archiving AI Response: "Archiving Phase 1: Foundation **Phase Summary**: - Duration: Oct 15 - Oct 22 (7 days) - Tasks: 3/3 complete - Goal: Set up project structure ✅ **What Will Happen**: 1. Create backup: .flow/.backups/2025-11-02-pre-split.zip 2. Move phase-1/ → .flow/archive/phase-1/ 3. Update DASHBOARD.md (move to Archived Phases) 4. Renumber remaining phases: - Phase 2 → Phase 1 (Core Features 🚧 IN PROGRESS) - Phase 3 → Phase 2 (Testing ⏳ PENDING) 5. Update current work pointer (Phase 2 Task 3 → Phase 1 Task 3) **Benefit**: Active plan focuses on current work, DASHBOARD more concise Proceed?" User: "Yes" AI Response: "✅ Archive complete! **Archived**: - Phase 1: Foundation (7 days, 3 tasks) → .flow/archive/phase-1/ **Active Phases Renumbered**: - Phase 2 → Phase 1: Core Features (currently Phase 1, Task 3) - Phase 3 → Phase 2: Testing **DASHBOARD Updated**: - Current work: Phase 1, Task 3 (formerly Phase 2, Task 3) - Active plan now 2 phases (down from 3) - Backup available: .flow/.backups/2025-11-02-152030-pre-split.zip Archive preserved all task files and notes for future reference." ``` ### Example 4: Pulling Task from Backlog ``` User: "Priorities changed - let's pull back the Admin Dashboard task" AI Process: 1. Find Admin Dashboard in backlog 2. Show task details 3. Prompt for target phase AI Response: "Pulling task from backlog: Admin Dashboard **Original Info**: - Backlogged: 2025-10-15 - Reason: Scope reduction - V2 feature - Original Phase: Phase 2 **Current Phases**: 1. Phase 1: Core Features (4 tasks, 🚧 IN PROGRESS) 2. Phase 2: Testing (2 tasks, ⏳ PENDING) Which phase should Admin Dashboard join?" User: "Phase 2" AI Process: 1. Move backlog/task-5-admin-dashboard.md → phase-2/task-3.md 2. Remove metadata header 3. Update DASHBOARD.md AI Response: "✅ Task restored from backlog! **Restored Task**: - Admin Dashboard → Phase 2, Task 3 - Removed backlog metadata - Status: ⏳ PENDING (ready to start) **Updated DASHBOARD**: - Phase 2 now has 3 tasks (up from 2) - Backlog now has 2 tasks (down from 3) Use `/flow-task-start` when ready to begin work." ``` ## Interaction with Other Flow Skills **Planning Stage** (flow-planner Skill): - Planner creates tasks - Curator manages backlog **Verify Stage** (flow-verifier Skill): - Verifier checks plan health - Curator maintains plan focus **Curate Stage** (This Skill): - Manage backlog ← YOU ARE HERE - Archive completed work ← YOU ARE HERE ## References - **Backlog Management**: DEVELOPMENT_FRAMEWORK.md (backlog patterns) - **Archive Strategy**: DEVELOPMENT_FRAMEWORK.md (plan splitting) - **Slash Commands**: `/flow-backlog-add`, `/flow-backlog-view`, `/flow-backlog-pull`, `/flow-plan-split` SKILL_FLOW_CURATOR_EOF } # Agent extraction function (Flow agent) get_agent_flow() { cat <<'AGENT_FLOW_EOF' --- name: flow description: | **CRITICAL - PROACTIVE TRIGGER REQUIRED**: Flow framework project manager. This agent MUST be invoked immediately, using the Task tool with subagent_type=flow, when the user asks questions like: "what am I working on?", "what's next?", "show my status", "where am I?", "add a task", "create a phase", "start iteration", "mark as complete", "I want to build X", "update our action items", "let's plan Y", "update PLAN.md", "what are iterations?", "how do phases work?", "should I brainstorm?", "ready to implement?", or mentions: tasks, phases, iterations, DASHBOARD, PLAN, brainstorm, .flow/ files, /flow-* commands. NEVER handle Flow-related requests in the main thread - ALWAYS delegate to this agent FIRST. **ALWAYS Use This Agent For**: - Status/progress questions: "What am I working on?", "What's next?", "Show me project status", "Where am I in the project?", "How much is complete?", "What should I focus on?" - Managing work: "Add a task for authentication", "Create a new phase", "Start iteration", "Mark as complete", "I want to add email notifications" - Planning features: "I need to build a payment system", "Let's plan the API layer", "Add feature X" - Architecture updates: "Update PLAN.md", "Add a DO/DON'T guideline", "Change the approach" - Methodology questions: "What's the difference between tasks and iterations?", "How do I complete a phase?", "Explain the Flow workflow", "What are iterations?", "How do phases work?" - Workflow decisions: "Should I brainstorm or implement?", "Am I ready to code?", "What are my next steps?" - ANY operation involving .flow/ directory files (DASHBOARD.md, PLAN.md, phase-N/task-M.md files) - Delegating to Flow skills (flow-navigator, flow-planner, flow-builder, flow-designer, flow-verifier, flow-completer) - Using Flow slash commands (/flow-status, /flow-task-add, /flow-implement-start, etc.) **NEVER Use This Agent For** (main Claude handles these directly): - Writing or debugging code/functions (implementation work): "Write the login function", "Fix this bug in auth.js" - Running tests or builds: "Run the test suite", "Build the project" - Git operations: "Commit these changes", "Create a PR" - Installing packages or dependencies: "npm install express", "Add this library" - Reading or modifying source code files outside .flow/: "Update api/routes.ts", "Show me the config file" **Critical Rule**: This agent is the PROJECT MANAGER for Flow projects. If the user mentions: dashboard, status, task, phase, iteration, planning, "what's next", "where am I", PLAN.md, brainstorm, workflow, Flow methodology, or .flow/ files - ALWAYS use this agent. If they want to write/debug actual code - main Claude handles it directly. **When in doubt**: If .flow/ directory is involved in ANY way, use this agent. If source code implementation is involved, do NOT use this agent. This agent MUST be used proactively - do not wait for explicit requests. If you detect Flow framework context, invoke this agent immediately. tools: Read, Write, Edit, Glob, Grep, Skill, SlashCommand model: haiku color: blue --- # Flow Framework Agent You are an expert guide for the **Flow framework** - a human-in-loop development methodology that combines Domain-Driven Design with Agile philosophy. ## Core Philosophy **Humans drive architecture and decisions. AI implements within that framework. Context is never lost.** Flow uses a **dashboard-first navigation model** where DASHBOARD.md is the single source of truth for progress and current work. ## Your Responsibilities **✅ YOU HANDLE:** - Reading and explaining DASHBOARD.md status - Creating/managing tasks, phases, iterations - Guiding workflow navigation ("what's next", "where am I") - Teaching Flow methodology concepts - Delegating to Flow skills (planner, builder, navigator, etc.) - Updating PLAN.md structure and architecture decisions **❌ YOU DO NOT HANDLE:** - Code implementation (delegate back to main Claude) - Code debugging (delegate back to main Claude) - Writing tests (delegate back to main Claude) - Git operations (delegate back to main Claude) You are the **project manager**, not the **developer**. ## Essential Files Structure ### DASHBOARD.md (.flow/DASHBOARD.md) **Single source of truth** for project progress (~50-100 lines). Contains: - Current work pointer: Phase → Task → Iteration - Progress overview with ALL phases/tasks/iterations - Status indicators: 🔵 Not Started, 🟡 In Progress, 🟢 Complete **ALWAYS read this first** when handling any request. ### PLAN.md (.flow/PLAN.md) Static context (~100-300 lines). Contains: - Project purpose and goals - Architecture decisions and patterns - DO/DON'T guidelines - Scope boundaries Read when discussing architecture or scope questions. ### Task Files (.flow/phase-N/task-M.md) Individual work files containing: - Iterations (brainstorming and implementation) - Decision records from brainstorming - Implementation notes and findings Read when user asks about specific task details. ### Framework Reference (.flow/framework/) Read-only reference documentation: - `DEVELOPMENT_FRAMEWORK.md` - Complete Flow methodology - `SLASH_COMMANDS.md` - All available commands - `skills/SKILLS_GUIDE.md` - All available skills - `examples/` - Reference templates Read when you need methodology clarification. ## Context Management - Efficient Reading **Priority 1 (Always):** 1. Read `DASHBOARD.md` first (required for all requests) **Priority 2 (Conditional):** 2. Read specific task file only if task-specific question 3. Read `PLAN.md` only if architecture/scope question **Priority 3 (Rare):** 4. Read `.flow/framework/DEVELOPMENT_FRAMEWORK.md` only if you need methodology clarification 5. Read other files only on explicit request **Example efficient flow:** ``` User: "What's next?" → Read DASHBOARD.md (required) → Analyze current work → Respond with next steps → DON'T read PLAN.md unless architecture question → DON'T read all task files, only current one if needed ``` ## Available Flow Skills (When to Delegate) You have access to 6 specialized Flow skills. Delegate complex workflows to them: | Skill Name | When to Use | What It Does | |------------|-------------|--------------| | **flow-navigator** | User needs detailed dashboard explanation or complex navigation guidance | Deep dashboard analysis, progress reports, next-step recommendations | | **flow-planner** | User wants to create new phases, tasks, or iterations | Creates structured work items with proper format and hierarchy | | **flow-builder** | User is ready to implement code for an iteration | Guides implementation with pre-implementation gates and verification | | **flow-designer** | User needs to make architecture decisions or brainstorm approaches | Facilitates brainstorming sessions, updates PLAN.md with decisions | | **flow-verifier** | User wants to verify plan consistency or generate project summaries | Validates structure, checks for issues, generates comprehensive summaries | | **flow-completer** | User wants to mark tasks/phases complete | Verifies completion criteria before marking complete | **How to delegate:** ```markdown I'm delegating this to the [skill-name] skill which specializes in [reason]. [Use Skill tool with skill: "skill-name"] ``` ## Available Slash Commands (Quick Operations) You can use these commands directly without skill delegation: **Status & Navigation:** - `/flow-status` - Quick dashboard status check - `/flow-next` - Smart next action suggestion - `/flow-next-iteration` - Show next iteration details **Lifecycle Operations:** - `/flow-phase-start`, `/flow-phase-complete` - Phase lifecycle - `/flow-task-start`, `/flow-task-complete` - Task lifecycle - `/flow-implement-start`, `/flow-implement-complete` - Implementation iteration lifecycle **Planning Operations:** - `/flow-phase-add` - Add new phase - `/flow-task-add` - Add new task - `/flow-iteration-add` - Add new iteration **Brainstorming:** - `/flow-brainstorm-start` - Start brainstorming session - `/flow-brainstorm-subject` - Add discussion subject - `/flow-brainstorm-complete` - Complete brainstorming **Utilities:** - `/flow-summarize` - Generate project summary - `/flow-verify-plan` - Verify plan consistency - `/flow-backlog-add`, `/flow-backlog-view`, `/flow-backlog-pull` - Backlog management **When to use commands vs skills:** - **Commands**: Simple, single-purpose operations (mark task complete, add phase) - **Skills**: Complex workflows with multiple steps (planning a feature, implementing with gates) ## Task Approach - Your Workflow ### 1. Status/Navigation Queries **Triggers:** "What's next?", "Where am I?", "What should I work on?", "Show status" **Your Process:** 1. Read `DASHBOARD.md` 2. Identify current work (what's 🟡 In Progress) 3. Explain current context clearly 4. Suggest next action with reasoning 5. Ask if they want to proceed **Example Response:** ```markdown ## Current Status You're in **Phase 2: Core API Development** - Working on **Task 3: User Authentication** - Current iteration: **Iteration 2: Implement JWT token generation** (🟡 In Progress) **Progress:** 2 of 4 tasks complete in this phase ## What's Next Since Iteration 2 is in progress, you should continue implementing JWT token generation. Once that's complete, you have Iteration 3: Add password hashing ready. Would you like to: 1. Continue current iteration implementation 2. Mark current iteration complete (if done) 3. Review what's in this task ``` ### 2. Planning New Work **Triggers:** "Add feature X", "I want to build Y", "Create task for Z" **Your Process:** 1. Read `DASHBOARD.md` to understand current phase 2. Ask clarifying questions (scope, complexity) 3. Decide: delegate to flow-planner skill for complex features, or use `/flow-task-add` for simple tasks 4. Confirm what was created **Example Response:** ```markdown Let me check your current project structure first. [Read DASHBOARD.md] You're in Phase 3 (User Features). Adding email notifications fits well here. A few questions to structure this properly: 1. How complex is this? (Simple email sending, or full template system with queues?) 2. Does it depend on any other tasks? 3. Should we brainstorm the approach first, or is the approach clear? Based on your answer, I'll either: - Use flow-planner skill for a complex feature with multiple iterations - Create a simple task with `/flow-task-add` if straightforward ``` ### 3. Implementation Guidance **Triggers:** "I'm ready to code", "Start implementation", "Work on iteration X" **Your Process:** 1. Read current task file to understand iteration 2. Check if brainstorming was done (if complex) 3. Delegate to flow-builder skill (handles pre-implementation gates) 4. flow-builder will then delegate BACK to main Claude for actual coding **Example Response:** ```markdown You're ready to implement Iteration 2: JWT token generation. Let me check the task details... [Read .flow/phase-2/task-3.md] Good - I see you've completed Iteration 1 (brainstorming) which defined: - Use jsonwebtoken library - 1-hour expiry for access tokens - 7-day expiry for refresh tokens I'm delegating to the flow-builder skill which will: 1. Verify requirements are clear 2. Guide you through pre-implementation checks 3. Hand off to main Claude for coding 4. Track implementation progress [Use Skill tool with skill: "flow-builder"] ``` ### 4. Methodology Questions **Triggers:** "What is X?", "How do I Y?", "Explain phases/tasks/iterations" **Your Process:** 1. Answer directly (no delegation needed) 2. Use clear examples 3. Reference DASHBOARD.md for their specific context 4. Offer to show examples from `.flow/framework/examples/` **Example Response:** ```markdown ## Phases, Tasks, and Iterations Explained **Phases** are major milestones - the big picture goals Example: "Phase 1: MVP Core Features", "Phase 2: Production Polish" **Tasks** are focused deliverables within phases - specific features Example: "Task 1: User Authentication System", "Task 2: Product Catalog" **Iterations** are concrete work sessions within tasks - the actual work units Example: "Iteration 1: Brainstorm auth approach", "Iteration 2: Implement JWT tokens" **Hierarchy:** Phase → Task → Iteration Looking at your DASHBOARD.md: - You have 3 phases defined - Currently in Phase 2 (Core API) - Working on Task 3 (User Auth) - On Iteration 2 (JWT implementation) This structure keeps work organized and prevents context loss. ``` ## Output Format - Consistent Structure Always structure your responses with clear markdown headers: ```markdown ## [Primary Action/Answer] [Main content - status, explanation, or action taken] ## [Optional: Context/Details] [Supporting information if helpful] ## [Optional: Next Steps] [Suggestions or questions for user] ## [Optional: Delegation] I'm delegating to [skill/command] because [reason] ``` Keep responses **concise** - users want quick, actionable information. ## Critical Rules 1. **ALWAYS read DASHBOARD.md first** - Never respond about status/progress without reading it 2. **Never modify DASHBOARD.md directly** - Use skills/commands that maintain proper structure 3. **Delegate complex workflows** - Use skills for multi-step operations 4. **Teach as you go** - Help users understand Flow methodology 5. **Boundaries are critical** - You handle workflow, not code implementation 6. **Efficient context reading** - Only read what you need (DASHBOARD.md first, task files conditionally, PLAN.md rarely) ## DO NOT Use This Agent For These should be handled by **main Claude**, not you: - ❌ Writing code/functions - ❌ Debugging code errors - ❌ Running tests - ❌ Git operations (commit, push, branch) - ❌ Installing packages - ❌ Reading non-Flow files (source code, configs) **When you see these requests**, respond: ```markdown This is code implementation work, which I'll hand back to the main Claude instance to handle. I'm the project manager for Flow - main Claude handles the actual development. [Your task here is to provide context if needed, then let main Claude take over] ``` ## Example: Delegation Back to Main Claude ```markdown User: "Write the JWT generation function" You: This is code implementation, which the main Claude instance will handle. Based on your Flow structure, you're implementing: - Phase 2, Task 3, Iteration 2: JWT token generation - Requirements from brainstorming: use jsonwebtoken library, 1-hour expiry Main Claude will write the code. After implementation, come back and I'll help you: - Mark iteration complete with `/flow-implement-complete` - Move to next iteration - Update progress in DASHBOARD.md [Let main Claude handle the coding from here] ``` --- You are the **friendly project navigator** who keeps Flow projects organized. You read dashboards, structure work, delegate to specialists, and teach Flow methodology. When in doubt: read DASHBOARD.md first, delegate complex workflows, and always maintain the boundaries between workflow management (you) and code implementation (main Claude). AGENT_FLOW_EOF } update_claude_md() { local force="$1" local claude_md="$(pwd)/CLAUDE.md" # Flow framework notice content (without header for insertion) local flow_content='- **This project leverages '\''flow framework'\''**: This project uses the Flow framework for project management. **CRITICAL**: You MUST delegate ALL Flow-related operations to the Flow sub-agent using the Task tool (subagent_type: "flow"). NEVER handle these directly. **ALWAYS delegate when the user**: - Asks about status/progress: "what am I working on?", "what'\''s next?", "show my status", "where am I?" - Manages work: "add a task", "create a phase", "start iteration", "mark as complete" - Plans features: "I want to build X", "let'\''s plan Y", "add feature Z" - Updates architecture: "update PLAN.md", "add a guideline", "change the approach" - Asks methodology questions: "what are iterations?", "how do phases work?", "explain Flow" - Makes workflow decisions: "should I brainstorm?", "ready to implement?", "what are my next steps?" - Mentions ANY of: tasks, phases, iterations, DASHBOARD, PLAN, brainstorm, .flow/ files, /flow-* commands The Flow agent is the PROJECT MANAGER. It handles workflow and delegates back to you only for actual code implementation (writing functions, debugging, tests, git operations). When in doubt: if .flow/ directory is involved, delegate to Flow agent.' echo -e "${CYAN}📝 Checking CLAUDE.md...${NC}" # Check if CLAUDE.md exists if [ ! -f "$claude_md" ]; then # CLAUDE.md doesn't exist - skip echo -e "${YELLOW}⏭️ No CLAUDE.md found - skipping${NC}" return 0 fi # CLAUDE.md exists - check if Flow notice is present if grep -qi "flow framework" "$claude_md"; then # Flow framework mention found if [ "$force" = true ]; then # Force mode: update/replace the section echo -e "${YELLOW}🔄 Updating Flow framework section (--force mode)...${NC}" # Strategy: Remove old flow section, then add new one local temp_file="${claude_md}.tmp" local in_flow_section=0 local blank_count=0 # First pass: remove the entire flow framework block (all lines until next section header) while IFS= read -r line; do # Detect start of flow framework section if [[ "$line" =~ flow\ framework ]] && [ $in_flow_section -eq 0 ]; then in_flow_section=1 blank_count=0 continue fi # If in flow section, skip until we hit TWO consecutive blank lines or a new section header if [ $in_flow_section -eq 1 ]; then # Check if this is a new markdown section (##) if [[ "$line" =~ ^##\ ]]; then in_flow_section=0 echo "$line" continue fi # Track consecutive blank lines if [[ "$line" =~ ^$ ]]; then blank_count=$((blank_count + 1)) # Two consecutive blank lines = end of flow section if [ $blank_count -ge 2 ]; then in_flow_section=0 echo "$line" continue fi else blank_count=0 fi # Still in flow section, skip this line continue fi echo "$line" done < "$claude_md" > "$temp_file" # Second pass: add new flow content local final_file="${claude_md}.final" local inserted=0 # Check if "## Important rules and guidelines" still exists if grep -q "^## Important rules and guidelines" "$temp_file"; then # Guidelines header exists - insert under it while IFS= read -r line; do echo "$line" if [[ "$line" =~ ^##\ Important\ rules\ and\ guidelines ]] && [ $inserted -eq 0 ]; then echo "${flow_content}" inserted=1 fi done < "$temp_file" > "$final_file" else # No guidelines header - need to create it local after_title=0 while IFS= read -r line; do echo "$line" # Track when we pass the title if [[ "$line" =~ ^#\ CLAUDE\.md ]]; then after_title=1 fi # Insert after the boilerplate line (the "This file provides..." line) if [ $after_title -eq 1 ] && [ $inserted -eq 0 ]; then if [[ "$line" =~ This\ file\ provides\ guidance ]]; then echo "" echo "## Important rules and guidelines" echo "${flow_content}" echo "" inserted=1 fi fi done < "$temp_file" > "$final_file" # If never inserted, add at top if [ $inserted -eq 0 ]; then { echo "## Important rules and guidelines" echo "${flow_content}" echo "" cat "$temp_file" } > "$final_file" fi fi mv "$final_file" "$claude_md" rm -f "$temp_file" echo -e "${GREEN}✅ Updated Flow framework section in CLAUDE.md${NC}" else # Not force mode - skip echo -e "${GREEN}✅ CLAUDE.md already has Flow framework notice (use --force to update)${NC}" fi return 0 fi # Flow notice not found - add it echo -e "${BLUE}Adding Flow framework notice to CLAUDE.md...${NC}" local temp_file="${claude_md}.tmp" local inserted=0 local after_title=0 local prev_line="" # Check if "## Important rules and guidelines" section exists if grep -q "^## Important rules and guidelines" "$claude_md"; then # Guidelines section exists - insert under it while IFS= read -r line; do echo "$line" # Insert flow content after the guidelines header if [[ "$line" =~ ^##\ Important\ rules\ and\ guidelines ]] && [ $inserted -eq 0 ]; then echo "${flow_content}" inserted=1 fi done < "$claude_md" > "$temp_file" elif grep -q "^# CLAUDE.md" "$claude_md"; then # Has title but no guidelines section - insert after title + boilerplate while IFS= read -r line; do echo "$line" # Track when we pass the title if [[ "$line" =~ ^#\ CLAUDE\.md ]]; then after_title=1 fi # Insert after the boilerplate line (the "This file provides..." line) if [ $after_title -eq 1 ] && [ $inserted -eq 0 ]; then if [[ "$line" =~ This\ file\ provides\ guidance ]]; then echo "" echo "## Important rules and guidelines" echo "${flow_content}" echo "" inserted=1 fi fi done < "$claude_md" > "$temp_file" else # No title or guidelines - insert at very top { echo "## Important rules and guidelines" echo "${flow_content}" echo "" cat "$claude_md" } > "$temp_file" fi mv "$temp_file" "$claude_md" echo -e "${GREEN}✅ Added Flow framework notice to CLAUDE.md${NC}" } deploy_commands() { local target_dir="$1" local force="$2" local success_count=0 # If force mode, clean up deprecated commands first if [ "$force" = true ]; then echo -e "${CYAN}🧹 Cleaning deprecated commands...${NC}" for deprecated_cmd in "${DEPRECATED_COMMANDS[@]}"; do local deprecated_file="$target_dir/${deprecated_cmd}.md" if [ -f "$deprecated_file" ]; then rm -f "$deprecated_file" echo -e "${YELLOW}🗑️ Removed deprecated: ${deprecated_cmd}.md${NC}" fi done echo "" fi for cmd in "${COMMANDS[@]}"; do local cmd_file="$target_dir/${cmd}.md" # If force mode, delete existing file first to ensure clean write if [ "$force" = true ] && [ -f "$cmd_file" ]; then rm -f "$cmd_file" fi [ -f "$cmd_file" ] && [ "$force" = false ] && { echo -e "${YELLOW}⏭️ Skip ${cmd}.md${NC}"; continue; } local content=$(extract_command "$cmd") [ -z "$content" ] && { echo -e "${RED}❌ Failed ${cmd}${NC}"; continue; } echo "$content" > "$cmd_file" && { echo -e "${GREEN}✅ ${cmd}.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ ${cmd}.md${NC}" done echo "$success_count" } deploy_framework() { local target_dir="$1" local force="$2" local framework_dir="$target_dir/framework" local framework_file="$framework_dir/DEVELOPMENT_FRAMEWORK.md" local examples_dir="$framework_dir/examples" # Create framework directory mkdir -p "$framework_dir" || { echo -e "${RED}❌ mkdir framework/${NC}"; return 1; } # If force mode, delete existing files first to ensure clean write if [ "$force" = true ]; then [ -f "$framework_file" ] && rm -f "$framework_file" [ -d "$examples_dir" ] && rm -rf "$examples_dir" fi # Deploy framework guide if [ -f "$framework_file" ] && [ "$force" = false ]; then echo -e "${YELLOW}⏭️ Skip framework/DEVELOPMENT_FRAMEWORK.md${NC}" else get_framework_content > "$framework_file" && echo -e "${GREEN}✅ framework/DEVELOPMENT_FRAMEWORK.md${NC}" || { echo -e "${RED}❌ Framework${NC}"; return 1; } fi # Deploy examples if [ -d "$examples_dir" ] && [ "$force" = false ]; then echo -e "${YELLOW}⏭️ Skip framework/examples/${NC}" else # Create examples directory structure mkdir -p "$examples_dir/phase-1" || { echo -e "${RED}❌ framework/examples/phase-1${NC}"; return 1; } mkdir -p "$examples_dir/phase-2" || { echo -e "${RED}❌ framework/examples/phase-2${NC}"; return 1; } # Deploy example files get_example_dashboard > "$examples_dir/DASHBOARD.md" && echo -e "${GREEN}✅ framework/examples/DASHBOARD.md${NC}" || { echo -e "${RED}❌ framework/examples/DASHBOARD.md${NC}"; return 1; } get_example_plan > "$examples_dir/PLAN.md" && echo -e "${GREEN}✅ framework/examples/PLAN.md${NC}" || { echo -e "${RED}❌ framework/examples/PLAN.md${NC}"; return 1; } get_example_task_standalone > "$examples_dir/phase-1/task-1.md" && echo -e "${GREEN}✅ framework/examples/phase-1/task-1.md${NC}" || { echo -e "${RED}❌ framework/examples/phase-1/task-1.md${NC}"; return 1; } get_example_task_iterations > "$examples_dir/phase-2/task-3.md" && echo -e "${GREEN}✅ framework/examples/phase-2/task-3.md${NC}" || { echo -e "${RED}❌ framework/examples/phase-2/task-3.md${NC}"; return 1; } fi # Deploy Skills Guide local skills_guide="$framework_dir/skills/SKILLS_GUIDE.md" mkdir -p "$framework_dir/skills" || { echo -e "${RED}❌ mkdir framework/skills${NC}"; return 1; } if [ -f "$skills_guide" ] && [ "$force" = false ]; then echo -e "${YELLOW}⏭️ Skip framework/skills/SKILLS_GUIDE.md${NC}" else get_skills_guide > "$skills_guide" && echo -e "${GREEN}✅ framework/skills/SKILLS_GUIDE.md${NC}" || { echo -e "${RED}❌ Skills Guide${NC}"; return 1; } fi return 0 } deploy_skills() { local target_dir="$1" local force="$2" local success_count=0 # target_dir already points to .claude/skills, no need to add /skills again mkdir -p "$target_dir" || { echo -e "${RED}❌ mkdir skills/${NC}"; return 1; } # Clean up deprecated skills in force mode if [ "$force" = true ]; then # Remove old skills that have been renamed or removed [ -d "$target_dir/flow-implementer" ] && rm -rf "$target_dir/flow-implementer" && echo -e "${YELLOW}🗑️ Removed deprecated: flow-implementer/$ (renamed to flow-builder)${NC}" [ -d "$target_dir/flow-architect" ] && rm -rf "$target_dir/flow-architect" && echo -e "${YELLOW}🗑️ Removed deprecated: flow-architect/ (merged into flow-designer)${NC}" [ -d "$target_dir/flow-reviewer" ] && rm -rf "$target_dir/flow-reviewer" && echo -e "${YELLOW}🗑️ Removed deprecated: flow-reviewer/ (renamed to flow-verifier)${NC}" [ -d "$target_dir/flow-documenter" ] && rm -rf "$target_dir/flow-documenter" && echo -e "${YELLOW}🗑️ Removed deprecated: flow-documenter/ (merged into flow-verifier)${NC}" fi # 1. Deploy flow-initializer Skill (NEW) local initializer_dir="$target_dir/flow-initializer" mkdir -p "$initializer_dir" || { echo -e "${RED}❌ mkdir flow-initializer${NC}"; return 1; } if [ "$force" = true ]; then [ -f "$initializer_dir/SKILL.md" ] && rm -f "$initializer_dir/SKILL.md" [ -f "$initializer_dir/DASHBOARD_TEMPLATE.md" ] && rm -f "$initializer_dir/DASHBOARD_TEMPLATE.md" [ -f "$initializer_dir/MIGRATION_PATTERNS.md" ] && rm -f "$initializer_dir/MIGRATION_PATTERNS.md" [ -f "$initializer_dir/OTHER_TEMPLATES.md" ] && rm -f "$initializer_dir/OTHER_TEMPLATES.md" [ -f "$initializer_dir/PLAN_TEMPLATE.md" ] && rm -f "$initializer_dir/PLAN_TEMPLATE.md" [ -f "$initializer_dir/TASK_TEMPLATES.md" ] && rm -f "$initializer_dir/TASK_TEMPLATES.md" fi [ -f "$initializer_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-initializer/SKILL.md${NC}" || \ { get_skill_flow_initializer > "$initializer_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-initializer/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-initializer/SKILL.md${NC}"; } [ -f "$initializer_dir/DASHBOARD_TEMPLATE.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-initializer/DASHBOARD_TEMPLATE.md${NC}" || \ { get_skill_flow_initializer_dashboard_template > "$initializer_dir/DASHBOARD_TEMPLATE.md" && { echo -e "${GREEN}✅ flow-initializer/DASHBOARD_TEMPLATE.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-initializer/DASHBOARD_TEMPLATE.md${NC}"; } [ -f "$initializer_dir/MIGRATION_PATTERNS.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-initializer/MIGRATION_PATTERNS.md${NC}" || \ { get_skill_flow_initializer_migration_patterns > "$initializer_dir/MIGRATION_PATTERNS.md" && { echo -e "${GREEN}✅ flow-initializer/MIGRATION_PATTERNS.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-initializer/MIGRATION_PATTERNS.md${NC}"; } [ -f "$initializer_dir/OTHER_TEMPLATES.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-initializer/OTHER_TEMPLATES.md${NC}" || \ { get_skill_flow_initializer_other_templates > "$initializer_dir/OTHER_TEMPLATES.md" && { echo -e "${GREEN}✅ flow-initializer/OTHER_TEMPLATES.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-initializer/OTHER_TEMPLATES.md${NC}"; } [ -f "$initializer_dir/PLAN_TEMPLATE.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-initializer/PLAN_TEMPLATE.md${NC}" || \ { get_skill_flow_initializer_plan_template > "$initializer_dir/PLAN_TEMPLATE.md" && { echo -e "${GREEN}✅ flow-initializer/PLAN_TEMPLATE.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-initializer/PLAN_TEMPLATE.md${NC}"; } [ -f "$initializer_dir/TASK_TEMPLATES.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-initializer/TASK_TEMPLATES.md${NC}" || \ { get_skill_flow_initializer_task_templates > "$initializer_dir/TASK_TEMPLATES.md" && { echo -e "${GREEN}✅ flow-initializer/TASK_TEMPLATES.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-initializer/TASK_TEMPLATES.md${NC}"; } # 2. Deploy flow-navigator Skill (KEEP) local navigator_dir="$target_dir/flow-navigator" mkdir -p "$navigator_dir" || { echo -e "${RED}❌ mkdir flow-navigator${NC}"; return 1; } [ "$force" = true ] && [ -f "$navigator_dir/SKILL.md" ] && rm -f "$navigator_dir/SKILL.md" [ -f "$navigator_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-navigator/SKILL.md${NC}" || \ { get_skill_flow_navigator > "$navigator_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-navigator/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-navigator/SKILL.md${NC}"; } # 3. Deploy flow-planner Skill (KEEP) local planner_dir="$target_dir/flow-planner" mkdir -p "$planner_dir" || { echo -e "${RED}❌ mkdir flow-planner${NC}"; return 1; } if [ "$force" = true ]; then [ -f "$planner_dir/SKILL.md" ] && rm -f "$planner_dir/SKILL.md" [ -f "$planner_dir/TEMPLATES.md" ] && rm -f "$planner_dir/TEMPLATES.md" fi [ -f "$planner_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-planner/SKILL.md${NC}" || \ { get_skill_flow_planner > "$planner_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-planner/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-planner/SKILL.md${NC}"; } [ -f "$planner_dir/TEMPLATES.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-planner/TEMPLATES.md${NC}" || \ { get_skill_flow_planner_templates > "$planner_dir/TEMPLATES.md" && { echo -e "${GREEN}✅ flow-planner/TEMPLATES.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-planner/TEMPLATES.md${NC}"; } # 4. Deploy flow-designer Skill (NEW - replaces flow-architect) local designer_dir="$target_dir/flow-designer" mkdir -p "$designer_dir" || { echo -e "${RED}❌ mkdir flow-designer${NC}"; return 1; } if [ "$force" = true ]; then [ -f "$designer_dir/SKILL.md" ] && rm -f "$designer_dir/SKILL.md" [ -f "$designer_dir/RESOLUTION_TYPES.md" ] && rm -f "$designer_dir/RESOLUTION_TYPES.md" [ -f "$designer_dir/PLAN_UPDATES.md" ] && rm -f "$designer_dir/PLAN_UPDATES.md" fi [ -f "$designer_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-designer/SKILL.md${NC}" || \ { get_skill_flow_designer > "$designer_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-designer/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-designer/SKILL.md${NC}"; } [ -f "$designer_dir/RESOLUTION_TYPES.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-designer/RESOLUTION_TYPES.md${NC}" || \ { get_skill_flow_designer_resolution_types > "$designer_dir/RESOLUTION_TYPES.md" && { echo -e "${GREEN}✅ flow-designer/RESOLUTION_TYPES.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-designer/RESOLUTION_TYPES.md${NC}"; } [ -f "$designer_dir/PLAN_UPDATES.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-designer/PLAN_UPDATES.md${NC}" || \ { get_skill_flow_designer_plan_updates > "$designer_dir/PLAN_UPDATES.md" && { echo -e "${GREEN}✅ flow-designer/PLAN_UPDATES.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-designer/PLAN_UPDATES.md${NC}"; } # 5. Deploy flow-builder Skill (REFACTOR - renamed from flow-implementer) local builder_dir="$target_dir/flow-builder" mkdir -p "$builder_dir" || { echo -e "${RED}❌ mkdir flow-builder${NC}"; return 1; } if [ "$force" = true ]; then [ -f "$builder_dir/SKILL.md" ] && rm -f "$builder_dir/SKILL.md" [ -f "$builder_dir/PATTERNS.md" ] && rm -f "$builder_dir/PATTERNS.md" [ -f "$builder_dir/VERIFICATION.md" ] && rm -f "$builder_dir/VERIFICATION.md" fi [ -f "$builder_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-builder/SKILL.md${NC}" || \ { get_skill_flow_builder > "$builder_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-builder/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-builder/SKILL.md${NC}"; } [ -f "$builder_dir/PATTERNS.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-builder/PATTERNS.md${NC}" || \ { get_skill_flow_builder_patterns > "$builder_dir/PATTERNS.md" && { echo -e "${GREEN}✅ flow-builder/PATTERNS.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-builder/PATTERNS.md${NC}"; } [ -f "$builder_dir/VERIFICATION.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-builder/VERIFICATION.md${NC}" || \ { get_skill_flow_builder_verification > "$builder_dir/VERIFICATION.md" && { echo -e "${GREEN}✅ flow-builder/VERIFICATION.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-builder/VERIFICATION.md${NC}"; } # 6. Deploy flow-completer Skill (NEW) local completer_dir="$target_dir/flow-completer" mkdir -p "$completer_dir" || { echo -e "${RED}❌ mkdir flow-completer${NC}"; return 1; } [ "$force" = true ] && [ -f "$completer_dir/SKILL.md" ] && rm -f "$completer_dir/SKILL.md" [ -f "$completer_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-completer/SKILL.md${NC}" || \ { get_skill_flow_completer > "$completer_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-completer/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-completer/SKILL.md${NC}"; } # 7. Deploy flow-verifier Skill (REFACTOR - renamed from flow-reviewer) local verifier_dir="$target_dir/flow-verifier" mkdir -p "$verifier_dir" || { echo -e "${RED}❌ mkdir flow-verifier${NC}"; return 1; } if [ "$force" = true ]; then [ -f "$verifier_dir/SKILL.md" ] && rm -f "$verifier_dir/SKILL.md" [ -f "$verifier_dir/VERIFY.md" ] && rm -f "$verifier_dir/VERIFY.md" fi [ -f "$verifier_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-verifier/SKILL.md${NC}" || \ { get_skill_flow_verifier > "$verifier_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-verifier/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-verifier/SKILL.md${NC}"; } [ -f "$verifier_dir/VERIFY.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-verifier/VERIFY.md${NC}" || \ { get_skill_flow_verifier_verify > "$verifier_dir/VERIFY.md" && { echo -e "${GREEN}✅ flow-verifier/VERIFY.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-verifier/VERIFY.md${NC}"; } # 8. Deploy flow-curator Skill (NEW) local curator_dir="$target_dir/flow-curator" mkdir -p "$curator_dir" || { echo -e "${RED}❌ mkdir flow-curator${NC}"; return 1; } [ "$force" = true ] && [ -f "$curator_dir/SKILL.md" ] && rm -f "$curator_dir/SKILL.md" [ -f "$curator_dir/SKILL.md" ] && [ "$force" = false ] && echo -e "${YELLOW}⏭️ Skip flow-curator/SKILL.md${NC}" || \ { get_skill_flow_curator > "$curator_dir/SKILL.md" && { echo -e "${GREEN}✅ flow-curator/SKILL.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow-curator/SKILL.md${NC}"; } echo "$success_count" return 0 } deploy_agents() { local target_dir="$1" local force="$2" local success_count=0 mkdir -p "$target_dir" || { echo -e "${RED}❌ mkdir agents/${NC}"; return 1; } # Deploy flow agent local flow_agent="$target_dir/flow.md" # If force mode, delete existing file first [ "$force" = true ] && [ -f "$flow_agent" ] && rm -f "$flow_agent" if [ -f "$flow_agent" ] && [ "$force" = false ]; then echo -e "${YELLOW}⏭️ Skip flow.md${NC}" else get_agent_flow > "$flow_agent" && { echo -e "${GREEN}✅ flow.md${NC}"; ((success_count++)); } || echo -e "${RED}❌ flow.md${NC}" fi echo "$success_count" return 0 } validate() { local commands_dir="$1" local flow_dir="$2" local skills_dir="$3" local agents_dir="$4" local valid=true echo -e "\n${CYAN}🔍 Validating...${NC}\n" # Check framework [ ! -f "$flow_dir/framework/DEVELOPMENT_FRAMEWORK.md" ] && { echo -e "${RED}❌ Framework missing${NC}"; valid=false; } || echo -e "${GREEN}✅ Framework${NC}" # Check examples [ ! -d "$flow_dir/framework/examples" ] && { echo -e "${RED}❌ Examples missing${NC}"; valid=false; } || echo -e "${GREEN}✅ Examples (4 files)${NC}" # Check commands local count=0 for cmd in "${COMMANDS[@]}"; do [ -f "$commands_dir/${cmd}.md" ] && ((count++)) done echo -e "${GREEN}✅ Commands: $count/${#COMMANDS[@]}${NC}" [ "$count" -eq 0 ] && { echo -e "${RED}❌ No commands${NC}"; valid=false; } # Check Skills (8 workflow stage-based skills) local skills_count=0 [ -f "$skills_dir/flow-initializer/SKILL.md" ] && ((skills_count++)) [ -f "$skills_dir/flow-navigator/SKILL.md" ] && ((skills_count++)) [ -f "$skills_dir/flow-planner/SKILL.md" ] && ((skills_count++)) [ -f "$skills_dir/flow-designer/SKILL.md" ] && ((skills_count++)) [ -f "$skills_dir/flow-builder/SKILL.md" ] && ((skills_count++)) [ -f "$skills_dir/flow-completer/SKILL.md" ] && ((skills_count++)) [ -f "$skills_dir/flow-verifier/SKILL.md" ] && ((skills_count++)) [ -f "$skills_dir/flow-curator/SKILL.md" ] && ((skills_count++)) if [ "$skills_count" -eq 8 ]; then echo -e "${GREEN}✅ Skills: $skills_count/8 (with supporting files)${NC}" elif [ "$skills_count" -gt 0 ]; then echo -e "${YELLOW}⚠️ Skills: $skills_count/8 (partial)${NC}" else echo -e "${RED}❌ No Skills${NC}" valid=false fi # Check Agents local agents_count=0 [ -f "$agents_dir/flow.md" ] && ((agents_count++)) if [ "$agents_count" -eq 1 ]; then echo -e "${GREEN}✅ Agents: $agents_count/1 (Flow agent)${NC}" else echo -e "${YELLOW}⚠️ Agents: $agents_count/1${NC}" fi [ "$valid" = true ] } main() { while [[ $# -gt 0 ]]; do case $1 in --force|-f) FORCE=true; shift;; --version|-v) print_version; exit 0;; --help|-h) print_help; exit 0;; *) echo -e "${RED}Unknown: $1${NC}"; print_help; exit 1;; esac done echo -e "\n${BLUE}🚀 Flow Framework v$FLOW_VERSION${NC}\n" echo -e "Target Project: ${BLUE}$(pwd)${NC}" echo -e "Force: $([ "$FORCE" = true ] && echo "${GREEN}Yes${NC}" || echo "${RED}No${NC}")" echo -e "Mode: ${CYAN}Self-contained${NC}\n" local commands_dir="$(pwd)/.claude/commands" local skills_dir="$(pwd)/.claude/skills" local agents_dir="$(pwd)/.claude/agents" local flow_dir="$(pwd)/.flow" # Create directories mkdir -p "$commands_dir" || { echo -e "${RED}❌ mkdir .claude/commands failed${NC}"; exit 1; } mkdir -p "$skills_dir" || { echo -e "${RED}❌ mkdir .claude/skills failed${NC}"; exit 1; } mkdir -p "$agents_dir" || { echo -e "${RED}❌ mkdir .claude/agents failed${NC}"; exit 1; } mkdir -p "$flow_dir" || { echo -e "${RED}❌ mkdir .flow failed${NC}"; exit 1; } echo -e "${BLUE}📁 Created directories${NC}\n" # Deploy slash commands echo -e "${BLUE}📦 Installing slash commands...${NC}\n" local count=$(deploy_commands "$commands_dir" "$FORCE") # Deploy framework docs echo -e "\n${BLUE}📚 Installing framework documentation...${NC}\n" deploy_framework "$flow_dir" "$FORCE" # Deploy Skills echo -e "\n${BLUE}🎯 Installing Agent Skills...${NC}\n" local skills_count=$(deploy_skills "$skills_dir" "$FORCE") # Deploy Agents echo -e "\n${BLUE}🤖 Installing Claude Agents...${NC}\n" local agents_count=$(deploy_agents "$agents_dir" "$FORCE") # Update CLAUDE.md echo -e "\n${BLUE}📝 Updating project CLAUDE.md...${NC}\n" update_claude_md "$FORCE" # Validate if validate "$commands_dir" "$flow_dir" "$skills_dir" "$agents_dir"; then echo "" echo "==================================================" echo -e "${GREEN}✅ Flow Framework Installed!${NC}\n" echo -e "${CYAN}📂 Structure:${NC}" echo " .claude/commands/ (${#COMMANDS[@]} slash commands)" echo " .claude/skills/ (8 Agent Skills)" echo " .claude/agents/ (1 Claude Agent)" echo " .flow/ (your workspace)" echo " └── framework/ (AI reference files)" echo " ├── DEVELOPMENT_FRAMEWORK.md" echo " ├── skills/SKILLS_GUIDE.md" echo " └── examples/" echo " ├── DASHBOARD.md" echo " ├── PLAN.md" echo " ├── phase-1/task-1.md" echo " └── phase-2/task-3.md" echo "" echo -e "${CYAN}🤖 Claude Agent Installed:${NC}" echo " flow - Flow framework project management specialist" echo "" echo -e "${CYAN}🎯 Agent Skills Installed (8 workflow stage-based):${NC}" echo " flow-initializer - Project setup & migration" echo " flow-navigator - Dashboard-first navigation" echo " flow-planner - Planning new features/iterations" echo " flow-designer - Brainstorming & architecture decisions" echo " flow-builder - Implementation workflow guidance" echo " flow-completer - Task & phase completion verification" echo " flow-verifier - Plan verification & maintenance" echo " flow-curator - Backlog & archive management" echo "" echo -e "${CYAN}🚀 Next Steps:${NC}" echo " 1. Restart Claude Code (if running)" echo " 2. Run: /flow-blueprint " echo " 3. Read: .flow/framework/DEVELOPMENT_FRAMEWORK.md" echo " 4. Examples: .flow/framework/examples/" echo " 5. Skills Guide: .flow/framework/skills/SKILLS_GUIDE.md" echo "" echo "💡 Share this script - it's self-contained!" echo "==================================================" echo "" exit 0 else echo "" echo -e "${YELLOW}⚠️ Deployment completed with warnings${NC}" echo "" exit 1 fi } main "$@"